text
stringlengths 37
1.41M
|
---|
#Initial Password Input
def passwordsetup():
from getpass import getpass as gp
passmatch = False
passcount = 0
passfinal = ""
while not passmatch and passcount < 3:
password_try1 = gp()
password_try2 = gp()
if password_try1 == password_try2:
print "Your password has been set"
passfinal = password_try2
passmatch = True
elif passcount < 2:
print "Sorry, those passwords did not match, try again"
passcount = passcount + 1
else:
print "Sorry, you clearly can't type. go home."
return passfinal |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
name = "I\'m {0},age {1}"
print name.format("alex",28)
"""
result = 'I an %s,age %s' % ('rain',27)
print result
"""
|
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#Description:This program is mainly practicing the bob sort method(冒泡算法)
#实际上是一个排列组合
li = [13,22,18,33,99,15]
for n in range(1,len(li)):
for m in range(len(li)-n):
#获取m个值
num1 = li[m]
#获取m+1个值
num2 = li[m+1]
if num1 > num2:
#将较大的值放在右侧
temp = li[m]
li[m] = num2
li[m+1] = temp
print li
'''
###算法解析####
#for m in range(5):
num1 = li[4]
num2 = li[5]
if num1 > num2:
temp = li[4]
li[4] = li[5]
li[5] = temp
print li
###
num1 = li[3]
num2 = li[4]
if num1 > num2:
temp = li[3]
li[3] = li[4]
li[4] = temp
print li
###
num1 = li[2]
num2 = li[3]
if num1 > num2:
temp = li[2]
li[2] = li[3]
li[3] = temp
print li
###
num1 = li[1]
num2 = li[2]
if num1 > num2:
temp = li[1]
li[1] = li[2]
li[2] = temp
print li
'''
|
#The code was run on PYCHARM IDE on WINDOWS python version 3.x
'''
Steps to recreate:
1)Open PYCHARM
2)Create a new project
3) Add a new python file and paste the code
4) Run the code
'''
print("Only one test data was added 8int.txt")
text=input("enter the file name excluding '.txt' extension as 8int:\n")
text=text+".txt"
try:
f = open(text, "r")
nums = f.readlines()
nums = [int(i) for i in nums]
s = len(nums)
nums.sort()
sum = int(input("Enter the sum value"))
# function to check if a pair of numbers sum up to '0'
def linear_pairs(arr):
l = 0
r = len(arr) - 1
c = 0
while l < r:
if arr[l] + arr[r] == 0:
c += 1
l += 1
elif arr[l] + arr[r] < 0:
l = l + 1
else:
r = r - 1
return c
count = 0
# Counting the number of triplets, that sum up to a given value
for i in range(0, len(nums)):
if nums[i] == sum:
count += linear_pairs(nums)
print('The number of triplets with sum', sum, 'is', count)
except:
print('File not found!!!')
|
# -*- coding: utf-8 -*-
# Name: Naga Venkata V Vinnakota
# Netid: nvv13
# Ran on Pycharm
#Submitted date: 04/17/2020
import math
import random
random.seed(0)
# Sigmoid activation and deactivation functions
def sigmoid(x):
return 1.0 / (1.0 + math.exp(-x))
def desigmoid(x):
return x * (1 - x)
# Random number creation for weight matrices
def randomNum(a, b):
return (b - a) * random.random() + a
# construction and randomizing the weight matrices
def create_matrix(in_matrix, out, fill=0.0):
m = []
for i in range(in_matrix):
m.append([fill] * out)
return m
def randomize_Matrix(matrix, lower, upper):
for i in range(len(matrix)):
for j in range(len(matrix[0])):
matrix[i][j] = random.uniform(lower, upper)
# creation of neural networks class
class NN:
def __init__(self, n_i, n_h, n_o):
self.layer_in = n_i + 1
self.hidden_layer = n_h
self.layer_out = n_o
self.a_in = [1.0] * self.layer_in
self.a_hidden = [1.0] * self.hidden_layer
self.a_out = [1.0] * self.layer_out
# weight matrices
# Theta1
self.w1 = create_matrix(self.layer_in, self.hidden_layer)
# Theta2
self.w2 = create_matrix(self.hidden_layer, self.layer_out)
randomize_Matrix(self.w1, -1, 1)
randomize_Matrix(self.w2, -1, 1)
print ("\n" + 'Initial print_weights before training:')
print ('Theta1: ')
for i in range(self.layer_in):
print (self.w1[i])
print ('Theta2: ')
for j in range(self.hidden_layer):
print (self.w2[j])
self.c_in = create_matrix(self.layer_in, self.hidden_layer)
self.c_out = create_matrix(self.hidden_layer, self.layer_out)
# computes the prediction
def predict(self, inputs):
for i in range(self.layer_in - 1):
self.a_in[i] = inputs[i]
for j in range(self.hidden_layer):
sum = 0.0
for i in range(self.layer_in):
sum += (self.a_in[i] * self.w1[i][j])
self.a_hidden[j] = sigmoid(sum)
for k in range(self.layer_out):
sum = 0.0
for j in range(self.hidden_layer):
sum += (self.a_hidden[j] * self.w2[j][k])
self.a_out[k] = sigmoid(sum)
return self.a_out
# reduces the errors by BackPropagation
def Back_Propagate(self, targets, N, M):
# calculates the delta for output layer
output_layer_deltas = [0.0] * self.layer_out
for k in range(self.layer_out):
error = targets[k] - self.a_out[k]
output_layer_deltas[k] = error * desigmoid(self.a_out[k])
# updates the Theta2
for j in range(self.hidden_layer):
for k in range(self.layer_out):
change = output_layer_deltas[k] * self.a_hidden[j]
self.w2[j][k] += N * change + M * self.c_out[j][k]
self.c_out[j][k] = change
# calculates the delta for hidden layer
hidden_layer_deltas = [0.0] * self.hidden_layer
for j in range(self.hidden_layer):
error = 0.0
for k in range(self.layer_out):
error += output_layer_deltas[k] * self.w2[j][k]
hidden_layer_deltas[j] = error * desigmoid(self.a_hidden[j])
# updates the Theta1
for i in range(self.layer_in):
for j in range(self.hidden_layer):
change = hidden_layer_deltas[j] * self.a_in[i]
self.w1[i][j] += N * change + M * self.c_in[i][j]
self.c_in[i][j] = change
error = 0.0
for k in range(len(targets)):
error = 0.5 * (targets[k] - self.a_out[k]) ** 2
return error
# prints the print_weights i.e Theta1 and Theta2
def print_weights(self):
print( 'Theta 1: ')
for i in range(self.layer_in):
print(self.w1[i])
print ('Theta 2: ')
for j in range(self.hidden_layer):
print (self.w2[j])
print ('')
# Trains the print_weights based for the given inputs and learning rate
def train(self, patterns,N, expectedError, max_iterations=1000):
M = N / 2
for i in range(max_iterations):
for p in patterns:
inputs = p[0]
targets = p[1]
self.predict(inputs)
error = self.Back_Propagate(targets, N, M)
if i == 0:
print ("\n" + 'First-batch error before training:', error)
if error < expectedError:
print("\n" + 'Final print_weights after training the data set:')
self.print_weights()
print ('Final error after training:', error)
print ('The total number of batches run in the training for achieving the expected error:', i + 1)
break
def main():
XOR = [
[[0, 0], [0]],
[[0, 1], [1]],
[[1, 0], [1]],
[[1, 1], [0]]
]
expectedError = float(input('Please enter the expected error: '))
learningRate = float(input('Please enter the learning rate: '))
neural = NN(2, 2, 1)
neural.train(XOR,learningRate,expectedError)
if __name__ == "__main__":
main() |
import time
count=0
count1=0
class Node:
def __init__(self):
self.children = {}
self.endOfWord = False
def insertWord(root, word):
'''
Loop through characters in a word and keep adding them at a new node, linking them together
If char already in node, pass
Increment the current to the child with the character
After the characters in word are over, mark current as EOW
'''
global count1
current = root
for char in word:
if char in current.children.keys():
pass
else:
count1 += 1
current.children[char] = Node()
current = current.children[char]
current.endOfWord = True
def allWords(prefix, node, results):
'''
Recursively call the loop
Prefix will be prefix + current character
Node will be position of char's child
results are passed by reference to keep storing result
Eventually, when we reach EOW, the prefix will have all the chars from starting and will be the word that we need. We add this word to the result
'''
global count
if node.endOfWord:
# count+=1
results.append(prefix)
for char in node.children.keys():
count+=1
# print char, node, node.children
allWords(prefix + char, node.children[char], results)
def searchWord(root, word):
'''
Loop through chars of the word in the trie
If char in word is not in trie.children(), return
If char found, keep iterating
After iteration for word is done, we should be at the end of word. If not, then word doesn't exist and we return false.
'''
current = root
search_result = True
for char in word:
if char in current.children.keys():
pass
else:
search_result = False
break
current = current.children[char]
return search_result
def getWordsWithPrefix(prefix, node, prefix_result):
'''
We loop through charcters in the prefix along with trie
If mismatch, return
If no mismatch during iteration, we have reached the end of prefix. Now we need to get words from current to end with the previx that we passed. So call allWords with prefix
'''
global count
current = node
for char in prefix:
if char in current.children.keys():
count += 1
pass
else:
return
current = current.children[char]
allWords(prefix, current, prefix_result)
def getcount(prefix, node, prefix_result):
'''
We loop through charcters in the prefix along with trie
If mismatch, return
If no mismatch during iteration, we have reached the end of prefix. Now we need to get words from current to end with the previx that we passed. So call allWords with prefix
'''
global count
current = node
for char in prefix:
if char in current.children.keys():
count += 1
pass
else:
return
current = current.children[char]
allWords(prefix, current, prefix_result)
def main():
# Input keys (use only 'a' through 'z' and lower case)
start_ = time.time_ns()
keys = ["the", "a", "there", "anaswe", "any",
"by", "their"]
# Trie object
root = Node()
level=0
# Construct trie
for key in keys:
insertWord(root, key)
stop = time.time_ns()
print(stop-start_)
print(count1)
prefix_result = []
start = time.time_ns()
str = input("Enter the Prefix you want")
getWordsWithPrefix(str, root, prefix_result)
print('\nWords starting with', str)
for word in prefix_result:
print(word)
stop = time.time_ns()
print(count)
print(stop-start)
if __name__ == '__main__':
main()
"""root = Node()
#words = ['bed', 'ben']
words = ['bed', 'bedlam', 'bond','bomb', 'bomber', 'bombay']
for word in words:
insertWord(root, word)
results = []
prefix = ''
allWords(prefix, root, results)
# prefix will be added to every word found in the result, so we start with ''
# results is empty, passed as reference so all results are stored in this list
print('All words in trie: {}\n\n'.format(results))
search_word = 'bomb'
search_result = searchWord(root, search_word)
print('Search {} in {}: {}'.format(search_word, words, search_result))
search_word = 'bomber'
search_result = searchWord(root, search_word)
print('Search {} in {}: {}'.format(search_word, words, search_result))
prefix_result = []
prefix = 'b'
getWordsWithPrefix(prefix, root, prefix_result)
print('\n\nWords starting with {}: {}'.format(prefix, prefix_result))""" |
# importing the socket and datagram modules
from socket import socket, AF_INET, SOCK_DGRAM
# creation of socket module
s = socket(AF_INET, SOCK_DGRAM)
# binding it to the local host
s.bind(('127.0.0.1', 8888))
# Keeps the server in listening mode forever
while True:
print('Waiting for the client')
# saves the command and address from which request is received
command_, addr = s.recvfrom(1024)
data='No Such Command'
# decodes the command
command=command_.decode()
# executes if the command is a GET command
if command[:3].upper() == 'GET':
try:
# Executes if a file name is present in the GET command
if command[3:] != '':
print('Client has requested for', command[4:])
# tries to open and read the contents of the file
f = open(command[4:], "r")
data1=[]
print('The file contains:')
data1.append('The file contains:')
# stores the data into list if there are multiple lines
for line in f.readlines():
print(line)
data1.append(line)
print('Sending the contents of',command[4:],'to the requested client')
# converts the data or the list into string in order to send the data to the client as a response.
data=str(data1)
except:
# executes if file name given in the command is not present
if command[3:] !='':
data = 'Error:File not found!!!'
print(data)
else:
data = 'Please provide the file name when using get'
print('No input for text file from the user!!!')
# executes if the client gives a BOUNCE command
elif command[:6].upper() == 'BOUNCE':
if command[7:] != '':
print('Message from the Client is \'',command[7:],'\'')
else:
print('Received Blank message from client')
# sends the client an echo of the text message sent by the client
data = 'echo:' + command[7:]
# Executes if the client gives an EXIT command
elif command[:4].upper() == 'EXIT':
# if no exit code is given
if len(command)==4:
data='Normal exit from server'
print('Client took normal exit from server')
# if an exit code is given by the user
else:
print('Client exited due to',command[5:])
data='Exit due to '+command[5:]
# executes if the user gives any other command other than these three
else:
print('Client requested invalid command')
print('\n')
# Encodes and sends the data to the client which has given the command
s.sendto(data.encode(), addr)
|
"""Module which contains shape area computation functions."""
def square_area(a):
"""Method which returns the area of a square."""
return a*a
def rectangle_area(a, b):
"""Method which returns the area of a rectangle."""
return a*b
def triangle_area(a, b, c):
"""Method which returns the area of a triangle."""
if is_triangle([a, b, c]) is True:
s = (a + b + c) / 2
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
return area
else:
print("The triangle is not valid.")
exit(-1)
def is_triangle(sides):
"""Checks whether the triangle is a valid one."""
smallest, medium, biggest = sorted(sides)
return smallest + medium > biggest and all(s > 0 for s in sides)
|
"""Module which holds the Army class."""
import random
class Army:
"""Class which holds Army methods."""
def __init__(self, name, fighters):
"""Initialises the name and fighter list for the army."""
self.name = name
self.fighters = fighters
def __str__(self):
"""Returns the string representation of the class."""
return str(self.__class__) + ": " + str(self.__dict__)
def fight(self, enemies):
"""Fights armies in turns as long as each one has at least one fighter."""
while True:
attack(self, enemies)
attack(enemies, self)
def focus_target(army):
"""Focuses a random target from the army list."""
try:
position = random.randint(0, len(army) - 1)
target = army[position]
return target
except (IndexError, ValueError):
return None
def attack(army, enemies):
"""Two random targets attack each other till no one is found."""
enemy_target = focus_target(enemies.fighters)
army_target = focus_target(army.fighters)
if enemy_target is None:
print("\n" + army.name + " WINS!")
exit(0)
elif army_target is None:
print("\n" + enemies.name + " WINS!")
exit(0)
else:
army_target.fight(enemy_target)
def print_army(army):
"""Pretty prints the armies."""
print("\n" + army.name)
for soldiers in army.fighters:
print(soldiers)
print("\n")
|
def check_divisible():
"""Stores in a list the elements from 1000 to 2000 which are divisible by 7 but not by 5."""
result = []
for i in range(1000, 2000):
if i % 7 == 0 and i % 5 != 0:
result.append(i)
print("result: {}".format(result))
check_divisible()
|
"""
Module which contains the Car thread.
"""
from threading import Thread
import random
class CarThread(Thread):
"""
Class which handles the baby car race.
"""
def __init__(self, name, target, args):
"""
Constructor of the CarThread class.
:param name: Name of the car
:param target: Method for the thread.
:param args: Arguments of the method.
"""
Thread.__init__(self, target=target, args=args)
self.name = name
self.delay = 0
def run(self):
"""
Method which sets the delay time and starts start_car.
"""
super(CarThread, self).run()
self.delay = random.randint(1, 5)
self.start_car()
def start_car(self):
"""
Just a tiny method to print the car status.
"""
print("{} started after {} seconds".format(self.name, self.delay))
|
def to_fahrenheit():
"""Gets the celsius degrees from the command line, transforms it into fahrenheit and prints."""
celsius = int(input("give the temperature..."))
fahrenheit = (9/5) * celsius + 32
print(fahrenheit)
to_fahrenheit()
|
def is_leap_year():
"""Takes an year given from command line and checks whether it is leap or not."""
year = int(input("give the year..."))
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
print("true")
else:
print("false")
is_leap_year()
|
"""
Module for cone thingy.
"""
from math import pi
class Cone:
"""
Class which handles cone thingy.
"""
def __init__(self, radius, height):
"""
Constructor of the Cylinder class.
:param radius: Radius of the cone.
:param height: Height of the cone.
"""
self.radius = radius
self.height = height
def get_volume(self):
"""
Method which returns the volume of the cone.
:return: Volume of the cone.
"""
return (1 / 3) * pi * (self.radius ** 2) * self.height
|
frase = input('Digite seu nome completo: ')
print(len(frase[0]))
num = input('Digite um número entre 0 e 9999: ')
m = num[0]
c = num[1]
d = num[2]
u = num[3]
print("""Unidade: {}
Dezena: {}
Centena: {}
Milhar: {}""".format(u, d, c, m)) |
pri = int(input('Primeiro termo da PA? '))
raz = int(input('Qual a razão da PA? '))
termo = pri
cont = 1
total = 0
mais = 10
while mais != 0:
total += mais
while cont <= total:
print('{} -> '.format(termo), end='')
termo += raz
cont += 1
print('PAUSA')
mais = int(input('Quantos termos você quer mostrar a mais? '))
print('FIM') |
geral = list()
dados = list()
while True:
dados.append(str(input('Nome: ')))
dados.append(float(input('Nota 1: ')))
dados.append(float(input('Nota 2: ')))
geral.append(dados[:])
dados.clear()
op = str(input('Quer adicionar mais um aluno?[S/N] ')).upper()
if op in 'SN':
if op == 'N':
break
else:
print('Opção inválida!')
op = str(input('Quer adicionar mais um aluno?[S/N] ')).upper()
print('{:^69}'.format('Boletim Geral'))
print('=-='*26)
for pos, element in enumerate(geral):
media = (element[1] + element[2]) / 2
print(f'| Nº {pos} | Nome: {element[0]:<15} | Nota 1: {element[1]:<5} | Nota 2: {element[2]:<5}| Média: {media:<5} |')
print('=-='*26)
while True:
aluno = str(input('Quer ver a o boletim de algúm aluno individualmente?[S/N] ')).upper()
if aluno in 'SN':
if aluno == 'S':
num = int(input('De qual aluno você quer ver o boletim? '))
mediai = (geral[num][1] + geral[num][2]) / 2
print(f'Boletim do aluno de número: {num}')
print(f'| Nº {num} | Nome: {geral[num][0]:<15} | Nota 1: {geral[num][1]:<5} | Nota 2: {geral[num][2]:<5}| Média: {mediai:<5} |')
else:
print('Fim do Programa!')
break
else:
print('[ERROR] Opção inválida!')
aluno = str(input('Quer ver a o boletim dos aulonos individualmente?[S/N] ')).upper() |
jogador = dict()
partidas = list()
jogador['nome'] = str(input('Nome do jogador: '))
tot = int(input(f'Quantas partidas o jogador {jogador["nome"]} jogou? '))
print('=-='*15)
for c in range(tot):
partidas.append(f'>>>>Quantos gols na partida {c}? ')
jogador['gols'] = partidas[:]
jogador['total'] = sum(partidas)
for k, v in jogador.items():
print(f'O campo {k} tem o valor {v}.')
|
maior = 0
media = 0
soma = 0
mulher = 0
for i in range(4):
nome = input('Qual é o seu nome? ')
idade = int(input('Qual é a sua idade? '))
sexo = input('Qual é o seu sexo?(M/F) ')
soma += idade
media = soma / 4
if sexo == 'M':
if idade > maior:
maior = idade
nome_maior = nome
else:
if idade < 20:
mulher += 1
print('A media de idade do grupo é de {:.2f} anos'.format(media))
print('O homem mais velho é o {}'.format(nome_maior))
print('No grupo há {} mulheres com menos de 20 anos'.format(mulher))
|
num = float(input('Digite um número: '))
print('Parte inteira do número: ',math.trunc(num)) |
from random import randrange
jogos = list()
qtdjogos = int(input('Quantos jogos serão? '))
for _ in range(qtdjogos):
jogo = [randrange(1,60),randrange(1,60),randrange(1,60),randrange(1,60),randrange(1,60),randrange(1,60)]
jogos.append(jogo)
print('Seus jogos serão:')
for num, element in enumerate(jogos):
print(f'Jogo {num+1}: {element}') |
# Bug Collector Project
# 20170625
# CTI-110 M4T1 - Bug Collector
# Loraine Armenta
#
# Total amount of days 5
days = 5
# Total number of bugs collected in five days
number_of_bugs = 0
# How many bugs were collected
for todate in range(1, days + 1):
bugs_collected = int (input ('How many bugs were collected on day'\
+ str (todate ) + ':' ))
number_of_bugs = number_of_bugs + bugs_collected
print()
print( ' The total number of bugs collected in all', days, 'days is', \
number_of_bugs )
|
# ft to in'
# 20170704
# CTI-110 M5T2_FeetToInches
# Loraine Armenta
#
INCHES_PER_FOOT = 12
def main ():
feet = int (input ( 'Enter a number of feet: ' ))
print (feet, 'equals' , feet_to_inches (feet), 'inches.')
def feet_to_inches (feet):
return feet * INCHES_PER_FOOT
main ()
|
a = input('enter the name of a doctor or specialization: ')
b = a.lower()
import csv
with open ('dr.csv','r') as csvfile:
reader = csv.DictReader(csvfile)
for i in reader:
if b in i.values():
d = i.get('name')
e = i.get('Eduction')
f = i.get('Experience')
h = i.get('specialist')
g = i.get('fees')
print('name --> '+ 'Dr.'+ d)
print('Eduction --> ' + e)
print('Experience --> ' + f)
print('fees --> ' + g)
print('specialization --> '+ h )
from datetime import datetime as dt
p = dt.now()
s = input('\nenter yes to book an appointment: ')
x = s.lower()
if x == 'yes':
print('\nyour appointment has been confirmed\n')
print('the details of the booking are:')
print('name --> '+ 'Dr.'+ d)
print('Eduction --> ' + e)
print('Experience --> ' + f)
print('fees --> ' + g)
print('specialization --> '+ h)
print('time of booking')
print(p)
else:
print('No Booking Made')
print('\nTHANK YOU') |
from datetime import datetime
print(datetime(1993,9,21).isocalendar()[1]-datetime(1993,9,25).isocalendar()[1])
print(datetime(1993,9,21).isocalendar()[2]-datetime(1993,9,25).isocalendar()[2]+2)
def lc_calc(start='1993-09-21', date):
start = datetime(start)
date = datetime(date)
timediff = datetime.timedelta(date - start)
diffyear = datetime.isocalendar()[0]
diffweeks = datetime.isocalendar()[1]
diffdays = datetime.isocalendar()[2]
print(diffyear)
print(diffweeks)
print(diffdays)
|
# Display window
# - Create main display window
# - moving tiles into their own class
# - create time/date bar?
# - add scroll bars if not full screen
# - get data from file to set up many tiles
import tkinter
from tiles import tile
from tiles import event_tile
# Display Window
class Disp_Dialog:
def __init__(self, parent):
print("init dialog class")
self.parent = parent
self.parent.geometry("800x200")
#self.parent.attributes('-fullscreen', True)
self.set_escapes() # function to set up safe exit commands
self.no_of_tiles = 10 # Number of tiles
# Display tiles:
print("creating tile object")
self.tile = event_tile(self.parent, self.no_of_tiles)
#safety button to exit fullscreen display
def set_escapes(self):
self.b = tkinter.Button(self.parent, text="Button", command=self.b)
self.b.place(width=50, height=20,
x=self.parent.winfo_screenwidth()-50,
y=self.parent.winfo_screenheight()-20)
#Bind keyboard for safe exit:
self.parent.bind("<Control-backslash>", self.get_exit)
return
def b(self):
print("Exiting")
self.parent.destroy()
# Exit the program
def get_exit(self, event):
print("keypress exit")
self.parent.destroy()
root = tkinter.Tk()
main = Disp_Dialog(root)
root.mainloop()
|
import threading
import Queue;
import time;
def test_lol(num1, num2):
while(1):
print(num1+num2)
def sleep_func(sleep_time, name):
print('Hi, I am {}. Going to sleep for {} seconds\n'.format(name, sleep_time));
print(time.localtime());
time.sleep(sleep_time);
print(time.localtime());
print('{} has woken up from sleep \n'.format(name));
if __name__=='__main__':
t=threading.Thread(target=sleep_func, name='thread 1', args=(5, 'thread 1'))
u=threading.Thread(target=sleep_func, name='thread 2', args=(10, 'thread 2'))
t.start();
print('LOL these guys are sleeping');
u.start();
while(1):
print('LOL')
time.sleep(40);
|
# coding:utf-8
# kaggle Jane Street Market Prediction代码
# 《深度学习入门:基于python的理论与实现》
# 第五章 误差反向传播法
import numpy as np
import matplotlib.pyplot as plt
import run
import pandas as pd
from PIL import Image
import random
import pickle
from collections import OrderedDict
# 乘法层的实现
class MulLayer:
def __init__(self):
self.x = None
self.y = None
def forward(self, x, y):
self.x = x
self.y = y
out = x*y
return out
def backward(self, dout):
dx = dout*self.y # 翻转x和y
dy = dout*self.x
return dx, dy
def testMul():
apple = 100
apple_num = 2
tax = 1.1
mul_apple_layer = MulLayer()
mul_tax_layer = MulLayer()
# 前向传播
apple_price = mul_apple_layer.forward(apple, apple_num)
price = mul_tax_layer.forward(apple_price, tax)
print(price)
# 反向传播
dprice = 1
dapple_price, dtax = mul_tax_layer.backward(dprice)
dapple, dapple_num = mul_apple_layer.backward(dapple_price)
print(dapple_price, dtax, dapple, dapple_num)
# 加法层实现
class AddLayer:
def __init__(self):
pass
def forward(self, x, y):
out = x+y
return out
def backward(self, dout):
dx = dout*1
dy = dout*1
return dx, dy
def testAdd():
apple = 100
apple_num = 2
orange = 150
orange_num = 3
tax = 1.1
mul_apple_layer = MulLayer()
mul_orange_layer = MulLayer()
add_apple_orange_layer = AddLayer()
mul_tax_layer = MulLayer()
# 前向传播
apple_price = mul_apple_layer.forward(apple, apple_num)
orange_price = mul_orange_layer.forward(orange, orange_num)
all_price = add_apple_orange_layer.forward(apple_price, orange_price)
price = mul_tax_layer.forward(all_price, tax)
print(price)
# 反向传播
dprice = 1
dall_price, dtax = mul_tax_layer.backward(dprice)
dapple_price, dorange_price = add_apple_orange_layer.backward(dall_price)
dorange, dorange_num = mul_orange_layer.backward(dorange_price)
dapple, dapple_num = mul_apple_layer.backward(dapple_price)
print(dapple_num, dapple, dorange, dorange_num, dtax)
# ReLU激活函数层
class ReLU:
def __init__(self):
self.mask = None
def forward(self, x):
self.mask = (x <= 0)
out = x.copy()
out[self.mask] = 0
return out
def backward(self, dout):
dout[self.mask] = 0
dx = dout
return dx
def testReLU():
x = np.array([[1.0, -0.5], [-2.0, 3.0]])
print(x)
mask = (x<0)
print(mask)
relu = ReLU()
out = relu.forward(x)
dout = relu.backward(out)
print(out, dout)
# Sigmoid激活函数层
class Sigmoid:
def __init__(self):
self.out = None
def forward(self, x):
out = 1/(1+np.exp(-x))
self.out = out
return out
def backward(self, dout):
dx = dout*(1.0-self.out)*self.out
return dx
def testSigmoid():
x = np.array([[1.0, -0.5], [-2.0, 3.0]])
print(x)
sigmoid = Sigmoid()
out = sigmoid.forward(x)
dout = sigmoid.backward(out)
print(out, dout)
def testSum():
print("求和")
x = np.array([[1, 2], [3, 4]])
s1 = np.sum(x, axis = 0)
s2 = np.sum(x, axis = 1)
s3 = np.sum(x)
print(x, s1, s2, s3)
# Affine层
class Affine:
def __init__(self, W, b):
self.W = W
self.b = b
self.x = None
self.dW = None
self.db = None
def forward(self, x):
self.x = x
out = np.dot(x, self.W) + self.b
return out
def backward(self, dout):
dx = np.dot(dout, self.W.T)
self.dW = np.dot(self.x.T, dout)
self.db = np.sum(dout, axis = 0)
return dx
def softmax(x):
if x.ndim == 2:
x = x.T
x = x - np.max(x, axis=0)
y = np.exp(x) / np.sum(np.exp(x), axis=0)
return y.T
x = x - np.max(x) # 溢出对策
return np.exp(x) / np.sum(np.exp(x))
def cross_entropy_error(y, t):
if y.ndim == 1:
t = t.reshape(1, t.size)
y = y.reshape(1, y.size)
# 监督数据是one-hot-vector的情况下,转换为正确解标签的索引
if t.size == y.size:
t = t.argmax(axis=1)
batch_size = y.shape[0]
return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-7)) / batch_size
# softmax和loss函数结合层
class SoftmaxWithLoss:
def __init__(self):
self.loss = None
self.y = None
self.t = None
def forward(self, x, t):
self.t = t
self.y = softmax(x)
self.loss = cross_entropy_error(self.y, self.t)
return self.loss
def backward(self, dout = 1):
batch_size = self.t.shape[0]
dx = (self.y - self.t)/batch_size
return dx
# 数值微分
def numerical_gradient(f, x):
h = 1e-4 # 0.0001
grad = np.zeros_like(x)
it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
idx = it.multi_index
tmp_val = x[idx]
x[idx] = float(tmp_val) + h
fxh1 = f(x) # f(x+h)
x[idx] = tmp_val - h
fxh2 = f(x) # f(x-h)
grad[idx] = (fxh1 - fxh2) / (2*h)
x[idx] = tmp_val # 还原值
it.iternext()
return grad
# 用上面这些构建神经网络
class TwoLayerNet:
def __init__(self, input_size, hidden_size, output_size, weight_init_std = 0.01):
# 初始化权重
self.params = {}
self.params["W1"] = weight_init_std*np.random.randn(input_size, hidden_size)
self.params["b1"] = np.zeros(hidden_size)
self.params["W2"] = weight_init_std*np.random.randn(hidden_size, output_size)
self.params["b2"] = np.zeros(output_size)
# 生成层
self.layers = OrderedDict()
self.layers["Affine1"] = Affine(self.params["W1"], self.params["b1"])
self.layers["Relu1"] = ReLU()
self.layers["Affine2"] = Affine(self.params["W2"], self.params["b2"])
self.lastLayer = SoftmaxWithLoss()
def predict(self, x):
for layer in self.layers.values():
x = layer.forward(x)
return x
def loss(self, x, t):
y = self.predict(x)
return self.lastLayer.forward(y, t)
def accuracy(self, x, t):
y = self.predict(x)
y = np.argmax(y, axis = 1)
if t.ndim != 1:
t = np.argmax(t, axis = 1)
accuracy = np.sum(y == t) / float(x.shape[0])
return accuracy
def numerical_gradient(self, x, t):
loss_W = lambda W : self.loss(x, t)
grads = {}
grads["W1"] = numerical_gradient(loss_W, self.params["W1"] )
grads["b1"] = numerical_gradient(loss_W, self.params["b1"] )
grads["W2"] = numerical_gradient(loss_W, self.params["W2"] )
grads["b2"] = numerical_gradient(loss_W, self.params["b2"] )
return grads
# 更快的求梯度的方法
def gradient(self, x, t):
# forward
self.loss(x, t)
# backward
dout = 1
dout = self.lastLayer.backward(dout)
layers = list(self.layers.values())
layers.reverse()
for layer in layers:
dout = layer.backward(dout)
grads = {}
grads["W1"] = self.layers["Affine1"].dW
grads["b1"] = self.layers["Affine1"].db
grads["W2"] = self.layers["Affine2"].dW
grads["b2"] = self.layers["Affine2"].db
return grads
# 手写数字识别
# 加载数据
@run.change_dir
def loadData():
training_data_file = open("mnist_train.csv", 'r')
training_data_list = training_data_file.readlines()
training_data_file.close()
testing_data_file = open("mnist_test.csv", 'r')
testing_data_list = testing_data_file.readlines()
testing_data_file.close()
x_train, t_train = [], []
for record in training_data_list:
# 通过','将数分段
all_values = record.split(',')
# 将所有的像素点的值转换为0.01-1.00
inputs = (np.asfarray(all_values[1:]) / 255.0 * 0.99 + 0.01)
# 创建标签输出值
target = int(all_values[0])
x_train.append(inputs)
t_train.append(target)
x_test, t_test = [], []
for record in testing_data_list:
# 通过','将数分段
all_values = record.split(',')
# 将所有的像素点的值转换为0.01-1.00
inputs = (np.asfarray(all_values[1:]) / 255.0 * 0.99 + 0.01)
# 创建标签输出值
target = int(all_values[0])
x_test.append(inputs)
t_test.append(target)
x_train = np.array(x_train)
t_train = np.array(t_train)
x_test = np.array(x_test)
t_test = np.array(t_test)
t_train = one_hot(t_train)
t_test = one_hot(t_test)
return x_train, t_train, x_test, t_test
# one_hot过程
def one_hot(t):
tmp = np.zeros((t.shape[0], 10))
for i in range(t.shape[0]):
tmp[i][t[i]] = 1
t = tmp
return t
# 梯度确认
def gradcheck():
print("梯度确认")
n = 10
x_train, t_train, x_test, t_test = loadData()
network = TwoLayerNet(input_size = 784, hidden_size = 50, output_size = 10)
x_batch = x_train[:n]
t_batch = t_train[:n]
grad_numerical = network.numerical_gradient(x_batch, t_batch)
grad_backprop = network.gradient(x_batch, t_batch)
for key in grad_numerical.keys():
diff = np.average(np.abs(grad_backprop[key] - grad_numerical[key]))
print(key + ":" + str(diff))
# 实际解决手写输入识别问题
@run.change_dir
@run.timethis
def minst():
print("实际解题")
x_train, t_train, x_test, t_test = loadData()
network = TwoLayerNet(input_size = 784, hidden_size = 50, output_size = 10)
iters_num = 10000
train_size = x_train.shape[0]
batch_size = 100
learning_rate = 0.1
train_loss_list = []
train_acc_list = []
test_acc_list = []
iter_per_epoch = max(train_size/batch_size, 1)
for i in range(iters_num):
batch_mask = np.random.choice(train_size, batch_size)
x_batch = x_train[batch_mask]
t_batch = t_train[batch_mask]
# 反向传播求梯度
grad = network.gradient(x_batch, t_batch)
# 更新参数
for key in ["W1", "b1", "W2", "b2"]:
network.params[key] -= learning_rate*grad[key]
loss = network.loss(x_batch, t_batch)
train_loss_list.append(loss)
# 计算每个epoch的识别精度
if i % iter_per_epoch == 0:
train_acc = network.accuracy(x_train, t_train)
test_acc = network.accuracy(x_test, t_test)
train_acc_list.append(train_acc)
test_acc_list.append(test_acc)
print("训练集准确率{},测试集准确率{}".format(train_acc, test_acc))
# 画图
plt.figure()
plt.plot(train_loss_list)
plt.savefig("./output/loss.png")
plt.close()
plt.figure()
plt.plot(train_acc_list)
plt.plot(test_acc_list)
plt.savefig("./output/accuracy.png")
plt.close()
if __name__ == "__main__":
testMul()
testAdd()
testReLU()
testSigmoid()
testSum()
gradcheck()
minst()
|
# coding:utf-8
# kaggle Jane Street Market Prediction代码
# 《深度学习入门:基于python的理论与实现》
# 第四章 神经网络的学习
import numpy as np
import matplotlib.pyplot as plt
import run
import pandas as pd
from PIL import Image
import random
import pickle
# 阶跃函数
def step_function(x):
"""
if x > 0:
return 1
else:
return 0
"""
# 用支持numpy的形式
y = x>0
return y.astype(np.int)
# 画图
@run.change_dir
def draw_step():
x = np.arange(-5.0, 5.0, 0.1)
y = step_function(x)
plt.plot(x, y)
plt.ylim(-0.1, 1.1)
plt.savefig("./output/step_function.png")
plt.close()
# sigmoid函数
def sigmoid(x):
return 1/(1+np.exp(-x))
# 画图
@run.change_dir
def draw_sigmoid():
x = np.arange(-5.0, 5.0, 0.1)
y = sigmoid(x)
plt.plot(x, y)
plt.ylim(-0.1, 1.1)
plt.savefig("./output/sigmoid_function.png")
plt.close()
# ReLU函数
def ReLU(x):
return np.maximum(0, x)
# 画图
@run.change_dir
def draw_ReLU():
x = np.arange(-5.0, 5.0, 0.1)
y = ReLU(x)
plt.plot(x, y)
plt.savefig("./output/ReLU_function.png")
plt.close()
# 恒等函数
def identity_function(x):
return x
# softmax函数
def softmax(a):
c = np.max(a)
exp_a = np.exp(a-c) #防止数值太大,溢出
sum_exp_a = np.sum(exp_a)
y = exp_a/sum_exp_a
return y
# 手写数字识别
# 加载数据
@run.change_dir
def loadData():
training_data_file = open("mnist_train.csv", 'r')
training_data_list = training_data_file.readlines()
training_data_file.close()
testing_data_file = open("mnist_test.csv", 'r')
testing_data_list = testing_data_file.readlines()
testing_data_file.close()
x_train, t_train = [], []
for record in training_data_list:
# 通过','将数分段
all_values = record.split(',')
# 将所有的像素点的值转换为0.01-1.00
inputs = (np.asfarray(all_values[1:]) / 255.0 * 0.99 + 0.01)
# 创建标签输出值
target = int(all_values[0])
x_train.append(inputs)
t_train.append(target)
x_test, t_test = [], []
for record in testing_data_list:
# 通过','将数分段
all_values = record.split(',')
# 将所有的像素点的值转换为0.01-1.00
inputs = (np.asfarray(all_values[1:]) / 255.0 * 0.99 + 0.01)
# 创建标签输出值
target = int(all_values[0])
x_test.append(inputs)
t_test.append(target)
x_train = np.array(x_train)
t_train = np.array(t_train)
x_test = np.array(x_test)
t_test = np.array(t_test)
# print(x_train.shape)
# print(t_train.shape)
# print(x_test.shape)
# print(t_test.shape)
return x_train, t_train, x_test, t_test
# 均方误差函数
def mse(y, t):
return 0.5*np.sum((y-t)**2)
# 交叉熵误差
def cee(y, t):
delta = 1e-7
return -np.sum(np.dot(t, np.log(y+delta)))
# mini-batch选取样本
def mini_batch(x_train, t_train, batch_size):
train_size = x_train.shape[0]
assert(train_size >= batch_size)
batch_mask = np.random.choice(train_size, batch_size)
x_batch = x_train[batch_mask]
t_batch = t_train[batch_mask]
return x_batch, t_batch
# mini_batch版交叉熵误差
def mb_cee(y, t, one_hot = False):
delta = 1e-7
if y.ndim == 1:
t = t.reshape(1, t.size)
y = y.reshape(1, y.size)
batch_size = y.shape[0]
if one_hot:
return -np.sum(t*np.log(y+delta))/batch_size
else:
return -np.sum(np.log(y[np.arange(batch_size), t]+delta))/batch_size
# 计算f在x处的导数
def numerical_diff(f, x):
h = 1e-4
return (f(x+h) - f(x-h))/(2*h)
# 定义求导的函数
def function_1(x):
return 0.01*x**2 + 0.1*x
def function_2(x):
return x[0]**2 + x[1]**2
# 测试数值微分
@run.change_dir
def test_diff():
# 画图
x = np.arange(0.0, 20.0, 0.1)
y = function_1(x)
plt.plot(x, y)
plt.savefig("./output/num_diff.png")
plt.close()
print(numerical_diff(function_1, 5))
print(numerical_diff(function_1, 10))
# (3, 4)时对x0的偏导函数
def function_tmp1(x0):
return x0**2+4.0**2
# (3, 4)时对x1的偏导函数
def function_tmp2(x1):
return 3.0**2+x1**2
# 测试偏导数
@run.change_dir
def test_pdiff():
# 画图
fig = plt.figure()
ax1 = plt.axes(projection='3d')
xx = np.arange(-5.0, 5.0, 0.5)
yy = np.arange(-5.0, 5.0, 0.5)
X, Y = np.meshgrid(xx, yy)
Z = X**2 + Y**2
ax1.plot_surface(X, Y, Z)
plt.savefig("./output/num_pdiff.png")
plt.close()
print(numerical_diff(function_tmp1, 3.0))
print(numerical_diff(function_tmp2, 4.0))
"""
# 求数值梯度
def numerical_grad(f, x):
h = 1e-4
grad = np.zeros_like(x)
print(x.shape, x.size)
for idx in range(x.size):
print(idx)
tmp_val = x[idx]
# f(x+h)
x[idx] = tmp_val + h
fx1 = f(x)
# f(x-h)
x[idx] = tmp_val - h
fx2 = f(x)
grad[idx] = (fx1 - fx2)/(2*h)
x[idx] = tmp_val
return grad
"""
def _numerical_gradient_no_batch(f, x):
h = 1e-4 # 0.0001
grad = np.zeros_like(x)
for idx in range(x.size):
tmp_val = x[idx]
x[idx] = float(tmp_val) + h
fxh1 = f(x) # f(x+h)
x[idx] = tmp_val - h
fxh2 = f(x) # f(x-h)
grad[idx] = (fxh1 - fxh2) / (2*h)
x[idx] = tmp_val # 还原值
return grad
def numerical_gradient(f, X):
if X.ndim == 1:
return _numerical_gradient_no_batch(f, X)
else:
grad = np.zeros_like(X)
for idx, x in enumerate(X):
grad[idx] = _numerical_gradient_no_batch(f, x)
return grad
def test_grad():
print(numerical_gradient(function_2, np.array([3.0, 4.0])))
print(numerical_gradient(function_2, np.array([0.0, 2.0])))
print(numerical_gradient(function_2, np.array([3.0, 0.0])))
# 梯度下降法
def gradient_descent(f, init_x, lr = 0.01, step_num = 100):
x = init_x
print("学习率{}".format(lr))
for i in range(step_num):
grad = numerical_gradient(f, x)
x -= lr*grad
return x
# 测试梯度下降法
def test_gd():
print("测试梯度下降")
init_x = np.array([-3.0, 4.0])
print(gradient_descent(function_2, init_x))
init_x = np.array([-3.0, 4.0])
print(gradient_descent(function_2, init_x, lr = 10.0))
init_x = np.array([-3.0, 4.0])
print(gradient_descent(function_2, init_x, lr = 1e-10))
# 定义简单的神经网络
class simpleNet:
def __init__(self):
# 用高斯分布进行初始化
self.W = np.random.randn(2, 3)
def predict(self, x):
return np.dot(x, self.W)
def loss(self, x, t):
z = self.predict(x)
y = softmax(z)
loss = cee(y, t)
return loss
# 测试神经网络
def test_nn():
print("测试神经网络")
net = simpleNet()
print(net.W)
x = np.array([0.6, 0.9])
p = net.predict(x)
print(p)
print(np.argmax(p))
t = np.array([0, 0, 1])
print(net.loss(x, t))
def f(W):
return net.loss(x, t)
dW = numerical_gradient(f, net.W)
print(dW)
def sigmoid_grad(x):
return (1.0 - sigmoid(x)) * sigmoid(x)
# 两层神经网络
class TwoLayerNet:
def __init__(self, input_size, hidden_size, output_size, weight_init_std = 0.01):
# 初始化权重
self.params = {}
self.params["W1"] = weight_init_std*np.random.randn(input_size, hidden_size)
self.params["b1"] = np.zeros(hidden_size)
self.params["W2"] = weight_init_std*np.random.randn(hidden_size, output_size)
self.params["b2"] = np.zeros(output_size)
def predict(self, x):
W1, W2 = self.params["W1"], self.params["W2"]
b1, b2 = self.params["b1"], self.params["b2"]
a1 = np.dot(x, W1) + b1
z1 = sigmoid(a1)
a2 = np.dot(z1, W2) + b2
y = softmax(a2)
return y
def loss(self, x, t):
y = self.predict(x)
return cee(y, t)
def accuracy(self, x, t):
tmp = np.zeros((t.shape[0], 10))+0.01
for i in range(t.shape[0]):
tmp[i][t[i]] = 0.99
t = tmp
y = self.predict(x)
y = np.argmax(y, axis = 1)
t = np.argmax(t, axis = 1)
accuracy = np.sum(y == t) / float(x.shape[0])
return accuracy
def numerical_gradient(self, x, t):
loss_W = lambda W : self.loss(x, t)
grads = {}
grads["W1"] = numerical_gradient(loss_W, self.params["W1"] )
grads["b1"] = numerical_gradient(loss_W, self.params["b1"] )
grads["W2"] = numerical_gradient(loss_W, self.params["W2"] )
grads["b2"] = numerical_gradient(loss_W, self.params["b2"] )
return grads
# 更快的求梯度的方法
def gradient(self, x, t):
W1, W2 = self.params['W1'], self.params['W2']
b1, b2 = self.params['b1'], self.params['b2']
grads = {}
batch_num = x.shape[0]
# forward
a1 = np.dot(x, W1) + b1
z1 = sigmoid(a1)
a2 = np.dot(z1, W2) + b2
y = softmax(a2)
# backward
# print(type(y), type(t))
# print(y.shape, t.shape)
# print(y[0], t[0])
tmp = np.zeros((t.shape[0], 10))+0.01
for i in range(t.shape[0]):
tmp[i][t[i]] = 0.99
# print(tmp.shape)
dy = (y - tmp) / batch_num
grads['W2'] = np.dot(z1.T, dy)
grads['b2'] = np.sum(dy, axis=0)
da1 = np.dot(dy, W2.T)
dz1 = sigmoid_grad(a1) * da1
grads['W1'] = np.dot(x.T, dz1)
grads['b1'] = np.sum(dz1, axis=0)
return grads
# 测试两层神经网络
@run.change_dir
@run.timethis
def test_2_nn():
print("测试两层神经网络")
# net = TwoLayerNet(input_size = 784, hidden_size = 100, output_size = 10)
# print(net.params["W1"].shape)
# print(net.params["b1"].shape)
# print(net.params["W2"].shape)
# print(net.params["b2"].shape)
# x = np.random.rand(100, 784)
# y = net.predict(x)
# # print(y)
# t = np.random.rand(100, 10)
# grads = net.numerical_gradient(x, t)
# print(grads["W1"].shape)
# print(grads["b1"].shape)
# print(grads["W2"].shape)
# print(grads["b2"].shape)
# 加载数据
x_train, t_train, x_test, t_test = loadData()
# 训练
train_loss_list = []
train_acc_list = []
test_acc_list = []
# 超参数
iters_num = 10000
train_size = x_train.shape[0]
batch_size = 100
learning_rate = 0.1
# 平均每个epoch的重复次数
iter_per_epoch = max(train_size/batch_size, 1)
network = TwoLayerNet(input_size = 784, hidden_size = 100, output_size = 10)
for i in range(iters_num):
# 获取mini_batch
batch_mask = np.random.choice(train_size, batch_size)
x_batch = x_train[batch_mask]
t_batch = t_train[batch_mask]
# 计算梯度
#grad = network.numerical_gradient(x_batch, t_batch)
grad = network.gradient(x_batch, t_batch)
# 更新参数
for key in ["W1", "b1", "W2", "b2"]:
network.params[key] -= learning_rate*grad[key]
# 记录学习过程
loss = network.loss(x_batch, t_batch)
train_loss_list.append(loss)
# print(i, loss)
# 计算每个epoch的识别精度
if i % iter_per_epoch == 0:
train_acc = network.accuracy(x_train, t_train)
test_acc = network.accuracy(x_test, t_test)
train_acc_list.append(train_acc)
test_acc_list.append(test_acc)
print("训练集准确率{},测试集准确率{}".format(train_acc, test_acc))
# 画图
plt.figure()
plt.plot(train_loss_list)
plt.savefig("./output/loss.png")
plt.close()
plt.figure()
plt.plot(train_acc_list)
plt.plot(test_acc_list)
plt.savefig("./output/accuracy.png")
plt.close()
if __name__ == "__main__":
# 测试mse
t = np.zeros(10)
t[2] = 1
y = np.array([0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0])
print(t, y)
print(mse(y, t))
print(cee(y, t))
# 测试mini_batch
x_train, t_train, x_test, t_test = loadData()
x_batch, t_batch = mini_batch(x_train, t_train, 10)
print(x_batch)
print(t_batch)
# 数值微分
test_diff()
test_pdiff()
test_grad()
test_gd()
# 测试神经网络
test_nn()
# 测试两层神经网络
test_2_nn()
|
from .keywords import *
from decimal import *
# imported functions and constants
functions = ("d", "root", "factorial", "log10", "log2", "sin", "cos", "tan", "rad", "deg")
constants = ("pi", "e")
# global variables for evaluation purposes
variables = {}
getcontext().prec = 6
def to_expr(_string):
"""
return type: string
This function is used to make any string,
as eval()-friendly as possible.
"""
string = ''
for key in _string:
if key.isupper():
key = key.lower()
string = string + key
# making the string more operation-friendly.
string = (
string
.replace(" ", "", -1)
.replace("++", "+", -1)
.replace("--", "-", -1)
)
# necessary variables.
temp_string = ""
parantheses = []
operations = [0]
i = 0
# necessary changes if user is not python-friendly.
for index, s in enumerate(string):
if (index - 1) > -1:
previous = string[index - 1]
condition = (previous != "*"
and previous != "-"
and previous != "+"
and previous != "/"
and previous != "(")
if s == "(" and condition:
temp_string += "*" + s
elif s.isalpha() and condition and not previous.isalpha() and previous != "(":
temp_string += "*" + s
else:
temp_string += s
else:
temp_string += s
string = temp_string
temp_string = ""
for f in functions:
target = string.find(f)
if target != -1:
string = string.replace(f+"*", f, -1)
###########################################################################################
# loop through string and convert it to temp_string.
for index, s in enumerate(string):
# keeping index up to date with additional symbols.
index += i
# when the current position is "!".
if s == '!':
# when the previous character was ")".
if temp_string[index - 1] == ")" and parantheses:
temp_string = (temp_string[:parantheses[-1]]
+ "!"
+ temp_string[parantheses[-1]:]
+ ")")
i += 1 # added ")"
# when there were no prior operations.
elif not operations[-1] and string.find("(") == -1: ### PROBLEM WITH CORRECT FACTORIAL ORDER FOR FIRST CHARACTERS AFTER THE "(".
temp_string = ("!"
+ temp_string
+ ")")
i += 1 # added ")"
### PROBLEM WITH CORRECT FACTORIAL ORDER FOR FIRST CHARACTERS AFTER THE "(".
# when there was nothing before it then ignore it.
elif not temp_string or operations[-1] == index-1:
i -= 1 # removed "!"
temp_string = temp_string[:operations[-1]]
i -= 1
# if none of the above.
else:
temp_string = (temp_string[:operations[-1] + 1]
+ "!"
+ temp_string[operations[-1] + 1:]
+ ")")
i += 1 # added ")"
else: # else
# add s to temp_string
temp_string += s
# operation append conditions
condition = (
s == '+'\
or s == '-'\
or s == '*'\
or s == '/'\
or s == '%'\
or s == '^'\
)
# when s is "(" then append the index to the parantheses list.
if s == "(":
parantheses.append(index)
# when s is ")" and next element is not "!" then remove it from the list.
elif s == ")":
try:
if string[index - i + 1] != "!":
parantheses.pop()
except:
parantheses.pop()
# when s is not a diggit or a special character.
elif condition:
operations.append(index)
# the end of iteration.
###########################################################################################
# necessary replacements.
temp_string = (
temp_string
.replace("!", "factorial(", -1)
.replace("^", "**", -1)
.replace("sqrt", "root", -1)
)
# returning converted string.
return temp_string
def evaluate(string):
# make the expression evaluation-friendly.
string = to_expr(string)
# trying to evaluate the expression.
try:
return (Decimal(round(eval(string), 6)), string)
except NameError as e:
return (None, "Invalid Function")
except ZeroDivisionError:
return (None, "Division by zero is not allowed.")
except:
return (None, "Invalid Syntax") |
import pandas as pd
def getURLs():
'''
Function to create a list of urls for the flightsfrom.com site for each airport.
Returns: url_list -- list of urls in the form of 'flightsfrom.com/<iata code>/destinations'
'''
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
url = url_start + iata + url_end
url_list.append(url)
return url_list
## -- Seperated into smaller sections to be increase speed --
def getAlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'A':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getBlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'B':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getClist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'C':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getDlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'D':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getElist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'E':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getFlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'F':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getGlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'G':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getHlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'H':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getIlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'I':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getJlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'J':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getKlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'K':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getLlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'L':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getMlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'M':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getNlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'N':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getOlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'O':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getPlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'P':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getQlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'Q':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getRlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'R':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getSlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'S':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getTlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'T':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getUlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'U':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getVlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'V':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getWlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'W':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getXlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'X':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getYlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'Y':
url = url_start + iata + url_end
url_list.append(url)
return url_list
def getZlist():
df = pd.read_csv('airport_data.csv')
iata_list = list(df['Unnamed: 0'])
url_start = 'https://www.flightsfrom.com/'
url_end = '/destinations'
url_list = []
for iata in iata_list:
if iata[0] == 'Z':
url = url_start + iata + url_end
url_list.append(url)
return url_list
|
"""
__title__ = ''
__author__ = 'Thompson'
__mtime__ = '2019/1/14'
# code is far away from bugs with the god animal protecting
I love animals. They taste delicious.
┏┓ ┏┓
┏┛┻━━━┛┻┓
┃ ☃ ┃
┃ ┳┛ ┗┳ ┃
┃ ┻ ┃
┗━┓ ┏━┛
┃ ┗━━━┓
┃ 神兽保佑 ┣┓
┃ 永无BUG! ┏┛
┗┓┓┏━┳┓┏┛
┃┫┫ ┃┫┫
┗┻┛ ┗┻┛
"""
from selenium import webdriver
import time
url='https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&suggest=2.def.0.V16&wq=%E6%89%8B%E6%9C%BA&pvid=8d5f606e5f7348c1bd8edb0480ba6ff6'
driver = webdriver.Chrome()
driver.get(url)
# 模拟下滑到底部的操作
for i in range(5):
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
time.sleep(1)
#goods_info = driver.find_elements_by_css_selector('.gl-item')
#goods_info = driver.find_elements_by_xpath('//li[@class="gl-item"]')
goods_info = driver.find_elements_by_class_name('gl-item')
print(len(goods_info))
for info in goods_info:
title = info.find_element_by_css_selector(".p-name.p-name-type-2 a").text.strip()
print('title:',title)
price = info.find_element_by_css_selector('.p-price').text.strip()
print('price:',price)
time.sleep(2)
driver.close() |
import unittest
def letterCasePermutation(S):
"""
:type S: str
:rtype: List[str]
"""
out = []
m = len([e for e in S if e.isalpha()])
for i in range(2 ** m):
new_str = ''
j = 0
for e in S:
if e.isalpha():
if 2 ** j & i:
new_str += e.upper()
else:
new_str += e.lower()
j += 1
else:
new_str += e
out.append(new_str)
return out
class test(unittest.TestCase):
def test1(self):
self.assertEqual(letterCasePermutation("a23"), ["a23", "A23"])
def test2(self):
self.assertEqual(letterCasePermutation("123"), ["123"])
def test3(self):
self.assertEqual(letterCasePermutation("a2c"), ["a2c", "A2c", "a2C", "A2C"])
def test4(self):
self.assertEqual(letterCasePermutation("mQe"), ["mqe","mqE","mQe","mQE","Mqe","MqE","MQe","MQE"])
if __name__ == '__main__':
unittest.main()
|
import unittest
def findTheDifference(s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
def letter_counts(string):
d = {}
for e in string:
try:
d[e] += 1
except:
d[e] = 1
return d
s_counts = letter_counts(s)
t_counts = letter_counts(t)
for t_key in t_counts.keys():
if t_key not in s_counts or t_counts[t_key] != s_counts[t_key]:
return t_key
return ""
class test(unittest.TestCase):
def test1(self):
self.assertEqual(findTheDifference("abcde", "abcdef"), "f")
def test2(self):
self.assertEqual(findTheDifference("a", "aa"), "a")
if __name__ == '__main__':
unittest.main()
|
from turtle import Turtle
import random
class Food(Turtle):
def __init__(self):
super().__init__()
self.color("red")
self.shape("circle")
self.shapesize(stretch_wid=0.5, stretch_len=0.5)
self.penup()
self.speed("fastest")
self.new_position()
def new_position(self):
self.randomx = random.randint(-280, 280)
self.randomy = random.randint(-280, 280)
self.goto(self.randomx, self.randomy)
|
#!/usr/bin/python
primes = [int(prime) for prime in open("primes").readlines()]
primedict = dict([(int(prime), True) for prime in primes])
nprimes = len(primes)
maxprime = 0
for i in range(nprimes):
sum = 0
nums = []
for j in range(i, nprimes):
sum += primes[j]
nums.append(primes[j])
if sum in primedict:
if sum > maxprime:
maxprime = sum
print nums
print maxprime
print maxprime
|
#!/usr/bin/python
def factorial(n):
if n <= 1:
return n
else:
return n * factorial(n - 1)
def nth_permutation(init, n):
nelts = len(init)
if nelts == 1:
return init
div = 0
nperms = factorial(nelts - 1)
rem = n
if nperms < n:
div = n / nperms
rem = n - div * nperms
if rem == 0:
div -= 1
rem -= nperms
print n, init, nelts, init[div]
return init[div] + nth_permutation(init[:div] + init[div+1:], rem)
target = 1000000
initial = "0123456789"
print nth_permutation(initial, target)
|
#!/usr/bin/python
n = 1
sum = 0
while n < 1000:
if n % 3 == 0:
sum += n
elif n % 5 == 0:
sum += n
n+=1
print sum
|
from findBestSequence import FindBestSequence
import random
import sys
sys.path.append("/Users/juliuside/Desktop/BWINF_Runde2/Aufgabe2")
import HelperMethods as hm
class Breeding:
def __init__(self, a, b, num_of_seq):
"""
a has the better fitness
"""
self.a = a
self.b = b
self.num_of_seq = num_of_seq
def child(self):
best_a = self.findBestNseqs(list(self.a), self.num_of_seq)
new = self.bred(self.a, self.b, best_a)
return new
def bred(self, a, b, seqs):
"""
a has the better sequence (seq)
"""
indexe = [a.index(s) for s in seqs]
remaining = self.removeSequences(list(a), seqs)
new = self.bestRemaining(remaining, 10)
for i, index in enumerate(indexe):
new.insert(index, seqs[i])
return new
def bestRemaining(self, remaining, times):
min = [None, None]
for _ in range(times):
random.shuffle(remaining)
new = FindBestSequence(remaining).finalSequence
v = hm.fitness(new)
if min[0] == None or v <= min[0]:
min[0] = v
min[1] = new
return min[1]
def removeSequences(self, a, seqs):
"""
- finds the remaining triangles so new sequences can be formed
- several sequences can be deleted
"""
all = [s for seq in a for s in seq]
for seq in seqs:
for s in seq:
all.remove(s)
return all
def findBestNseqs(self, a, n):
"""
input: - a: (list of named tuple) triangles
- n: (int) number of desired sequences to stay in the next individual
"""
seqs = []
for _ in range(n):
seq = self.findBestSeq(a)
seqs.append(seq)
a.remove(seq)
return seqs
def findBestSeq(self, a):
min = None
index = 0
for i, seq in enumerate(a):
v = self.sequenceFitness(seq)
if min == None or v <= min:
min = v
index = i
return a[index]
def sequenceFitness(self, seq):
if seq == []:
return 0
l = [f[1] for f in seq]
lf = 0
lf = self.__lengths_fitness__(l) * 10
lf += seq[0][2][1]
lf += seq[len(seq) - 1][2][0]
return lf ** 5
def __lengths_fitness__(self, lengths):
""" This function to determine how well the lengths are distributed in order to be able to calculate the fitness
of all the lengths.
In the ideal case the slopes between the lengths on the left side equal the ones on the right side
with the largest length in the middle. (Gaussian Distribution)
Then it returns the difference between the sums of the left and right side.
"""
peak = int(len(lengths) / 2)
left = []
right = []
for i, l in enumerate(lengths):
if i < peak:
left.append(l)
if i > peak:
right.append(l)
left_slopes = self.__calculate_slopes__(left)
right_slopes = self.__calculate_slopes__(right)
left = abs(sum(left_slopes))
right = sum(right_slopes)
return (left - right)
def __calculate_slopes__(self, lengths):
"""This function calculates all the slopes between the largest lengths of the triangles of a sequence.
The idea behind this is that if a sequence has triangles with varying lengths it will take less space.
input: lengths = a list of lengths as integers
"""
for i in range(len(lengths) - 1):
rate = lengths[i + 1] / lengths[i]
if rate < 1:
#goes down
yield -(lengths[i] / lengths[i + 1])
else:
yield rate |
from collections import namedtuple
class Knapsack:
def __init__(self, triangles, capacity):
self.triangles = list(triangles)
self.w = [t[0] for t in triangles]
self.v = [t[1] for t in triangles]
self.capacity = capacity
def main(self):
w = self.w
v = self.v
maxCost = self.capacity
answer = self.zeroOneKnapsack(v,w,maxCost)
result = []
for i in range(len(answer[1])):
if (answer[1][i] != 0):
result.append(self.triangles[i])
return result
def zeros(self, rows, cols):
row = []
data = []
for i in range(cols):
row.append(0)
for i in range(rows):
data.append(row[:])
return data
def getItemsUsed(self, w,c):
# item count
i = len(c)-1
# weight
currentW = len(c[0])-1
# set everything to not marked
marked = []
for i in range(i+1):
marked.append(0)
while (i >= 0 and currentW >=0):
# if this weight is different than
# the same weight for the last item
# then we used this item to get this profit
#
# if the number is the same we could not add
# this item because it was too heavy
if (i==0 and c[i][currentW] >0 )or c[i][currentW] != c[i-1][currentW]:
marked[i] =1
currentW = currentW-w[i]
i = i-1
return marked
# v = list of item values or profit
# w = list of item weight or cost
# W = max weight or max cost for the knapsack
def zeroOneKnapsack(self, v, w, W):
# c is the cost matrix
c = []
n = len(v)
# set inital values to zero
c = self.zeros(n,W+1)
#the rows of the matrix are weights
#and the columns are items
#cell c[i,j] is the optimal profit
#for i items of cost j
#for every item
for i in range(0,n):
#for ever possible weight
for j in range(0,W+1):
#if this weight can be added to this cell
#then add it if it is better than what we aready have
if (w[i] > j):
# this item is to large or heavy to add
# so we just keep what we aready have
c[i][j] = c[i-1][j]
else:
# we can add this item if it gives us more value
# than skipping it
# c[i-1][j-w[i]] is the max profit for the remaining
# weight after we add this item.
# if we add the profit of this item to the max profit
# of the remaining weight and it is more than
# adding nothing , then it't the new max profit
# if not just add nothing.
c[i][j] = max(c[i-1][j],v[i] + c[i-1][j-w[i]])
return [c[n-1][W], self.getItemsUsed(w,c)]
|
import numpy as np
from collections import namedtuple
Triangle = namedtuple("Triangle", "smallest_angle, largest_edge, edges")
class PolygonesToAngle:
def __init__(self, polygones):
self.polygones = polygones
self.main()
def main(self):
"""
output:
the output is a Triangle tuple
!!!! first edge: left side, second edge: right side
"""
triangles = []
for polygon in self.polygones:
edges = self.coordinatesToEdges(polygon)
smallest_angle = min(self.calculateAngles(edges))
largest_edge = max(edges)
#remove the smallest edge
#the smallest edge is the edge of the smallest angle, therefore, it wont be required to reassemble the triangles
edges.remove(min(edges))
triangles.append(Triangle(int(smallest_angle), int(largest_edge), edges))
self.triangles = triangles
def coordinatesToEdges(self, nodes):
if len(nodes) != 3:
raise ValueError("A triangle must have exactly three edges")
edges = []
for i in range(len(nodes)):
#(y2 - y1)^2 + (x2 - x1)^2 = edge
length = lambda a: nodes[(i + 1) % len(nodes)][a] - nodes[i][a]
edges.append(int(np.sqrt(np.power(length(0), 2) + np.power(length(1), 2))))
return edges
def calculateAngles(self, edges):
#this function calculates the inner angles of the Triangle
#by using the law of cosine
#a^2 = b^2 + c^2 - 2ab * cos(alpha)
# -> alpha = acos()
angles = []
for i in range(len(edges)):
dividend = - edges[i]**2 + edges[(i + 1) % len(edges)]**2 + edges[(i - 1) % len(edges)]**2
divisor = 2 * edges[(i + 1) % len(edges)] * edges[(i - 1) % len(edges)]
#print(edges[i], "Dividend", dividend, "Divisor", divisor)
angle = np.rad2deg(np.arccos(dividend / divisor))
angles.append(round(angle))
return angles
|
class FindBestSequence:
def __init__(self, triangles):
"""
input: - triangles = list of [smallest_angle, lengths]
"""
self.vertex = []
self.triangles = list(triangles)
self.len = len(triangles)
@property
def finalSequence(self):
LIMIT = 180
self.findVertices([], self.triangles, LIMIT)
result = self.result
return result
def findVertices(self, vertices, numbers, limit=180):
"""
finds all sequences
vetices = points where the road and the triangles meet
"""
self.findSequence(numbers, limit)
vertices.append(self.vertex)
for v in self.vertex:
numbers.remove(v)
if numbers == []:
self.result = vertices
else:
self.findVertices(vertices, numbers, limit)
def findSequence(self, numbers, limit):
"""
This function finds a sequence (list of numbers that add up to a specific limit).
In case this is not excatly possible the limit is graduallly decreased.
input: - numbers: list of
- limit: int
"""
try:
next(self.subset_sum(numbers, limit))
except StopIteration:
self.findSequence(numbers, (limit - 1))
else:
self.vertex = next(self.subset_sum(numbers, limit))
def subset_sum(self, numbers, target, partial=[], partial_sum=0):
"""
This recursive function adds elements of a list of numbers up to fit a specified limit (target)
"""
if partial_sum == target:
yield partial
if partial_sum >= target:
return
for i, n in enumerate(numbers):
remaining = numbers[i + 1:]
yield from self.subset_sum(remaining, target, partial + [n], partial_sum + n[0])
|
text = input("Enter your comment\n")
if("make a lot of money"in text):
spam = True
elif("buy this"in text):
spam = True
elif("subscribe this"in text):
spam = True
if("click this"in text):
spam = True
else:
spam = False
if(spam):
print("This comment is a spam")
else:
print("This comment is not a spam") |
a = input("Enter the number :")
a = int(a)
b = a*a
print("The square of the number is ", b) |
__author__ = 'Liam'
from random import randrange
from room import *
class Player:
"""The Player object, with associated variables and methods. This is you!
"""
def __init__(self, location):
"""When initialising the character, we'll later give the player the
choice of a name and spirit animal type, which will affect the chance
of certain events/room types/items. For now, the inventory and location
are all that actually matter.
self.name = input('Hey kid, it\'s your Spirit Animal. What\'s your '
'name?\n>')
self.spirit = input('{} eh? Cool, I guess. So, currently I don\'t have'
' any shape or form. What should I be?\n>'
.format(self.name))"""
self.name = 'Billy Boy'
self.spirit = 'Boar'
self.inventory = []
self.location = location
self.actions = {'1': self.search, '2': self.grab, '3': self.gurgle}
def forward(self):
pass
def backward(self):
pass
def left(self):
pass
def right(self):
pass
def grab(self):
"""Grabs a random item from the room, if any exist. Hey, you're a baby,
you're lucky to be able to grab anything.
"""
if len(self.location.contents) == 0:
print('Hate to break it to you, but there\'s nothing to grab.')
elif random() >= .75:
item = self.location.contents[
randrange(len(self.location.contents))]
self.inventory.append(item)
self.location.remove(item)
print('Nice one, you actually managed to grab the {}! '
'I\'m not even angry, I\'m impressed.'.format(item))
else:
print('Well, at least you flailed in an impressive fashion.')
def gurgle(self, enemy):
print('Look at that, you can laugh. The {} noticed, too.'
.format(self.name, enemy.species))
def search(self):
print('\nYou found the following items. Neat.\n{}'
.format(', '.join(self.location.contents)))
def main():
"""The main logic loop for the game, and it's pretty simple. Loop and a
half for the win. Initiates the player in a Living Room. Needs tidying.
"""
player = Player(LivingRoom())
escaping = True
print('Alright kid, it\'s you and me on a grand adventure. We\'re '
'currently in the {}, and I can see {} possible exits. You can '
'search the room or try exploring, if you like.'
.format(player.location.name, player.location.exits))
while escaping:
# need to replace hard list with extract from player.actions
action = input('\nWhat now?\n\n1. Search\t2. Grab\t3. Gurgle\n>')
if action in player.actions.keys():
player.actions[action]()
main()
# print(c.contents)
# a.gurgle(b) |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 6 19:41:44 2020
@author: baotr
"""
class Graph(object):
def __init__(self, graph_dict=None):
if graph_dict == None:
graph_dict={}
self.graph_dict=graph_dict
def neighbors(self, node):
return self.graph_dict[node]
def add_vertex(self, vertex):
if vertex not in self.graph_dict.keys():
self.graph_dict[vertex]=[]
def vertices(self):
return list(self.graph_dict.keys())
def add_edge(self, edge):
vert1, vert2 = edge[0], edge[1]
if vert1 in self.graph_dict.keys():
self.graph_dict[vert1].append(vert2)
else:
self.graph_dict[vert1]=[vert2]
## All paths between two nodes
def find_path(self, start_vertex, end_vertex, path=None, paths=None):
""" find a path from start_vertex to end_vertex in graph """
if path == None:
path = []
if paths==None:
paths=[]
self.paths=paths
if start_vertex not in self.graph_dict.keys():
return None
path = path + [start_vertex]
if start_vertex == end_vertex:
return path
if start_vertex not in self.graph_dict.keys():
return None
for vertex in self.graph_dict[start_vertex]:
if vertex not in path:
new_path = self.find_path(vertex, end_vertex, path, paths)
if new_path and isinstance(new_path[0], str):
self.paths.append(new_path)
return self.paths
graph_dict = { "a" : ["b", "c"],
"b" : ["a"],
"c" : ["b", "a", "e", "d"],
"d" : ["b", "c","e"],
"e" : ["d", "b"],
"f" : [] }
graph = Graph(graph_dict)
print(graph.find_path("a", "d")) |
"""
使用列表推导式写下面这个算法题
给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。
• 示例 1:
输入:[-4,-1,0,3,10]
输出:[0,1,9,16,100]
• 示例 2:
输入:[-7,-3,2,3,11]
输出:[4,9,9,49,121]
• 提示:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A 已按非递减顺序排序。
"""
# 列表推导式,sorted()表示对列表推导出来的结果进行排序
list_a = [-7, -3, 2, 3, 11, -4, -1, 0, 3, 10, -10000, 10000]
print(sorted([i ** 2 for i in list_a]))
# 用函数改造,列表推导式
# def list_methon(list):
# print(sorted([i ** 2 for i in list]))
# # 调用函数并传参
# list_a = [-7, -3, 2, 3, 11, -4, -1, 0, 3, 10, -10000, 10000]
# list_methon(list_a)
# 先用for循环实现需求
# 定义一个需要操作的列表
# list_a = [-4, -1, 0, 3, 10]
# list_a = [-7, -3, 2, 3, 11]
# list_a = [-4]
# list_a = [-7, -3, 2, 3, 11, -4, -1, 0, 3, 10, -10000, 10000]
# 定义一个空列表,用于存放每个数字的平方组成的新数组
# list_b = []
# # 遍历需操作的整个列表list_a
# for i in list_a:
# # print(i)
# # 将列表中的每个数字求平方,并存入新列表list_b中
# list_b.append(i ** 2)
# # # 方法一:对list_b进行升序排序,对新列表进行冒泡排序
# # # 第m次排序
# # for m in range(len(list_b) - 1):
# # # 每次排序,比较的次数为n次
# # for n in range(len(list_b) - 1 - m):
# # # 比较相邻两个数的大小
# # if list_b[n] > list_b[n + 1]:
# #
# # # 如果前一个数大于后一个数,就交换两个数的位置
# # list_b[n], list_b[n + 1] = list_b[n + 1], list_b[n]
#
# # 方法二:对list_b进行升序排序
# list_b.sort()
# # 打印新数组
# print(list_b)
|
from pilas import Stack
def suma_lista_rec(lista):
if len(lista)==1:
return lista[0]
else:
return lista.pop()+suma_lista_rec(lista)
def cuenta_regresiva(n):
if n ==0:
return n
else :
print(n)
print("----")
return cuenta_regresiva(n-1)
def eliminar_medio(pilas):
o=Stack()
a=pilas.length()/2
d=round(a)
for x in range(1,(d)):
u=pilas.pop()
o.push(u)
t=o.length()
f=pilas.pop()
for x in range(1,(t+1)):
l=o.pop()
pilas.push(l)
return pilas.to_string()
def main():
datos=[4,2,3,5]
res=print(suma_lista_rec(datos))
print(res)
def main2():
nu=6
print(cuenta_regresiva(nu),"BOOM!! no te ama ")#cuanta regresiva
def main3():
k=Stack()
k.push(47)
k.push(42)
k.push(49)
k.push(44)
k.push(33)
k.push(21)
k.push(90)
k.push(69)
k.push(59)
k.push(74)
k.push(26)
k.push(35)
print("*******************")
print(k.to_string())
print("*******************")
eliminar_medio(k)#saca el valor de la mitad de la pila pero enpesando a contar del tope
main3()
|
# https://leetcode.com/contest/weekly-contest-183/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/
# If the current number is even, you have to divide it by 2.
# If the current number is odd, you have to add 1 to it.
s = "1101"
# to convert into decimal
dec,cnt = int(s,2),0
while dec!=1:
# if odd number
if dec%2==1:
dec+=1
cnt+=1
# if even number
else:
dec = dec//2
cnt+=1
print (cnt) |
# It is a tree-like structure where each node represents a single character of a given string.
# And unlike binary trees, a node may have more than two children.
class Trienode(object):
def __init__(self, char):
self.char = char
self.children=[]
# Is it the last character of the word.
self.word_finish = False
# How many times this character appeared in the addition process
self.counter = 1
def add(root,word):
node = root
for char in word:
found_in_child = False
# Search for the character in the children of the present `node`
for child in node.children:
if child.char == char:
# We found it, increase the counter by 1
child.counter+=1
# And point the node to the child that contains this char
node = child
found_in_child = True
break
if not found_in_child:
new_node = Trienode(char)
node.children.append(new_node)
# And then point node to the new child
node = new_node
# Every thing finished mark it as word finish
node.word_finish = True
def find_prefix(root,prefix):
node=root
# If the root node has no children, then return False.
# Because it means we are trying to search in an empty trie
if not root.children:
return False,0
for char in prefix:
char_not_found=True
# Search through all the children of the present `node`
for child in node.children:
if child.char==char:
# We found the char existing in node
char_not_found = False
# Assign node as the child containing the char and break
node = child
break
if char_not_found:
return False,0
return True,node.counter
if __name__ == "__main__":
root = Trienode('*')
add(root, "ahishers")
#add(root, 'hack')
print(find_prefix(root, 'his'))
print(find_prefix(root, 'he'))
print(find_prefix(root, 'she'))
print(find_prefix(root, 'hers'))
#print(find_prefix(root, 'happy')) |
from collections import deque
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def levelorder(root):
# Create a empty queue for level order traversal
queue = deque()
queue.append(root)
while queue:
# Get the first data from queue
print(queue[0].data, end = ' ')
node = queue.popleft()
# if node-> left is present than append
if node.left:
queue.append(node.left)
# if node-> right is present than append
if node.right:
queue.append(node.right)
if __name__ == '__main__':
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
levelorder(root) |
#The distance value is defined as the number of elements arr1[i]
# such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d.
# https://leetcode.com/contest/biweekly-contest-22/problems/find-the-distance-value-between-two-arrays/
# Complexity : n^2
# Difficulty : Easy
# Naive Approach (two loops)
arr1 = list(map(int,input().split()))
arr2 = list(map(int,input().split()))
d = int(input())
for i in arr1:
for j in arr2:
if abs(i-j)<=d:
c+=1
break
print (len(arr1)-c)
# Can be done in O(nlogm) by using sort + two pointers |
# Spanning tree: That connect all vertices together
# MST: That connect all vertices with minimum weight
# If there are V -> vertices in graph
# Than there are V-1 edges in MST
"""
Algorithm
1. Sort all edges according to their weight
2. Pick smallest weight edge check if it form cycle
2.1 If cycle then discard it
2.2 Else include it
3. Repeat step 2 for rest V-1 edges
"""
class Graph:
def __init__ (self, v):
self.v = vertices
self.graph = []
def addedge(u,v,w):
self.graph.append([u,v,w])
def find(self, parent, i):
if
def kruskal(self):
result = []
i = 0
e = 0
self.graph = sorted(self.graph, key = lambda x: x[2]0)
|
# @Date: 2020-05-02T16:43:47+05:30
# @Last modified time: 2020-05-02T16:47:26+05:30
# The goal in this problem is to count the number of inversions of a given sequence
def merge(a, b, left, mid, right):
# Let i is used for indexing the left sublist and j for the right sublist.
# At any step in the merge process, if a[i] is greater than a[j],
# then there are (mid - i) inversions, because the left and right sublists are sorted
number_of_inversions = 0
i = left # the index for the left sublist
j = mid # the index for the right sublist
k = left # the index for the result sublist
while (i <= mid - 1) and (j < right):
if a[i] <= a[j]:
b[k] = a[i]
k, i = k+1, i+1
else:
b[k] = a[j]
k, j = k+1, j+1
number_of_inversions += mid - i
# copy the remaining elements of the left sublist if any
while i <= mid - 1:
b[k] = a[i]
k, i = k+1, i+1
# copy the remaining elements of the right sublist if any
while j < right:
b[k] = a[j]
k, j = k+1, j+1
# move the merged elements to the original list
for i in range(left, right):
a[i] = b[i]
return number_of_inversions
def get_number_of_inversions(a, b, left, right):
# number of inversions of a sequence in some sense measures how close the sequence is to being sorted
# sequence sorted in descending order any two elements constitute an inversion (total of n(n−1)/2 inversions )
number_of_inversions = 0
if right - left <= 1:
return number_of_inversions
mid = (left + right) // 2
number_of_inversions += get_number_of_inversions(a, b, left, mid )
number_of_inversions += get_number_of_inversions(a, b, mid, right)
number_of_inversions += merge(a, b, left, mid, right)
return number_of_inversions
a = [2, 3, 9, 2, 9]
b = [0, 0, 0, 0, 0]
left = 0
right = len(a)-1
print(get_number_of_inversions(a,b,left,right))
|
class Node:
def __init__ (self, data):
self.head = None
self.data = data
class Linkedlist:
def __init__(self):
self.head = None
def push(self, data):
newnode = Node(data)
newnode.next = self.head
self.head = newnode
def printlist(self):
temp = self.head
while temp:
print(temp.data, end=' -> ')
temp = temp.next
print(None)
def rotate(self, k):
curr = self.head
prev = None
for _ in range(k):
prev = curr
curr = curr.next
# if length == k then simply return original one
if curr is None:
return
rece = curr
prev.next = None
while curr.next:
curr = curr.next
curr.next = self.head
self.head = rece
if __name__ == '__main__':
ll = Linkedlist()
ll.push(2)
ll.push(8)
ll.push(3)
ll.push(5)
ll.push(6)
ll.push(1)
ll.printlist()
ll.rotate(6)
ll.printlist() |
# Approach
# (i) We use a counter to count the occurance of letters in our given word
# (ii) We get the run the loop times len(text)-len(word)
# (iii) We match the counter of words from this loop and match with previous counter
from collections import Counter
p = int(input())
while p:
t = input()
w = input()
s,lt,lw,cnt = Counter(w),len(t),len(w),0
for i in range(lt-lw+1):
word = t[i:i+lw]
if s == Counter(word):
cnt+=1
print(cnt)
p-=1 |
# Task : Return no. as sum of two prime numbers
# Approach : (i)To find all position of prime numbers in whole range using sieve of eratos
# (ii) Rup loop to half of numbers and get those numbers whole sum is 2 in prev stored array
arr = [1]*10001
for i in range(2,len(arr)):
if arr[i]==1:
for j in range(i*i,len(arr),i):
arr[j]=0
for _ in range(int(input())):
p = int(input())
for i in range(3,p//2):
if arr[i]+arr[p-i]==2:
print(i,p-i)
break |
for _ in range(int(input())):
s = list(input())
flag = 0
# to keep track of opening brackets
stack = []
# Hashmap for keeping track of mappings
mappings = {"]":"[", "}":"{", ")":"("}
for char in s:
# if character is closing bracket
if char in mappings:
# pop topmost element from stack
# Else dummy variable
top = stack.pop() if stack else '#'
# if mapping don't match from top of stack
if mappings[char] != top:
flag = 1
break
# if character is not closing bracket
else:
stack.append(char)
# if stack is not empty
if stack or flag==1:
print("not balanced")
else:
print("balanced") |
arr = ["cat", "dog", "tac", "god", "act"]
def all_ana(arr):
words = [''.join(sorted(i)) for i in arr]
dct = {}
for n, i in enumerate(words):
if i in dct:
dct[i].append(n)
else:
dct[i] = [n]
print([[arr[i] for i in lst] for lst in dct.values()])
all_ana(arr)
# words = [''.join(sorted(i)) for i in arr]
# dct = defaultdict(list)
# for n, i in enumerate(words):
# dct[i].append(n)
# return [[arr[i] for i in lst] for lst in dct.values()] |
# @Date: 2020-04-30T17:20:23+05:30
# @Last modified time: 2020-04-30T17:29:52+05:30
# https://leetcode.com/problems/largest-number/
# Given a list of non negative integers, arrange them such that they form the largest number.
# Approach (Libarary Fuction)
from functools import cmp_to_key as cmp
nums = [3,30,34,5,9]
# convert all elements of the list from int to string
nums = map(str, nums)
# we define a function that compares two string (a,b)
# we consider a bigger than b if a+b>b+a
# for example : (a="2",b="11") a is bigger than b because "211" >"112"
comp = lambda a,b:1 if a+b < b+a else -1 if a+b > b+a else 0
# sort the list descendingly using the comparing function we defined
# for example sorting this list ["2","11","13"] produce ["2","13","11"]
# Then concatenate
biggest = ''.join(sorted(nums, key=cmp(comp)))
# convert to int to remove leading zeroes
print (str(int(biggest)))
# Approach Custom operator
# Detailed : https://leetcode.com/problems/largest-number/solution/
def __lt__(x, y):
return x+y > y+x
|
# Given an array of positive integers. Your task is to find the leaders in the array.
# Note: An element of array is leader if it is greater than or equal to all the elements to its right side.
# Also, the rightmost element is always a leader.
for i in range(int(input())):
n = int(input())
lst = list(map(int, input().split()))
mx = lst[-1]
arr=[mx]
if len(lst)==1:
print(arr)
else:
for i in range(n-2,-1,-1):
if lst[i]>=mx:
arr.append(lst[i])
mx = max(lst[i],mx)
print(*(arr[::-1]))
|
# Check that the same number is not present in the current row, current column and current 3X3 subgrid
# After checking for safety, assign the number, and recursively check whether this assignment leads to a solution or not
# If the assignment doesn’t lead to a solution, then try the next number for the current empty cell
def emptycell(grid, pos):
for i in range(9):
for j in range(9):
if grid[i][j]==0:
pos[0], pos[1] = i, j
return True
return False
def safebox(grid, row, col, num):
row -= row%3
col -= col%3
for i in range(row, row+3):
for j in range(col, col+3):
if num==grid[i][j]:
return False
return True
def safecol(grid, col, num):
for i in range(9):
if num==grid[i][col]:
return False
return True
def saferow(grid, row, num):
for i in range(9):
if num==grid[row][i]:
return False
return True
def safe_location(grid, row, col, num):
return saferow(grid, row, num) and safecol(grid, col, num) and safebox(grid, row, col, num)
def solve(grid):
pos = [0,0]
if not emptycell(grid, pos):
return True
row, col = pos[0], pos[1]
for num in range(1, 10):
if safe_location(grid, row, col, num):
grid[row][col] = num
if solve(grid):
return True
grid[row][col] = 0
return False
for _ in range(int(input())):
grid = []
for i in range(9):
lst = map(int, input().split())
grid.append(list(lst))
if(solve(grid)):
for i in range(9):
print(*grid[i])
|
# Problem is to find prime numbers that are in arrays pf numbers
t = int(input())
arr = list(map(int,input().split()))
for j in arr:
d,primes=[],[]
for i in range(2,j+1):
if i not in d:
primes.append(i)
for i in range(i*i,j-1,2):
d.append(i)
print(list(set(primes))) |
# The idea is to use a queue to store only the left child of current node.
# After printing the data of current node make the current node to its right child, if present.
# A delimiter NULL is used to mark the starting of next diagonal.
from collections import deque
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def diagonal(root):
if root is None:
return
queue = deque()
queue.append(root)
queue.append(None)
while queue:
node = queue.popleft()
if not node:
if not queue:
return
print(' ')
queue.append(None)
else:
while node:
print(node.data, end = ' ')
if node.left:
queue.append(node.left)
node = node.right
if __name__ == '__main__':
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
diagonal(root) |
# <left subtree> <root> <right subtree>
# Create an empty stack s
# Initialize current node as root
# Push current node to S and set curr=curr->left
# If curr is NULL and stack is not empty
# (i) Pop the top and print
# (ii) Set curr = popped->right
# If curr is NULL and stack is empty
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def inorder(root):
curr = root
stack = []
while True:
# reach the left most node of curr
if curr is not None:
stack.append(curr)
curr = curr.left
elif stack:
curr = stack.pop()
print(curr.data, end = ' -> ')
curr = curr.right
else:
break
print(None)
if __name__ == '__main__':
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
inorder(root) |
# Leftmost Column with at Least a One
# https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/530/week-3/3306/
binaryMatrix = [[0,0],[0,1]]
#n, m = len(binaryMatrix), len(binaryMatrix[0])
n, m = binaryMatrix.dimensions()
row = 0
col = m-1
# last column where we found 1, default case is -1
lastOneCol = -1
while 0 <= row < n and col >= 0:
#value = binaryMatrix[row][col]
value = binaryMatrix.get(row, col)
# one found - update lastOneCol, go left
if value == 1:
lastOneCol = col
col -= 1
# zero found - go down
else:
row += 1
# return last column where we met 1
print (lastOneCol) |
# @Date: 2020-04-04T13:30:44+05:30
# @Last modified time: 2020-04-30T17:10:42+05:30
# Maximum subarray (Dp Problem)
# https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/528/week-1/3285/
# Given an integer array nums, find the contiguous subarray
# which has the largest sum and return its sum.
nums = [-2,1,-3,4,-1,2,1,-5,4]
max_ending = 0
max_so_far = -1*float("inf")
for i in range(len(nums)):
max_ending = max_ending + nums[i]
if (max_so_far < max_ending):
max_so_far = max_ending
# If sum upto position is less then 0 then reset the sum
if max_ending < 0:
max_ending = 0
print (max_so_far)
|
Pick_a_number = input("pick a number: ")
def character_name():
char_name = input("Please enter your name: ")
print(f"Hello {char_name}. Welocme to the game.")
if(Pick_a_number == "5"):
character_name()
else:
print("You did not pick the right number.")
character_name()
|
"""
Given an array nums, write a function to move all 0's to the end of it while
maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums
should be [1, 3, 12, 0, 0].
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and
creating all test cases.
"""
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
count=0
while True:
try:
nums.remove(0)
except:
break
count+=1
for i in xrange(count):
nums.append(0)
|
"""
This is a follow up of Shortest Word Distance. The only difference is now you
are given the list of words and your method will be called repeatedly many times
with different parameters. How would you optimize it?
Design a class which receives a list of words in the constructor, and implements
a method that takes two words word1 and word2 and return the shortest distance
between these two words in the list.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = “coding”, word2 = “practice”, return 3.
Given word1 = "makes", word2 = "coding", return 1.
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are
both in the list.
"""
class WordDistance(object):
def __init__(self, words):
"""
initialize your data structure here.
:type words: List[str]
"""
self.wordLocs = collections.defaultdict(list)
for i, word in enumerate(words):
self.wordLocs[word].append(i)
def shortest(self, word1, word2):
"""
Adds a word into the data structure.
:type word1: str
:type word2: str
:rtype: int
"""
return min(abs(x - y)
for x in self.wordLocs[word1]
for y in self.wordLocs[word2])
import collections
a = WordDistance(["practice", "makes", "perfect", "coding", "makes"])
print(a.shortest("coding", "practice"))
print(a.shortest("makes", "coding"))
b = WordDistance(["a","a","b","b"])
print(b.shortest("a", "b"))
print(b.shortest("b", "a"))
# Your WordDistance object will be instantiated and called as such:
# wordDistance = WordDistance(words)
# wordDistance.shortest("word1", "word2")
# wordDistance.shortest("anotherWord1", "anotherWord2")
|
"""
Given a positive integer n, find the least number of perfect square numbers (for
example, 1, 4, 9, 16, ...) which sum to n.
For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return
2 because 13 = 4 + 9.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating
all test cases.
"""
class Solution(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
dp = collections.defaultdict(int)
j = 1
while j ** 2 <= n:
dp[j ** 2] = 1
j += 1
for i in range(1, n + 1):
j = 1
while i + j ** 2 <= n:
if i + j ** 2 not in dp or dp[i] + 1 < dp[i + j ** 2]:
dp[i + j ** 2] = dp[i] + 1
j += 1
return dp[n]
import collections
a = Solution()
print(a.numSquares(12) == 3)
print(a.numSquares(13) == 2)
print(a.numSquares(9925) == 2)
"""
Fast (O\sqrt(n)) solution based on Lagrange's Four-Square Theorem:
Original C++ code is here:
https://discuss.leetcode.com/topic/49126/simple-math-solution-4ms-in-c-explained-now
def numSquares(self, n):
while n % 4 == 0:
n /= 4
if n % 8 == 7:
return 4
i = 0
while i ** 2 <= n:
j = int(math.sqrt(n - i ** 2))
if i ** 2 + j ** 2 == n:
return int(i != 0) + int(j != 0)
i += 1
return 3
"""
|
"""
The API: int read4(char *buf) reads 4 characters at a time from a file.
The return value is the actual number of characters read. For example, it
returns 3 if there is only 3 characters left in the file.
By using the read4 API, implement the function int read(char *buf, int n) that
reads n characters from the file.
Note:
The read function will only be called once for each test case.
"""
# The read4 API is already defined for you.
# @param buf, a list of characters
# @return an integer
# def read4(buf):
class Solution(object):
def read(self, buf, n):
"""
:type buf: Destination buffer (List[str])
:type n: Maximum number of characters to read (int)
:rtype: The number of characters read (int)
"""
totalLen=0
buf4=['']*4
while totalLen<n:
readLen=read4(buf4)
buf[totalLen:totalLen+readLen]=buf4[0:readLen]
totalLen+=readLen
if readLen<4:
break
if totalLen>n:
buf=buf[0:n]
return n
else:
return totalLen
|
#
# @lc app=leetcode id=20 lang=python3
#
# [20] Valid Parentheses
#
# https://leetcode.com/problems/valid-parentheses/description/
#
# algorithms
# Easy (38.24%)
# Likes: 4571
# Dislikes: 207
# Total Accepted: 936.3K
# Total Submissions: 2.4M
# Testcase Example: '"()"'
#
# Given a string containing just the characters '(', ')', '{', '}', '[' and
# ']', determine if the input string is valid.
#
# An input string is valid if:
#
#
# Open brackets must be closed by the same type of brackets.
# Open brackets must be closed in the correct order.
#
#
# Note that an empty string is also considered valid.
#
# Example 1:
#
#
# Input: "()"
# Output: true
#
#
# Example 2:
#
#
# Input: "()[]{}"
# Output: true
#
#
# Example 3:
#
#
# Input: "(]"
# Output: false
#
#
# Example 4:
#
#
# Input: "([)]"
# Output: false
#
#
# Example 5:
#
#
# Input: "{[]}"
# Output: true
#
#
#
# @lc code=start
class Solution:
def isValid(self, s: str) -> bool:
l = []
for ch in s :
if ch == '(' or ch == '{' or ch == '[' :
l.append(ch)
else :
if len(l) == 0 :
return False
elif ch == ')' :
if l.pop() != '(' :
return False
elif ch == '}' :
if l.pop() != '{' :
return False
elif ch == ']' :
if l.pop() != '[' :
return False
return len(l) == 0
# @lc code=end
|
# Generates a list of prime numbers
value = int(input("Enter a value: "))
values = list(range(2, value + 1))
print(f"Input: {values}")
for i in values:
for j in values:
if j > i and j % i == 0:
values.remove(j)
print(f"Result: {values}") |
year_str = input('あなたの生まれの年を西暦で入力してください: ')
# タプル型・変更できない
eto_tuple = ("子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥")
year = int(year_str)
num_of_eto = (year + 8) % 12
# print('あなたの干支は', eto_tuple[num_of_eto], 'です。', sep='===')
eto_name = eto_tuple[num_of_eto]
print('あなたの干支は{}です。'.format(eto_name))
|
import random #importing random to allow random gneration of word from list.
HANGMANPICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
#wordList = "cunning bats problem avacado boxing bright elbow knowlege strings integers mistake parsing error guitar road brick".split() # SPLIT at end defaults as splitting where the space is and turning into a list.
#wordList = "cunning bats".split()
#List = open("filename.txt").readlines()
def pickRandomWord(fname): #.readlines(), #line.split(), #for i in fname: wordList.append(i.rstrip().split(','))
wordList = open(fname).readlines()
wordIndex = random.randint(0, len(wordList)-1)
word = wordList[wordIndex]
#print (word)
return word
def changeWordToStars (word):
starVersionOfWord = "*" * len(word) #creates starVersionOfWord list of starts (*) by multiplying the string value '*' by the amount of letters in the variable word.
starVersionOfWord = list(starVersionOfWord) # this converts the '*' version of the word into a list, to allow better indexing and replacing of letters, also comparing of lists.
return starVersionOfWord
def convertStarsToList (starVersionOfWord):
listStarVersionOfWord = list(starVersionOfWord)
return listStarVersionOfWord
'''
def pickRandomWord(fname):
wordList = []
with open(fname) as inputfile:
for line in inputfile:
wordList.append(line.split())
wordIndex = random.randint(0, len(wordList)-1)
word = wordList[wordIndex]
print (word)
return word
'''
'''
def pickRandomWord (wordList): # paramter is the list created above (which has been "split" where space are and turned into a list. Thus allowing indexing
wordIndex = random.randint(0, len(wordList)-1) #creating a varaible to use to pick a word at a random index. -1 as otherwise list index out of range
word = wordList[wordIndex] # creates word variable (to be returned and used elsewhere) by calling the string that is at the index position in the word list.
return word #OTHER OPTION ##RANDOM.CHOICE(WORDLIST).LOWER WOULD WORK TOO??
'''
'''def pickRandomWord (wordList):
wordList = importfromtxt()
word = random.choice(wordList).lower
return word
'''
def compareGuess (listStarVersionOfWord, word, word_listversion): # function asks for letter, compares against secret word
print (listStarVersionOfWord)
guesses_made = []
lives = 6 #defined lives outside of while loop. this figure will reduce every time a wrong guess is made. when it hits 0, the loop below ends, printing line 36 "the end"
while(lives > 0 and listStarVersionOfWord != word_listversion): # as long as the user has lives, and the blank word(which is a list) does not match the random word (also converted to a list) this will loop
image_to_display = int(6 - lives)
print (HANGMANPICS[image_to_display])
print ("lives = ", lives) #prints lives, a variable assigned in this function, but outside of this while loop.
print ("guesses made so far", guesses_made) #prints guesses made , an empty list assigned in this function, but outside of this while loop.
while True: #Sets loop to true (means it will loop infinitely until value returns as "false" or told to break. ASKS USER FOR INPUT
guess = str.lower(input("enter letter or guess full word: ")) ## asks for input, converts to lower case.
if guess in guesses_made: #if the user input is in the guesses made list (defined above) it will NOT break the true loop as it REMAINS TRUE.
print ("You have already guessed this, no lives lost. Guess again.")
print ("guesses made so far", guesses_made)
elif guess not in "abcdefghijklmnopqrstuvwyxz":
print ("Please enter VALID letter")
elif guess in "abcdefghijklmnopqrstuvwyxz" or word: #other wise, if user input is a letter or is in the word (so as letter combinations that are included in the word are accepted
guesses_made.append(guess) # this takes what the user has just input and adds it to the guesses made list, only if it satisfyes conditions before.
break # if above happens, conditions are satisfied and while loop breaksm going on to the if conditions below.
print(listStarVersionOfWord) ## this prints blank at start of guess
if guess == word: # correct guess # if full word guessed correctly. will print full word (list version) and break loop to end game.
print (list(word))
print ("Great guess! You won the game! http://linuxart.com/stuff/gnome/gegl.png ")
break
elif guess in word: # letter in word # otherwise, if the user input is in the word it will loop through to replace '*' with correct letter
for i in range(len(word)): # i loops through the range of the word, range being defined as th length of the word.(i being the int that represents the position of the loop inside of the range),
if guess == word[i]: #if the user input matches exactly the letter that is in the word at i, then it will....
listStarVersionOfWord[i] = guess #... replace the '*' that is in the same position that was just checked above. So 3rd * will be replaced with user input, IF the user input matched the 3rd LETTER of the Word
print ("congratulations, correct guess")
print(listStarVersionOfWord) #prints new version of blank that has just been amended to include letter (if matched)
elif guess not in word: # letter not in word
print ("sorry, wrong guess")
lives -= 1 # this removes a life from the accumular defined at the begining of this function(def compareGuess (blank, word, word_listversion))
def main():
#pickRandomWord (wordList) # runs function that picks random word from list
#word = pickRandomWord (wordList) #defines variable word which is apart of function "def pickRandomWord (wordList)"
#pickRandomWord("listofwords.txt")
word = pickRandomWord("listofwords.txt")
starVersionOfWord = changeWordToStars (word)
listStarVersionOfWord = convertStarsToList (starVersionOfWord)
word_listversion = list(word) #converst variable "word" into a list. This allows us to better calculate index of each letter and compare vs other lists..
'''blank = "*" * len(word) #creates blank list of starts (*) by multiplying the string value '*' by the amount of letters in the variable word.
blank = list(blank) # this converts the '*' version of the word into a list, to allow better indexing and replacing of letters, also comparing of lists.
'''
compareGuess (listStarVersionOfWord, word, word_listversion ) #this runs function where most of the work for the game is happening.
print("THE END")
playAgain = str.lower(input("Would you like to play again?")) ## play again, if yes, run main.
if playAgain in "yes":
main()
print ("Goodbye")
main() |
import copy
class const:
SHEEP_DEFENSE = 1000
SHEEP_MANA = 1000
BOAR_DEFENSE = 2000
BOAR_MANA = 500
SEAL_DEFENSE = 1500
SEAL_MANA = 750
class BeastPrototype:
_defense = None
_mana = None
def clone(self):
pass
def getDefense(self):
return self._defense
def getMana(self):
return self._mana
class Sheep(BeastPrototype):
def __init__(self):
self._defense = const.SHEEP_DEFENSE
self._mana = const.SHEEP_MANA
def clone(self):
return copy.copy(self)
class Boar(BeastPrototype):
def __init__(self):
self._defense = const.BOAR_DEFENSE
self._mana = const.BOAR_MANA
def clone(self):
return copy.copy(self)
class Seal(BeastPrototype):
def __init__(self):
self._defense = const.SEAL_DEFENSE
self._mana = const.SEAL_MANA
def clone(self):
return copy.copy(self)
class BeastPrototypeFactory:
__sheep = None
__boar = None
__seal = None
@staticmethod
def initialize():
BeastPrototypeFactory.__sheep = Sheep()
BeastPrototypeFactory.__boar = Boar()
BeastPrototypeFactory.__seal = Seal()
@staticmethod
def createSheep():
return BeastPrototypeFactory.__sheep.clone()
@staticmethod
def createBoar():
return BeastPrototypeFactory.__boar.clone()
@staticmethod
def createSeal():
return BeastPrototypeFactory.__seal.clone()
def main():
BeastPrototypeFactory.initialize()
dolly = BeastPrototypeFactory.createSheep()
sally = BeastPrototypeFactory.createSheep()
print('=======SHEEPS=======')
print('DOLLY: Defense: ', dolly.getDefense(), ' Mana: ', dolly.getMana())
print('SALLY: Defense: ', sally.getDefense(), ' Mana: ', sally.getMana())
print([i for i in (dolly, sally)])
if __name__ == '__main__' :
main()
|
#!/usr/bin/python3
"""Amenity Model Unit tests"""
import unittest
import datetime
from models.base_model import BaseModel
from models.amenity import Amenity
class TestAmenity(unittest.TestCase):
"""Test normal base instantiation"""
def test_Amenity(self):
# Tests values after creating Base Model
amenity = Amenity()
self.assertIsInstance(amenity, Amenity)
self.assertIsInstance(amenity, BaseModel)
self.assertIsInstance(amenity.id, str)
self.assertEqual(Amenity.name, "")
if __name__ == '__main__':
unittest.main()
|
#3장 1번
##chi=2
##pig=4
##cow=3
##leg=(chi*2)+(pig*4)+(cow*4)
##print("닭의 수: " ,chi)
##print("돼지의 수: " ,pig)
##print("소의 수: " ,cow)
##print("전체 다리의 수 :",leg)
#3장 2번
##x1=int(input("x1:"))
##y1=int(input("y1:"))
##x2=int(input("x2:"))
##y2=int(input("y2:"))
##result=(((x2-x1)**2)+((y2-y1)**2))**0.5
##print("두 점 사이의 거리= ",result)
#3장 3번
##r=141
##import turtle
##t=turtle.Turtle()
##t.shape("turtle")
##t.left(45)
##t.forward(r)
##t.up()
##t.goto(0,0)
##t.down()
##t.setheading(0)
##t.forward(100)
##t.left(90)
##t.forward(100)
#3장 4번 다시 풀어
'''
import turtle
t=turtle.Turtle()
t.shape("turtle")
##x1=int(input("x1:"))
##y1=int(input("y1:"))
##x2=int(input("x2:"))
##y2=int(input("y2:"))
##result=(((x2-x1)**2)+((y2-y1)**2))**0.5
##r=result
x1=turtle.textinput("x1:","x1의 값을 입력하세요")
y1=turtle.textinput("y1:","y1의 값을 입력하세요")
x2=turtle.textinput("x2:","x2의 값을 입력하세요")
y2=turtle.textinput("y2:","y2의 값을 입력하세요")
##result=(((x2-x1)**2)+((y2-y1)**2))**0.5
t.goto(x1,y1)
t.up
t.goto(x2,y2)
t.down
t.write("선의 길이="+((((x2-x1)**2)+((y2-y1)**2))**0.5))
##t.write("직선의 길이="+result);
'''
import time
sec=time.time()
x_1=sec//60 # 전체시간 (분)단위
realmin=int(x_1%60)
x_2=x_1//60
enghour=int(x_2%24+1)
print("현재 시간(영국 그리니치 시각): ",enghour,"시",realmin,"분")
|
# ch07 추가 연습문제 2번
import random
values=[]
for i in range(5):
values.append(random.randint(1,20))
print(values)
for j in range(5):
print(str(values[j])+"\t\t"+'*'*int(values[j]))
|
print("hello world")
message = "hellow world python"
message = message + "nihao"
print(message)
name = 'wang "shuai"'
address = "shanxi"
print(name.title())
print(name.upper())
print("\n"+name + "\t"+address)
trim = " polunzi "
print(trim + name)
print(trim.rstrip() + name)
print(trim + name)
print(3*0.1)
age = 25
print(name + str(age))
print(name.contains('wang'))
|
wangshuai = {'age': 20, 'city':"beijing"}
print(wangshuai['age'])
wangshuai['sex']= 'male'
print(wangshuai)
wangshuai['age'] = 25
print(wangshuai)
#del wangshuai['age']
#print(wangshuai)
for k,v in wangshuai.items() :
print(k + "=======>" + str(v) + "\n")
users = {
'wangshuai': {'age': 25, 'sex': 'male', 'language': ['zh_cn', 'en_lang']},
'jinhui': {'age': 21, 'sex': 'female'}
}
wangshuai = users['wangshuai']
print(wangshuai)
wangshuai_language = wangshuai['language']
print(wangshuai_language[0])
|
import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
#init a ship to the screen
def __init__(self, screen, setting):
super().__init__()
self.screen = screen
self.image = pygame.image.load("images/alien.jpg")
# rect == Rectangle (chang fang xing)
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
self.setting = setting
# init the position of this ship
self.rect.centerx = self.screen_rect.centerx
self.center = float(self.rect.centerx)
self.rect.bottom = self.screen_rect.bottom
self.move_right = False
self.move_left = False
# repaint
def blitme(self):
self.screen.blit(self.image, self.rect)
# update the x, y of this ship
def update(self):
if self.move_right and self.rect.right < self.screen_rect.right:
self.center += self.setting.ship_speed
if self.move_left and self.rect.left > 0:
self.center -= self.setting.ship_speed
self.rect.centerx = self.center
def put_center(self):
self.center = self.screen_rect.centerx
|
arr = [1,2,3,4,5]
for num in arr:
print(num)
nums = []
for value in range(1, 5):
print(value)
nums.append(value * value)
print(nums)
# form 1(default 0) to 20 (required)increase 3(default 1) everytime
for value in range(1, 20, 3):
print(value)
test_list = list(range(1,10))
print(test_list)
print(max(test_list))
print(sum(test_list))
#print(list(range(1,1000000)))
#copy a arr
food = ["fish", "rice", "cake", "candy"]
# direct value copy is transfer the handle , they share the same ram
new_food = food
print(new_food)
new_food[0] = "chicken"
print(food)
# the real ram copy need to use the next line code
_food = food[:]
print(_food)
_food[1] = "noodels"
print(food)
|
#!usr/bin/env python3
# -*- coding: utf-8 -*-
' Queue Reconstruction by Height - Medium '
__author__ = 'Roger Cui'
'''
Suppose you have a random list of people standing in a queue. Each person
is described by a pair of integers (h, k), where h is the height of the person
and k is the number of people in front of this person who have a height greater
than or equal to h. Write an algorithm to reconstruct the queue.
Note:
The number of people is less than 1,100.
Example
Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
Results:
Run time: beats 66.67%
Time complex: O()
Space complex: O()
'''
class Solution(object):
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
people.sort(key=lambda p: (-p[0], p[1]))
queue = []
for p in people:
queue.insert(p[1], p)
return queue
if __name__ == '__main__':
obj = Solution()
l = [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
result = obj.reconstructQueue(l)
print(result)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'Complex Number Multiplication - medium'
__author__ = 'Roger Cui'
'''
Given two strings representing two complex numbers.
You need to return a string representing their multiplication. Note i2 = -1 according to the definition.
Example 1:
Input: "1+1i", "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.
Example 2:
Input: "1+-1i", "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.
Note:
1.The input strings will not have extra blank.
2.The input strings will be given in the form of a+bi, where the integer a and b will both belong to the
range of [-100, 100]. And the output should be also in this form.
Results:
Run time: 36ms, beats 47%
Time complex: O(n)
Space complex: O(n)
'''
class Solution(object):
def complexNumberMultiply(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
# original method
# a = a.split('+')
# n1 = int(a[0])
# m1 = int(a[1].split('i')[0])
# b = b.split('+')
# n2 = int(b[0])
# m2 = int(b[1].split('i')[0])
# return str(n1*n2 - m1*m2) + '+' + str(n1*m2 + n2*m1) + 'i'
# second method
n1, m1 = map(int, a[:-1].split('+'))
n2, m2 = map(int, b[:-1].split('+'))
return str(n1*n2 - m1*m2) + '+' + str(n1*m2 + n2*m1) + 'i'
if __name__ == '__main__':
A = Solution()
print(A.complexNumberMultiply('1+1i', '1+1i'))
print(A.complexNumberMultiply('1+-1i', '1+-1i'))
|
#!usr/bin/env python3
# -*- coding: utf-8 -*-
' Maximum Depth of Binary Tree - easy '
__author__ = 'Roger Cui'
'''
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Results:
Run time: 59ms, beats 48.11%
Time complex: O()
Space complex: O()
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# first version
if root == None:
return 0
else:
left_count = self.maxDepth(root.left) + 1
right_count = self.maxDepth(root.right) + 1
max_count = max(left_count, right_count)
return max_count
# second version
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 if root else 0
# third version
return max(map(self.maxDepth, [root.left, root.right])) + 1 if root else 0
if __name__ == '__main__':
pass
|
#!usr/bin/env python3
# -*- coding: utf-8 -*-
' Maximum Binary Tree - Medium '
__author__ = 'Roger Cui'
'''
Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
The root is the maximum number in the array.
The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.
Construct the maximum tree by the given array and output the root node of this tree.
Example 1:
Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:
6
/ \
3 5
\ /
2 0
\
1
Note:
The size of the given array will be in the range [1,1000].
Results:
Run time: 212ms, beats 72.13%
Time complex: O()
Space complex: O()
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def constructMaximumBinaryTree(self, nums):
# first try
l = len(nums)
if l == 1:
return TreeNode(nums[0])
else:
maxnum = max(nums)
maxidx = nums.index(maxnum)
node = TreeNode(maxnum)
node.left = self.constructMaximumBinaryTree(nums[:maxidx]) if maxidx != 0 else None
node.right = self.constructMaximumBinaryTree(nums[maxidx+1:]) if maxidx != l-1 else None
return node
if __name__ == '__main__':
Solution().constructMaximumBinaryTree([3,2,1,6,0,5])
|
#EXAMPLE 1
"""
a=23
b=23
if a > b:
print("A is Greater than B")
elif a==b: #---Otherwise
print("A is Equal to B")
else:
print("A is Less than B")
"""
# EXAMPLE 2:
x=39
if x==23:
print("X is 23")
elif x==36:
print("X is 36")
else:
print("X is not 36")
|
# 参数默认值
def f1(a, b=5, c=10):
return a + b * 2 + c * 3
print(f1(1, 2, 3))
print(f1(100, 200))
print(f1(100))
print(f1(c=2, b=3, a=1))
# 可变参数
def f2(*args):
sum = 0
for num in args:
sum += num
return sum
print(f2(1, 2, 3))
print(f2(1, 2, 3, 4, 5))
print(f2())
# 关键字参数
def f3(**kw):
if 'name' in kw:
print('欢迎你%s!' % kw['name'])
elif 'tel' in kw:
print('你的联系电话是: %s!' % kw['tel'])
else:
print('没找到你的个人信息!')
param = {'name': 'make', 'age': 26}
f3(**param)
f3(name='make', age=26, tel='13866778899')
f3(user='make', age=26, tel='13866778899')
f3(user='make', age=26, mobile='13866778899')
|
#!/usr/bin/env python
from __future__ import print_function
import argparse
import sys
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('input_file', type=argparse.FileType())
parser.add_argument('output_file', type=argparse.FileType('w'), nargs='?', default=sys.stdout)
args = parser.parse_args()
lines = args.input_file.readlines()
i = len(lines) - 1
trimmed = False
# step backwards through the lines, removing all As until we find a non-A nucleotide
while not trimmed:
line = lines[i].upper().rstrip()
for j in range(len(line) - 1, -1, -1):
# walk backwards through the line, checking for a non-A (and non-space) character
if line[j] not in ['A', ' ']:
lines[i] = line[:j + 1] + '\n'
trimmed = True
break
else:
# we processed the whole line - all As - so we don't include this line in the output
i -= 1
args.output_file.write(''.join(lines[:i + 1]))
|
#!/usr/bin/env python
"""Calculate scores for Heinz.
This script transform a p-value into a score:
1. Use alpha and lambda to calculate a threshold P-value.
2. Calculate a score based on each P-value by alpha and the threshold.
For more details, please refer to the paper doi:10.1093/bioinformatics/btn161
Input:
P-values from DESeq2 result: first column: names, second column P-values
Output:
Scores, which will be used as the input of Heinz.
First column: names, second column: scores.
Python 3 is required.
"""
# Implemented by: Chao (Cico) Zhang
# Homepage: https://Hi-IT.org
# Date: 14 Mar 2017
# Last modified: 23 May 2018
import argparse
import sys
import numpy as np
import pandas as pd
parser = argparse.ArgumentParser(description='Transform a P-value into a '
'score which can be used as the input of '
'Heinz')
parser.add_argument('-n', '--node', required=True, dest='nodes',
metavar='nodes_pvalue.txt', type=str,
help='Input file of nodes with P-values')
parser.add_argument('-f', '--fdr', required=True, dest='fdr',
metavar='0.007', type=float, help='Choose a value of FDR')
parser.add_argument('-m', '--model', required=False, dest='param_file',
metavar='param.txt', type=str,
help='A txt file contains model params as input')
parser.add_argument('-a', '--alpha', required=False, dest='alpha',
metavar='0.234', type=float, default=0.5,
help='Single parameter alpha as input if txt input is '
'not provided')
parser.add_argument('-l', '--lambda', required=False, dest='lam',
metavar='0.345', type=float, default=0.5,
help='Single parameter lambda as input if txt input is '
'not provided')
parser.add_argument('-o', '--output', required=True, dest='output',
metavar='scores.txt', type=str,
help='The output file to store the calculated scores')
args = parser.parse_args()
# Check if the parameters are complete
if args.output is None:
sys.exit('Output file is not designated.')
if args.nodes is None:
sys.exit('Nodes with p-values must be provided.')
if args.fdr is None:
sys.exit('FDR must be provided')
if args.fdr >= 1 or args.fdr <= 0:
sys.exit('FDR must greater than 0 and smaller than 1')
# run heinz-print according to the input type
if args.param_file is not None: # if BUM output is provided
with open(args.param_file) as p:
params = p.readlines()
lam = float(params[0]) # Maybe this is a bug
alpha = float(params[1]) # Maybe this is a bug
# if BUM output is not provided
elif args.alpha is not None and args.lam is not None:
lam = args.lam
alpha = args.alpha
else: # The input is not complete
sys.exit('The parameters of the model are incomplete.')
# Calculate the threshold P-value
pie = lam + (1 - lam) * alpha
p_threshold = np.power((pie - lam * args.fdr) / (args.fdr - lam * args.fdr),
1 / (alpha - 1))
print(p_threshold)
# Calculate the scores
input_pvalues = pd.read_csv(args.nodes, sep='\t', names=['node', 'pvalue'])
input_pvalues.loc[:, 'score'] = input_pvalues.pvalue.apply(lambda x:
(alpha - 1) * (np.log(x) - np.log(p_threshold)))
# print(input_pvalues.loc[:, ['node', 'score']])
input_pvalues.loc[:, ['node', 'score']].to_csv(args.output, sep='\t',
index=False, header=False)
|
# -*- coding: utf-8 -*-
"""
Simple Span Beam Design
Author: Margaret Wang
This program is developed to design a beam for the geometry and loading provided by a user.
Design uses LRFD factors in calculating capacity and loading requirements.
The shape database used is limited to W shapes.
For this design, gravity loading in the major axis is considered.
Moment, shear, and axial load is considered.
+ gravity loading is downward
+ axial loading is compressive
"""
### Import libraries
# importing division from the 'future' release of Python (i.e. Python 3)
from __future__ import division
# importing libraries
import os
import pandas as pd
import math
### Define path to database of shapes for design
# defining path of directory where shapes database lives
# os.getcwd() # provides current working directory
path = "/Users/Margaret/Desktop/structural_data/"
os.chdir(os.path.dirname(path))
os.path.dirname(os.path.realpath('__file__'))
# importing database
shapes = pd.read_csv("AISC Shapes Database v14.1.csv")
### Define constants
# steel material properties
Fy = 50 #ksi
Fu = 65 #ksi
E = 29000 #ksi
# LRFD Factors
phi_yield = 0.90
phi_rupture = 0.75
phi_compression = 0.90
phi_flexure = 0.90
phi_shear = 1.0
#####
### Define Functions
#####
def check_value(num):
''' Checks if number entered is a float or not.
'''
valid = False
while not valid:
try:
float(num)
valid = True
except ValueError:
num = raw_input("Sorry, not a number. Please input a number: ")
value = float(num)
return value
def check_string(char):
''' Checks if number entered is a float or not.
'''
valid = False
while not valid:
valid = char.upper() == 'Y' or char.upper() == 'N'
if not valid:
char = raw_input("Sorry, not a valid input. Please re-enter: ")
return char.upper()
def request_areaload(load_case):
''' Requests area load input from user.
'''
area_load = raw_input("What is the " + load_case + " load in psf? ")
area_value = check_value(area_load)
return area_value
def request_axialload(load_case):
''' Requests point load input from user.
'''
point_load = raw_input("What is the " + load_case + " axial load in kips? ")
point_value = check_value(point_load)
return point_value
def request_geometry():
''' Requests geometry from user.
'''
length = raw_input("Enter length of beam in ft: ")
length_value = check_value(length)
spacing = raw_input("Enter beam spacing in ft: ")
spacing_value = check_value(spacing)
unbraced_L = raw_input("Enter unbraced length of beam in ft (0 for fully braced): ")
unbraced_L_value = check_value(unbraced_L)
K = raw_input("Enter effective length factor, K: ")
K_value = check_value(K)
return length_value, spacing_value, unbraced_L_value, K_value
def request_deflcriteria():
''' Requests total and live load deflection criteria from user.
'''
default = raw_input("Use default maximum total deflection of L/240 and "
" maximum live load deflection of L/360? \n Enter Y/N: ")
default_YN = check_string(default)
if default_YN == 'Y':
total_defl_value = 240.0
live_defl_value = 360.0
else:
total_defl = raw_input("Enter maximum total deflection of beam, L/: ")
total_defl_value = check_value(total_defl)
live_defl = raw_input("Enter maximum live load deflection of beam, L/: ")
live_defl_value = check_value(live_defl)
return total_defl_value, live_defl_value
def input_loading():
''' Inputs gravity loading requirements.
'''
dead_area = request_areaload("dead")
live_area = request_areaload("live")
snow_area = request_areaload("snow")
dead_axial = request_axialload("dead")
live_axial = request_axialload("live")
snow_axial = request_axialload("snow")
return dead_area, live_area, snow_area, dead_axial, live_axial, snow_axial
def max_loading(D,L,S):
''' ASCE 7-05 load combinations, focusing on gravity
'''
lc1 = 1.4*D
lc2 = 1.2*D + 1.6*L + 0.5*S
lc3 = 1.2*D + 1.0*L + 1.6*S
strength = max(lc1, lc2, lc3)
serviceability = D + L + S
return strength, serviceability
def max_loading_df(df,col,D,L,S,spacing):
''' ASCE 7-05 load combinations, focusing on gravity
'''
df['lc1'] = 1.4*(D + df[col]/spacing)
df['lc2'] = 1.2*(D + df[col]/spacing) + 1.6*L + 0.5*S
df['lc3'] = 1.2*(D + df[col]/spacing) + 1.0*L + 1.6*S
df['strength_load'] = df[['lc1', 'lc2', 'lc3']].max(axis=1)
df['service_load'] = (D + df[col]/spacing) + L + S
return df
def max_shaperatios(df, axial=False):
''' Checks compactness and slenderness of flanges and webs in
flexure and in axial compression
'''
compact_class_flanges_flex = 0.38*math.sqrt(E/Fy)
#noncompact_class_flanges_flex = 1.0*math.sqrt(E/Fy)
df = df[df.bf_2tf < compact_class_flanges_flex]
compact_class_webs_flex = 3.76*math.sqrt(E/Fy)
df = df[df.d_2k_tw < compact_class_webs_flex]
if axial:
compact_class_flanges_comp = 0.56*math.sqrt(E/Fy)
df = df[df.bf_2tf < compact_class_flanges_comp]
compact_class_webs_comp = 1.49*math.sqrt(E/Fy)
df = df[df.d_2k_tw < compact_class_webs_comp]
return df
def compare_cols(df,col1,col2):
subset = df[df[col1] > df[col2]]
return subset
####
## Design Process
####
### Request information from users
D_psf, L_psf, S_psf, D_kip, L_kip, S_kip = input_loading() # generates loads for load cases
L, spacing, Lb, K = request_geometry() # generates spacing
### Prepare database of shapes to check
# isolating W shapes
W_shapes = shapes[shapes['Type']=='W']
# limiting to necessary elements
W_shapes = W_shapes[['AISC_Manual_Label','W','A','d','bf','tw','tf','kdes','bf/2tf','h/tw',
'Ix','Zx','Sx','rx','Iy','Zy','Sy','ry','J','Cw','rts','ho']]
W_shapes.rename(columns = {'AISC_Manual_Label':'Shape','bf/2tf':'bf_2tf','h/tw':'h_tw'}, inplace=True) # renames columns
#W_shapes = W_shapes.convert_objects(convert_numeric=True) # convert numeric (deprecated)
W_shapes = W_shapes.apply(pd.to_numeric, errors='ignore') # convert numeric
### Perform design
### develop design requirements
strength_psf, service_psf = max_loading(D_psf,L_psf,S_psf) # generates area load before beam laod
strength_kip, service_kip = max_loading(D_kip, L_kip, S_kip) # generates axial point loading
strength_w = strength_psf*spacing/1000
service_w = service_psf*spacing/1000
live_w = L_psf*spacing/1000
W_shapes = max_loading_df(W_shapes,'W',D_psf,L_psf,S_psf,spacing) # generates line loading
W_shapes['strength_w'] = W_shapes['strength_load']*spacing/1000
W_shapes['service_w'] = W_shapes['service_load']*spacing/1000
strength_kip, service_kip = max_loading(D_kip, L_kip, S_kip) #generates axial point loading
W_shapes['strength_k'] = strength_kip
W_shapes['service_k'] = service_kip
W_shapes['moment_ult'] = W_shapes.strength_w*L**2/8
W_shapes['shear_ult'] = W_shapes.strength_w*L/2
W_shapes['axial_ult'] = strength_kip
W_shapes['moment_nom'] = W_shapes.service_w*L**2/8
W_shapes['shear_nom'] = W_shapes.service_w*L/2
W_shapes['axial_nom'] = service_kip
moment_ult = strength_w*L**2/8
shear_ult = strength_w*L/2
axial_ult = strength_kip
moment_nom = service_w*L**2/8
shear_nom = service_w*L/2
axial_nom = service_kip
print('The LRFD design values (without beam weight) are: \n' +
'Moment: %0.2f kip-ft\n' +
'Shear: %0.2f kips\n' +
'Axial Load: %0.2f kips\n') % (moment_ult, shear_ult, axial_ult)
print('The unfactored design values (without beam weight) are: \n' +
'Moment: %0.2f kip-ft\n' +
'Shear: %0.2f kips\n' +
'Axial Load: %0.2f kips\n') % (moment_nom, shear_nom, axial_nom)
W_shapes['d_2k_tw'] = (W_shapes.d - 2*W_shapes.kdes) / W_shapes.tw # create (d-2*k)/tw column
W_shapes['A_web'] = W_shapes.d*W_shapes.tw # create area of web column = d*tw
# defines subset of shapes that fit shape ratio requirements in flexure and compression
axial = service_kip > 0
W_shapes = max_shaperatios(W_shapes, axial)
####
## Deflection Design
####
### ∆ = 5wL^4/384EI
### Imin = 5wL^4/384EI∆
total_defl_crit, live_defl_crit = request_deflcriteria()
total_defl_limit = L*12/total_defl_crit
live_defl_limit = L*12/live_defl_crit
print('The deflection criteria translates to: \n' +
'Total (L/%d): %0.2f in\n' +
'Live (L/%d): %0.2f in\n') % (total_defl_crit, total_defl_limit, live_defl_crit, live_defl_limit)
# Calculate minimum Ix
W_shapes['Imin'] = 5*(W_shapes.service_w/12)*(L*12)**4/(384*E*(L*12/total_defl_crit))
Imin_L = 5*(live_w/12)*(L*12)**4/(384*E*(L*12/live_defl_crit))
# remove from list sections where the live load deflection governs
W_shapes.loc[W_shapes.Imin < Imin_L, 'Imin'] = Imin_L
# compares shape Ix to Imin
W_shapes = compare_cols(W_shapes,'Ix','Imin')
# Deflections
W_shapes['total_defl'] = 5*(W_shapes.service_w/12)*(L*12)**4/(384*E*W_shapes.Ix)
W_shapes['live_defl'] = 5*(live_w/12)*(L*12)**4/(384*E*W_shapes.Ix)
# Return database of shapes that satisfy criteria
valid_defl_shapes = W_shapes[W_shapes.Ix > W_shapes.Imin].sort_values(by=['Ix']) # all valid shapes
top_10_defl_shapes = valid_defl_shapes[['Shape','Ix', 'total_defl', 'live_defl']].head(10)
lightest_defl_shape = W_shapes.loc[W_shapes[W_shapes.Ix > W_shapes.Imin].W.idxmin(),'Shape'] # smallest shape
print 'Lightest shape for deflection is: ' + lightest_defl_shape
print 'Top 10 efficient shapes for deflection: \n' + top_10_defl_shapes.to_string(index=False)
####
## Flexural Design (Chapter C and F)
####
### Amplified first order elastic analysis
Cm = 1.0 # coefficient assuming no lateral translation, Cm = 0.6 - 0.4 M1/M2
alpha = 1.0 # for LRFD
Pe1 = math.pi**2*E*W_shapes.Ix/(K*L*12)**2
W_shapes['B1'] = Cm/(1-alpha*W_shapes.axial_ult/Pe1)
W_shapes.loc[W_shapes['B1']<1, 'B1'] = 1
W_shapes['moment_ult'] = W_shapes.B1*W_shapes.moment_ult
### Flexural yielding
### Mn = FyZx
### phiMn = phi_flexure*Fy*Zx
W_shapes['M_fy'] = phi_flexure*Fy*W_shapes.Zx/12
### Lateral-torsional buckling
c = 1.0
Lb_in = Lb*12
Cb = 1.0
h0 = W_shapes.d-W_shapes.tf
W_shapes['Lp'] = 1.76*W_shapes.ry*(E/Fy)**0.5
W_shapes['Lr'] = 1.95*W_shapes.rts*E/(0.7*Fy)*(W_shapes.J*c/(W_shapes.Sx*h0)+((W_shapes.J*c/(W_shapes.Sx*h0))**2+6.76*(0.7*Fy/E)**2)**0.5)**0.5
## Case: Lb < Lp, no lateral torsional buckling, yield moment governs
no_LTB = W_shapes['Lp'] > Lb_in # boolean mask for Lp > Lb
#W_shapes.loc[no_LTB, 'Shape'] # list of shapes that encounter lateral torsional buckling
W_shapes.loc[no_LTB, 'M_LTB'] = W_shapes['M_fy'] #dataframe of no_LTB shapes
## Case: Lp < Lb < Lr, inelastic lateral torsional buckling
LTB_ie = (W_shapes['Lp'] < Lb_in) & (W_shapes['Lr'] > Lb_in) # boolean mask
M_LTB_ie = Cb*(W_shapes.M_fy - (W_shapes.M_fy-0.7*Fy*W_shapes.Sx)*(Lb_in - W_shapes.Lp)/(W_shapes.Lr-W_shapes.Lp))
W_shapes.loc[LTB_ie, 'M_LTB'] = phi_flexure*M_LTB_ie/12 # assign to frame
## Case: Lb > Lr, elastic lateral torsional buckling
LTB_e = W_shapes['Lr'] < Lb_in # boolean mask
Fcr = Cb*math.pi**2*E/(Lb_in/W_shapes.rts)**2*(1+0.78*W_shapes.J*c/(W_shapes.Sx*h0)*(Lb_in/W_shapes.rts)**2)**0.5
M_LTB_e = Fcr*W_shapes.Sx
W_shapes.loc[LTB_e, 'M_LTB'] = phi_flexure*M_LTB_e/12
W_shapes['M'] = W_shapes[['M_fy', 'M_LTB']].min(axis=1)
# available shapes that fit design criteria
valid_flex_shapes = W_shapes[W_shapes.M > W_shapes.moment_ult].sort_values(by=['Zx']) # all valid shapes
top_flex_shapes = valid_flex_shapes[['Shape','Zx','M']].head(10)
lightest_flex_shape = W_shapes.loc[W_shapes[W_shapes.M > W_shapes.moment_ult].W.idxmin(),'Shape'] # smallest shape
print 'Lightest shape for flexure is: ' + lightest_flex_shape
print 'Top 10 efficient shapes for flexure: \n' + top_flex_shapes.to_string(index=False)
####
## Shear Design (Chapter G)
####
## Vn = 0.6*Fy*Aw*Cv
## phiVn = phi_shear*0.6*Fy*Aw*Cv
Cv = 1.0 # From user note Chapter G2.1
W_shapes['V'] = phi_shear*0.6*Fy*Cv*W_shapes.A_web
# available shapes that fit design criteria
valid_shear_shapes = W_shapes[W_shapes.V > W_shapes.shear_ult].sort_values(by=['A_web']) # all valid shapes
top_shear_shapes = valid_shear_shapes[['Shape','A_web','V']].head(10)
lightest_shear_shape = W_shapes.loc[W_shapes[W_shapes.V > W_shapes.shear_ult].W.idxmin(),'Shape'] # smallest shape
print 'Lightest shape for shear is: ' + lightest_shear_shape
print 'Top 10 efficient shapes for shear: \n' + top_shear_shapes.to_string(index=False)
####
## Axial Loading in Compression (Chapter E)
####
# Minimum Slenderness
KL_r200 = K*L*12/W_shapes.rx < 200
# remove from list sections where the live load deflection governs
W_shapes = W_shapes.loc[KL_r200]
# Major Axis Buckling
W_shapes['Fe'] = math.pi**2*E/(K*L*12/W_shapes.rx)**2 # elastic buckling stress
KL_r = 4.71*(E/Fy)**0.5 # slenderness
W_shapes['Fc'] = 0.877*W_shapes.Fe # critical stress
## Case: KL/R < KL_r
KL_r_crit = K*L*12/W_shapes.rx < KL_r # boolean
Fc_crit = Fy*0.658**(Fy/W_shapes.Fe)
W_shapes.loc[KL_r_crit, 'Fc'] = Fc_crit # replacing other critical stress
W_shapes['P'] = phi_compression*W_shapes.Fc*W_shapes.A
####
## Combined Forces (Chapter H)
####
W_shapes['P_M'] = W_shapes.axial_ult/(2*W_shapes.P) + W_shapes.moment_ult/W_shapes.M
combined_forces = W_shapes.P_M < 1
W_shapes[combined_forces]
valid_combined_shapes = W_shapes[combined_forces].sort_values(by=['A']) # all valid shapes
top_combined_shapes = valid_combined_shapes[['Shape','Ix','Zx','A','M','V','P']].head(10)
lightest_combined_shape = W_shapes.loc[W_shapes[combined_forces].W.idxmin(),'Shape'] # smallest shape
print 'Lightest shape for combined forces is: ' + lightest_combined_shape
print 'Top 10 lightest shapes for combined forces: \n' + top_combined_shapes.to_string(index=False)
print 'The selected shape for the loading: '
print W_shapes[W_shapes.Shape.isin([lightest_combined_shape])][['Shape',
'Ix','total_defl','live_defl','Zx','moment_ult','M','shear_ult','V','axial_ult','P', 'P_M']]
|
# Standard widget used to input and/or output a single line of text
# To enter multiple lines, use the Text widget
from tkinter import *
master = Tk()
e = Entry(master)
e.pack()
# To add text, use insert, but first use a delete to replace current text
# e.delete(0, END)
e.insert(0, 'a default value')
# To fetch the current value, use the get method:
s = e.get()
mainloop() |
# Labels are used to display text and images
# Uses double buffering, so it can be updated at any time without pesky flickering
# To display data for users to manipulate, one may wish to consider Canvas widgets
#
# To use a label, just specify what to display in it (text, bitmap, or image)
from tkinter import *
from PIL import Image, ImageTk
master = Tk()
longtext = 'Hello this is an awful lot of text, dont you just love how much text there is in this long text box? I know that I do, all this text, just texting everywhere, not really doing anything except being a text...'
# Basic basic call
# w = Label(master, text='Hello, world!')
# can use height or width for size, fg for text color, font to choose your font
# w = Label(master, text="Rouge", fg="red")
# w = Label(master, text="Helvetica", font=("Helvetica", 16))
# can also wrap text
w = Label(master, text=longtext, wraplength=100, anchor=W, justify=LEFT)
w.pack()
# Can also use variables for the text, label automatically updates when the text does.
v = StringVar()
Label(master, textvariable=v).pack()
# Also to do pictures, but make sure to keep a reference to the image object, otherwise it will be garbage collected
# Use a global variable or instance attribute or just add an attribute to the widget instance like so:
pachi = Image.open('pachi.png')
photo = ImageTk.PhotoImage(pachi)
x = Label(master, image=photo)
x.photo = photo
x.pack()
v.set("New Text!")
mainloop() |
# Creates an entry widget, and a button that prints the current contents
from tkinter import *
master = Tk()
e = Entry(master)
e.pack()
e.focus_set() # This sets the cursor to start here?
def callback():
print(e.get())
b = Button(master, text='get', width=10, command=callback)
b.pack()
mainloop()
e = Entry(master, width=50)
e.pack()
text = e.get() |
print("Введите 3 целых числа: ")
a = int(input ("А: "))
b = int(input ("Б: "))
c = int(input ("B: "))
while a<b:
print((a), "Пока что нет")
a=int(a + c)
if a>b:
print("Дождались",(a))
|
print("Загадай два числа")
a=int(input ("a= "))
b=int(input ("b= "))
if a==b:
print (int(a))
elif a>b:
print("Разница чисел =",int(a-b))
else:
print("Сумма чисел =", int(a+b))
|
import json
import string
#get the food_name_dataset from Vasily
#food_name_dataset is the food name
#do the demo data for a popular restaurant nearby here with a lot of review on yelp
def remove_punctuation(word = " "):
"Remove punctuation from a word if there is punctuation at the end"
punct = set(string.punctuation)
if word[-1] in punct:
return word[0:-1]
def pick_out_food(food_name_dataset, review_string = " "):
"Given a string, return the food name in the string "
word_in_review = review_string.split()
for i in range(len(word_in_review)):
word_in_review[i] = remove_punctuation(word_in_review[i])
food_in_review = []
for word in word_in_review:
if word in food_name_dataset:
food_in_review.append(word)
return food_in_review
def parse_business(business_file = " "):
"parse business json file, return the restaurants in a list"
"limit the location to dubai for now"
restaurant_dataset = []
#limit the count to 1 now
count = 1
with open(business_file) as f:
for line in f:
json_object = json.loads(line)
if "Restaurants" in json_object["categories"]:
if json_object["city"] == "Dubai":
restaurant_dataset.append(json_object)
count -= 1
if count == 0: break
print "finish parsing business_file"
return restaurant_dataset
def get_business_id(restaurant_list):
"return the business_id of the businesses from restaurant list as a list "
restaurant_business_id_dataset = []
for restaurant in restaurant_dataset:
restaurant_business_id_dataset.append(restaurant["business_id"])
return restaurant_business_id_dataset
def get_review(business_id, review_file = " "):
"get the review of the restaurants whose business id in is business_id "
review_dataset = []
with open(review_file) as f:
for line in f:
if len(review_dataset) == len(business_id): break
json_object = json.loads(line)
if json_object["business_id"] in restaurant_business_id_dataset:
review_dataset.append(json_object)
print "finish getting the review"
return review_dataset
if __name__ == '__main__':
"Yelp does not have the data of Dubai "
"zomato api and tripadvisor api are not available right now "
"will be using copy and paste from website to get data instead " "parse html would take too long "
# restaurant_dataset = parse_business("yelp_academic_dataset_business.json")
# restaurant_business_id_dataset = get_business_id(restaurant_dataset)
# review_dataset = get_review(restaurant_business_id_dataset, "yelp_academic_dataset_review.json")
|
#!/usr/bin/env python
# START STUDENT CODE HW32CFREQMAPPER
import re
import sys
# input here is p32c_results.txt
# read from standard input
for line in sys.stdin:
line = line.strip().lower()
words = line.split()
for word in words:
if word[0]< "f":
print '%s\t%s\t%s' % ("A",word, 1)
else:
print '%s\t%s\t%s' % ("B",word, 1)
print '%s\t%s\t%s' % ("A",1, 0)
print '%s\t%s\t%s' % ("B",1, 0)
# END STUDENT CODE HW32CFREQMAPPER |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.