text stringlengths 37 1.41M |
|---|
from abc import ABC, abstractmethod
class Piece:
@property
def opposite(self):
raise NotImplementedError('Should be implemented by subclasses')
class Board(ABC):
@property
@abstractmethod
def turn(self):
...
@abstractmethod
def move(self, location):
...
@property
@abstractmethod
def legal_moves(self):
...
@property
@abstractmethod
def is_won(self):
...
@property
def is_drawn(self):
return not self.is_won and len(self.legal_moves) == 0
@abstractmethod
def evaluate(self, player):
...
|
from enum import Enum
from board import Board, Piece
class TicTacToePiece(Piece, Enum):
X = 'X'
O = 'O'
E = ' '
@property
def opposite(self):
if self == self.__class__.X:
return self.__class__.O
elif self == self.__class__.O:
return self.__class__.X
else:
return self.__class__.E
def __str__(self):
return self.value
class TicTacToeBoard(Board):
def __init__(self, position=[TicTacToePiece.E] * 9, turn=TicTacToePiece.X):
self.position = position
self._turn = turn
@property
def turn(self):
return self._turn
def move(self, location):
temp_position = self.position.copy()
temp_position[location] = self._turn
return TicTacToeBoard(temp_position, self._turn.opposite)
@property
def legal_moves(self):
return [i for i in range(len(self.position)) if self.position[i] == TicTacToePiece.E]
@property
def is_won(self):
# Three row, three column, and then two diagonal checks
return self.position[0] == self.position[1] and self.position[0] == self.position[2] and self.position[0] != TicTacToePiece.E or \
self.position[3] == self.position[4] and self.position[3] == self.position[5] and self.position[3] != TicTacToePiece.E or \
self.position[6] == self.position[7] and self.position[6] == self.position[8] and self.position[6] != TicTacToePiece.E or \
self.position[0] == self.position[3] and self.position[0] == self.position[6] and self.position[0] != TicTacToePiece.E or \
self.position[1] == self.position[4] and self.position[1] == self.position[7] and self.position[1] != TicTacToePiece.E or \
self.position[2] == self.position[5] and self.position[2] == self.position[8] and self.position[2] != TicTacToePiece.E or \
self.position[0] == self.position[4] and self.position[0] == self.position[8] and self.position[0] != TicTacToePiece.E or \
self.position[2] == self.position[4] and self.position[2] == self.position[6] and self.position[2] != TicTacToePiece.E
def evaluate(self, player):
if self.is_won and self.turn == player:
return -1
elif self.is_won and self.turn != player:
return 1
else:
return 0
def __repr__(self):
return f"""{self.position[0]}|{self.position[1]}|{self.position[2]}
-----
{self.position[3]}|{self.position[4]}|{self.position[5]}
-----
{self.position[6]}|{self.position[7]}|{self.position[8]}"""
|
counter = 1
row = int(input("Input Row Number: "))
while row>26:
row = row-26
counter += 1
print(chr(ord('A')+row-1)*counter) |
print("Welcome to my program! If you put in 2 colors I will combine them for you!")
def color():
color1 = input("What is the first color?: ").lower()
color2 = input("What is the second color?: ").lower()
colorlist = ["red","orange","yellow","green","blue","purple","white","black","brown","grey"]
if color1 in colorlist:
if color2 in colorlist:
print ("Result...")
if color1 == color2:
print (color1)
elif color1 == "red":
if color2 =="yellow":
print (colorlist[1])
elif color2 =="blue":
print (colorlist[5])
elif color2 =="red":
print (colorlist[0])
elif color2 =="white":
print ("pink")
elif color2 =="black":
print (colorlist[7])
else:
print ("Combine primary colors only please!")
color()
elif color1 == "blue":
if color2 =="yellow":
print (colorlist[3])
elif color2 =="red":
print (colorlist[5])
elif color2 =="blue":
print (colorlist[4])
elif color2 =="white":
print ("sky blue")
elif color2 =="black":
print (colorlist[7])
else:
print ("Combine primary colors only please!")
color()
elif color1 =="yellow":
if color2 =="yellow":
print (colorlist[2])
elif color2 =="red":
print (colorlist[1])
elif color2 =="blue":
print (colorlist[3])
elif color2 =="white":
print ("light yellow")
elif color2 =="black":
print (colorlist[7])
else:
print ("Combine primary colors only please!")
color()
elif color1 == "white":
if color2 =="yellow":
print ("light yellow")
elif color2 =="red":
print ("pink")
elif color2 =="blue":
print ("sky blue")
elif color2 =="white":
print (colorlist[6])
elif color2 =="black":
print (colorlist[9])
else:
print ("Combine primary colors only please!")
color()
elif color1 == "black":
if color2 =="white":
print (colorlist[9])
else:
print ("Combine primary colors only please!")
color()
else:
print ("Combine primary colors only please!")
color()
else:
print ("I'm sorry,", color2, "is not in my database!")
print ("Please try again!")
color()
elif color2 in colorlist:
print ("I'm sorry,", color1, "is not in my database!")
print ("Please try again!")
color()
else:
print ("I'm sorry,", color1, "and", color2, "are not colors in my database!")
print ("Please try again!")
color()
def rgb():
print("Im still making this!")
which = input("Would you like to use RGB values or color names? ").lower()
if which == "color":
color()
elif which == "rgb":
rgb()
|
#!/usr/bin/env python3.5.2
# -*- coding: utf-8 -*-
from collections import Counter
#结果分析:
def resultType(result):
count = 0
indexNum = list()
for kk in range(len(result)):
if(result[count][result[count].argmax()]>=0.5):
index = result[count].argmax()+1 #判断最大值是否大于0.5,大于则统计,不大于则舍弃
indexNum.append(index)
count += 1
#统计分析最大值的出现次数与最大值下标,如果次数大于总结过次数的一半再减一,则返回下标,否则返回0;
index=Counter(indexNum)
if(index.__len__()!=0):
maxIndex,maxValue=index.most_common(1).pop()
if (maxValue >= len(result) / 2 - 1):
return maxIndex
else:
return 0
else:
return 0
|
'''
Faça um programa que leia um comprimento do cateto oposto e do cateto adjacente de um triângulo retangulo,
calcule e mostre o comprimento da hipotenusa.
13/01/2020
'''
from math import hypot
cateto_oposto = float(input('Digite o comprimento do cateto oposto: '))
cateto_adjacente = float(input('Digite o comprimento do cateto oposto: '))
print('O comprimento da Hipotenusa é: {:.2f}'.format(hypot(cateto_oposto, cateto_adjacente))) |
'''
Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos digitos separados.
Ex:
Digite um número: 1834
unidade: 4
dezena:3
centena:8
milhar:1
Rafael Bispo
14/01/2020
'''
numero = int(input('Digite um numero entre 0 e 9999: '))
unidade = numero // 1 % 10
dezena = numero // 10 % 10
centena = numero // 100 % 10
milhar = numero // 1000 % 10
print('Unidade: {} \nDezena: {} \nCentena: {} \nMilhar: {} '.format(unidade, dezena, centena, milhar)) |
'''
Escreva um programa que pergunte a quantidade de Km percorridos por um carro alugado e a quantidade de dias
pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$ 60 por dia e R$ 0,15 por Km Rodado.
13/01/2020
'''
km = float(input('Digite quantos Kms percorridos: '))
dias = int(input('Digite quantos dias carro esta alugado: '))
preco = (dias * 60) + (km * 0.15)
print('O carro andou durante {} dias, {} Kms, o preço total é R$ {:.2f}'.format(dias, km, preco)) |
'''
Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar 80 Km/h. mostre uma mensagem dizendo que ele
foi multado. A multa vai custar R$ 7,00 por cada Km acima do limite.
Rafael Bispo
14/01/2020
'''
velocidade = float(input('Informa a velocidade do carro: '))
if velocidade > 80:
kmAcima = velocidade - 80
print('Você foi multado por esta á {} Km/h o valor da multa é de R$ {:.2f}.'.format(velocidade, kmAcima * 7))
print('Digija sempre com conciência')
print('\nFIM')
|
def positiveInt(value):
vallist = list(range(10, 0, -1))
for num in vallist:
if value % num == 0:
print(num)
else:
print('Nope')
print(positiveInt(10))
|
def returnThree(x): # define our function
return x[0:3] # What do we want our function to do?
ask = input("Please enter a long word: ") # User prompt
value = returnThree(ask) # apply function to prompted value
if len(ask) < 3: # conditions for printing
print("too tiny")
else:
print("Here are the first three letters: ", value)
|
''' write a function that excepts a parameter as a
string and compute the average length of all the words in the string'''
def average(string):
table = str.maketrans(',.?!@#$%^&*', '***********') # replace all punctuation with one value
string = string.translate(table) # applies the translate based on the table
string1 = string.replace('*', '') # replaces * with a NULL string and removes all puntuation
list1 = string1.split() # split string into a list by space
aveList = [] # initiates a NULL list
for word in list1: # for loop for checking each word in the list
aveList.append(len(word)) # add the length of each word in the list
return [sum(aveList)/len(aveList)] # add all the list contents and divide by how many there is
print(average('This is the test data to be used for the forth assignment.')) # test sentence
print(average('Does... this? work&&')) # example 1
print(average('a sample sentence')) # example 2
print(average('@@@@I ^LOVE..**# PYTHON,,,')) # example 3
|
hours = eval(input("Enter hours driven (> 0): "))
avSpeed = eval(input("Enter average speed (> 0): "))
# Formula is d = x*t where x is speed & t is time
if hours <= 0 or avSpeed <= 0:
print("This is an invalid value, Please enter a positive value.")
else: print("Hours driven: " , hours , ", ", "Average Speed: " , avSpeed, " and Distance Traveled: ", (hours*avSpeed))
|
'''
While - indefinite loop
write a function that prompts the user to enter cities and appends to a list
and stops when a null string is entered/just hiting enter
'''
def cities():
lst = []
city = input("Enter a city (NULL to stop): ")
while city != '':
lst.append(city)
city = input("Enter a city (NULL to stop): ")
return lst
print(cities())
|
import math
def perimeter(radius):
return 2 * math.pi * radius # formula: 2*pi*r
rad = eval(input("Enter a value: "))
print(perimeter(rad))
|
'''
Rock - Paper - Scissors Function
Rules:
a. Rock always beats Scissors (rock dulls scissors)
b. Scissors always beats Paper (scissors cut paper)
c. Paper always beats Rock (paper covers rock)
'''
def rps(choice1, choice2):
if choice1 == 'R' and choice2 == 'S':
print("Player 1 is the round winner")
elif choice1 == 'P' and choice2 == 'R':
print("Player 1 is the round winner")
elif choice1 == 'S' and choice2 == 'P':
print("Player 1 is the round winner")
elif choice1 == choice2:
print("This is a tie round")
else:
print("Player 2 is the round winner")
keepPlaying = input("Would you like to play Rock, Paper, Scissors? (y to continue) ")
possibleResponses = ['y', 'Y', 'yes', 'Yes', 'OK']
player1Counter = 0
player2Counter = 0
gameTie = 0
while keepPlaying in possibleResponses:
player1 = input("Player 1, enter R, P, S: ")
player2 = input("Player 2, enter R, P, S: ")
keepPlaying = input("Do you still want to play? ")
if player1 == 'R' and player2 == 'S':
player1Counter += 1
print(rps(player1, player2))
elif player1 == 'P' and player2 == 'R':
player1Counter += 1
print(rps(player1, player2))
elif player1 == 'S' and player2 == 'P':
player1Counter += 1
print(rps(player1, player2))
elif player1 == player2:
gameTie += 1
print(rps(player1, player2))
else:
player2Counter += 1
print(rps(player1, player2))
print("Player 1 won {} times\nPlayer 2 won {} times \nThere were {} ties.".format(player1Counter, player2Counter, gameTie))
|
''' don't need address directory if both the .py program and the text file
are in the same directory'''
def numChars(filename):
infile = open(filename, 'r') # 'r' is default & can be left off
content = infile.read() # read the whole file to the console
infile.close() # always close your file
return len(content)
print(numChars('example.txt'))
|
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
"""
General method for preprocessing any dataset in the best way posible in a generalized way.
The steps done are:
1. Fix missing values
2. Normalize categorical data
3. Normalize all data to the same numerical domain
"""
def preprocess(dataset):
dataset = fix_na(dataset)
dataset = fix_categorical(dataset)
dataset = normalize(dataset)
return dataset
"""
Fixes missing values for all the columns of the given DataFrame.
"""
def fix_na(dataset):
for column in dataset:
# Get not None data to check its type
i = 0
while dataset[column][i] is None:
i = i+1
# Check type
# If it's float the we compute mean and we assign it to NA values
if isinstance(dataset[column][i], float):
col_mean = dataset[column].mean(skipna=True)
dataset[column] = dataset[column].fillna(col_mean)
else:
col_moda = dataset[column].mode()
dataset[column] = dataset[column].fillna(col_moda[0])
return dataset
"""
Normalizes categorical data by separating categories into different columns of 0s and 1s.
"""
def fix_categorical(dataset):
dataset = pd.get_dummies(dataset, dtype=float)
return dataset
"""
Normalizes dataset by putting all numeric data into same scale of values (domain of values).
"""
def normalize(dataset):
scaler = MinMaxScaler()
dataset[list(dataset.columns.values)] = scaler.fit_transform(dataset)
return dataset
|
# name = input()
# print('Enter name')
# age = input()
# print('Enter age')
# if name == 'Alice':
# print('Hi, Alice')
# elif age < 12:
# print('You are not Alice, kidddo')
# else:
# print('You are a nobody')
# name = 'Bob'
# age = 5
# if name == 'Alice':
# print('Hi Alice')
# elif age < 12:
# print('You are not Alice, kiddo.')
# print('Enter Name:')
# name = input()
# print('Enter Age:')
# age = int(input())
# if name == 'Alice':
# print('Hi, Alice.')
# elif age < 12:
# print('You are not Alice, kiddo.')
# elif age > 100:
# print('You are not Alice, grannie.')
# elif age > 2000:
# print('Unlike you, Alice is not an undead, immortal vampire.')
# spam = 0
# while spam < 5:
# print('Hello World')
# spam = spam + 1
# name = ''
# while name != 'Your Name':
# print('Enter Your Name')
# name = input()
# print('Thank You')
########
# while breakTime != True:
# breakTime = False
# print('Enter Your Name:')
# name = input()
# if name == 'Your name':
# breakTime = True
# print('Thanks')
#################
# import random
# for i in range(5):
# print(random.randint(1,10))
#################
# import sys
# while True:
# print('Type exit to exit.')
# response = input()
# if response == 'exit':
# sys.exit()
# print('You typed ' + response + '.')
# for i in range(1,11):
# print(i)
i = 1
while i < 11:
print(i)
i = i + 1 |
def printInvites(glist):
print "--**--"
for g in glist:
print "Welcome "+ g
print "--**--"
guestList = ['Mike Butterworth','Mark Carson','Kiet Pham']
#print guestList
printInvites(guestList)
print "Kiet cant make it :("
del guestList[2]
#print guestList
printInvites(guestList)
print "Sid will be invited instead :)"
guestList.append("Sid Paliwal")
#print guestList
printInvites(guestList)
print "Invite family first"
guestList.insert(0,"Dad")
guestList.insert(2,"Sam")
#print guestList
printInvites(guestList)
print guestList.__len__()
print "Too many guests! Remove until two left"
for i in guestList:
#print guestList.__len__()
#print guestList.pop()
guestList.pop()
if guestList.__len__() == 2:
#print "Loop "+ str(guestList.__len__())
break
printInvites(guestList)
|
# Understanding functions
def print_student(salutation,fname,lname):
print(salutation + ' ' + fname + ' ' + lname)
def default_print_student(fname,lname,salutation='Mr.'):
"""Non-default parameter preceed default parameters"""
print(salutation + ' ' + fname + ' ' + lname)
#Positional arguements
print_student('Mr','Rahul','Tekchandani')
#Keyword arguements
print_student(salutation='Mr',fname='Rahul',lname='Tekchandani')
print_student(salutation='Mr',lname='Tekchandani',fname='Rahul')
#Default arguements
default_print_student(fname='Rahul',lname='Tekchandani')
default_print_student(fname='Rahul',lname='Tekchandani',salutation='Dr.')
# Understanding functions with return values
def get_formatted_student(salutation,fname,lname,middle=''):
if middle:
fullname = salutation + ' ' + fname + ' ' + middle + ' ' + lname
else:
fullname = salutation + ' ' + fname + ' ' + lname
return fullname.upper()
studentname = get_formatted_student('Mr','Rahul','Tekchandani')
print(studentname)
studentname = get_formatted_student('Mr','Rahul','Tekchandani',middle='Anil')
print(studentname)
def build_addressbk(fname,lname,city=''):
person={'firstname':fname,'lastname':lname}
if city:
person['city'] = city
return person
person = build_addressbk('neha','valeja','charlotte')
print(person)
person = build_addressbk('natasha','tekchandani','charlotte')
print(person)
|
import sys
ALPHABET_SIZE = 26
def getKey(keyword, count):
"""Calculating positions to shift in plain text for a particular letter according to"""
"""the KEYWORD and amount of alphabetical letters passed in the plain text (COUNT)"""
count %= len(keyword)
return ord(keyword[count]) - ord('a') if keyword[count].islower() else ord(keyword[count]) - ord('A')
# Check proper usage
if len(sys.argv) != 2 or not sys.argv[1].isalpha():
print("Usage: python vigenere.py KEYWORD, where KEYWORD is a non-zero sequence of alphabetical characters")
sys.exit(1)
# Get the key
keyword = sys.argv[1]
# Get the plain text from user
text = input("plaintext: ")
print("ciphertext: ", end="")
count = 0
# Calculate the cipher text and print it out char by char
for c in text:
if c.isalpha():
if c.islower():
c = chr((ord(c) - ord('a') + getKey(keyword, count)) % ALPHABET_SIZE + ord('a'))
else:
c = chr((ord(c) - ord('A') + getKey(keyword, count)) % ALPHABET_SIZE + ord('A'))
count += 1
print(c, end="")
# Print a newline
print()
|
import unittest
def num_squares(n):
squares = []
i = p = 1
while p <= n:
squares.append(p)
i += 1
p = pow(i, 2)
squares.reverse()
from collections import OrderedDict
lasts = OrderedDict({n:0})
while lasts:
last, c = lasts.popitem(last=False)
#last = lasts.keys()[0]
#c = lasts.pop(last)
for i in squares:
if last == i:
return c+1
elif last > i and last-i not in lasts:
lasts[last - i] = c+1
return least
def num_squares_their(n):
if n < 2:
return n
lst = []
i = 1
while i * i <= n:
lst.append( i * i )
i += 1
cnt = 0
toCheck = {n}
while toCheck:
cnt += 1
temp = set()
for x in toCheck:
for y in lst:
if x == y:
return cnt
if x < y:
break
temp.add(x-y)
toCheck = temp
return cnt
class tests(unittest.TestCase):
def test_12(self):
self.assertEqual(num_squares(12), 3)
def test_13(self):
self.assertEqual(num_squares(13), 2)
def test_6255(self):
self.assertEqual(num_squares(6255), 4)
def test_427(self):
self.assertEqual(num_squares(427), 3)
def test_162(self):
self.assertEqual(num_squares(162), 2)
def test_7691(self):
self.assertEqual(num_squares(7691), 3)
def test_8935(self):
self.assertEqual(num_squares(8935), 4)
unittest.main()
|
#
#
def dfs(graph, s, t=None):
"""
:param graph:
:param t:
:return:
"""
stack = [s]
visited = set()
traversal = []
while stack:
n = stack[-1]
stack = stack[:-1]
if n not in visited:
traversal.append(
n
) # you can olways return visited instead but there traversal keeps the order
visited.add(n)
if n == t:
return traversal
for c in graph[n]:
if c not in visited:
stack.append(c)
return traversal
import unittest
class Tests(unittest.TestCase):
def setUp(self):
self.graph = {
"A": ["B", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F"],
"D": ["B"],
"E": ["B", "F"],
"F": ["C", "E"],
}
def test_01(self):
self.assertEqual(dfs(self.graph, "A"), ["A", "C", "F", "E", "B", "D"])
def test_02(self):
self.assertEqual(dfs(self.graph, "A", "E"), ["A", "C", "F", "E"])
unittest.main()
|
#
# #206 Reverse Linked List
from leetcode import ListNode, linked_list_to_list, list_to_linked_list
class Solution(object):
def reverseList_mine(self, head):
queue = []
n = head
while n:
queue.append(n)
n = n.next
i = 0
j = len(queue) - 1
h = queue[0]
while i < j:
queue[i].next = queue[j].next
queue[j].next = queue[i].next
if i == 0:
h = queue[j]
else:
queue[i - 1].next = queue[j]
queue[j - 1].next = queue[i]
tmp = queue[i]
queue[i] = queue[j]
queue[j] = tmp
i += 1
j -= 1
if i == j and i != 0:
queue[i - 1].next = queue[i]
elif i > j:
queue[j].next = queue[i]
if i + 1 < len(queue):
queue[i].next = queue[i + 1]
else:
queue[i].next = None
return h
def reverseList(self, head):
prev = None
curr = head
while curr:
tmp = curr.next
curr.next = prev
prev = curr
curr = tmp
return prev
import unittest
class Tests(unittest.TestCase):
def setUp(self):
self.s = Solution()
def test_00(self):
self.assertEqual(
linked_list_to_list(self.s.reverseList(list_to_linked_list([1]))), [1]
)
def test_01(self):
self.assertEqual(
linked_list_to_list(
self.s.reverseList(list_to_linked_list([1, 2, 3, 4, 5]))
),
[5, 4, 3, 2, 1],
)
def test_02(self):
self.assertEqual(
linked_list_to_list(
self.s.reverseList(list_to_linked_list([1, 3, 2, 4, 6, 7]))
),
[7, 6, 4, 2, 3, 1],
)
def test_03(self):
self.assertEqual(
linked_list_to_list(self.s.reverseList(list_to_linked_list([1, 2]))), [2, 1]
)
unittest.main()
|
# 16. 3Sum Closest
#
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:param nums: List[int]
:param target: int
:return: int
"""
nums.sort()
k = 0
closest = None
len_nums = len(nums)
while k < len_nums:
two_sum_tgt = target - nums[k]
i = k + 1
j = len_nums - 1
while i < j:
two_sum = nums[i] + nums[j]
gap = abs(two_sum_tgt - two_sum)
if closest is None:
closest = (two_sum + nums[k], gap)
elif gap < closest[1]:
closest = (two_sum + nums[k], gap)
if two_sum < two_sum_tgt:
i += 1
elif two_sum > two_sum_tgt:
j -= 1
else:
return target
k += 1
return closest[0]
import unittest
class Tests(unittest.TestCase):
def setUp(self):
self.s = Solution()
def test_01(self):
self.assertEqual(self.s.threeSumClosest([-1,2,1,4], 1), 2)
def test_02(self):
self.assertEqual(self.s.threeSumClosest([0,1,2], 3), 3)
unittest.main() |
#1st
#name = "Harry"
#print(name[0])
# ----------------
# 2nd
#names = ["Harry", "Ron", "Ahmed"]
#print(names)
#print(names [0])
# 3th
cordinateX = 10.0
cordinateY = 20.0
cordinate = (10.0, 20.0)
#-------------------
# Data Structure
# list --> sequence of mutable values
# tuple --> sequence of immutable vaules
# set --> collection of unique values
# dict --> collection of key-value pairs.
|
# Uses python3
import sys
def get_optimal_value(capacity, weights, values):
value = 0.
vwr = []
if max(values)*capacity == 0:
return 0.0
for i in range(len(weights)):
vwr.append([values[i],weights[i],float(values[i]/weights[i])])
sorted_vwr = sorted(vwr, key = lambda ratio: ratio[2], reverse = True)
for i in range(len(sorted_vwr)):
item_weight = min(sorted_vwr[i][1], capacity)
value += item_weight*sorted_vwr[i][2]
capacity -= item_weight
return value
if __name__ == "__main__":
data = list(map(int, sys.stdin.read().split()))
n, capacity = data[0:2]
values = data[2:(2 * n + 2):2]
weights = data[3:(2 * n + 2):2]
opt_value = get_optimal_value(capacity, weights, values)
print("{:.10f}".format(opt_value))
|
# Uses python3
import sys
def get_change(n):
tens = n//10
fives = (n - tens*10)//5
ones = n%5
n = tens + fives + ones
return n
if __name__ == '__main__':
n = int(sys.stdin.read())
print(get_change(n))
|
from sorting import Sorting
k = 6
arr = [4,1,6,7,8,2,65,143,5]
#arr = [1]
print(arr)
if k > len(arr):
print("Error: k larger than array")
exit()
sort = 'qsel'
#sort = 'merge'
#-----------------test mergesort implementation------------------------
if sort == 'merge':
print('\nMerge-sorting...')
Sorting().mergesort(arr)
print(arr)
print('The kth smallest element is: ', arr[k-1])
#------------------test quickselect-----------------------------------
else:
print('\nQuick-selecting...')
pivot = Sorting().quickSelect(arr, k)
print(arr)
print('The kth smallest element is: ', arr[pivot])
|
# Escrever o codigo aqui
salaAtual = 1
contadorDeTentativas = 0
perdeu = False
def Escolhercaminho():
global salaAtual
global contadorDeTentativas
global perdeu
print("Voce esta na sala {}".format(salaAtual))
print("Escolha seu caminho:")
print("[1] - Caminho Vermelho")
print("[2] - Caminho Preto")
caminhoEscolhido = int(input())
contadorDeTentativas += 1
if (contadorDeTentativas == 7):
perdeu = True
if (SalaAtual == 6 and caminhoEscolhido == 1):
SalaAtual = 5
print("Nao eh possivel sair dessa sala por esse caminho")
if (caminhoEscolhido == 1):
SalaAtual+= 1
elif (caminhoEscolhido == 2):
SalaAtual += 2
else:
print("Erro nao existe esse caminho")
if (SalaAtual == 8):
print("Voce caiu em um portal portanto voce vai retornar para uma sala aleatoria")
SalaAtual = random.randint(1, 5)
print("Voce retornou para a sala {}".format(SalaAtual))
while (salaAtual < 9 and not(perdeu)):
Escolhercaminho()
else:
if perdeu: print("\n\nVoce usou mais tentativas do que podiam vc PERDEU! \n \n \n \n")
else: print("\n\nVoce conseguiu sair da dungeon com apenas {} tentativas \n \n \n \n".format(contadorDeTentativas))
|
import requests
class IRCTC:
def __init__(self):
user_input=input("""how would you like to procde?
1. enter 1 to check live train status
2.enter 2 to check pnr
3.enter 3 to check train schedule""")
if user_input=="1":
self.live_status()
elif user_input =="2":
self.pnr()
else:
self.train_schedule()
def pnr(self):
pnr_no=input("enter the pnr no.")
self.fetch_result(pnr_no)
def fetch_result(self,pnr_no):
data=requests.get("https://indianrailapi.com/api/v2/PNRCheck/apikey/9485fe667278d32f90d3337b8e025db0/PNRNumber/{}".format(pnr_no))
data=data.json()
print(data['Passangers'])
for i in data['Passangers']:
print(i['passanger'],"|",i["Booking_status"],"|",i["current_status"],"|")
def live_status(self):
train_no=input("enter the train no")
year=input("enter the year")
month=input("enter the month")
day=input("enter the day")
hello=year+month+day
self.fetch_traindata(train_no,hello)
def fetch_traindata(self,train_no,hello):
data=requests.get("https://indianrailapi.com/api/v2/livetrainstatus/apikey/9485fe667278d32f90d3337b8e025db0/trainnumber/{}/date/{}".format(train_no,hello))
data=data.json()
print(data['TrainRoute'])
for i in data['TrainRoute']:
print(i['StationName'],"|",i["ScheduleArrival"],"|",i["ActualArrival"],"|",i["ActualDeparture"],"pm")
def train_schedule(self):
train_no=input("enter the train no")
self.fetch_data(train_no)
def fetch_data(self,train_no):
data=requests.get("https://indianrailapi.com/api/v2/TrainSchedule/apikey/9485fe667278d32f90d3337b8e025db0/TrainNumber/{}".format(train_no))
data = data.json()
print(data['Route'])
for i in data['Route']:
print(i['StationName'],"|",i["ArrivalTime"],"|",i["DepartureTime"],"|",i["Distance"],"kms")
obj = IRCTC()
|
print("Hello!") #simple string printing
print(5) #print a number; doesn't requires the double inverted commas{ " " }
#defining integer variables and having matematical operations
num1=10
num2=20
print(num1+num2)
#defining float variable
x=5.5
y=5.5
print(x+y)
print(x*y)
print(x*y+y*x)
#defining string variables
greet="Hello! How are you? "
print(greet) #printing string variable
print(greet + "Hope you are good.") #printing variable with some extra string
# SPLIT
wish=greet
print(wish.split(" ")[0]) #here the desired word is printed with the help of string
print("Good:Great:Fine".split(":")[0])
print(greet+"Good:Great:Fine".split(":")[0])
|
'''---------------CS3A04: LAB 7--------------------'''
'''---------------CODE------------------------------'''
'''No user input should be done in this program'''
# 1. Create a class called TripleString
class TripleString:
# Class level constants
MIN_LEN = 1
MAX_LEN = 50
DEFAULT_STRING = "Ready, Steady, Go"
#Create the constructor method
def __init__(self, string1 = DEFAULT_STRING, string2 = DEFAULT_STRING, string3 = DEFAULT_STRING):
# class-defined instance attributes (attributes)
self.string1 = string1
self.string2 = string2
self.string3 = string3
# mutator ("Set") methods
def set_string1(self, the_mg):
if self.valid_string(the_mg):
self.string1 = the_mg
return True
else:
self.string1 = TripleString.DEFAULT_STRING
return False
def set_string2(self, the_mg):
if self.valid_string(the_mg):
self.string2 = the_mg
return True
else:
self.string2 = TripleString.DEFAULT_STRING
return False
def set_string3(self, the_mg):
if self.valid_string(the_mg):
self.string3 = the_mg
return True
else:
self.string3 = TripleString.DEFAULT_STRING
return False
# Accessor ("Set") methods
def get_string1(self):
return self.string1
def get_string2(self):
return self.string2
def get_string3(self):
return self.string3
# Helper methods
def valid_string(self, string_to_set):
if len(string_to_set) < 1 or len(string_to_set) > 50:
return False
else:
return True
def to_string(self):
master_string = ("strings are:\n\t{}\n\t{}\n\t{}\n".format(self.string1, self.string2, self.string3) )
print (master_string)
# Client
# 1. Create 4 TripleString objects
print ("#1 Create 4 TripleString objects")
triple_string_num_1 = TripleString() # Use defaults
triple_string_num_2 = TripleString("And the Raven", "never flitting", "still is sitting") # Different values for all strings
triple_string_num_3 = TripleString("Only the first string is not a default") # One string
triple_string_num_4 = TripleString("One", "Two", "Three")
#2. Immediately display all objects.
print ("\n")
print ("#2 Display all objects:")
print( ""
.format(triple_string_num_1.to_string(),
triple_string_num_2.to_string(),
triple_string_num_3.to_string(),
triple_string_num_4.to_string(),
))
#3. Mutate one or more attributes of every object.
print ("\n")
print ("#3. Mutate one or more attributes of every object")
# Set strings 1 and 2 for first object
triple_string_num_1.set_string1("And my soul from out that shadow ")
triple_string_num_1.set_string2("La la la")
# Set string 2 for second object
triple_string_num_2.set_string2('that lies floating on the floor')
# Set string 1 for third object
triple_string_num_3.set_string1("Shall be lifted")
#Set string 1 and 3 for fourth object
triple_string_num_4.set_string1("Adding another string")
triple_string_num_4.set_string3("nevermore")
#4.Display all objects a second time.
print ("\n")
print ("#4. Display all objects")
print( ""
.format(triple_string_num_1.to_string(),
triple_string_num_2.to_string(),
triple_string_num_3.to_string(),
triple_string_num_4.to_string(),
))
#5. Mutator tests
print ("\n")
print ("#5. Mutator tests:")
# Should succeed
if triple_string_num_1.set_string1("And the Raven"):
print ("Success")
else:
print ("Fail")
# Should fail
if triple_string_num_2.set_string1(""):
print ("Success")
else:
print ("Fail")
#6. Make two accessor calls to demonstrate that they work.
print ("\n")
print ("#6. Two accessor calls")
print ("Object 1, string 1:")
print (triple_string_num_1.get_string1())
print ("Object 2, string 3: ")
print (triple_string_num_2.get_string3())
'''
------------------OUTPUT----------------------------------
#1 Create 4 TripleString objects
#2 Display all objects:
strings are:
Ready, Steady, Go
Ready, Steady, Go
Ready, Steady, Go
strings are:
And the Raven
never flitting
still is sitting
strings are:
Only the first string is not a default
Ready, Steady, Go
Ready, Steady, Go
strings are:
One
Two
Three
#3. Mutate one or more attributes of every object
#4. Display all objects
strings are:
And my soul from out that shadow
La la la
Ready, Steady, Go
strings are:
And the Raven
that lies floating on the floor
still is sitting
strings are:
Shall be lifted
Ready, Steady, Go
Ready, Steady, Go
strings are:
Adding another string
Two
nevermore
#5. Mutator tests:
Success
Fail
#6. Two accessor calls
Object 1, string 1:
And the Raven
Object 2, string 3:
still is sitting
'''
|
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 10 14:29:23 2017
@author: Nilton Junior
"""
def index_power(array, n):
if n > len(array) - 1:
return -1
else:
return array[n]**n |
def checkio(str_number, radix):
result = 0
base = list(range(0, 10))
for i in range(0, len(base)):
base[i] = str(base[i])
ordA = ord('A')
ordZ = ord('Z')
for i in range(ordA, ordZ + 1):
base.append(chr(i))
base = base[0:radix]
for i in range(0, len(str_number)):
try:
temp = base.index(str_number[len(str_number) - i - 1])
except ValueError:
return -1
result += temp*radix**i
return result
|
def checkio(number):
prod = 1
num_str = str(number)
for i in num_str:
if i != '0':
prod *= int(i)
return prod
|
import sys
# sanity chekc the number of arguments
def sanity_check(argv):
if len(sys.argv) != 2:
print "Please provide only the file name"
sys.exit(0)
# take a text file and extracts the word as well as their frequency
def process_file(text_file):
word_list = {}
# read file and only keep alphabet and spaces
line = text_file.read()
line = line.replace('-', ' ')
line = line.replace('\n', ' ')
line = ''.join([i for i in line if (i.isalpha() or i == ' ')])
# for each word, if it's not empty, add it in the dictionary
for word in line.split(' '):
word = word.strip(".,!?()\{\}[]\'\"")
word = word.lower()
if word == '':
continue
if word in word_list:
word_list[word] += 1
else:
word_list[word] = 1
# sort word-frequency dictionary based on how many times they showed up
word_list = sorted(word_list.items(), key=lambda x:x[1], reverse=True)
return word_list
# print word-frequency dictionary in a nice format
def print_words(word_list):
for (k,v) in word_list:
print k+':'+str(v)
def main():
sanity_check(sys.argv);
# open the txt file if it exists
try:
text_file = open(sys.argv[1]);
except Exception as e:
print "File provided does not exist"
sys.exit(0)
word_list = process_file(text_file)
print_words(word_list)
if __name__ == '__main__':
main() |
print("Welcome to Gabriel's Function Calculator")
num1 = int(raw_input("Give me a number please: "))
num2 = int(raw_input("Give me another number please: "))
def myAddFunction(add1, add2):
sum = add1 + add2
return sum
print("Here is the sum: " + str(myAddFunction(num1, num2)))
def mySubtractFunction(sub1, sub2):
dif = sub1 - sub2
return dif
print("Here is the difference: " + str(mySubtractFunction(num1, num2)))
def myMultFunction(mult1, mult2):
product = mult1 * mult2
return product
print("Here is the product: " + str(myMultFunction(num1, num2)))
|
import sys
class Point :
def __init__(self, x_val, y_val):
self.x = x_val
self.y = y_val
def __repr__(self):
return "(%.2f, %.2f)" % (self.x, self.y)
def Read_Points_From_Command_Line_File():
points = []
number_of_args = len(sys.argv)
file = open(sys.argv[1],"r")
for line in file:
line.strip()
x_y = line.split(" ")
points.append(Point(float(x_y[0]),float(x_y[1])))
return points
def Write_to_File(filename, s):
output = open(filename ,'w')
output.write(str(s))
output.write('\n')
list = Read_Points_From_Command_Line_File()
print(list)
Write_to_File("output.txt", list)
|
name = input("What's your name?\n")
print("hello, " + str(name)) |
# import modules to read csv file
import os # module for path in different OS systems
import csv # module for csv files
# file path
election_csv = os.path.join('Resources', 'election_data.csv')
# create Lists and Dictionary to store data
voters = []
# dictionary to store candidate name as key and votes as value
candidates_with_votes = {}
# open csv file
with open(election_csv) as csvfile:
# Split the data on commas
csvreader = csv.reader(csvfile, delimiter=',')
# if header row exist
header = next(csvreader)
# read each row of data
for row in csvreader:
# iterate through each row and append to new lists
voters.append(row[0])
# A complete list of candidates who received votes and the total number of votes each candidate won
if row[2] not in candidates_with_votes:
candidates_with_votes[row[2]] = 1
else:
candidates_with_votes[row[2]] += 1
# The total number of votes
total_votes = len(voters)
# The winner of the election based on popular vote
winner = max(candidates_with_votes, key=candidates_with_votes.get)
#------- Print the Analysis to the Terminal ------------
print(30*'-')
print('Election Results')
print(30*'-')
print(f"Total Votes: {total_votes}")
print(30*'-')
for x, y in candidates_with_votes.items():
print(f"{x}: "+"{:.3%}".format((candidates_with_votes[x] / total_votes)) +f" ({y})")
print(30*'-')
print(f"Winner: {winner}")
print(30*'-')
#------- Export the results to a text file ------------
# Set variable for output file
output_file = os.path.join('Analysis', 'election_final.txt')
# Open the output file for writing into it
with open(output_file, 'w') as txt_file:
# writing data to a file
txt_file.write(30*'-')
txt_file.write('\nElection Results \n')
txt_file.write(30*'-')
txt_file.write(f"\nTotal Votes: {total_votes}\n")
txt_file.write(30*'-'+'\n')
for x, y in candidates_with_votes.items():
txt_file.write(f"{x}: "+"{:.3%}".format((candidates_with_votes[x] / total_votes)) +f" ({y})\n")
txt_file.write(30*'-')
txt_file.write(f"\nWinner: {winner}\n")
txt_file.write(30*'-')
|
from sys import argv
def get_next(nums1, p1, nums2, p2):
less_than = -1
if p1 < len(nums1) and p2 < len(nums2):
if nums1[p1] < nums2[p2]:
less_than = nums1[p1]
p1 += 1
else:
less_than = nums2[p2]
p2 += 1
elif p1 < len(nums1):
less_than = nums1[p1]
p1 += 1
elif p2 < len(nums2):
less_than = nums2[p2]
p2 += 1
return float(less_than), p1, p2
def findMedianSortedArrays(nums1, nums2):
half_iterations = ((len(nums1) + len(nums2)) / 2)
is_even = (len(nums1) + len(nums2)) % 2 == 0
p1 = 0
p2 = 0
while p1 + p2 < half_iterations:
curr, p1, p2 = get_next(nums1, p1, nums2, p2)
if is_even:
curr_next, p1, p2 = get_next(nums1, p1, nums2, p2)
curr = (curr_next + curr) / 2
return curr
if __name__ == "__main__":
with open (argv[1]) as fin:
for line in fin:
line = line.strip()
num1, num2, expected = line.split(',')
num1 = num1.split()
num2 = num2.split()
expected = expected.strip()
print(line)
solution = findMedianSortedArrays(num1, num2)
if str(solution) == expected:
print('success')
else:
print('failure')
print("line %s expected %s solution %s\n"%(line, expected, solution))
|
# A password is considered strong if below conditions are all met:
# It has at least 6 characters and at most 20 characters.
# It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit.
# It must NOT contain three repeating characters in a row ("...aaa..." is weak, but "...aa...a..." is strong,
# assuming other conditions are met).
# first decide if valid
# then decide changes
# 6<=length<=20
# scan ::
# hash lookup char in a row
# break aprt
# after complete scan
# did have upper? lower? digit?
def strongPasswordChecker(s: str) -> int:
return 0
|
class Vertice_P:
def __init__(self, n):
self.nome = n
self.vizinhos = list()
self.tempo_descoberta = 0
self.tempo_fim = 0
self.cor = "preto"
def add_vizinho(self, v):
nset = set(self.vizinhos)
if v not in nset:
self.vizinhos.append(v)
self.vizinhos.sort()
class Grafo_P:
vertices = {}
tempo = 0
def add_vertice(self, vertice):
if isinstance(vertice, Vertice_P) and vertice.nome not in self.vertices:
self.vertices[vertice.nome] = vertice
return True
else:
print("Erro ao registrar novo vértice.")
return False
def add_aresta(self, u, v):
if u in self.vertices and v in self.vertices:
for key, value in self.vertices.items():
if key == u:
value.add_aresta(v)
if key == v:
value.add_aresta(u)
return True
else:
return False
def print_mapa(self):
for key in sorted(list(self.vertices.keys())):
print(key
+ str(self.vertices[key].vizinhos) + " "
+ str(self.vertices[key].tempo_descoberta) + " "
+ str(self.vertices[key].tempo_fim) + " "
+ str(self.vertices[key].cor))
# Cor Vermelho = vértice atual
# Cor Preto = vértice ainda não visitado
# Cor Azul = vértice já visitado
def _buscaEmProfundidade(self, vertice):
global tempo
vertice.cor = "vermelho"
vertice.tempo_descoberta = tempo
tempo += 1
for v in vertice.vizinhos:
if self.vertices[v].cor == "preto":
self._buscaEmProfundidade(self.vertices[v])
vertice.cor = "azul"
vertice.tempo_fim = tempo
tempo += 1
def buscaEmProfundidade(self, vertice):
global tempo
tempo = 1
self._buscaEmProfundidade(vertice) |
y=int(input("enter an integer 1\n"))
x=int(input("enter an integer 2\n"))
z=int(input("enter an integer 3\n"))
if (y==x and x==z):
print("Equal")
else:
print("Not Equal")
|
#Binary search Algorithm
def BinarySearch(list1,key): #define the binary Search function
lowindex=0
highindex= len(list1)-1
found =False
while lowindex<=highindex and not found:
midelement =(lowindex+highindex)//2
if key==list1[midelement]: #checking if key matches our middle element
found=True
elif key>list1[midelement]:
lowindex=midelement+1
else:
highindex=midelement-1
if found==True:
print("element found")
else:
print("Element not Found")
list1= [1,3,14,5,12,23] #define a list
list1.sort() #sort the list
print(list1) #printing the Sorted List
key=int(input("Enter the Key to Search\n")) #Prompt the user to enter the key to search.
BinarySearch(list1,key) #calling the Binary Search Function |
"""Functions used for processing the results of the optimisation runs and
plotting them.
"""
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import StrMethodFormatter
from scipy.stats import median_absolute_deviation, wilcoxon
from statsmodels.stats.multitest import multipletests
from .. import test_problems
def get_colors(crange, cmap_name="rainbow"):
"""Returns the named colour map"""
cmap = getattr(plt.cm, cmap_name)
return cmap(crange)
def process_results(
results_dir, problem_names, method_names, budget=250, exp_no_start=1, exp_no_end=51
):
"""Processes the optimisation runs and returns a dictionary of results.
The function reads attempts to read in npz files in the ``results_dir``
directory that match the mask:
f'{problem_name:}_{run_no:}_{budget:}_{method_name:}.npz',
where problem_name is each of the problem names in ``problem_names``,
method_name is each of the methods in ``method_names``, and
run_no is in the range [exp_no_start, exp_no_end].
It returns a dictionary of the form:
results[problem_name][method_name] = Y, numpy.npdarray (N_EXPS, budget)
where and N_EXPS = exp_no_end - exp_no_start + 1.
The numpy.ndarray contains the minimum seen expensive function evaluations
from each optimisation run in its rows, such that Y[i, j] >= Y[i, k] for
optimisation runs 'i' and elements 'j' and 'k'.
"""
# results[problem_name][method_name] = array of shape (N_EXPS, budget)
results = {}
for problem_name in problem_names:
results[problem_name] = {}
# load the problem
f_class = getattr(test_problems, problem_name)
f = f_class()
f_yopt = f.yopt
for method_name in method_names:
D = np.zeros((exp_no_end - exp_no_start + 1, budget))
# get the raw results for each problem instance
for i, run_no in enumerate(range(exp_no_start, exp_no_end + 1)):
fn = f"{problem_name:}_{run_no:}_{budget:}_{method_name:}.npz"
filepath = os.path.join(results_dir, fn)
try:
with np.load(filepath, allow_pickle=True) as data:
Ytr = np.squeeze(data["Ytr"])
D[i, : Ytr.size] = Ytr
if Ytr.size != budget:
print(
f"{fn:s} not enough function evaluations: "
+ f"{Ytr.size:d} ({budget:d})"
)
D[i, Ytr.size :] = Ytr[-1]
except Exception as e:
print(fn)
print(e)
# calculate the absolute distance to the minima
D = np.abs(D - f_yopt)
# calculate the best (lowest) value seen at each iteration
D = np.minimum.accumulate(D, axis=1)
results[problem_name][method_name] = D
return results
def plot_convergence(
data,
problem_names,
problem_names_for_paper,
problem_logplot,
method_names,
method_names_for_paper,
LABEL_FONTSIZE,
TITLE_FONTSIZE,
TICK_FONTSIZE,
LEGEND_FONTSIZE,
save=False,
):
for problem_name, paper_problem_name, logplot in zip(
problem_names, problem_names_for_paper, problem_logplot
):
# load the problem
f_class = getattr(test_problems, problem_name)
f = f_class()
dim = f.dim
D = {"yvals": [], "y_labels": [], "xvals": [], "col_idx": []}
method_to_col = {}
col_counter = 0
for method_name, paper_method_name in zip(method_names, method_names_for_paper):
res = data[problem_name][method_name]
# take into account the fact the first 2 * dim points are LHS
# so we start plotting after it
xvals = np.arange(2 * dim + 1, res.shape[1] + 1)
res = res[:, 2 * dim :]
D["yvals"].append(res)
D["y_labels"].append(paper_method_name)
D["xvals"].append(xvals)
if method_name not in method_to_col:
method_to_col[method_name] = col_counter
col_counter += 1
D["col_idx"].append(method_to_col[method_name])
# create total colour range
colors = get_colors(np.linspace(0, 1, col_counter))
# plot!
fig, ax = plt.subplots(1, 1, figsize=(8, 5), sharey=False)
results_plot_maker(
ax,
D["yvals"],
D["y_labels"],
D["xvals"],
D["col_idx"],
xlabel="Function Evaluations",
ylabel="Regret",
title="{:s} ({:d})".format(paper_problem_name, dim),
colors=colors,
LABEL_FONTSIZE=LABEL_FONTSIZE,
TITLE_FONTSIZE=TITLE_FONTSIZE,
TICK_FONTSIZE=TICK_FONTSIZE,
semilogy=logplot,
use_fill_between=True,
)
if save:
fname = f"convergence_{problem_name:s}.pdf"
plt.savefig(fname, bbox_inches="tight")
plt.show()
# create separate legend image
fig, ax = plt.subplots(1, 1, figsize=(19, 1), sharey=False)
results_plot_maker(
ax,
D["yvals"],
D["y_labels"],
D["xvals"],
D["col_idx"],
xlabel="Function Evaluations",
ylabel="Regret",
title="",
colors=colors,
LABEL_FONTSIZE=LABEL_FONTSIZE,
TITLE_FONTSIZE=TITLE_FONTSIZE,
TICK_FONTSIZE=TICK_FONTSIZE,
semilogy=True,
use_fill_between=False,
)
legend = plt.legend(
loc=3,
framealpha=1,
frameon=False,
fontsize=LEGEND_FONTSIZE,
handletextpad=0.25,
columnspacing=1,
ncol=9,
)
# increase legend line widths
for legobj in legend.legendHandles:
legobj.set_linewidth(5.0)
# remove all plotted lines
for _ in range(len(ax.lines)):
ax.lines.pop(0)
fig.canvas.draw()
bbox = legend.get_window_extent()
bbox = bbox.from_extents(*[bbox.extents + np.array([-5, -5, 5, 5])])
bbox = bbox.transformed(fig.dpi_scale_trans.inverted())
if save:
fname = "convergence_LEGEND.pdf"
fig.savefig(fname, dpi="figure", bbox_inches=bbox)
plt.show()
def plot_convergence_combined(
data,
problem_names,
problem_names_for_paper,
problem_logplot,
method_names,
method_names_for_paper,
LABEL_FONTSIZE,
TITLE_FONTSIZE,
TICK_FONTSIZE,
save=False,
):
N = len(problem_names)
fig, ax = plt.subplots(N // 2, 2, figsize=(16, 4 * N // 2), sharex="all")
for a, problem_name, paper_problem_name, logplot in zip(
ax.flat, problem_names, problem_names_for_paper, problem_logplot
):
# load the problem
f_class = getattr(test_problems, problem_name)
f = f_class()
dim = f.dim
D = {"yvals": [], "y_labels": [], "xvals": [], "col_idx": []}
method_to_col = {}
col_counter = 0
for method_name, paper_method_name in zip(method_names, method_names_for_paper):
res = data[problem_name][method_name]
# take into account the fact the first 2 * dim points are LHS
# so we start plotting after it
xvals = np.arange(2 * dim + 1, res.shape[1] + 1)
res = res[:, 2 * dim :]
D["yvals"].append(res)
D["y_labels"].append(paper_method_name)
D["xvals"].append(xvals)
if method_name not in method_to_col:
method_to_col[method_name] = col_counter
col_counter += 1
D["col_idx"].append(method_to_col[method_name])
# create total colour range
colors = get_colors(np.linspace(0, 1, col_counter))
# only the bottom row should have x-axis labels
if problem_name in problem_names[-2:]:
xlabel = "Function Evaluations"
else:
xlabel = None
# only the left column should have y-axis labels
if problem_name in problem_names[::2]:
ylabel = "Regret"
else:
ylabel = None
results_plot_maker(
a,
D["yvals"],
D["y_labels"],
D["xvals"],
D["col_idx"],
xlabel=xlabel,
ylabel=ylabel,
title="{:s} ({:d})".format(paper_problem_name, dim),
colors=colors,
LABEL_FONTSIZE=LABEL_FONTSIZE,
TITLE_FONTSIZE=TITLE_FONTSIZE,
TICK_FONTSIZE=TICK_FONTSIZE,
semilogy=logplot,
use_fill_between=True,
)
# ensure labels are all in the same place!
a.get_yaxis().set_label_coords(-0.08, 0.5)
plt.subplots_adjust(left=0, right=1, bottom=0, top=1, wspace=0.1, hspace=0.14)
if save:
probs = "_".join(problem_names)
fname = f"convergence_combined_{probs:s}.pdf"
plt.savefig(fname, bbox_inches="tight")
plt.show()
def results_plot_maker(
ax,
yvals,
y_labels,
xvals,
col_idx,
xlabel,
ylabel,
title,
colors,
LABEL_FONTSIZE,
TITLE_FONTSIZE,
TICK_FONTSIZE,
semilogy=False,
use_fill_between=True,
):
# here we assume we're plotting to a matplotlib axis object
# and yvals is a LIST of arrays of size (n_runs, iterations),
# where each can be different sized
# and if xvals is given then len(xvals) == len(yvals)
# set the labelling
ax.set_xlabel(xlabel, fontsize=LABEL_FONTSIZE)
ax.set_ylabel(ylabel, fontsize=LABEL_FONTSIZE)
ax.set_title(title, fontsize=TITLE_FONTSIZE)
for c, x, Y, Y_lbl in zip(col_idx, xvals, yvals, y_labels):
color = colors[c]
# calculate median run and upper/lower percentiles
bot, mid, top = np.percentile(Y, [25, 50, 75], axis=0)
if use_fill_between:
ax.fill_between(x, bot.flat, top.flat, color=color, alpha=0.25)
ax.plot(x, mid, color=color, label="{:s}".format(Y_lbl), lw=2)
ax.plot(x, bot.flat, "--", color=color, alpha=0.25)
ax.plot(x, top.flat, "--", color=color, alpha=0.25)
# set the xlim
min_x = np.min([np.min(x) for x in xvals])
max_x = np.max([np.max(x) for x in xvals])
ax.set_xlim([0, max_x + 1])
if semilogy:
ax.semilogy()
else:
ax.yaxis.set_major_formatter(StrMethodFormatter("{x: >4.1f}"))
ax.axvline(min_x, linestyle="dashed", color="gray", linewidth=1, alpha=0.5)
ax.tick_params(axis="both", which="major", labelsize=TICK_FONTSIZE)
ax.tick_params(axis="both", which="minor", labelsize=TICK_FONTSIZE)
def plot_boxplots(
data,
budgets,
problem_names,
problem_names_for_paper,
problem_logplot,
method_names,
method_names_for_paper,
LABEL_FONTSIZE,
TITLE_FONTSIZE,
TICK_FONTSIZE,
save=False,
):
for problem_name, paper_problem_name, logplot in zip(
problem_names, problem_names_for_paper, problem_logplot
):
# load the problem
f_class = getattr(test_problems, problem_name)
f = f_class()
dim = f.dim
D = {"yvals": [], "y_labels": [], "xvals": [], "col_idx": []}
method_to_col = {}
col_counter = 0
for method_name, paper_method_name in zip(method_names, method_names_for_paper):
res = data[problem_name][method_name]
D["yvals"].append(res)
D["y_labels"].append(paper_method_name)
if method_name not in method_to_col:
method_to_col[method_name] = col_counter
col_counter += 1
D["col_idx"].append(method_to_col[method_name])
# create total colour range
colors = get_colors(np.linspace(0, 1, col_counter))
# plot!
fig, ax = plt.subplots(1, 3, figsize=(16, 3), sharey=True)
for i, (a, budget) in enumerate(zip(ax, budgets)):
YV = [Y[:, :budget] for Y in D["yvals"]]
title = "{:s} ({:d}): T = {:d}".format(paper_problem_name, dim, budget)
y_axis_label = "Regret" if i == 0 else None
box_plot_maker(
a,
YV,
D["y_labels"],
D["col_idx"],
colors,
y_axis_label,
title,
logplot,
LABEL_FONTSIZE,
TITLE_FONTSIZE,
TICK_FONTSIZE,
)
plt.subplots_adjust(left=0, right=1, bottom=0, top=1, wspace=0.03, hspace=0.16)
if save:
fname = f"boxplots_{problem_name:s}.pdf"
plt.savefig(fname, bbox_inches="tight")
plt.show()
def box_plot_maker(
a,
yvals,
y_labels,
col_idx,
colors,
y_axis_label,
title,
logplot,
LABEL_FONTSIZE,
TITLE_FONTSIZE,
TICK_FONTSIZE,
):
data = [Y[:, -1] for Y in yvals]
medianprops = dict(linestyle="-", color="black")
bplot = a.boxplot(data, patch_artist=True, medianprops=medianprops)
if y_labels is not None:
a.set_xticklabels(y_labels, rotation=90)
for patch, c in zip(bplot["boxes"], col_idx):
patch.set(facecolor=colors[c])
a.set_ylabel(y_axis_label, fontsize=LABEL_FONTSIZE)
a.set_title(title, fontsize=TITLE_FONTSIZE)
if logplot:
a.semilogy()
else:
a.yaxis.set_major_formatter(StrMethodFormatter("{x: >4.1f}"))
a.tick_params(axis="both", which="major", labelsize=TICK_FONTSIZE)
a.tick_params(axis="both", which="minor", labelsize=TICK_FONTSIZE)
def plot_boxplots_combined(
data,
budgets,
problem_names,
problem_names_for_paper,
problem_logplot,
method_names,
method_names_for_paper,
LABEL_FONTSIZE,
TITLE_FONTSIZE,
TICK_FONTSIZE,
save=False,
):
N = len(problem_names)
fig, ax = plt.subplots(N, 3, figsize=(16, 3.5 * N), sharex="all", sharey="row")
for a, problem_name, paper_problem_name, logplot in zip(
ax, problem_names, problem_names_for_paper, problem_logplot
):
# load the problem
f_class = getattr(test_problems, problem_name)
f = f_class()
dim = f.dim
D = {"yvals": [], "y_labels": [], "xvals": [], "col_idx": []}
method_to_col = {}
col_counter = 0
for method_name, paper_method_name in zip(method_names, method_names_for_paper):
res = data[problem_name][method_name]
D["yvals"].append(res)
D["y_labels"].append(paper_method_name)
if method_name not in method_to_col:
method_to_col[method_name] = col_counter
col_counter += 1
D["col_idx"].append(method_to_col[method_name])
# create total colour range
colors = get_colors(np.linspace(0, 1, col_counter))
for i, (aa, budget) in enumerate(zip(a, budgets)):
YV = [Y[:, :budget] for Y in D["yvals"]]
title = "{:s} $({:d})$: T = {:d}".format(paper_problem_name, dim, budget)
y_axis_label = "Regret" if i == 0 else None
box_plot_maker(
aa,
YV,
D["y_labels"],
D["col_idx"],
colors,
y_axis_label,
title,
logplot,
LABEL_FONTSIZE,
TITLE_FONTSIZE,
TICK_FONTSIZE,
)
# ensure labels are all in the same place!
aa.get_yaxis().set_label_coords(-0.13, 0.5)
plt.subplots_adjust(left=0, right=1, bottom=0, top=1, wspace=0.03, hspace=0.18)
if save:
probs = "_".join(problem_names)
fname = f"boxplots_combined_{probs:s}.pdf"
plt.savefig(fname, bbox_inches="tight")
plt.show()
def plot_egreedy_comparison(
data,
budgets,
problem_names,
problem_names_for_paper,
problem_logplot,
method_names,
x_labels,
LABEL_FONTSIZE,
TITLE_FONTSIZE,
TICK_FONTSIZE,
save=False,
):
for problem_name, paper_problem_name, logplot in zip(
problem_names, problem_names_for_paper, problem_logplot
):
# load the problem
f_class = getattr(test_problems, problem_name)
f = f_class()
dim = f.dim
D = {"yvals": [], "y_labels": [], "xvals": [], "col_idx": []}
for method_name in method_names:
res = data[problem_name][method_name]
D["yvals"].append(res)
# plot!
fig, ax = plt.subplots(1, 3, figsize=(16, 3), sharey=True)
for i, (a, budget) in enumerate(zip(ax, budgets)):
YV = [Y[:, :budget] for Y in D["yvals"]]
N = len(method_names)
# offset indicies for each box location to space them out
box_inds = np.arange(N)
c = 0
for i in range(0, N, 2):
box_inds[i : i + 2] += c
c += 1
medianprops = dict(linestyle="-", color="black")
bplot = a.boxplot(
[Y[:, -1] for Y in YV],
positions=box_inds,
patch_artist=True,
medianprops=medianprops,
)
a.set_xticks(np.arange(3 * len(x_labels))[::3] + 0.5)
a.set_xticklabels(x_labels, rotation=0)
for i, patch in enumerate(bplot["boxes"]):
if i % 2 == 0:
patch.set_facecolor("g")
else:
patch.set_facecolor("r")
patch.set(hatch="//")
if budget == budgets[0]:
a.set_ylabel("Regret", fontsize=LABEL_FONTSIZE)
title = "{:s} ({:d}): T = {:d}".format(paper_problem_name, dim, budget)
a.set_title(title, fontsize=TITLE_FONTSIZE)
if logplot:
a.semilogy()
else:
a.yaxis.set_major_formatter(StrMethodFormatter("{x: >4.1f}"))
a.tick_params(axis="both", which="major", labelsize=TICK_FONTSIZE)
a.tick_params(axis="both", which="minor", labelsize=TICK_FONTSIZE)
plt.subplots_adjust(left=0, right=1, bottom=0, top=1, wspace=0.03, hspace=0.16)
if save:
fname = f"egreedy_compare_{problem_name:s}.pdf"
plt.savefig(fname, bbox_inches="tight")
plt.show()
def plot_egreedy_comparison_combined(
data,
budgets,
problem_names,
problem_names_for_paper,
problem_logplot,
method_names,
x_labels,
LABEL_FONTSIZE,
TITLE_FONTSIZE,
TICK_FONTSIZE,
save=False,
):
N = len(problem_names)
fig, ax = plt.subplots(N, 3, figsize=(16, 3.5 * N), sharex="all", sharey="row")
for a, problem_name, paper_problem_name, logplot in zip(
ax, problem_names, problem_names_for_paper, problem_logplot
):
# load the problem
f_class = getattr(test_problems, problem_name)
f = f_class()
dim = f.dim
D = {"yvals": [], "y_labels": [], "xvals": [], "col_idx": []}
for method_name in method_names:
res = data[problem_name][method_name]
D["yvals"].append(res)
for i, (aa, budget) in enumerate(zip(a, budgets)):
YV = [Y[:, :budget] for Y in D["yvals"]]
N = len(method_names)
# offset indicies for each box location to space them out
box_inds = np.arange(N)
c = 0
for i in range(0, N, 2):
box_inds[i : i + 2] += c
c += 1
medianprops = dict(linestyle="-", color="black")
bplot = aa.boxplot(
[Y[:, -1] for Y in YV],
positions=box_inds,
patch_artist=True,
medianprops=medianprops,
)
aa.set_xticks(np.arange(3 * len(x_labels))[::3] + 0.5)
aa.set_xticklabels(x_labels, rotation=0)
for i, patch in enumerate(bplot["boxes"]):
if i % 2 == 0:
patch.set_facecolor("g")
else:
patch.set_facecolor("r")
patch.set(hatch="//")
if budget == budgets[0]:
aa.set_ylabel("Regret", fontsize=LABEL_FONTSIZE)
title = "{:s} ({:d}): T = {:d}".format(paper_problem_name, dim, budget)
aa.set_title(title, fontsize=TITLE_FONTSIZE)
if logplot:
aa.semilogy()
else:
aa.yaxis.set_major_formatter(StrMethodFormatter("{x: >4.1f}"))
aa.tick_params(axis="both", which="major", labelsize=TICK_FONTSIZE)
aa.tick_params(axis="both", which="minor", labelsize=TICK_FONTSIZE)
# ensure labels are all in the same place!
aa.get_yaxis().set_label_coords(-0.11, 0.5)
plt.subplots_adjust(left=0, right=1, bottom=0, top=1, wspace=0.03, hspace=0.18)
if save:
probs = "_".join(problem_names)
fname = f"egreedy_compare_combined_{probs:s}.pdf"
plt.savefig(fname, bbox_inches="tight")
plt.show()
def create_table_data(results, problem_names, method_names, n_exps):
"""
"""
method_names = np.array(method_names)
n_methods = len(method_names)
# table_data[problem_name] = {'median', 'MAD', 'stats_equal_to_best_mask'}
table_data = {}
for problem_name in problem_names:
best_seen_values = np.zeros((n_methods, n_exps))
for i, method_name in enumerate(method_names):
# best seen evaluate at the end of the optimisation run
best_seen_values[i, :] = results[problem_name][method_name][:, -1]
medians = np.median(best_seen_values, axis=1)
MADS = median_absolute_deviation(best_seen_values, axis=1)
# best method -> lowest median value
best_method_idx = np.argmin(medians)
# mask of methods equivlent to the best
stats_equal_to_best_mask = np.zeros(n_methods, dtype="bool")
stats_equal_to_best_mask[best_method_idx] = True
# perform wilcoxon signed rank test between best and all other methods
p_values = []
for i, method_name in enumerate(method_names):
if i == best_method_idx:
continue
# a ValueError will be thrown if the runs are all identical,
# therefore we can assign a p-value of 0 as they are identical
try:
_, p_value = wilcoxon(
best_seen_values[best_method_idx, :], best_seen_values[i, :]
)
p_values.append(p_value)
except ValueError:
p_values.append(0)
# calculate the Holm-Bonferroni correction
reject_hyp, pvals_corrected, _, _ = multipletests(
p_values, alpha=0.05, method="holm"
)
for reject, method_name in zip(
reject_hyp, [m for m in method_names if m != method_names[best_method_idx]]
):
# if we can't reject the hypothesis that a technique is
# statistically equivilent to the best method
if not reject:
idx = np.where(np.array(method_names) == method_name)[0][0]
stats_equal_to_best_mask[idx] = True
# store the data
table_data[problem_name] = {
"medians": medians,
"MADS": MADS,
"stats_equal_to_best_mask": stats_equal_to_best_mask,
}
return table_data
def create_table(
table_data,
problem_rows,
problem_paper_rows,
problem_dim_rows,
method_names,
method_names_for_table,
):
"""
"""
head = r"""
\begin{table}[t]
\setlength{\tabcolsep}{2pt}
\sisetup{table-format=1.2e-1,table-number-alignment=center}
\resizebox{\textwidth}{!}{%
\begin{tabular}{l | SS| SS| SS| SS| SS}"""
foot = r""" \end{tabular}
}
\vspace*{0.1mm}
\caption{}
\label{tbl:synthetic_results}
\end{table}"""
print(head)
for probs, probs_paper, probs_dim in zip(
problem_rows, problem_paper_rows, problem_dim_rows
):
print(r" \toprule")
print(r" \bfseries Method")
# column titles: Problem name (dim).
print_string = ""
for prob, dim in zip(probs_paper, probs_dim):
print_string += r" & \multicolumn{2}{c"
# last column does not have a vertical dividing line
if prob != probs_paper[-1]:
print_string += r"|"
print_string += r"}{\bfseries "
print_string += r"{:s} ({:d})".format(prob, dim)
print_string += "} \n"
print_string = print_string[:-2] + " \\\\ \n"
# column titles: Median MAD
for prob in probs:
print_string += r" & \multicolumn{1}{c}{Median}"
print_string += r" & \multicolumn{1}{c"
# last column does not have a vertical dividing line
if prob != probs[-1]:
print_string += r"|"
print_string += "}{MAD}\n"
print_string = print_string[:-1] + " \\\\ \\midrule"
print(print_string)
# results printing
for i, (method_name, method_name_table), in enumerate(
zip(method_names, method_names_for_table)
):
print_string = " "
print_string += method_name_table + " & "
# table_data[problem_name] = {'median', 'MAD', 'stats_equal_to_best_mask'}
for prob in probs:
med = "{:4.2e}".format(table_data[prob]["medians"][i])
mad = "{:4.2e}".format(table_data[prob]["MADS"][i])
best_methods = table_data[prob]["stats_equal_to_best_mask"]
best_idx = np.argmin(table_data[prob]["medians"])
if i == best_idx:
med = r"\best " + med
mad = r"\best " + mad
elif best_methods[i]:
med = r"\statsimilar " + med
mad = r"\statsimilar " + mad
print_string += med + " & " + mad + " & "
print_string = print_string[:-2] + "\\\\"
print(print_string)
print("\\bottomrule")
print(foot)
print()
|
#! /usr/bin/env python3
table_data = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'mouse', 'goose']]
def print_table(tables):
col_widths = [0] * len(tables)
for i in range(len(tables)):
for j in range(1, len(tables[0])):
if col_widths[i] < len(tables[i][j]):
col_widths[i] = len(tables[i][j])
for i in range(len(tables[0])):
for j in range(len(tables)):
print(tables[j][i].rjust(col_widths[j]), end=' ')
print("\n")
if __name__ == '__main__':
print_table(table_data)
|
l1=[89,87,989,76,56]
l2=[8,9800,0]
def maxlist(l):
m=max(l)
print("largest number in the list: ",m)
maxlist(l1)
maxlist(l2)
|
l=[9,8,7,6,5,4,3,2,678]
m=sum(l)
print("the sum of elements of list is: ",m)
|
s=input("enter a non-empty string: ")
n=int(input("enter the index number where deletion is to take place: "))
print(s.replace(s[n],""))
|
b=0
if b:
print("value")
else:
print("falsey")
n=0
while n<10:
print(n)
n+=1
|
print("1.farhenheit to celsius")
print("2.celsius to farhenheit")
n=int(input("enter your choice: "))
if n==1:
m=int(input("enter temparature in farhenheit: "))
o=(m-32)/1.8
print("temparature in celcius: ",o)
elif n==2:
p=int(input("enter temparature in celcius: "))
q=1.8*p+32
print("temparature in farhenheit: ",q)
|
n=int(input("enter the number of terms in fibonacci series: "))
print("the fibonacci series is: ")
t1=0
t2=1
for i in range(0,n):
print(t1)
t3=t2+t1
t1=t2
t2=t3
|
import math
class PriorityQueue:
def __init__(self):
self.elements = []
def is_empty(self):
return self.size() == 0
def size(self):
return len(self.elements)
def swap_elements(self, index_first, index_last):
aux = self.elements[index_first]
self.elements[index_first] = self.elements[index_last]
self.elements[index_last] = aux
def enqueue(self, element):
if not (isinstance(element, dict)):
return
self.elements.append(element)
def is_element_greater_than_father(ix):
ix_father = math.floor((ix + 1) / 2) - 1
if ix_father < 0:
return False
return self.elements[ix]['priority'] > self.elements[ix_father]['priority']
index_aux = self.size() - 1
while (is_element_greater_than_father(index_aux)):
index_father = math.floor((index_aux + 1) / 2) - 1
self.swap_elements(index_father, index_aux)
index_aux = index_father
return element
def dequeue(self):
if self.is_empty():
return
first_index = 0
last_index = self.size() - 1
self.swap_elements(0, last_index)
elementDequeued = self.elements.pop()
def has_more_priority(ix1, ix2):
return self.elements[ix1]['priority'] > self.elements[ix2]['priority']
def sort_index_with_its_children(index_parent):
index_child_1 = (index_parent + 1) * 2 - 1
index_child_2 = (index_parent + 1) * 2
def does_elem_exist(elem_index):
return elem_index < self.size()
is_parent_the_greatest = (does_elem_exist(index_child_1)
and has_more_priority(index_parent, index_child_1)
and does_elem_exist(index_child_2)
and has_more_priority(index_parent, index_child_2))
shoud_swap_with_second_child = (does_elem_exist(index_child_2)
and has_more_priority(index_child_2, index_child_1)
and has_more_priority(index_child_2, index_parent))
shoud_swap_with_first_child = (does_elem_exist(index_child_1)
and has_more_priority(index_child_1, index_parent))
if is_parent_the_greatest:
return elementDequeued
elif shoud_swap_with_second_child:
self.swap_elements(index_parent, index_child_2)
return sort_index_with_its_children(index_child_2)
elif shoud_swap_with_first_child:
self.swap_elements(index_parent, index_child_1)
return sort_index_with_its_children(index_child_1)
else:
return elementDequeued
return sort_index_with_its_children(first_index)
def execute_quick_tests():
print("""\nQUICK TESTS:\n""")
empty_PQ = PriorityQueue()
print(empty_PQ.is_empty() == True, ': is_empty() returns True when PQ is empty')
print(empty_PQ.size() == 0, ': size() returns 0 when PQ is empty')
my_PQ = PriorityQueue()
my_PQ.enqueue({ 'value': 'Nico', 'priority': 1 })
print(my_PQ.is_empty() == False, ': is_empty() returns False when it has elements')
print(my_PQ.size() == 1, ': size() returns 1 when PQ has one element')
my_PQ.enqueue('invalidElem')
print(my_PQ.size() == 1, ': size() should be the same after enqueue invalid element')
my_PQ.enqueue({ 'value': 'Sherlock', 'priority': 4 })
print(my_PQ.size() == 2, ': size() should add +1 after enqueue valid element')
print(my_PQ.elements[0]['priority'] == 4, ': enqueue() should sort elements in one level')
my_PQ.enqueue({ 'value': 'Pepe', 'priority': 3 })
print(my_PQ.elements[2]['priority'] == 3, ': enqueue() does not sort elements if it is not needed')
my_PQ.enqueue({ 'value': 'John', 'priority': 1 })
my_PQ.enqueue({ 'value': 'Katja', 'priority': 6 })
print(my_PQ.elements[0]['priority'] == 6, ': enqueue() sorts element in two levels')
my_PQ.enqueue({ 'value': 'Sarah', 'priority': 2 })
my_PQ.enqueue({ 'value': 'Delfina', 'priority': 5 })
my_PQ.enqueue({ 'value': 'Riley', 'priority': 9 })
my_PQ.enqueue({ 'value': 'Alexa', 'priority': 8 })
my_PQ.enqueue({ 'value': 'Seven', 'priority': 7 })
print(my_PQ.elements[0]['priority'] == 9, ': enqueue() sorts element in three levels')
print(my_PQ.dequeue()['priority'] == 9, ': dequeue() returns correctly first element')
print(my_PQ.dequeue()['priority'] == 8, ': dequeue() returns correctly second element')
print(my_PQ.dequeue()['priority'] == 7, ': dequeue() returns correctly third element')
print(my_PQ.dequeue()['priority'] == 6, ': dequeue() returns correctly fourth element')
print(my_PQ.dequeue()['priority'] == 5, ': dequeue() returns correctly fifth element')
print(my_PQ.dequeue()['priority'] == 4, ': dequeue() returns correctly sixth element')
print(my_PQ.dequeue()['priority'] == 3, ': dequeue() returns correctly seventh element')
print(my_PQ.dequeue()['priority'] == 2, ': dequeue() returns correctly eighth element')
print(my_PQ.dequeue()['priority'] == 1, ': dequeue() returns correctly ninth element')
print(my_PQ.dequeue()['priority'] == 1, ': dequeue() returns correctly last element')
print(my_PQ.dequeue() == None, ': dequeue() of empty PQ should return None')
execute_quick_tests()
|
print ("\t\tThis is a python converter")
"""step one, determine what conversion to perform
step two get user input on what conversions they want
step three convert and display to ouput"""
#How many pounds are in a kilogram?
#How many miles is 1km?
# what is xMbps in KB/s?
def prompt(weight,dist,band_w):
"""this function prompts the user which type of conversion they want to make"""
pass
def weight():
"""Converts weights between pounds and kilogrammes"""
#prompt()
def kg_pounds(kg):
pounds = kg / 0.45
return pounds
def pounds_kg(pounds):
# 1 pound = 0.45kg
kg = pounds * 0.45
return kg
try:
weight_var = raw_input("1. Kg to Pounds \n2. Pounds to Kg\n3. Back to main menu\n")
if (weight_var == "1"):
print(str(kg_pounds(float(raw_input("Enter number of Kgs to convert__>")))) + "pounds")
#Consider simplifying the above function
weight()
elif (weight_var == "2"):
#pounds_kg()
print(str(pounds_kg(float(raw_input("Enter number of Pounds to convert__>")))) + "Kgs")
weight()
elif (weight_var == "3"):
main_loop()
else:
print("Please enter either 1,2 or 3")
weight()
except ValueError as err:
print("Please enter valid digits")
weight()
def km_to_mile():
# 1 km = 0.621371mi1
mile_const = 0.621371
km = int(input("enter distance in km: "))
km_to_mi = km * mile_const
print (str(km) + "km in miles is: " + str(km_to_mi) + "miles")
def mile_to_km():
#1mi = 1.60934km
km_const = 1.60934
mi = int(input("enter distance in miles: "))
mi_to_km = mi * km_const
print (str(mi) + " miles in kilometers is: " + str(mi_to_km) + "km")
def data_trans():
def mbps_KBps(mbps=0,KBps=0):
"""Converts given bandwidth value to either Mbps or to KB/s"""
# 1KB/s 0.0078125Mbps
# 1Mbps = 128KB/s
if mbps == 0 and not(KBps ==0):
mbps = KBps * 0.0078125
print( str(KBps) + " KB/s is equal to " + str(mbps) + " mbps")
elif KBps == 0 and not (mbps == 0):
KBps = 128 * mbps
print( str(mbps) + " Mbps is equal to " + str(KBps) + " KB/s")
#1Mbps = 128KB/s
#Determine what exactly the user wants to convert:
conv = raw_input(" 1. Mbps to KB/s \n 2. KB/s to Mbps \n 3. Back To Main Menu \n")
try:
if (conv == "1"):
mbps = float(raw_input("Mbps to convert to KB/s: \n Value__>"))
mbps_KBps(mbps)
if not (mbps):
print ("\n Please enter some data to convert \n")
data_trans()
#else:
elif (conv =="2"):
KBps = int(raw_input("\n KB/s to convert to Mbps: \n Value__>"))
mbps_KBps(0,KBps)
elif (conv == "3"):
main_loop()
except ValueError as err:
print("Please enter a valid response: Error code \n " + str(err))
data_trans()
#if (KBps == 0):
# print ("Please enter some data to convert")
# data_trans()
#else:
def main_loop():
"""Main program runner loop"""
finished = False
while (not finished):
print ("\n\n\t\tHello and welcome to the conversion app")
print "\n"
c_type = raw_input("What would you like to convert?\n1: Distance \n2: Weight \n3: Bandwidth \nPress \"x\" to quit\n >__")
if ("1") in c_type:
print ("Distance")
print("What would you like to convert? \n1: Kilometers to Miles \n2: Miles to Kilometers? \n3: Back to main menu\n")
dist = raw_input(">__")
if "1" in dist:
km_to_mile()
elif "2" in dist:
mile_to_km()
else:
continue
elif ("2") in c_type:
print ("Weight")
weight()
elif ("3") in c_type:
data_trans()
elif ("x") in c_type:
print("goodbye")
finished = True
break
else:
print ("Please enter 1,2,3 or x to quit")
main_loop()
|
import os
#type hint for input parameters for python >3.5
def multiplyList(aList : list, n):
j = 0
for i in aList:
aList[j] = i * n
j += 1
return aList
# lambda programming
# lbd essentially a function pointer
def transform_to_newlist(aList: list,lbd):
# apply lbd operator to each element of the list
return [lbd(x) for x in aList]
def apply_to_list(aList: list,lbd):
# apply lbd operator to each element of the list
j = 0
for i in aList:
aList[j] = lbd(i)
j += 1
return aList
def apply_to_list_v2(aList: list,lbd):
map(lbd,aList)
def genSquares(n=10):
print("Generating squares of numbers from 1 to {}".format(n))
for i in range(1,n+1):
yield i**2
def emit_lines(pattern="DSTI", originPath = "c:\temp"):
lines = []
#browses the directory called test in the current directory of execution
for dir_path, dir_names, file_names in os.walk(originPath):
#iterate over the all the files in test
for file_name in file_names:
if file_name.endswith('.txt'):
#if current file has a .txt extension
for line in open(os.path.join(dir_path, file_name)):
#open the file and load its content in memory, by providing the full file path
#open provide a collection of lines in the file
if pattern in line:
#if pattern found in line, add the line in the lines list
lines.append(line)
return lines
#now, let's divide this code into various functions yielding generators
def generate_filenames(directory="./"):
"""
generates a sequence of opened files
matching a specific extension
"""
for dir_path, dir_names, file_names in os.walk(directory):
for file_name in file_names:
if file_name.endswith('.txt'):
yield open(os.path.join(dir_path, file_name))
def cat_files(files):
"""
takes in an iterable of filenames
"""
for fname in files:
for line in fname:
yield line
def grep_files(lines, pattern=None):
"""
takes in an iterable of lines
"""
for line in lines:
if pattern in line:
yield line
class myGoodTools:
#syntaxically speaking, a method is "static" in Python if there's no "self" parameter
#attribute
#class attribute, shared by all instances of the class (static attribute in C++ / Java, etc.)
#in C++ and others, only a static method can change the value of a static attribute
#class methods don't exists in C++ etc. --> static methods
counter = 50
#making matters clear with decorators
@staticmethod
def staticmethod():
myGoodTools.counter=500
return "I am a static method"
@classmethod
def classmethod(cls): #cls is the name of the class
cls.counter = cls.counter+1
return "I am a class method: {}".format(cls.counter), cls
#instance method, no particular decorator
def method(self):
return "I am an instance method {}".format(self.counter), self |
nome = input ('qual o seu nome?')
print('ola',nome,'! Prazer em te conhecer')
print(nome,'que dia vc nasceu?')
dia = input()
print('dia',dia,'jura, e qual mes?')
mes = input()
print(nome,',se vc me falar o ano te dou um presente')
ano = input()//jgjgj
print('vc nasceu dia',dia,'do mes',mes,'e do ano',ano)
print('e seu presente é um sorriso :)')
print(':p')
|
"""
page: http://www.pythonchallenge.com/pc/def/map.html
General tips:
Use the hints. They are helpful, most of the times.
Investigate the data given to you.
Avoid looking for spoilers.
Forums: Python Challenge Forums
"""
def solution():
text = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
translated_text = translate(text)
# now apply on url
url = 'map'
answer = translate(url)
return 'http://www.pythonchallenge.com/pc/def/' + answer + '.html'
# i hope you didnt translate it by hand. thats what computers are for. doing it in by hand is inefficient and that's why this text is so long. using string.maketrans() is recommended. now apply on the url.
def translate(text):
return ''.join(letter_map(l) for l in text)
def letter_map(letter):
if letter >= 'a' and letter <= 'z':
letter_space_size = 26
translated_ltr = chr((ord(letter) - ord('a') + 2) % 26 + ord('a'))
return translated_ltr
else:
return letter
if __name__ == '__main__':
print(solution())
|
from weapon import Weapon
class Robot:
def __init__(self, name, health):
self.name = name
self.health = health
self.attack_power = 25
self.power_level = 50
self.weapon_names = ["laser cannon", "plasma rifle", "lightsaber"]
self.set_weapon()
def set_weapon(self):
loop = True
while loop is True:
answer = input(f"do you want {self.name} to have a weapon(y/n)? ")
if answer == "y":
self.users_input = input(f"using the number keys, what weapon would you like {self.name} to use: {self.weapon_names[0]}, {self.weapon_names[1]}, or {self.weapon_names[2]}\n")
while loop is True:
if self.users_input == "1":
self.weapon = Weapon(self.weapon_names[0], 50)
self.attack_power = 50
loop = False
continue
elif self.users_input == "2":
self.weapon = Weapon(self.weapon_names[1], 30)
self.attack_power = 30
loop = False
continue
elif self.users_input == "3":
self.weapon = Weapon(self.weapon_names[2], 100)
self.attack_power = 100
loop = False
continue
else:
print("please use the '1', '2', or '3' keys to make a selection")
elif answer == "n":
loop = False
continue
else:
print("please use the 'y' or 'n' keys to make a selection.")
def robo_attack(self, dino_to_attack):
dino_to_attack.health -= self.attack_power
self.power_level -= 10
|
def add(a, b):
"""Add 2 numbers"""
return a+b
def sub(a, b):
"""Substract 2 numbers"""
return a-b
|
import unittest
from collections import deque
def bfs(graph, start_node, end_node):
if start_node not in graph:
raise Exception("Start node not in graph!")
if end_node not in graph:
raise Exception("End node not in graph!")
nodes_to_visit = deque()
nodes_to_visit.append(start_node)
# Keep track of what nodes we've already visited
# so that we don't revisit them
nodes_already_seen = set([start_node])
while len(nodes_to_visit) > 0:
current_node = nodes_to_visit.popleft()
# stop when we reach the end node
if current_node == end_node:
# Found it!
return True
for neighbor in graph[current_node]:
if neighbor not in nodes_already_seen:
nodes_already_seen.add(neighbor)
nodes_to_visit.append(neighbor)
return False
# Tests
class Test(unittest.TestCase):
def setUp(self):
self.graph = {
'a': ['b', 'c', 'd'],
'b': ['a', 'd'],
'c': ['a', 'e'],
'd': ['a', 'b'],
'e': ['c'],
'f': ['g'],
'g': ['f'],
}
def test_two_hop_path_1(self):
actual = bfs(self.graph, 'a', 'e')
expected = True
self.assertEqual(actual, expected)
def test_two_hop_path_2(self):
actual = bfs(self.graph, 'd', 'c')
expected = True
self.assertEqual(actual, expected)
def test_one_hop_path_1(self):
actual = bfs(self.graph, 'a', 'c')
expected = True
self.assertEqual(actual, expected)
def test_one_hop_path_2(self):
actual = bfs(self.graph, 'f', 'g')
expected = True
self.assertEqual(actual, expected)
def test_one_hop_path_3(self):
actual = bfs(self.graph, 'g', 'f')
expected = True
self.assertEqual(actual, expected)
def test_zero_hop_path(self):
actual = bfs(self.graph, 'a', 'a')
expected = True
self.assertEqual(actual, expected)
def test_no_path(self):
actual = bfs(self.graph, 'a', 'f')
expected = False
self.assertEqual(actual, expected)
def test_start_node_not_present(self):
with self.assertRaises(Exception):
bfs(self.graph, 'h', 'a')
def test_end_node_not_present(self):
with self.assertRaises(Exception):
bfs(self.graph, 'a', 'h')
unittest.main(verbosity=2)
|
def construct_dataset(x, f):
n = len(x)
s = []
for i in range(n):
for j in range(f[i]):
s.append(x[i])
s = sorted(s)
return s
def median(x):
sz = len(x)
if sz % 2 != 0:
return x[sz // 2]
else:
return (x[sz // 2] + x[sz // 2 - 1]) / 2
def inter_quartile_range(x, f):
sz = sum(f)
# construct and output a sorted dataset
s = construct_dataset(x, f)
# separate left and right parts of dataset
sleft = [int(i) for i in s[0:sz // 2]]
if (sz % 2 == 0):
sright = [int(i) for i in s[(sz // 2):sz]]
else:
sright = [int(i) for i in s[(sz // 2) + 1:sz]]
# compute lower and upper quartiles
q1 = median(sleft)
q3 = median(sright)
# compute inter quartile range
iqr = q3 - q1
return iqr
n = int(input())
x = [int(i) for i in input().split()]
f = [int(i) for i in input().split()]
iqr = inter_quartile_range(x, f)
print(round(iqr, 1))
|
# find a researcher's h-index
# h-index: The largest number of papers h that have atleast h citations
# Input: Papers(A, B, C, D, E) and Citations (2, 4, 1, 8, 7)
# Output: 3 (corresponding to B, D, E)
# How to think about this?
# Given an array of n elements, Are there atleast h elements greater than or equal to h?
# Questions
# Can I assume array is non-empty?
# Can I assume each array element is non-negative? ( >= 0 )
def find_h_index_brute(arr):
if(sum(arr) == 0): # assuming array has no negative elements
return 0
h = 1
# check if there's 1 element greater than 1
i = 0
while(i < range(len(arr) and count == 0):
if arr[i] >= h:
count = count + 1
i = i + 1
if i == len(arr)
|
import unittest
import math
import numpy as np
def hash_scores(scores_list, max_score):
hash_array = [0] * (max_score+1)
for score in scores_list:
hash_array[score] += 1
return hash_array
def sort_scores(scores_list, max_score):
hash_array = hash_scores(scores_list, max_score)
sorted_scores = []
for i in range(max_score, -1, -1):
if(hash_array[i] > 0):
for j in range(hash_array[i]):
sorted_scores.append(i)
return sorted_scores
# Tests
class Test(unittest.TestCase):
def test_no_scores(self):
actual = sort_scores([], 100)
expected = []
self.assertEqual(actual, expected)
def test_one_score(self):
actual = sort_scores([55], 100)
expected = [55]
self.assertEqual(actual, expected)
def test_two_scores(self):
actual = sort_scores([30, 60], 100)
expected = [60, 30]
self.assertEqual(actual, expected)
def test_many_scores(self):
actual = sort_scores([37, 89, 41, 65, 91, 53], 100)
expected = [91, 89, 65, 53, 41, 37]
self.assertEqual(actual, expected)
def test_repeated_scores(self):
actual = sort_scores([20, 10, 30, 30, 10, 20], 100)
expected = [30, 30, 20, 20, 10, 10]
self.assertEqual(actual, expected)
def test_random_simulation_20_scores(self):
n = 20
scores_list = [np.random.randint(0, 100) for i in range(n)]
actual = sort_scores(scores_list, 100)
expected = sorted(scores_list, reverse=True)
self.assertEqual(actual, expected)
def test_random_simulation_100_scores(self):
n = 100
scores_list = [np.random.randint(0, 100) for i in range(n)]
actual = sort_scores(scores_list, 100)
expected = sorted(scores_list, reverse=True)
self.assertEqual(actual, expected)
def test_random_simulation_random_number_of_scores(self):
n = np.random.randint(0, 1000)
scores_list = [np.random.randint(0, 100) for i in range(n)]
actual = sort_scores(scores_list, 100)
expected = sorted(scores_list, reverse=True)
self.assertEqual(actual, expected)
unittest.main(verbosity=2)
|
n = int(input())
zero = 0
while n >= 5:
zero += n // 5
n = n // 5
print(zero)
|
from datetime import timedelta, date
# Day of Week --> Date
# DoW = day of week
# Assumes the date only gets smaller.
# e.g. querying about "Wed", "Tue", "Wed" means this Wednesday, this Tuesday...
# and the Wednesday from last week.
# Usage:
# 1. Use the factory to create a function with starting date and the DoW of that date.
# 2. Supply the DoW of the day you want to know the date.
# 3. The function returns the date.
# Tweak it to conform to date formats you use.
def calc_date_factory(start_dow, start_date):
# remember the results from the previous query
last_date = start_date
last_dow = start_dow
def calc_date(dow, skipped_weeks=0):
# binds the names to the outside variables
nonlocal last_date
nonlocal last_dow
# diff: the # of days from the desired date to now
diff = (last_dow - dow) % 7 + skipped_weeks * 7
this_date = last_date - timedelta(days=diff) # tweak this
# update states
last_date = this_date
last_dow = dow
return this_date
return calc_date
if __name__ == "__main__":
calc_date = calc_date_factory(1, date(2020, 3, 30)) # Today is Monday, 30th
l = [7, 5, 4, 4, 3, 7]
print(list(map(lambda x: calc_date(x).strftime('%d, %b %Y'), l)))
# # See the attached image to get what this does
# print(calc_date(7)) # Last Sunday (Sunday from 1 week ago) is 29th
# print(calc_date(5)) # Last Friday is 27th
# print(calc_date(4)) # Last Thursday is 26th
# print(calc_date(4)) # Same, still 26th
# print(calc_date(3)) # Last Wednesday is 25th
# # If you want to specify skipped weeks
# # Same as regular results minus (7 * skipped_weeks)
# print(calc_date(2, 1)) # Tuesday from 2 weeks ago is 17th
# print(calc_date(5, 1)) # Friday from 4 weeks ago is 6th
|
# from recommendations import critics
from math import sqrt
# Returns a distance-based similarity score for person1 and person2
def sim_distance(prefs, person1, person2):
# get the list of shared_items
si = {}
# for every movie person1 rated, if person2
# also rated it, add to si
for item in prefs[person1]:
if item in prefs[person2]:
si[item] = 1
# if no common ratings, return 0
if len(si) == 0:
return 0
# Add up the squares of all the differences
# where each axis is a movie title, and we are squaring
# the difference between points of a similar axis (movie).
# This is a huge distance formula with a lot more variables
# than just x and y.
sum_of_squares = sum([pow(prefs[person1][item] - prefs[person2][item], 2)
for item in si])
return 1 / (1 + sqrt(sum_of_squares))
# print(sim_distance(critics, 'Lisa Rose', 'Gene Seymour'))
|
name = input('Enter your name: ')
age = int(input('Enter your age: '))
if age > 19:
print('Your name is',name,'and you are an Adult')
elif age > 12:
print('Your name is', name, 'and you are a teenager')
else:
print('Your name is', name, 'and you are a kid')
|
import threading
import time
# Define a function for the thread
thread_signal = True
def wait_for_other_thread():
"""Thread needs a function to call
in this example the thread executing this
function simply waits for the global variable
to change value. Which is done by the other thread"""
while thread_signal == True:
print("still no signal at {}\n".format(time.ctime(time.time())))
time.sleep(0.1)
def send_signal():
""" global keywords is necessary to change a variable
outside of this functions namespace"""
global thread_signal
print("sender is sending")
time.sleep(1)
print("waiting is over")
thread_signal = False
# keyword target is necessary, since many more arguments could be given
# target is set to callable object
t1 = threading.Thread(target=wait_for_other_thread)
t2 = threading.Thread(target=send_signal)
# Thread.start() forces the object to execute its target()
t1.start()
t2.start()
# join() waits for the thread to finish
t1.join()
t2.join()
|
#!/usr/bin/env python
# comms.py
# Alexander Looi
# Last Modified: March 26rd, 2017
"""COMMS
This module has all the components to create, manipulate and analyze communities for
a graph. In addition to manipulating and analyzing communities this module builds graphs.
to associate with communities the user wishes to analyze and edit. Thus, this module
requires the nets.py module to run work. There is one main class:
The comms_graph object - This class allows a user to manually build communities
for a network given existing nodes in a graph. There is also an option to auto-
detect networks as well. Information on the methods within the comms_graph
class is in the the comms_graph docstring.
There are four additional functions within this module.
1) readcomms() - allows the user to read in a node to community file, or an
edge list with a third column indicating the community a node in the first column
belongs to
2) writecomms() - writes a node to community list with the option to include an
edgelist.
3) Erdos_Renyi() - creates an Erdos Renyi Graph with 'size' number of nodes and
probability 'p' of linking two nodes.
4) BlockModel() - a net work of 'n' Erdos_Renyi Graphs with probability p_in of
linking two nodes within a Erdos Renyi graph, and probability p_btwn of linking
two nodes between seperate Erdos Renyi graphs."""
import nets
from nets import Graph
import sys, os
import itertools
import csv
import random
import numpy as np
def readcomms(filename, delimiter="\t", with_graph = True):
"""Read community file
This function can read two kinds of files:
1) an edge list with another column showing the community that the first column
of nodes belongs to (the originating node of an edge in the edge list). The first
two columns are read in as an edge list and creates a graph. The third column is
read in with the first column, and builds a community of nodes according to the
communities in the third column.
2) Reads in a node to community list where the first column is the node, and the
second column the community the node belongs to. This does not build a graph,
and thus needs the 'read_edgelist' function from nets.py.
When either file type are read in two community data structures are created.
1) The NIC data structure (Node in Community). This is a dictionary, where the
dictionary key is the community name, and values associated with each community
are node names.
2) The CBN data structure (Community by node). This is another dictionary data
structure where the node is the key and the community a node belongs to is the value
for that node.
Lastly, there are 3 inputs for this function:
1) filename - the name of the file read in. This file can by an edge list
with a third column denoting the community the node in the first column
belongs to. Or it can be a node to community list. Here the first column is
node and the second column is the community the node belongs to.
2) delimiter - How data entries are seperated. All data in rows must use
the same delimiter.
3) with_graph - a boolean specifying if there is a graph attached to the
data file (i.e. is the file an edgelist with a third column specifying
communities)."""
# open the comms file
read_comms = open(filename, "r", errors="ignore")
# create a community object, stores all communities
net_com = comms_graph() # should also create a graph object
# read the data line by line. building two dictionaries.
if with_graph:
#New_Graph = nets.read_edgelist(filename, delimitedby=delimiter)
#net_com.G = New_Graph.G
# build the communities and graph
# reset the readline function back to the top
#read_comms.seek(0)
# Create a Graph "network" from class Graph()
nodes = set() # an empty set to store nodes
edge_list = [] # an edge list (list of lists)
counter = 0 # Used to count the number of commented "junk" lines
for ln, line in enumerate(read_comms):
# make sure the line is read in as a string
strline = line
# Remove any blank spaces from the front and end of the string
li=strline.strip()
# make sure lines that begin with a "#" are not read in
# make sure the line being read in does not have commented items
if li.startswith("#"):
counter = 0
else:
counter = counter + 1
# remove any spaces that may occur after the "#"
net_line = line.rstrip()
# seperate out the lines using "delimitedby"
node_edge_comm = net_line.split(delimiter)
nodes.add(node_edge_comm[0])
# initialize the first node if it's the
# first iteration/ first line actual of
# data in the network
comm = node_edge_comm[2]
node_c = node_edge_comm[0]
edge_list.append(node_edge_comm[0:2])
if counter == 1:
prev_node = node_edge_comm[0]
counter = 100
# create a node, and neighbors entry
# keep track of when the node changes
prev_node = node_edge_comm[0]
First_line = False
net_com.add_node_to_comm(comm, node_c)
# build the graph
net_com.add_nodes_from(nodes)
net_com.add_edges_from(edge_list)
net_com.build_CBN()
else:
nodes = set() # an empty set to store nodes
counter = 0 # Used to count the number of commented "junk" lines
for ln, line in enumerate(read_comms):
# make sure the line is read in as a string
strline = line
# Remove any blank spaces from the front and end of the string
li=strline.strip()
# make sure lines that begin with a "#" are not read in
# make sure the line being read in does not have commented items
if li.startswith("#"):
counter = 0
else:
counter = counter + 1
# remove any spaces that may occur after the "#"
net_line = line.rstrip()
# seperate out the lines using "delimitedby"
node_edge_comm = net_line.split(delimiter)
nodes.add(node_comm[0])
# initialize the first node if it's the
# first iteration/ first line actual of
# data in the network
comm = node_comm[1] # community
node_c = node_comm[0] # node community
if counter == 1:
prev_node = node_edge_comm[0]
counter = 100
# create a node, and neighbors entry
# keep track of when the node changes
prev_node = node_comm[0]
First_line = False
# add the node to the community
net_com.add_node_to_comm(comm, node_c)
# build the community
net_com.add_nodes_from(nodes)
net_com.build_CBN()
return(net_com)
#########################################################################################
def writecomms(Graph, filename, delimiter = "\t", edge_list = False):
"""This function takes in a graph in 'dictionary form' and
writes it to a file of text. There are three values it
requires: 1) the Graph() class or network that the user
wants written, 2) a file name for the file that will be printed,
and 3) the desired delimiter that will seperate values.
The Graph() lass is specific to this particular module.
The actual graph object in the Graph() class must be in
dictionary form. Here the nodes are dictionary keys
and values of keys are the other nodes the key node are linked
to.
The default setting will only create a node to community list. if
edge_list = True then it was print a and edge list as well as the
community that first column node belongs to.
The file name can be made up of any alpha numeric combination.
However, it must be utf-8 encoding.
The delimiter default is a tab denoted by '\t'. However,
the user can specify any utf-8 alpha-numeric character.
This does not return anything, but prints to a file through
standard out."""
network_file = open(filename, "w")
# G has to be a dictionary object
# loop through each dictionary key
if edge_list:
for n in Graph.G:
# loop through each item in a dictionary
for ne in Graph.G[n]:
comm = C.CBN[n][0]
# write each edge as a seperate line in the output file
network_file.write(''.join([n,delimiter,ne,delimiter,comm,'\n']))
# print to console to make sure things look okay
print(n,delimiter,ne)
# close the file
network_file.close()
else:
for n in Graph.nodes():
# loop through each item in a dictionary
comm = C.CBN[n][0]
# write each edge as a seperate line in the output file
network_file.write(''.join([n,delimiter,comm,'\n']))
# print to console to make sure things look okay
print(n,delimiter,ne)
# close the file
network_file.close()
#########################################################################################
class comms_graph(Graph):
"""COMMUNITY GRAPH
This suite of modules provide all the tools to build, edit, and analyze
a communities of nodes. This class inherits from Class NETS to build,
manipulate, and help with community analysis. There are two data structures
in this class
1) The NIC data structure (Node in Community). This is a dictionary, where the
dictionary key is the community name, and values associated with each community
are node names.
2) The CBN data structure (Community by node). This is another dictionary data
structure where the node is the key and the community a node belongs to is the value
for that node.
Additionally, there are several modules that allow for simple editing, building
and analysis of communities of nodes.
1) communities - returns a list of all communities within a graph
2) has_comm - returns true or false if a communities specified by the user exists.
3) node_in_comm - returns the community a node belongs to, if it doesn't belong
to a community it returns false
4) build_CBN - builds the CBN data structure from data in the NIC data structure.
5) build_NIC - builds the NIC data structure from the data in the CBN data structure.
6) add_node_to_comm - Adds a node to a community specified by the user. for both
data structures if the community doesn't exist, it is created and the user
specified node is added.
7) remove_node_from_comm - removes a node from a community from both data structures.
Does not delete or remove communities even if a community is empty.
8) remove_comm - deletes a community from both data structures regardless if
nodes are present in the community.
9) configuration_model - Builds the configuration model, a hypothetical null model
usually used to test significance to communities in a graph.
10) modularity - Calculates modularity. How well is the graph partitioned?
11) comm_part - A greedy single node or multi node algorithm, used to partition
graphs.
"""
def __init__(self):
"""INIT
1) Inherit the graph class from nets
2) Create the CBN and NIC data structures.
"""
Graph.__init__(self)
self.CBN = {} # nodes are the key, community the value.
self.NIC = {} # communities are the key, nodes the values.
############################################################
def communities(self):
"""communities()
Returns a list of communities of a graph
Needs no user input. If there are no communities associated with the graph
then the module returns false."""
communities = [] # set a list to store all communities
# loop through all communties in the dictionary
if bool(self.NIC):
return(False)
for comm in self.NIC:
# append the community name to the comms list
communities.append(comm)
# return the comms list
return(communities)
############################################################
def has_comm(self, comm):
"""has_comm(comm)
If a community is present in a graph, then return true,
else return false. There is one user specified input needed.
1) comm - community to check existance in graph."""
# check to see if there is an empty list
# if it's an empty list return false
if bool(comm):
# check to see if the commmunity exists in the comm obj
if comm in self.NIC:
return(True)
else:
# return false if the community doesn't exist
return(False)
else:
return(False)
############################################################
def node_in_comm(self, node):
"""node_in_comm(node)
Returns the community or communities that the node belongs
to. If the node does not exist as part of any community
the method will return false.
1) node - The node to search communities in the graph."""
if isinstance(node, list):
node = node[0]
if node in self.CBN:
return(self.CBN[node])
else:
return(False)
############################################################
def build_CBN(self):
"""build_CBN()
After communities as been added to the NIC data strucutre, this
builds another community reference system. CBN has nodes as the
keys in the data structure. It is recommended that you use build_CBN
only after you've finished creating communities and adding nodes
to those communities. No user input is needed because the CBN
is built through the NIC."""
self.CBN = {}
for c in self.NIC.keys():
# for each community, set the nodes as a key
# communities that nodes belong to become the
# associated values
for n in self.NIC[c]:
# when node n is in more than one community
#print(n, c)
if n in self.CBN:
self.CBN[n].append(c)
else:
# when node n is only in one community
self.CBN[n] = [c]
############################################################
def build_NIC(self):
"""build_NIC()
Build a NIC community data structure from the CBN"""
self.NIC = {}
nodes = list(self.CBN.keys())
for n in nodes:
comm = self.CBN[n][0]
if comm not in self.NIC:
self.NIC[comm] = [n]
else:
self.NIC[comm].append(n)
self.build_CBN()
############################################################
def add_node_to_comm(self, comm, node):
"""add_node_to_com(comm, node)
Add a community and populate with one node. If a community already
exists but the node being added does not exist within the community,
then just add the node. This only adds one community and node pair
at a time. There are two user inputs:
1) comm - The community to add
2) node - the node that is added to community 'comm'
"""
# check to see if the comm entry is a single entry
# if it's a list only use the first value
if isinstance(comm, list) and bool(comm):
comm = comm[0]
elif bool(comm) == False:
print("variable 'comm' is empty")
return(False)
# check to see if the node entry is a single entry
# if it's a list only use the first value
if isinstance(node, list) and bool(node):
node = node[0]
elif bool(node) == False:
print("variable 'node' is empty")
return(False)
# see if the community already exists, if it does
# add a node to the community, if it doesn't have the community
# add the community as a key and add the associated
# node to the new community
if self.has_comm(comm):
if node in self.NIC[comm]:
# check to see if the node exists in the NIC community,
# if it does, return false, for both the CBN and
# NIC data structures
self.CBN[node] = [comm]
return(False)
else:
# if the node does not exist in NIC but the community
# exists in NIC add the node to the community
self.NIC[comm].append(node)
# check to see if the community exists and if the node
# is present in the community
elif self.has_comm(comm) and node not in self.NIC[comm]:
# if the community is empty, add the node to the community
if bool(self.NIC[comm]) == False:
self.NIC[comm] = [node]
else:
# if the community has nodes in it, append the node
# to a list of nodes in the community.
self.NIC[comm].append(node)
else: # if the community does not exist add the community and node
self.NIC[comm] = [node]
# also add to the CBN data structure
# add the node and community to the CBN data structure
self.CBN[node] = [comm]
############################################################
def remove_comm(self, comm):
"""remove_comm(comm)
Removes a community from a graph from both the CBN and NIC data
structure regardless if the communities are empty. There is one
input needed.
1) comm - the community to be removed."""
# check to see if the comm var is empty
if bool(comm) == False:
print("this list is empty")
elif self.has_comm(comm):
nodes = self.NIC[comm][0]
for n in nodes:
self.CBN[n].remove(comm)
del self.NIC[comm]
else:
print(comm, "cannot be removed because it does not exist as a community")
return(False)
############################################################
def remove_node_from_comm(self, comm, node):
"""remove_node_from_comm(comm, node)
Remove a node from community that it is in. If there are no nodes
remaining in a community, the community will still remain. There are
two pieces of input needed:
1) comm - The community to look in
2) node - The node to remove from community comm."""
# check to see if node is a single char var or a list
if isinstance(node, list):
node = node[0]
if isinstance(comm, list):
comm = comm[0]
if node in self.CBN and comm in self.NIC:
print(node)
if node in self.NIC[comm]:
# the community the node to be deleted is associated with
# delete the node from the communty key
self.NIC[comm].remove(node)
# delete the community from the node key
self.CBN[node].remove(comm)
else:
print("node", node, "does not exist in community", comm)
return(False)
else:
return(False)
############################################################
def configuration_model(self):
"""configuration_model()
Build a configuration model using the degree distribution
of the current graph."""
DD = self.degree_distribution()
# build a second dictionary from DD where each node is a key
# and the value is the node's degree distribution.
keys_DD = DD.keys()
cm_DD = {}
num_edges = 0
# loop through all degrees and find all the nodes with that
# degree
for nn in keys_DD:
# grab each node with a particular degree
nodes = DD[nn]
# put that node with its degree into a dictionary where
# the node is the key, and its degree is the value
# there should only be 1 value for each key
for d in nodes:
num_edges = num_edges + nn
cm_DD[d] = [nn]
# loops through all the nodes, and randomly
# connect them with other nodes, creating a
# new randomly generated graph.
nodes = list(cm_DD.keys())
num_nodes = len(nodes)
edge_listCM = []
# create a graph and add all nodes
CMG = Graph()
CMG.add_nodes_from(nodes)
choices = list(range(0,num_nodes))
NN_remain = len(choices)
while NN_remain > 0:
#print(choices)
# randomly choose a "originating node"
pick_n1 = random.choice(choices)
node1 = nodes[pick_n1]
C_index1 = choices.index(pick_n1)
# randomly choose another node for the
# "orginating node" to connect to
# ("connecting node")
if C_index1 == len(choices)-1:
choices2 = choices[0:C_index1]
elif C_index1 == 0:
choices2 = choices[1:len(choices)+1]
else:
P1 = choices[0:C_index1]
P2 = choices[C_index1+1:len(choices)]
choices2 = P1+P2
pick_n2 = random.choice(choices2)
node2 = nodes[pick_n2]
# create an edge
edge = [node1, node2]
rev_edge = [node2, node1]
# add the node to the graph
EB1 = CMG.add_edge(edge)
#EB2 = CMG.add_edge(rev_edge)
#print(EB1, EB2)
# if the edge sets did not exist then remove a degree
# from the two randomly choosen nodes, remove a node from
# NN_remain if the degree of a node reaches 0. If
# the edge set already existed then choose another edge set
if EB1:
node_val1 = [cm_DD[node1][0]-1]
node_val2 = [cm_DD[node2][0]-1]
#print(node_val1, node_val2)
cm_DD[node1] = node_val1
cm_DD[node2] = node_val2
if cm_DD[node1][0] == 0:
#print(choices)
#print("P1", pick_n1)
#print(choices)
choices.remove(pick_n1)
if cm_DD[node2][0] == 0:
#print(choices2)
#print("P2", pick_n2)
choices.remove(pick_n2)
#print(choices)
NN_remain = len(choices)
#print(NN_remain)
#print(NN_remain, choices)
#print(cm_DD)
#num_edges = num_edges/2
#for e in num_edges:
#random.random()
#return(cm_DD)
return(CMG.G)
############################################################
def modularity(self):
"""modularity()
calculate the modularity of a graph. No user input required."""
# calculate the total number of edges in a graph "M"
M = len(self.edges())
Mat_sum = []
# loop through all nodes and all the other nodes they share a
# connection with.
nodes = self.nodes()
for n in nodes:
# edges of node "n"
N_edges = self.G[n]
# determine community of node "v"
C_v = self.CBN[n][0]
for e in nodes:
k_v = self.degree(n)[n][0]
k_w = self.degree(e)[e][0]
# determine community of node "w"
C_w = self.CBN[e][0]
# determine if the nodes share a link
edge_t = [n,e]
if self.has_edge(edge_t):
#print(edge_t)
Avw = 1
else:
Avw = 0
# determine if they are in the same community
if C_v == C_w:
delta = 1
else:
delta = 0
#print(C_v, C_w)
# compute a single element of the sum
Mat_cell = (Avw-(k_v*k_w)/(2*M))*delta
Mat_sum.append(Mat_cell)
Q = sum(Mat_sum)/(2*M)
return(Q)
############################################################
def comm_find(self, multi = False):
"""comm_find(multi=T or F)
partitions nodes in a graph using a greedy algorithm. This can either
work node by node or by groups of nodes that belong the same
community. Here we try and maximize modularity. There is one piece of
user input.
1) multi - Default False. True if the user wants the algorithm to
include groups of nodes from the same community in calculating"""
self.NIC = {}
self.CBN = {}
# get nodes and assign a single community to each
nodes = list(self.nodes())
num_nodes = [str(i) for i in range(0,len(nodes))]
node_comms = ["C" + nn for nn in num_nodes]
for nn,n in enumerate(nodes):
self.add_node_to_comm(node_comms[nn], n)
self.build_CBN()
# start at the first node_comm individual, look at all their neighbors
# and add the node to the originating community where the modularity
# increases the most.
max_m = self.modularity() # initialize max_modularity parm to optimize
for on in nodes:
neighbors = self.G[on]
org_comm = np.copy(self.CBN[on])[0]
for nv, neigh in enumerate(neighbors):
# if the neighboring node belongs to a larger community
# bring in all nodes from that community.
comm = np.copy(self.CBN[neigh])[0]
nodes_in_comm = self.NIC[comm]
num_nodes_comm = len(nodes_in_comm)
# if a node belongs to a larger community include all
# those nodes.
if num_nodes_comm > 1 and multi == True:
for cn in nodes_in_comm:
self.remove_node_from_comm(comm, cn)
self.add_node_to_comm(org_comm, cn)
# calculate the modularity
# find the node that gives the max modularity
if new_modularity > max_m:
max_node = neigh
max_m = new_modularity
remove_comm = comm
del self.NIC[remove_comm]
else:
# remove the node from its community
self.remove_node_from_comm(comm, neigh)
# add node to the originating node's community
self.add_node_to_comm(org_comm, neigh)
# Calculate the modularity of the new communities.
new_modularity = self.modularity()
# find the node that gives the max modularity
if new_modularity > max_m:
max_node = neigh
max_m = new_modularity
remove_comm = comm
del self.NIC[remove_comm]
#########################################################################################
def Erdos_Renyi(size, p):
"""Erdos_Renyi(size, p)
Create an Erdos Renyi Graph. Create a graph with 'size' number of nodes
with probability p of a connection between any two nodes. There are two
required inputs:
1) size - the size in number of nodes of the graph.
2) p - the probability p of a connection between any two nodes. p must
be a number between 0 and 1."""
# Create nodes of length size
if size < 1:
print("cannot have a network less than one node")
return(False)
numbers = list(range(1,size+1))
n_num = [str(i) for i in numbers]
all_nodes_names = ["N" + nn for nn in n_num]
# Create an Erdos Renyi graph obj
ERG = comms_graph()
ERG.add_nodes_from(all_nodes_names)
# loop through all the nodes in graph ERG with probability "p" of making a
# connection. If a connection is made, assume the graph is non-directional
# and make the opposite connection as well
#if p > 1:
# print("p cannot be greater than 1.0")
# break
# loop through all nodes, this is the originating node
for n in all_nodes_names:
org_edge = n
# loop through all nodes that can be connected to
for e in all_nodes_names:
# there is probability 'p' of making a connection
con_edge = e
edge1 = [org_edge, con_edge]
edge2 = [con_edge, org_edge]
if ERG.has_edge(edge1) == False and ERG.has_edge(edge2) == False:
if random.random() < p:
# connect the two nodes in both directions
ERG.add_edge(edge1)
ERG.add_edge(edge2)
return(ERG)
#########################################################################################
def BlockModel(list_group_sizes, p_in, p_btwn):
"""BlockModel(list_group_sizes, p_in, P_btwn)
Create a block model. This will create several Erdos Renyi graphs
specified by the number of entries in 'list_group_sizes', and values.
nodes within each Erdos Renyi graph have probability p_in of being
connected. Between Erdos Renyi graphs there is probability p_btwn of
two nodes from seperate graphs of being connected. There are three
required inputs:
1) list_group_sizes - a list of integers specifying the size
of each Erdos Renyi graph to create. There can be any number
of integers, as well as any number as the integers.
2) p_in - the probability two nodes will connect within an
Erdoes Renyi graph.
3) p_btwn - the probability two nodes from seperate Erdos Renyi
graphs will connect."""
All_comms = {}
for cn, c in enumerate(list_group_sizes):
# Create a name for the community
comm_name = "C"+str(cn)
# create an ER graph
C = Erdos_Renyi(size=c,p=p_in)
All_comms[comm_name] = C
# relabel all nodes
new_nodes_num = list(range(0,sum(list_group_sizes)))
new_node_names = ["T"+str(i) for i in new_nodes_num]
comms = list(All_comms.keys())
start = 0
Block_graph = comms_graph()
# put nodes into communities
for cn, c_rename in enumerate(comms):
# grab the appropriate number of new node names for the
# ER graph.
end = sum(list_group_sizes[0:1+cn])
comm_node_names = new_node_names[start:end]
#print(len(comm_node_names))
start = end
# assign node from each ER graph to a community
# after relabeling.
# relabel the nodes
All_comms[c_rename].relabel_nodes(comm_node_names)
# assign newly relabelled nodes to a community in a
# large graph which houses the block graph
block_nodes = All_comms[c_rename].nodes()
Block_graph.add_nodes_from(block_nodes)
ERG_edges = All_comms[c_rename].edges()
Block_graph.add_edges_from(ERG_edges)
for bn in block_nodes:
Block_graph.add_comm_node(c_rename, bn)
# add edges for each newly added node
Block_graph.G[bn] = All_comms[c_rename].G[bn]
# build the CBN community data structure
Block_graph.build_CBN()
# Connect ER graphs using betweeness. Loop through all
# nodes not in the current community. There is a prob.
# p_btwn of two nodes from differing communities to connect
for c in comms:
# grab all nodes from the current community
current_comm = Block_graph.NIC[c]
other_comms = []
for oc in comms:
if oc != c:
# grab all nodes from other communities
other_comms = other_comms + Block_graph.NIC[oc]
# start linking nodes between communities
for n in current_comm:
for en in other_comms:
if p_btwn > random.random():
Block_graph.add_edge([n,en])
return(Block_graph)
#########################################################################################
|
#!/usr/bin/env python3
#_*_utf-8_*_
'''This script separates out the all the different finishing times of the Boston Marathon for every year there is data present. The resulting file is a text file called ParsedBoston{}.txt where the {} represents the specific year the marathon was run. '''
import os
import numpy as np
import re
import glob
Boston_file = open('BostonMarathonAllParsed.txt', 'r')
uni_years = set()
new_file = False
for r in Boston_file:
row = r.split(',')
year = row[0].strip('\x0c')
row[0] = year
try:
new_year = int(year)
if new_year not in uni_years:
new_file = True
else:
new_file = False
except ValueError:
new_file = False
if new_file:
print('#'*60)
print('ParsedBoston{}.txt'.format(new_year))
print('#'*60)
out_year = open('ParsedBoston{}.txt'.format(new_year), 'w')
old_year = new_year
uni_years.add(new_year)
out_year.write(','.join(row))
print(row)
else:
try:
out_year.write(','.join(row))
print(row)
except NameError:
pass
|
#Problem 743. Network Delay Time
'''
Problem statement:
There are N network nodes, labelled 1 to N.
Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target.
Now, we send a signal from a certain node K. How long will it take for all nodes to receive the signal? If it is impossible, return -1.
Example 1:
Input: times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2
Output: 2
Note:
N will be in the range [1, 100].
K will be in the range [1, N].
The length of times will be in the range [1, 6000].
All edges times[i] = (u, v, w) will have 1 <= u, v <= N and 0 <= w <= 100.
'''
from collections import defaultdict
import heapq
#Approach: Heap implemenation
def networkDelayTime(times, N, K):
#base case:
if not times or not N or not K: #no set of nodes, so we cannot return anything
return -1
#creating a graph from the list of nodes:
graph = defaultdict(list)
for u, v, w in times:
graph[u].append((v,w))
#heap to store all the current node to check if a network needed to be broacasted
nodeQ = [(0, K)] #this heap would store the distance needed to reach the node and the node itself
#dictionary to store the distance of each node that has been broadcasted
dist = {}
while nodeQ:
distance, node = heapq.heappop(nodeQ)
#if the node already broadcasted the signal, then we do not need to check it
if node in dist: continue
dist[node] = distance
#loop through the neighbors of the current node and broadcast the signal
for neigh, d in graph[node]:
if neigh not in dist:
heapq.heappush(nodeQ, (d+distance, neigh))
return max(dist.values()) if len(dist) == N else -1
#Main function to test the program
def main():
print("TESTING NETWORK DELAY TIME...")
test_times = [[2,1,1],[2,3,1],[3,4,1]]
test_N = 4
test_K = 2
print(networkDelayTime(test_times, test_N, test_K))
print("END OF TESTING....")
main() |
#Problem 1792. Maximum Average Pass Ratio
'''
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam.
You are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes.
The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes.
Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: classes = [[1,2],[3,5],[2,2]], extraStudents = 2
Output: 0.78333
Explanation: You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.
Example 2:
Input: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4
Output: 0.53485
Constraints:
1 <= classes.length <= 105
classes[i].length == 2
1 <= passi <= totali <= 105
1 <= extraStudents <= 105
#Approach:
1. Brute force + Heap data structure: from the list of extra students, we will add the one of them to each claseses and calculat the difference betweem the original raitos
with the new ratios after being updated with the new extra students.
2. Any classes with the higher difference will be stored into the heap data struture, where we can pop them out and check with the new updaed ratios
Time complexity: O(n)
'''
import heapq
def maxAverageRatio(classes, extraStudents):
result = 0
#the heap to store the differences between the current passing ratios and updated passing ratios
difference = [0] * len(classes)
for i in range(len(classes)):
passCount = classes[i][0]
totalCount = classes[i][1]
#init the heap with some preliminary differences, just add 1 student into each class
currentRatio = passCount / totalCount
updatedRatio = (passCount + 1) / (totalCount + 1)
diff = updatedRatio - currentRatio
difference[i] = (-diff, passCount, totalCount)
heapq.heapify(difference)
#start adding the extra students into the array
while(extraStudents > 0):
#pop the highest element from the heap, this would give us the difference with the highest value
_, passCount, totalCount = heapq.heappop(difference)
#assign a student to a class
passCount += 1
totalCount += 1
currentRatio = passCount / totalCount
updatedRatio = (passCount + 1) / (totalCount + 1)
diff = updatedRatio - currentRatio
heapq.heappush(difference, (-diff, passCount, totalCount))
extraStudents -= 1
for _, passCount, totalCount in difference:
result += passCount / totalCount
return result/len(classes)
#Main function to run the test case:
def main():
print("TESTING MAXIMUM AVERAGE PASS RATIO...")
#test cases:
classes =[[1,2],[3,5],[2,2]]
extraStudents = 2
print(maxAverageRatio(classes, extraStudents))
classes =[[2,4],[3,9],[4,5],[2,10]]
extraStudents = 4
print(maxAverageRatio(classes, extraStudents))
print("END OF TESTING...")
main()
|
#Problem 1705. Maximum Number of Eaten Apples
'''
There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0.
You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days.
Given two integer arrays days and apples of length n, return the maximum number of apples you can eat.
Example 1:
Input: apples = [1,2,3,5,2], days = [3,2,1,4,2]
Output: 7
Explanation: You can eat 7 apples:
- On the first day, you eat an apple that grew on the first day.
- On the second day, you eat an apple that grew on the second day.
- On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot.
- On the fourth to the seventh days, you eat apples that grew on the fourth day.
Example 2:
Input: apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]
Output: 5
Explanation: You can eat 5 apples:
- On the first to the third day you eat apples that grew on the first day.
- Do nothing on the fouth and fifth days.
- On the sixth and seventh days you eat apples that grew on the sixth day.
Constraints:
apples.length == n
days.length == n
1 <= n <= 2 * 104
0 <= apples[i], days[i] <= 2 * 104
days[i] = 0 if and only if apples[i] = 0.
'''
#Function to solve the program using heap data structure.
#Eat the apple that is going to rot first, we do this by storing the number of apple grown in each day and its rot day onto a heap and then we pop out the one with
#the smallest or completely run out of time rot day
import heapq
def eatenApples(apples, days):
#base case:
if not len(apples) or not len(days):
return None
day = 0
heap = []
result = 0
while heap or day < len(apples):
#put all value of apple and its rot day onto the heap
#if the apple is still within the list boundary and still have valid apple
if day < len(apples) and apples[day] > 0:
heapq.heappush(heap, [days[day] + day, apples[day]])
#Throwing out the rotten apples: (we have passed the rotten day or we dont have anymore apple to eat)
while heap and (heap[0][0] <= day or heap[0][1] <= 0):
heapq.heappop(heap)
#otherwise: we keep eating the apple until they are rotten or run out
if heap:
heap[0][1] -= 1
result += 1
day += 1
return result
#Time complexity: O(n), since len(apples) == len(days) so the algorithm only needs to push onto the heap and pop from them
#Space complexity: O(n) we built a heap that can store n amount apple+rot day into the heap
#Main function to run the test cases:
def main():
print("TESTING MAXIMUM OF APPLE EATEN")
apples = [1,2,3,5,2]
days = [3,2,1,4,2]
apples_1 = [3,0,0,0,0,2]
days_1 = [3,0,0,0,0,2]
print(eatenApples(apples, days))
print(eatenApples(apples_1, days_1))
print("END OF TESTING...")
main() |
from tkinter import *
import random
class Application(Frame): # Extend Frame's function
globalnumber = 1
def division():
try: # Try to get numbers from input
num = int(n1.get()) # Get num from n1
num_list_1 = int(nl1.get()) # Get num_list_1 from nl1
num_list_2 = int(nl2.get()) # Get num_list_1 from nl2
num_list_3 = int(nl3.get()) # Get num_list_1 from nl3
num_list_4 = int(nl4.get()) # Get num_list_1 from nl4
num_list_5 = int(nl5.get()) # Get num_list_1 from nl5
if num == 0: # If x is 0
Label(root, text="Please enter a new x.").grid()
else: # If x is not 0
num_list = [num_list_1, num_list_2, num_list_3, num_list_4, num_list_5] # Fill the number list
dv_result = list(filter(lambda x: (x % num == 0), num_list)) # Use lambda to find division number
Label(root, text="Numbers divisible by " + str(num) + " are"+str(dv_result)+".").grid() # Show the result
Label(root, text="Did you get the same answer?").grid() # Label show tips
Button(root, text="Yes", command=correct).grid() # Button "Yes"
Button(root, text="No", command=wrong).grid() # Button "No"
except:
Label(root, text="Please Enter Appropriate Values.").grid() # Tell user re-enter a new value
def correct(): # Function to show correct word
correct_word = int(random.randint(0, 2)) # Import random to choose word
correct_wordlist = ["Perfect!", "Nice job!", "Well done!"] # Make a word list
Label(root, text=correct_wordlist[correct_word]).grid() # Display word in grid
def wrong(): # Function to show correct word
wrong_word=int(random.randint(0, 2)) # Import random to choose word
wrong_wordlist=["Try again.", "Sorry.", "What a pity."] # Make a word list
Label(root, text=wrong_wordlist[wrong_word]).grid() # Display word in grid
root = Tk() # Assign Tkinter to root GUI
root.title("Divisible") # Title for GUI
Label(root, text="Input x: ").grid(row=0) # Display a label
n1 = Entry(root) # Make an input "n1"
n1.grid(row=0, column=1) # "n1"'s position
Label(root, text="Input number 1 of list: ").grid(row=1) # Display a label
nl1 = Entry(root) # Make an input "nl1"
nl1.grid(row=1, column=1) # "nl1"'s position
Label(root, text="Input number 2 of list: ").grid(row=2) # Display a label
nl2 = Entry(root) # Make an input "nl2"
nl2.grid(row=2, column=1) # "nl2"'s position
Label(root, text="Input number 3 of list: ").grid(row=3) # Display a label
nl3 = Entry(root) # Make an input "nl3"
nl3.grid(row=3, column=1) # "nl3"'s position
Label(root, text="Input number 4 of list: ").grid(row=4) # Display a label
nl4 = Entry(root) # Make an input "nl4"
nl4.grid(row=4, column=1) # "nl4"'s position
Label(root, text="Input number 5 of list: ").grid(row=5) # Display a label
nl5 = Entry(root) # Make an input "nl5"
nl5.grid(row=5, column=1) # "nl5"'s position
b1 = Button(root, text="Find", bg="#52da56", command=division) # Button "Find" and trigger division
b1.grid(row=6, column=0) # "Find"'s position
b2 = Button(root, text="Quit", bg="White", command=root.destroy) # Button "Quit" and trigger root.destroy
b2.grid(row=6, column=1) # "Quit"'s position
root.mainloop() # Main Loop
|
"""
O(n log n), or O(n + d) where d is the number of inversions
"""
import math
#list = [-1,6,3,2,1,7,9,8,10,12,11,8,4,5]
list = [-1,2,5,4,8,7,6,9,8,10,12,11,5,90,80,70,60,65,45,35,42]
def insertion_sort(list):
n = len(list)
for i in range(1,n):
# save value to be positioned
value = list[i]
pos = i
while pos > 0 and value < list[pos - 1]:
list[pos] = list[pos-1]
pos -= 1
list[pos] = value
return list |
import numpy as np
# single dimentional array
a = np.array([1,2,3])
# multi dimentional array
b = np.array([(1,2,3),(4,5,6)])
print(a)
print(b)
# create a array of 1000 number
d = np.arange(1000)
print(d)
print(d.itemsize)
# to get a tupple having array dimensions
print(a.shape)
print(b.shape)
# to reshap a array
c = b.reshape(3,2)
print(c) |
a = 10
b = 20
print("value of a is : ",a)
print("value of b is : ",b)
print("opeations examples: ")
print("a + b : ",a+b)
print("a - b : ",a-b)
print("a * b : ",a*b)
print("a / b : ",a/b)
print("a // b : ",a//b)
print("a % b : ",a%b)
print("a ** b is a to power b : ",a**b)
|
# declaring class and using oops concepts
class Employee:
#declaring class varianble
no_of_emps = 0
raise_amt = 1.04
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
self.email = first+last+'@testmail.com'
Employee.no_of_emps += 1
def fullname(self):
fullname = self.first + ' '+ self.last
return fullname
def apply_raise(self):
self.pay = float(self.pay) * float(self.raise_amt)
@classmethod
def set_raise_amout(cls,amount):
cls.raise_amt = amount
@classmethod
def split_from_string(cls,inp_str):
first,last,pay = inp_str.split('-')
return cls(first,last,pay)
@staticmethod
def is_workday(day):
if day.weekday() == 5 or day.weekday() == 6:
return False
return True
class Developer(Employee):
raise_amt = 1.10
def __init__(self, first, last, pay,pro_lang):
super().__init__(first, last, pay)
self.pro_lang = pro_lang
class Manager(Employee):
raise_amt = 1.12
def __init__(self, first, last, pay,employees = None):
super().__init__(first, last, pay)
if employees is None:
self.employees = []
else:
self.employees = employees
def add_emp(self, emp):
if emp not in self.employees:
self.employees.append(emp)
def remove_emp(self, emp):
if emp in self.employees:
self.employees.remove(emp)
def print_emps(self):
for emp in self.employees:
print('-->', emp.fullname())
emp1 = Employee('jeetendra','kumar','60000')
emp2 = Employee.split_from_string('raja-H-70000')
dev1 = Developer('lokesh','singh',75000,'python')
man1 = Manager('Dina','Ravinderan',100000,[dev1,emp1,emp2])
print(emp1.fullname())
print(emp1.email)
print(dev1.email)
print(dev1.apply_raise())
print(dev1.pay)
print(emp2.fullname())
emp2.set_raise_amout(1.05)
emp2.apply_raise()
print(emp2.pay)
print(emp2.no_of_emps)
import datetime
my_date = datetime.date(2016, 7, 11)
print(Employee.is_workday(my_date))
man1.remove_emp(emp2)
print (man1.print_emps()) |
a =5
b = 6
print(a)
print(b)
print("\n\n")
a,b =b,a
print("numbers after swaping")
print(a)
print(b) |
x = input("enter first value")
y = input("enter second value")
a = int(x)
b = int(y)
z = a+b
print(z)
result = eval(input("input a math expression"))
print(result) |
def is_prime(num):
for n in range(2,num):
if num % n ==0:
print('Not prime')
else:
print('Number is prime')
is_prime(5)
|
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
l = [i.lower() for i in s if i.isalnum()]
return l == l[::-1]
s = Solution()
print(s.isPalindrome('A man, a plan, a canal: Panama')) |
#求两数的最大公约数
# c=a%b,c=0则b是最大公约数 ,否则a=b,b=c,继续计算a%b
a = input("a=")
b = input("b=")
c = 0
while 1:
c = int(a)%int(b)
#print("输出",c)
if c == 0:
print("最大公约数:",b)
break
else:
a = b
b = c
|
# -*- coding: utf-8 -*-
import sys
import random
import curses
from itertools import chain
class Action(object):
'''
游戏控制显示
'''
UP = 'up'
LEFT = 'left'
DOWN = 'down'
RIGHT = 'right'
RESTART = 'restart'
EXIT = 'exit'
letter_codes = [ord(ch) for ch in 'WASDRQwasdrq']
# 字母编码,ord返回对应的十进制整数
actions = [UP, LEFT, DOWN, RIGHT, RESTART, EXIT]
# 用户行为
actions_dict = dict(zip(letter_codes, actions * 2))
# 将字母的十进制整数和用户行为一一对应组合起来,并转换成字典类型
# 因为不区分大小写,所以这里用户行为需要*2
def __init__(self, stdscr):
self.stdscr = stdscr
def get(self):
char = "N"
while char not in self.actions_dict:
char = self.stdscr.getch()
return self.actions_dict[char]
class Grid(object):
def __init__(self, size):
self.size = size
self.cells = None
self.reset()
def reset(self):
self.cells = [[0 for i in range(self.size)] for j in range(self.size)]
# 初始化一个二维数组,值都是0,作为棋盘的每格。
self.add_random_item()
self.add_random_item()
def add_random_item(self):
'''
随机在某个格子输出2或4
'''
empty_cells = [(i, j) for i in range(self.size) for j in range(self.size) if self.cells[i][j] == 0]
(i, j) = random.choice(empty_cells)
self.cells[i][j] = 4 if random.randrange(100) >= 90 else 2
def transpose(self):
'''
利用 Python 内置的 zip(*) 方法来进行矩阵转置
'''
self.cells = [list(row) for row in zip(*self.cells)]
def invert(self):
'''
将矩阵的每一行倒序
'''
self.cells = [row[::-1] for row in self.cells]
@staticmethod
def move_row_left(row):
'''
一行向左合并
'''
def tighten(row):
'''把零散的非零单元挤到一块'''
new_row = [i for i in row if i != 0]
# 先将非零的元素全拿出来加入到新列表
new_row += [0 for i in range(len(row) - len(new_row))]
# 按照原列表的大小,给新列表后面补零
return new_row
def merge(row):
'''对邻近元素进行合并'''
pair = False
new_row = []
for i in range(len(row)):
if pair:
new_row.append(2 * row[i])
# 合并后,加入乘 2 后的元素在 0 元素后面
GameManager.score += 2 * row[i]
# 更新分数
pair = False
else:
# 判断邻近元素能否合并
if i + 1 < len(row) and row[i] == row[i + 1]:
pair = True
new_row.append(0)
# 可以合并时,新列表加入元素 0
else:
new_row.append(row[i])
# 不能合并,新列表中加入该元素
# 断言合并后不会改变行列大小,否则报错
assert len(new_row) == len(row)
return new_row
# 先挤到一块再合并再挤到一块
return tighten(merge(tighten(row)))
def move_left(self):
self.cells = [self.move_row_left(row) for row in self.cells]
def move_right(self):
self.invert()
self.move_left()
self.invert()
def move_up(self):
self.transpose()
self.move_left()
self.transpose()
def move_down(self):
self.transpose()
self.move_right()
self.transpose()
@staticmethod
def row_can_move_left(row):
def change(i):
if row[i] == 0 and row[i + 1] != 0:
return True
if row[i] != 0 and row[i + 1] == row[i]:
return True
return False
return any(change(i) for i in range(len(row) - 1))
def can_move_left(self):
return any(self.row_can_move_left(row) for row in self.cells)
def can_move_right(self):
self.invert()
can = self.can_move_left()
self.invert()
return can
def can_move_up(self):
self.transpose()
can = self.can_move_left()
self.transpose()
return can
def can_move_down(self):
self.transpose()
can = self.can_move_right()
self.transpose()
return can
def can_move_restart(self):
self.transpose()
can = self.can_move_down()
self.transpose()
return can
def can_move_exit(self):
self.transpose()
can = self.can_move_up()
self.transpose()
return can
class Screen(object):
'''
棋盘类
'''
help_string1 = '(W)up (S)down (A)left (D)right'
help_string2 = ' (R)Restart (Q)Exit'
over_string = ' GAME OVER'
win_string = ' YOU WIN!'
def __init__(self, screen=None, grid=None, score=0, best_score=0, over=False, win=False):
self.grid = grid
self.score = score
self.over = over
self.win = win
self.screen = screen
self.counter = 0
def cast(self, string):
'''
绘制函数
'''
self.screen.addstr(string + '\n')
# addstr() 方法将传入的内容展示到终端
def draw_row(self, row):
'''
绘制竖直分割线的函数
'''
self.cast(''.join('|{: ^5}'.format(num) if num > 0 else '| ' for num in row) + '|')
def draw(self):
self.screen.clear()
# 清空屏幕
self.cast('SCORE: ' + str(self.score))
for row in self.grid.cells:
self.cast('+-----' * self.grid.size + '+')
self.draw_row(row)
self.cast('+-----' * self.grid.size + '+')
# 绘制分数
if self.win:
self.cast(self.win_string)
else:
if self.over:
self.cast(self.over_string)
else:
self.cast(self.help_string1)
self.cast(self.help_string2)
# 绘制提示文字
class GameManager(object):
score = 0
'''
游戏状态控制类
'''
def __init__(self, size=4, win_num=2048):
self.size = size
# 棋盘宽高
self.win_num = win_num
# 过关分数
self.reset()
# 重置清屏
def reset(self):
self.state = 'init'
# 初始化状态
self.win = False
# 胜利状态
self.over = False
# 失败状态
# self.score = GameManager.score
# 当前分数
self.grid = Grid(self.size)
# 创建棋盘
self.grid.reset()
# 棋盘清屏
@property
def screen(self):
'''
显示棋盘
'''
return Screen(screen=self.stdscr, score=GameManager.score, grid=self.grid, win=self.win, over=self.over)
def move(self, direction):
# 判断棋盘操作是否存在且可行
if self.can_move(direction):
getattr(self.grid, 'move_' + direction)()
# getattr会调用grid类中的move_left、move_right
# move_up、move_down
self.grid.add_random_item()
return True
else:
return False
@property
def is_win(self):
'''
判断是否胜利
'''
self.win = max(chain(*self.grid.cells)) >= self.win_num
return self.win
@property
def is_over(self):
'''
判断是否失败
'''
self.over = not any(self.can_move(move) for move in self.action.actions)
return self.over
def can_move(self, direction):
# getattr会调用grid类中的can_move__left、can_move_right
# can_move_up、can_move_down
return getattr(self.grid, 'can_move_' + direction)()
def state_init(self):
'''
初始化状态
'''
self.reset()
return 'game'
def state_game(self):
'''
游戏状态
'''
self.screen.draw()
# 显示得分和棋盘
action = self.action.get()
# 获取当前用户行为
if action == Action.RESTART:
return 'init'
if action == Action.EXIT:
return 'exit'
if self.move(action):
if self.is_win:
return 'win'
if self.is_over:
return 'over'
return 'game'
def _restart_or_exit(self):
'''
重置游戏或退出游戏
'''
self.screen.draw()
return 'init' if self.action.get() == Action.RESTART else 'exit'
def state_win(self):
'''
胜利状态
'''
return self._restart_or_exit()
def state_over(self):
'''
失败状态
'''
return self._restart_or_exit()
def __call__(self, stdscr):
curses.use_default_colors()
self.stdscr = stdscr
self.action = Action(stdscr)
while self.state != 'exit':
self.state = getattr(self, 'state_' + self.state)()
# getattr会依次调用当前类中的state_init、state_game
if __name__ == '__main__':
recursionlimit = sys.getrecursionlimit()
# 因为此游戏中的递归调用可能会超过最大递归深度,
# 这里判断python中的最大递归深度是否小于2000,
# 没有则赋值2000
if recursionlimit < 2000:
sys.setrecursionlimit(2000)
curses.wrapper(GameManager()) |
# https://leetcode.com/problems/two-sum/submissions/
# 1__2_Sum_problem
# TimeComplexity
# O(n)
def twoSum(nums, target):
arr = nums
arr_inv_map = {}
for i in range(len(arr)):
if arr_inv_map.get(arr[i], 'X') == 'X':
arr_inv_map[target-arr[i]] = i
else:
return arr_inv_map[arr[i]], i
if __name__ == "__main__":
arr = [2, 7, 3, 9, 1]
target = 10
m, n = twoSum(arr, target)
|
#3__Merge_two_sorted_Linked_List
from dataStructure.linkedList import singlyLinkedList, Node
def mergeTwoLists(l1,l2):
if l1 and l2:
if l1.val < l2.val:
newHead,l1 = l1,l1.next
else:
newHead,l2 = l2,l2.next
cur = newHead
while l1 and l2:
if l1.val < l2.val:
cur.next,l1 = l1,l1.next
else:
cur.next,l2 = l2,l2.next
cur = cur.next
cur.next=l2 if l2 else l1
return newHead
else:
if l1:
return l1
elif l2:
return l2
else:
return None
l1 = singlyLinkedList()
l2 = singlyLinkedList()
a = []
b = []
for i in a:
l1.add(i)
for i in b:
l2.add(i)
# print(l1)
# print(l2)
h = mergeTwoLists(l1.head,l2.head)
if h:
h.displayTillEnd()
else:
print('<empty>')
|
# https://leetcode.com/problems/copy-list-with-random-pointer/
#7__Clone_a_Linked_List_with_random_and_next_pointer_
from dataStructure.linkedList import singlyLinkedList as sLL, Node
def copyRandomList(head):
if not head:
return head
newhead = Node('-1')
hmap = {}
hmap[None]=None
nh = newhead
h = head
while h:
cur = Node(h.val)
hmap[h] = cur
nh.next = cur
nh = cur
h=h.next
h =head
nh = newhead.next
while h:
nh.random = hmap[h.random]
h = h.next
nh = nh.next
return newhead.next
# if __name__ == "__main__":
# start = 1
# end=5
# k = 6
# ll = sLL()
# for i in range(start, end+1):
# ll.push(i)
# l2 = copy(ll.head)
# l2.displayTillEnd() |
# https://leetcode.com/problems/rotate-list/
#6__Rotate_a_LinkedList
from dataStructure.linkedList import singlyLinkedList as sLL, Node
def rotateRight(head,k):
if k and head:
length = 0
cur = head
while cur:
length+=1
cur = cur.next
k = k%length
if k==0:
return head
else:
last = head
while k:
k-=1
last = last.next
newlast = head
while last.next:
last = last.next
newlast = newlast.next
newHead =newlast.next
newlast.next = None
last.next = head
head = newHead
return head
return head
if __name__ == "__main__":
start = 1
end=5
k = 6
ll = sLL()
for i in range(start, end+1):
ll.push(i)
print(ll)
ll.head = rotateRight(ll.head,k)
print(ll) |
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
# Input: [7,1,5,3,6,4]
# Output: 5
# Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
# Not 7-1 = 6, as selling price needs to be larger than buying price.
def maxProfitBrute(arr):
# O(n^2)
arr_len = len(arr)
profit = -1
for i in range(arr_len-1):
for j in range(i+1, arr_len):
diff = arr[j]-arr[i]
if (profit <= diff):
profit = diff
start = i
end = j
return start, end, arr[end]-arr[start]
def maxProfit(prices):
# O(n)
arr = prices
arr_len = len(arr)
if len(arr) < 2:
return 0
elif len(arr) == 2:
return arr[1]-arr[0] if arr[1] > arr[0] else 0
mini = arr[0]
profit = arr[1]-arr[0]
for idx, item in enumerate(arr):
mini = min(mini, item)
profit = max(profit, item-mini)
return profit
arr = [5, 5]
# arr_len = len(arr)
# start, end, profit = bestBuy(arr, arr_len)
# print(f'start = {start}\nend = {end}\nProfit = {profit}')
profit = maxProfit(arr)
print(f'\nProfit = {profit}')
|
# https://www.interviewbit.com/problems/subarray-with-given-xor/
# 5__Count_number_of_subarrays_with_given_XOR(this_clears_a_lot_of_problems)
from collections import defaultdict
from functools import reduce
def visualize(arr, m):
print(f'Valid subarray with xor = {m}')
for i in range(len(arr)):
for j in range(i, len(arr)):
val = arr[i:j+1]
ans = reduce(lambda x, y: x ^ y, val)
if ans == m:
print(val)
def solve(arr, m):
from collections import defaultdict
hashMap = defaultdict(int)
hashMap[0] += 1
cur = 0
x = 0
for i in arr:
cur ^= i
hashMap[cur] += 1
# print(f'hashmap = {dict(hashMap)} \nm^cur = {m^cur} \ncur = {cur}\n\n')
x += hashMap.get(m ^ cur, 0)
return x
if __name__ == "__main__":
arr = [5, 2, 1, 4, 6, 3]
m = 5
visualize(arr, m)
print(f'Number of subarray with xor = {m} is {solve(arr,m)}')
|
import timeit
def sqrd_list(sqrd):
for i in sqrd:
print(i**2, end=" ")
a=list(range(10))
sqrd_list(a)
b=list(range(100))
sqrd_list(b)
c=list()
sqrd_list(c)
mycode = '''
def sqrd_list(sqrd):
for i in sqrd:
print(i**2, end=" ")
a=list(range(10))
sqrd_list(a)
'''
print(timeit.timeit(stmt=mycode, number=100))
|
# *функция niter(iterable, n=2)
# возвращает кортеж из "копий"-итераторов по переданному итератору,
# каждый итератор должен предоставлять то же, что и итератор-источник.
# Новые итераторы независимы в смысле их текущих позиций (в первом может вычитаться значение,
# а в последующих они неизменны, возвращают первое значение)
import collections
def niter(iterable, n=2):
it = iter(iterable)
deques = [collections.deque() for i in range(n)]
def gen(my_deque):
while True:
if not my_deque:
try:
new_val = next(it)
except StopIteration:
return
for d in deques:
d.append(new_val)
yield my_deque.popleft()
return tuple(gen(d) for d in deques)
a = [1, 2, 3, 4]
ab = niter(a, 8)
print(ab)
|
# Класс “линейная функция”.
# И основные ее операции:
# -вычисление в точке,
# -сложение с другой линейной функцией,
# -умножение на константу,
# -композиция с другой линейной функцией, -
# строковое представление.
# Нужно уточнить формулировку, но суть примерно такая.
import numbers
class Linear_function:
def __init__(self, k=0, b=0):
self.k = k
self.b = b
def __call__(self, x0):
if isinstance(x0, Linear_function):
return Linear_function(self.k * x0.k, self.b + self.k * x0.b)
elif isinstance(x0, numbers.Number):
return self.k * x0 + self.b
def __add__(self, other):
if isinstance(other, Linear_function):
return Linear_function(other.k + self.k, self.b + other.b)
elif isinstance(other, numbers.Number):
return Linear_function(self.k, self.b + other)
def __mul__(self, other):
if isinstance(other, Linear_function):
return Linear_function(other.k * self.k, self.b + self.k * other.b)
elif isinstance(other, numbers.Number):
return Linear_function(self.k * other, self.b * other)
def __repr__(self):
if self.k == 0 and self.b == 0:
return "f(x)=0"
elif self.k == 0:
return "f(x)={}".format(round(self.b, 2))
elif self.b == 0:
return "f(x)={}x".format(round(self.k, 2))
elif self.b > 0:
return "f(x)={}x+{}".format(round(self.k, 2), round(self.b, 2))
elif self.b < 0:
return "f(x)={}x-{}".format(round(self.k, 2), abs(round(self.b, 2)))
def main():
f = Linear_function(5, 2)
print(f)
y = Linear_function(3, 2)
print(y)
print(f(y))
print(y(f))
if __name__ == '__main__':
main()
|
# Read a file "mbox-short.txt and search for lines that start with From and a character
# like "From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008m"
# followed by a two digit number between 00 and 99 followed by ':'
# Then print the number if it is greater than zero
import re
filename = input("Enter a file name:")
try:
stream = open(filename)
for eachline in stream:
eachline = eachline.strip()
# hour = re.findall('^From .* [0-9][0-9]:',eachline) try running and check
# hour = re.findall('^From .* ([0-9][0-9]):',eachline)try running and check
hour = re.findall('^From .* ([0-9][0-9]):',eachline)
if len(hour) > 0:
print(hour)
except:
print("Enter a valid file")
quit()
|
import numpy as np
from numpy import sin, cos, pi
import matplotlib.pyplot as plt
np.set_printoptions(precision=3, linewidth=200)
def wrap(x, m, M):
"""
:param x: a scalar
:param m: minimum possible value in range
:param M: maximum possible value in range
Wraps ``x`` so m <= x <= M; but unlike ``bound()`` which
truncates, ``wrap()`` wraps x around the coordinate system defined by m,M.\n
For example, m = -180, M = 180 (degrees), x = 360 --> returns 0.
"""
diff = M - m
while x > M:
x = x - diff
while x < m:
x = x + diff
return x
def bound(x, m, M=None):
"""
:param x: scalar
Either have m as scalar, so bound(x,m,M) which returns m <= x <= M *OR*
have m as length 2 vector, bound(x,m, <IGNORED>) returns m[0] <= x <= m[1].
"""
if M is None:
M = m[1]
m = m[0]
# bound x between min (m) and Max (M)
return min(max(x, m), M)
def rk4(derivs, t, y0, *args, **kwargs):
"""
Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta.
This is a toy implementation which may be useful if you find
yourself stranded on a system w/o scipy. Otherwise use
:func:`scipy.integrate`.
*y0*
initial state vector
*t*
sample times
*derivs*
returns the derivative of the system and has the
signature ``dy = derivs(yi, ti)``
*args*
additional arguments passed to the derivative function
*kwargs*
additional keyword arguments passed to the derivative function
Example 1 ::
## 2D system
def derivs6(x,t):
d1 = x[0] + 2*x[1]
d2 = -3*x[0] + 4*x[1]
return (d1, d2)
dt = 0.0005
t = arange(0.0, 2.0, dt)
y0 = (1,2)
yout = rk4(derivs6, y0, t)
Example 2::
## 1D system
alpha = 2
def derivs(x,t):
return -alpha*x + exp(-t)
y0 = 1
yout = rk4(derivs, y0, t)
If you have access to scipy, you should probably be using the
scipy.integrate tools rather than this function.
"""
try:
Ny = len(y0)
except TypeError:
yout = np.zeros((len(t),), np.float_)
else:
yout = np.zeros((len(t), Ny), np.float_)
yout[0] = y0
for i in np.arange(len(t) - 1):
thist = t[i]
dt = t[i + 1] - thist
dt2 = dt / 2.0
y0 = yout[i]
k1 = np.asarray(derivs(thist, y0, *args, **kwargs))
k2 = np.asarray(derivs(thist + dt2, y0 + dt2*k1, *args, **kwargs))
k3 = np.asarray(derivs(thist + dt2, y0 + dt2*k2, *args, **kwargs))
k4 = np.asarray(derivs(thist + dt, y0 + dt*k3, *args, **kwargs))
yout[i + 1] = y0 + dt / 6.0 * (k1 + 2*k2 + 2*k3 + k4)
return yout |
#!/usr/bin/python
#encoding=utf-8
import urllib2
import sys
import re
import base64
from urlparse import urlparse
# The two normal authentication schemes are basic and digest authentication.
# Between these two, basic is overwhelmingly the most common.
# As you might guess, it is also the simpler of the two.
#
# A summary of basic authentication goes like this :
#
# 1.client makes a request for a webpage
# 2. server responds with an error(Error code is 401 and
# The 'WWW-Authenticate' header line looks like ' WWW-Authenticate: SCHEME realm="REALM" ',requesting authentication)
# 3.client retries request - with authentication details encoded in request
# This is request include Username/Password by encoding it as base 64 string(Base64)
# 4.server checks details and sends the page requested, or another error
# The more detail: http://www.voidspace.org.uk/python/articles/authentication.shtml
def getHeader():
username = 'username'
password = 'xxxxxxxx'
url = "http://api.minicloud.com.cn/statuses/friends_timeline.xml" #一个需要basic authentication验证的页面
#url = "http://www.baidu.com"
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-agent' : user_agent }
req = urllib2.Request(url, headers = headers)
try:
response = urllib2.urlopen(req)
print response.headers
except IOError, e:
pass
else:
#没有异常就是一个正常的页面
print 'This page isn\'t protected by authentication'
sys.exit(1)
if not hasattr(e, 'code') or e.code != 401:
#we get a error - but not a 401 error
print 'This page isn\'t protected by authentication'
print 'code :', e.code
print 'reason :', e.reason
sys.exit(1)
print e.headers
authline = e.headers['www-authenticate']
print authline
authobj = re.compile( \
r'''(?:\s*www-authentication\s*:)?\s*(\w*)\s+realm=['"]([^'"]+)['"]''',\
re.IGNORECASE)#忽略大小写
mathobj = authobj.match(authline)
if not mathobj:
#无法匹配返回头部有问题
print 'The authentication header is badly formed'
print authline
sys.exit(1)
#获取头部的配置
scheme = mathobj.group(1)
realm = mathobj.group(2)
if schemes.lower() != 'basic':
print 'this example only works with BASIC authentication'
sys.exit(1)
if authline.lower() != 'basic':
print 'this example only works with BASIC authentication'
sys.exit(1)
base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
#base64.encodestring生成的字符串会在最后加入换行,要去掉
authheader = "Basic %s" % base64string
req.add_header("Authorization", authheader)
try:
response = urllib2.urlopen(req)
except IOError, e:
#此处异常用户名或密码错误
print "It look like the Username or Password is wrong."
sys.exit(1)
page = response.read()
print page
if __name__ == '__main__':
getHeader()
|
'''
Pandas Homework with IMDb data
'''
'''
BASIC LEVEL
'''
import pandas as pd
import matplotlib.pyplot as plt
# read in 'imdb_1000.csv' and store it in a DataFrame named movies
file_path = 'C:\Users\Matt\githubclones\GA-SEA-DAT1\data\\'
movies_url = file_path + 'imdb_1000.csv'
movies = pd.read_table(movies_url, sep=',', header=0)
movies.head()
# check the number of rows and columns
movies.shape
# check the data type of each column
movies.dtypes
# calculate the average movie duration
movies.duration.mean()
# sort the DataFrame by duration to find the shortest and longest movies
movies.sort('duration')
''' The shortest movie is Freaks, at 64 mins. The longest is Hamlet, at 242 mins'''
# create a histogram of duration, choosing an "appropriate" number of bins
movies.duration.plot(kind = 'hist', bins=20, title = 'Histgram of Movie Duration')
plt.xlabel('Duration (minutes)')
plt.ylabel('Count of Movies by Duration Bucket')
# use a box plot to display that same data
movies.duration.plot(kind='box')
'''
INTERMEDIATE LEVEL
'''
# count how many movies have each of the content ratings
movies.groupby('content_rating').content_rating.describe()
# use a visualization to display that same data, including a title and x and y labels
movies.content_rating.value_counts().plot(kind='bar')
plt.xlabel('Rating')
plt.ylabel('Count by Rating')
# convert the following content ratings to "UNRATED": NOT RATED, APPROVED, PASSED, GP
# replace all instances of a value in a column (must match entire value)
movies.content_rating.replace(('NOT RATED', 'APPROVED', 'PASSED', 'GP'), "UNRATED", inplace=True)
movies.groupby('content_rating').content_rating.describe()
# convert the following content ratings to "NC-17": X, TV-MA
movies.content_rating.replace(('X', 'TV-MA'), "NC-17", inplace=True)
movies.groupby('content_rating').content_rating.describe()
# count the number of missing values in each column
movies.isnull().sum()
# if there are missing values: examine them, then fill them in with "reasonable" values
import numpy as np
movies[movies['content_rating'].isnull()]
movies.content_rating.fillna(value='UNRATED', inplace=True)
movies.isnull().sum()
# calculate the average star rating for movies 2 hours or longer,
movies[movies.duration > 120].star_rating.mean()
movies.duration.describe()
movies.star_rating.describe()
# and compare that with the average star rating for movies shorter than 2 hours
movies[movies.duration < 120].star_rating.mean()
# use a visualization to detect whether there is a relationship between duration and star rating
plt.rcParams['figure.figsize'] = (8, 6)
plt.rcParams['font.size'] = 14
movies.plot(kind='scatter', x='duration', y='star_rating')
# calculate the average duration for each genre
movies.groupby('genre').mean()
'''
ADVANCED LEVEL
'''
# visualize the relationship between content rating and duration
movies.boxplot(column='duration', by='content_rating')
# determine the top rated movie (by star rating) for each genre
movies.sort(['genre', 'star_rating']).groupby('genre').head(1)
# check if there are multiple movies with the same title, and if so, determine if they are actually duplicates
movies.sort('title').title.duplicated()
movies.duplicated(['title']).sum()
movie_dupes = movies[movies.duplicated('title')].title
# calculate the average star rating for each genre, but only include genres with at least 10 movies
'''
I can't get this approach to work. I think it should be somethign like 1) find the genre's with >= 10 movies (done),
2) create a boolean mask that picks out records in those genres; 3) for that subset, group by genre and take the mean.
'''
movies.genre.value_counts()
movies[movie_subset >= 10].star_rating.mean()
movies[movies['genre'].value_counts() >= 10].groupby('genre').star_rating.mean()
'''
BONUS
'''
# Figure out something "interesting" using the actors data!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.