text stringlengths 37 1.41M |
|---|
#
#
## Tom
#
#
## Use the linked list class
from linkedlist import *
MyList = linkedList()
MyList.insert(Node("Lars"))
MyList.insert(Node("Alex"))
print(MyList.getSize())
MyList.insert(Node("Tom"))
MyList.insert(Node("Mike"))
print(MyList.getSize())
# Use the print method
MyList.printLL()
|
import sys
args=sys.argv[1]
count=0
file=open("iphorizontal.txt","r")
f=file.readline()
file_list=f.split(" ")
print("list of IP's is:",file_list)
for line in file_list:
if(args==line):
#print("ip found in list:",line)
count=count+1;
if(count>0):
print("Ip found")
print("number of times ip found is:",count)
else:
print("Ip not found") |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
# TODO(mzc) 将 level = 2 对应 book set URL 记录 到 csv 中
def read_record(cls_id=None, clsname=None, baseUrl=None, max_page_num=None):
with open('./level2url.csv', 'rb+') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
pass
def write_record(book_cls_list):
with open('./level2url.csv', 'ab+') as csvfile:
fieldnames = ['cls_id', 'cls_name', 'base_url', 'cls_num', 'max_page_num']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
# writer.writerow()
writer.writerows() |
# Command-line program that takes a file containing a maze representation
# and finds the shortest path from the starting point to the endpoint,
# if it exists
class Node:
def __init__(self, state, parent, action):
self.state = state
self.parent = parent
self.action = action
class StackFrontier:
def __init__(self):
self.frontier = []
def push(self, node):
self.frontier.append(node)
def containsState(self, state):
return any(node.state == state for node in self.frontier)
def isEmpty(self):
return len(self.frontier) == 0
def pop(self):
if self.isEmpty():
raise Exception("Empty StackFrontier")
else:
node = self.frontier[-1]
self.frontier = self.frontier[:-1]
return node
class QueueFrontier(StackFrontier):
def pop(self):
if self.isEmpty():
raise Exception("Empty QueueFrontier")
else:
node = self.frontier[0]
self.frontier = self.frontier[1:]
return node
class Maze:
def __init__(self, mazeFile):
self.mazeFile = mazeFile
self.mazeLayout = []
self.mazeHeight = 0
self.mazeWidth = 0
self.numExplored = 0
self.startState = None
self.goalState = None
self.shortestPath = None
self.parseMazeFile()
def parseMazeFile(self):
"""
Parses maze file, sets maze layout and finds start and endpoint of the maze
"""
with open(self.mazeFile) as f:
for row in f:
self.mazeLayout.append(row.rstrip().split())
for row in self.mazeLayout:
for node in row:
if node == "A":
self.startState = (self.mazeLayout.index(row), row.index(node))
elif node == "B":
self.goalState = (self.mazeLayout.index(row), row.index(node))
self.mazeHeight = len(self.mazeLayout)
self.mazeWidth = len(self.mazeLayout[0])
def printShortestPath(self):
"""
Prints the shortest path from start to end
"""
assert self.shortestPath != None
for i in range(self.mazeHeight):
for j in range(self.mazeWidth):
if (i, j) in self.shortestPath[1] and (i, j) != self.startState and (i, j) != self.goalState:
print("*", end=" ")
else:
print(self.mazeLayout[i][j], end=" ")
print()
def getShortestPath(self):
"""
Find the shortest path from start to end
"""
start = Node(state=self.startState, parent=None, action=None)
frontier = QueueFrontier()
explored = set()
frontier.push(start)
while (not frontier.isEmpty()):
currNode = frontier.pop()
self.numExplored += 1
# If the node contains a goal state, then we're done
if currNode.state == self.goalState:
actions = []
cells = []
# Backtrack to get path
while currNode.parent is not None:
actions.append(currNode.action)
cells.append(currNode.state)
currNode = currNode.parent
# Reorder path from start to end
actions.reverse()
cells.reverse()
self.shortestPath = (actions, cells)
return len(self.shortestPath[0])
# Mark node as explored so we don't revisit
explored.add(currNode.state)
# Add neighboring nodes if they have not been explored and aren't in the frontier
for d, a in self.getValidDirections(currNode):
newChild = Node(state=(d[0], d[1]), parent=currNode, action=a)
if newChild.state not in explored and not frontier.containsState(newChild):
frontier.push(newChild)
def getValidDirections(self, node):
"""
Return a list of node states representing valid neighbors
"""
up, down = (-1, 0), (1, 0)
left, right = (0, -1), (0, 1)
directions = [up, down, left, right]
validDirections = []
for d in directions:
potentialNeighbor = (node.state[0] + d[0], node.state[1] + d[1])
# Check for invalid indexes
if (potentialNeighbor[0] < 0) or (potentialNeighbor[0] > self.mazeHeight - 1) or (potentialNeighbor[1] < 0) or (potentialNeighbor[1] > self.mazeWidth - 1):
continue
# Add node if it isn't a wall
elif self.mazeLayout[potentialNeighbor[0]][potentialNeighbor[1]] != "1":
validDirections.append((potentialNeighbor, d))
return validDirections
def __str__(self):
maze = ""
for row in self.mazeLayout:
for cell in row:
maze += str(cell) + " "
maze += "\n"
return maze
if __name__ == "__main__":
file = input("Enter filename to test: ")
maze = Maze(file)
print("\nMaze Layout:\n{}".format(maze))
print("Length of Shortest Path: {}\n".format(maze.getShortestPath()))
print("Shortest Path:")
maze.printShortestPath() |
def replace_number(number, value, replace_by):
if number == 0:
return 0
digit = number % 10
if digit == value:
digit = replace_by
return digit + 10 * replace_number(number/10, value, replace_by)
print 12120234212, replace_number(12120234212, 2, 5)
print 12129294292, replace_number(12129294292, 9, 3)
|
# Return index, value and a string if value found else return -1
def binary_search(alist, value, left, right):
if right >= left:
mid = left + (right - left) / 2
if alist[mid] == value:
return mid, alist[mid], "found"
if value < alist[mid]:
right = mid -1
if value > alist[mid]:
left = mid + 1
return binary_search(alist, value, left, right)
else:
return - 1
li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
print binary_search(li, 23, 0, len(li)-1)
print binary_search(li, 11, 0, len(li)-1)
|
class Queue(object):
def __init__(self):
self.data = []
super(Queue, self).__init__()
def enqueue(self, value):
self.data.append(value)
return self.data
def dequeue(self):
if self.data:
return self.data.pop()
return None
def is_empty(self):
if not len(self.data):
return True
return False
def rear(self):
if not self.is_empty():
return self.data[-1]
return False
def front(self):
if not self.is_empty():
return self.data[0]
return False
q = Queue()
print q.enqueue(10)
print q.enqueue(20)
print q.dequeue()
print q.dequeue()
print q.data |
num1= float(input("Enter first number:"))
operator= input("Enter operator:")
num2= float(input("Enter second number:"))
if operator=="+":
print(num1+num2)
elif operator=="-":
print(num1-num2)
elif operator=="*":
print(num1*num2)
elif operator=="/":
print(num1/num2)
|
tries=0
secret_word="giraffe"
guess=0
while guess!=secret_word:
guess=input("Choose and animal in all lowercase letters:")
tries=tries+1
if tries==1:
print("The animal is yellow")
if tries==2:
print("The animal is yellow and has spots")
if tries==3:
print("The animal is yellow,has spots, and has a long neck")
if guess==secret_word:
print("You win!")
""" print("You are incorrect,please try again")
tries=tries+1
if tries==1:
print("The animal is yellow")
if tries==2:
print("The animal is yellow and has spots")
if tries==3:
print("The animal is yellow, has spots, and has a long neck")
"""
|
matrix = [[int(num) for num in input().split(", ")] for _ in range(int(input()))]
first_diagonal = [matrix[n][n] for n in range(len(matrix))]
second_diagonal = [matrix[n][len(matrix) - 1 - n] for n in range(len(matrix))]
print(f"First diagonal: {', '.join([str(x) for x in first_diagonal])}. Sum: {sum(first_diagonal)}")
print(f"Second diagonal: {', '.join([str(x) for x in second_diagonal])}. Sum: {sum(second_diagonal)}")
|
from collections import deque
commands = deque()
cars = deque()
passed_cars = 0
green_time = int(input())
window_time = int(input())
crash_flag = False
def crash(car, hit):
global crash_flag
print("A crash happened!")
print(f"{car} was hit at {hit}.")
crash_flag = True
def move_cars(time):
global passed_cars
if cars:
car = cars.popleft()
passed_cars += 1
if len(car) < time:
time -= len(car)
move_cars(time)
elif len(car) > time + window_time:
hit = car[time + window_time]
crash(car, hit)
command = input()
while command != "END":
if command != "green":
cars.append(command)
else:
move_cars(green_time)
if crash_flag:
break
command = input()
if not crash_flag:
print("Everyone is safe.")
print(f"{passed_cars} total cars passed the crossroads.")
|
def first_triangle(size):
for row in range(1, size + 2):
nums = [x for x in range(1, row)]
if nums:
print(" ".join(map(str, nums)))
def second_triangle(size):
for row in range(size, 0, -1):
nums = [x for x in range(1, row)]
if nums:
print(" ".join(map(str, nums)))
def triangle(n):
first_triangle(n)
second_triangle(n) |
lists = list(reversed([[n for n in peace.split()] for peace in input().split("|")]))
flatten_list = [el for sublist in lists for el in sublist]
print(*flatten_list, sep=" ")
|
def num_of_player(turn):
if turn % 2:
return 1
return 2
def get_turn(turn, free_r_in_c):
player = num_of_player(turn)
while True:
print(f"Player {player}, please choose a column.")
number_of_column = input()
if number_of_column.isnumeric():
number_of_column = int(number_of_column) - 1
if number_of_column in range(rows) \
and free_r_in_c[number_of_column] >= 0:
return free_r_in_c[number_of_column], number_of_column, player
print("Invalid column index!")
def push_mark(i, j, num):
global game_board
game_board[i][j] = num
def print_board():
[print(row) for row in game_board]
def positions(r, c):
return [[i*r, i*c] for i in range(1, N)]
def check_for_winner(i, j, num):
winning_lines = [
[positions(*DL), positions(*UR)], # primary diagonal: down-left half, up-right half
[positions(*DR), positions(*UL)], # secondary diagonal: down-right half, up-left half
[positions(*LL), positions(*RR)], # horizontal: left half, right half
[positions(*DD)] # vertical: down half
]
for line in winning_lines:
four_in_line = 1
for half_line in line:
for row_col in half_line:
n_row, n_col = i + row_col[0], j + row_col[1]
if n_row in range(rows) and n_col in range(columns) and game_board[n_row][n_col] == num:
four_in_line += 1
if four_in_line == 4:
return num
else:
break
N = 4 # N-consistent in line
DL, UR, DR, UL, LL, RR, DD = (1, -1), (-1, 1), (1, 1), (-1, -1), (0, -1), (0, 1), (1, 0)
rows, columns = [int(x) for x in input().split()]
game_board = [[0 for col in range(columns)] for row in range(rows)]
free_row_in_columns = [rows - 1 for _ in range(columns)]
turns = 1
while True:
row, col, mark = get_turn(turns, free_row_in_columns)
free_row_in_columns[col] -= 1
push_mark(row, col, mark)
print_board()
winner = check_for_winner(row, col, mark)
if winner:
print(f"The Winner is Player {winner}!")
break
if turns == rows * columns:
print("No winner!")
break
turns += 1
|
import os
def create(f_name):
with open(f_name, "w") as file:
pass
def add(f_name, content):
with open(f_name, 'a') as file:
file.write(f"{content}\n")
def replace(f_name, old_str, new_str):
if os.path.exists(f_name):
with open(f_name, 'r') as file:
text = file.read()
text = text.replace(old_str, new_str)
with open(f_name, 'w') as file:
file.writelines(text)
else:
print("An error occurred")
def delete(f_name):
try:
os.remove(f_name)
except FileNotFoundError:
print("An error occurred")
command = input() # for line in iter(input(), "End")
while command != "End":
action, file_name, *data = command.split("-")
if action == "Create":
create(file_name)
elif action == "Add":
add(file_name, data[0])
elif action == "Replace":
replace(file_name, data[0], data[1])
elif action == "Delete":
delete(file_name)
command = input()
|
# numbers_list = [int(x) for x in input().split(', ')]
# result = 1
#
# for number in numbers_list:
# if number <= 5:
# result *= number
# elif number > 5:
# result /= number
#
# print(result)
from errors import ValueCannotBeNegative
for _ in range(5):
num = int(input())
if num < 0:
raise ValueCannotBeNegative
|
from checks import num_of_player
def push_mark(i, j, num, game_board):
game_board[i][j] = num
def get_turn(turn, free_r_in_c, rows):
player = num_of_player(turn)
while True:
print(f"Player {player}, please choose a column.")
number_of_column = input()
if number_of_column.isnumeric():
number_of_column = int(number_of_column) - 1
if number_of_column in range(rows) \
and free_r_in_c[number_of_column] >= 0:
return free_r_in_c[number_of_column], number_of_column, player
print("Invalid column index!")
|
# def entry_list(n):
# lines = []
# for _ in range(n):
# lines.append(input())
# return lines
#
#
# count = int(input())
# names = entry_list(count)
#
# unique_names = set(names)
# for n in unique_names:
# print(n)
n = int(input())
names = set()
for _ in range(n):
names.add(input())
for n in names:
print(n)
|
nums = [int(n) for n in input().split(', ')]
result = {'Positive:': [el for el in nums if el >= 0], 'Negative:': [el for el in nums if el < 0], 'Even:': [el for el in nums if el % 2 == 0], 'Odd:': [el for el in nums if el % 2 != 0]}
for k, v in result.items():
n = ", ".join([str(x) for x in v])
print(f"{k} {n}")
# positive = []
# negative = []
# [negative.append(x) if x < 0 else positive.append(x) for x in nums]
#
# odd = []
# even = []
# [even.append(x) if x % 2 == 0 else odd.append(x) for x in nums]
|
contacts = {}
command = input()
while not command.isnumeric():
name, phone = command.split("-")
contacts[name] = phone
command = input()
for _ in range(int(command)):
n = input()
if n not in contacts:
print(f"Contact {n} does not exist.")
else:
print(f"{n} -> {contacts[n]}")
|
# define list
lst = [7, 8, 9, 2, 3, 1, 4, 10, 5, 6]
# sort list in ascending order without modify the list
l1 = sorted(lst)
# print sorted list in ascending order
print(l1)
# sort in descending order without modify the list
l1.reverse()
# print list
print(l1)
# print the even numbers in a list
even = l1[::2]
print(sorted(even))
# print the odd numbers in a list
odd = l1[1::2]
print(sorted(odd))
# print numbers of multiple of 3 in a list
multi = [y for y in l1 if y % 3 == 0]
sm = sorted(multi)
print(sm)
|
import random
def guessNumber():
attempts = 1
player = input(f"Let's play Number Guessing Game! \nWhat's your name? ")
print(f"Hello {player}! Let the fun begin! Just keep it in mind, you have 5 chances only!")
number = int(input("Guess A Number between 1 - 10!: "))
randomNumber = random.randint(1, 10)
if number < 1 or number > 10:
print("Please enter the number is range! (Between 1 - 100!)")
else:
try:
while(attempts < 5):
if(number == randomNumber):
print(f"{player}, You Got it in {attempts} attempts. Congratulations !!")
break
else:
if (number > randomNumber):
print(f"{player}, you guessed it a bit high!")
elif(number < randomNumber):
print(f"{player}, you guessed it a bit low!")
print("Let's try again! Enter another number!")
number = int(input())
attempts+=1
if(attempts == 5):
print(f"Oops! You Ran Out of Attempts! The number is: {randomNumber}")
except:
print("Oops! An Error Occured!!")
if __name__ == '__main__':
guessNumber() |
from fractions import Fraction
import math
class Calculator:
#odd se usa como fracc,pero no es igual,tener cuidado
def oddToProb(self,odd):
num,den=odd
return float(num)/(num+den)
def probToOdd(self,prob):
if prob==1:
return(1,0)
fracc=Fraction(prob)
haps=fracc.numerator
nothaps=fracc.denominator-fracc.numerator
while(haps>1000):
haps/=10
nothaps/=10
haps=math.floor(haps)
nothaps=math.floor(nothaps)
fracc=Fraction(haps,nothaps)
haps=fracc.numerator
nothaps=fracc.denominator
return (haps,nothaps)
#se considera el pot antes de apuesta
def betToPot(self,bet,pot):
return float(bet)/(pot+bet)
#def expectedValue(self,bet,pot,prob=None,odd=None):
def isProfitable(self,bet,pot,prob=None,odd=None):
btp=self.betToPot(bet,pot)
#print("btp:",btp)
if prob is not None:
#print("probability:",prob)
return prob>btp
if odd is not None:
probfromodd=self.oddToProb(odd)
return probfromodd>btp
|
# from math import gcd
# Usage:
# ans = gcd(100, 54)
# Euclid's algorithm
def gcd(a, b):
tmp = 0
while b > 0:
tmp = a
a = b
b = tmp % b
return a
|
import math
def prime_factors(n):
factors = []
while n % 2 == 0:
factors.append(2)
n = n // 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
factors.append(i)
n = n // i
if n > 2:
factors.append(n)
return factors
# Time Complexity: O(sqrt(N)), Space Complexity: O(N)
# usage:
# n = 100;
# factors = prime_factors(n);
# {2, 2, 5, 5}
# 2*2*5*5 = 2^2 * 5^2 = 100 |
from math import sqrt
def divisors(number: int) -> List[int]:
solutions = []
number = int(number)
for i in range(1, int(sqrt(number)) + 1):
if number % i == 0:
if number // i == i:
solutions.append(i)
else:
solutions.append(i)
solutions.append(number // i)
return solutions
# Time Complexity: O(sqrt(N)), Space Complexity: O(N)
# usage:
# number = 100;
# ans = divisors(number) # [1, 100, 2, 50, 4, 25, 5, 20, 10] |
char = str(input("please input a word:"))
vowels = "aeiou"
found = False
vowel = 0
cons = 0
for letter in char:
for vow in vowels:
if letter == vow:
found = True
break
if found == True:
vowel += 1
else: cons += 1
found = False
print("Your word has", vowel, "vowels, and", cons, "consonants.")
|
roman = str(input("Plese input a simplified roman numeral number:"))
numeral = "MDCLXVI"
total = 0
for letter in roman:
print(letter)
if letter == "M":
total += 1000
elif letter == "D":
total += 500
elif letter == "C":
total += 100
elif letter == "L":
total += 50
elif letter == "X":
total += 10
elif letter == "V":
total += 5
elif letter == "I":
total += 1
print("This is the number:", total)
|
weight = int(input("Please in put your weight in kilograms:"))
height = float(input("Now please input you height in meters:"))
bmi = weight/height**2
print("Your Body Mass Index is:", bmi)
|
phrase = str(input("Please type out a phase that has an odd amount of characters, spaces count too."))
print("This is the middle chracter:", phrase[len(phrase)//2:len(phrase)//2+1])
print("This is the first half:", phrase[:len(phrase)//2])
print("This is the latter half:", phrase[len(phrase)//2+1:])
|
import datetime
year = 2018
month = 2
day = 10
x = datetime.date(year,month,day)
print("This is today's date:", x)
|
# count the no. of duplicates word and print the count.
dict={}
#loop for taking the input words.
for i in range(int(input())):
#If input not in the dictionary, then add it
#else increment the counter
key = input()
if not key in dict.keys(): #keys() returns keys used in the dictionary.
dict.update({key : 1})
continue
dict[key] += 1
print(len(dict.keys()))
print(*dict.values())
|
#here compute the minimum price from given list of items
#here you have to select K items and l[J] must be purchased
#return the minimum price to purchase K items given l[J] must be included.
price=0
N,K,J=[int(i) for i in input().split()]
l = [int(i) for i in input().split()][:N]
price=price+l[J-1]
l.remove(l[J-1]
l.sort()
for i in range(0,K-1):
price=price+l[i]
print(price)
|
number=int(input("Enter a number N: "))
for x in range(1,6):
print(number*x)
|
n=input("Enter a number to find factorial: ")
r=1
if n>0:
for x in range(1,n+1):
r=r*x
print (r)
else:
print ("Enter a positive number")
|
print("hello")
a=int(input("enter the value"))
b = int (input("enter the second value"))
c=a+b
print("the vale is ",c)
print("welcome")
#hello |
''' Assumptions made : All laptops have Manufacturer name .
Gaming are expensive than'''
class Laptop(object):
def __init__(self,name):
self.name = name
class Gaminglaptop(Laptop):
def BuyLaptop(self, amount):
if amount < 0:
return "invalid amount"
if amount >=0 and amount <=50000:
return "we Currently do have the Laptop that fits that amount"
if amount >= 50000 and amount <= 70000:
return "you can buy a Core i3 660M "
elif amount >=70000 and amount <= 85000:
return "you can buy a Core i3 760M"
elif amount > 100000:
return "you can customized your laptop specs"
class Normallaptop(Laptop):
def __init__(self,amount):
self.Amount =Amount
def BuyLaptop(self, amount):
if amount <0:
return "invalid amount"
if amount >=0 and amount <=50000:
return "we Currently do have the Laptop that fits that amount"
if amount >= 50000 and amount <= 70000:
return "you can buy a Core i5 8gb RAM "
elif amount >=70000 and amount <= 85000:
return "you can buy a Core i7 4th Gen 16gb RAM"
elif amount > 10000:
return "you can customized your laptop specs"
Laptop("HP")
i = Gaminglaptop("hp")
print (i.BuyLaptop(70000)) |
"""
helper methods/globals for pgn_writer and pgn_reader
"""
#rows are 1-8
#assumed 8x8 2d array
#flipped means display w/ black pieces on bottom
COL_HEADS = {chr(i+97): i for i in range(8)} #ltrs a-h
def display(board, flipped=False):
if flipped:
board = board[::-1]
left_margin = " "*3
output = "\n"+left_margin
for k in COL_HEADS:
output += " {} ".format(k)
line = left_margin + '-'*33
output += "\n" + line
for r in range(8):
row_head = " "+str(r+1)+" " if flipped else " "+str(8-r)+" "
output += "\n{}| ".format(row_head)
for c in range(7):
output += str(board[r][c])+' | '
output += str(board[r][-1])+ ' |{}\n'.format(row_head)
output += line
output += "\n"+left_margin
for k in COL_HEADS:
output += " {} ".format(k)
output += "\n"
print(output)
return output
#useful helpers
# def get_col(array, i):
# return [r[i] for r in array]
def in_bounds(pos): #checking against negative coords or coords > 8
return pos[0]>=0 and pos[1]>=0 and pos[0]<8 and pos[1]<8
#lookup table
REL_STARTS = {
"N": [[(1,2),(2,1)],[(-1,2),(-2,1)],[(1,-2),(2,-1)],[(-1,-2),(-2,-1)]],
"R": [[(0,i) for i in range(-1, -8, -1)], [(0,i) for i in range(1, 8)], [(i,0) for i in range(-1, -8, -1)], [(i,0) for i in range(1, 8)]],
"B": [[(i,i) for i in range(-1, -8, -1)], [(i,i) for i in range(1, 8)], [(-i,i) for i in range(-1, -8, -1)], [(-i,i) for i in range(1, 8)]],
"K": [[t] for t in ({(i,j) for i in range(-1, 2) for j in range(-1, 2)} - {(0,0)})],
}
REL_STARTS["Q"] = REL_STARTS["R"]+REL_STARTS["B"] #add in queen moves
|
x = int(input("enter a number"))
if x%2 ==0 :
print("x is even")
else:
print("x is odd")
|
#Copy the contents from http://arcade.academy/examples/move_keyboard.html#move-keyboard and see if you can figure out what is going on. Add comments to any uncommented lines
"""
This simple animation example shows how to move an item with the keyboard.
If Python and Arcade are installed, this example can be run from the command line with:
python -m arcade.examples.move_keyboard
"""
import arcade
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
SCREEN_TITLE = "Move Keyboard Example"
MOVEMENT_SPEED = 3
class Ball:
def __init__(self, position_x, position_y, change_x, change_y, radius, color):
# Take the parameters of the init function above, and create instance variables out of them.
self.position_x = position_x #creating x variable position
self.position_y = position_y #creating y variable position
self.change_x = change_x #creating the variable of the x change
self.change_y = change_y #creating the variable of the y change
self.radius = radius #radius variable of the ball
self.color = color #color variable of the ball
def draw(self): #drawing itself
""" Draw the balls with the instance variables we have. """
arcade.draw_circle_filled(self.position_x, self.position_y, self.radius, self.color) # draw circle with variables
def update(self):
# Move the ball
self.position_y += self.change_y # variable y is equal to itself + whatever the change in y is
self.position_x += self.change_x # variable x is equal to istelf + whatever the change in x is
# See if the ball hit the edge of the screen. If so, change direction
if self.position_x < self.radius: # center of circle is not touching left boundary
self.position_x = self.radius # radius of circle is the distance of the center of the circle to the boundary
if self.position_x > SCREEN_WIDTH - self.radius: # if center of circle is greater than screen width, subtract the radius
self.position_x = SCREEN_WIDTH - self.radius
if self.position_y < self.radius: # center of circle is not touching top and bottom boundaries
self.position_y = self.radius # radius of circle is the distance from the center of the circle to the boundaries of the top and bottom parts of the screen
if self.position_y > SCREEN_HEIGHT - self.radius: # if center of circle is greater than screen height than subract the radius of the circle and show location
self.position_y = SCREEN_HEIGHT - self.radius
class MyGame(arcade.Window):
def __init__(self, width, height, title):
# Call the parent class's init function
super().__init__(width, height, title)
# Make the mouse disappear when it is over the window.
# So we just see our object, not the pointer.
self.set_mouse_visible(False) #if visible cant be true
arcade.set_background_color(arcade.color.ASH_GREY) # set background color of game to grey
# Create our ball
self.ball = Ball(50, 50, 0, 0, 15, arcade.color.AUBURN) #creating the ball
def on_draw(self):
""" Called whenever we need to draw the window. """
arcade.start_render() #rendering game
self.ball.draw() #draw ball
def update(self, delta_time): #update self
self.ball.update() #update location of ball
def on_key_press(self, key, modifiers):
""" Called whenever the user presses a key. """
if key == arcade.key.LEFT: # if key on keyboard is left
self.ball.change_x = -MOVEMENT_SPEED # move ball towards left
elif key == arcade.key.RIGHT: # if not left then right
self.ball.change_x = MOVEMENT_SPEED # move ball to the right
elif key == arcade.key.UP: # if up key is pressed
self.ball.change_y = MOVEMENT_SPEED # move location up on screen
elif key == arcade.key.DOWN: # else must be down
self.ball.change_y = -MOVEMENT_SPEED # move location down on screen
def on_key_release(self, key, modifiers): # defining key release
""" Called whenever a user releases a key. """
if key == arcade.key.LEFT or key == arcade.key.RIGHT: # once either left or right key are released
self.ball.change_x = 0 # ball position will not change
elif key == arcade.key.UP or key == arcade.key.DOWN: # once either up or down key are released
self.ball.change_y = 0 # ball position won't change
def main():
print("my game")
window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
arcade.run()
if __name__ == "__main__":
main() |
# Uses python3
import sys
def fibonacci_partial_sum_naive(n):
if n <= 2:
return n
#The pisano period of modulo by 10 is 60
num = n%60
if num == 0:
sum = 0
else:
sum = 1
div = int(n/60)
ar = [0,1]
for i in range (2,num+1):
ar.append((ar[i-1]+ar[i-2])%10)
sum = sum + ar[i]
return sum%10
from_, to = map(int, sys.stdin.readline().split())
n = fibonacci_partial_sum_naive(to)
m = fibonacci_partial_sum_naive(from_-1)
if n-m<0:
print(10+n-m)
else:
print (n-m) |
# Uses python3
def calc_fib(n):
ar = [0,1]
for i in range (2,n+1):
ar.append(ar[i-1]+ar[i-2])
return ar[n]
n = int(input())
print(calc_fib(n))
|
"""
Problem Statement:
Design the class structure for a keyword-based document search engine.
Requirements
- A document consists of an integer ID, a title, and a body.
- A keyword search consists of a short set of tokens (<= ~10) and should return
the documents which contain the highest number of occurrences
of the given tokens.
- Function for adding new documents without a given list of stop-words.
(Stop-words are the same for all documents)
- Function for querying given a string and returning the top n documents.
- Support multiple backends for document storage - e.g. an in-memory
data store which can't hold a ton of data but is convenient for
development and testing, and a Postgres database which would be used
in production.
- Provide an example of how the search engine would be used with some
short dummy documents.
Loose Criteria:
- Concrete classes for Document and SearchEngine.
- Abstract class for DataStore with concrete classes for the different backends.
- SearchEngine encapsulates the search-specific logic (tokenizing, stop-words, getting top n)
- DataStore implementations encapsulate the storage-specific logic
- store documents easily retrievable by id.
- store an inverted-index of keywords pointing to document ids.
- SearchEngine calls the DataStore methods the same way regardless of the backend.
- Recognizes that the DataStore methods could be wildly different based on the implementation.
- DataStore and stop words injected into SearchEngine.
- Postgres connection or connection parameters injected into the SearchEngine.
- Uses idiomatic language constructs, e.g.:
- @dataclass for the Document class
- defaultdict for the inverted index
- Recognizes the need/uses efficient algos and data structures, e.g.:
- hashmap for storing documents and ids
- inverted index stores the ids, not the full documents
- partial sort for the _top_n method
- Uses dummy/partially-implemented functions where appropriate.
Follow-up topics:
- Schema, indexing, and queries in postgres database.
- Partial sort implementation.
- How to handle queries that consist entirely of stop-words
- How to parallelize
"""
from collections import defaultdict
from dataclasses import dataclass
from typing import List, Iterator, Set, Dict
DEFAULT_STOP_WORDS = frozenset({"a", "an", "and", "the"})
@dataclass()
class Document:
id: int
title: str
body: str
class DataStore(object):
def insert(self, token: str, doc: Document):
...
def get_ids(self, token: str) -> Iterator[Document]:
...
def get_doc(self, id: int) -> Document:
...
class InMemoryDataStore(DataStore):
def __init__(self):
self._id_to_doc: Dict[int, Document] = dict()
self._token_to_doc_ids: Dict[str, Iterator[int]] = defaultdict(list)
def insert(self, token: str, doc: Document):
self._id_to_doc[doc.id] = doc
self._token_to_doc_ids[token] = doc.id
def get_ids(self, token: str) -> Iterator[int]:
return self._token_to_doc_ids[token]
def get_doc(self, id: int) -> Document:
return self._id_to_doc[id]
class PostgresDataStore(DataStore):
def __init__(self, conn):
...
class SearchEngine(object):
def __init__(self, data_store: DataStore, stop_words: Set[str] = DEFAULT_STOP_WORDS):
self.data_store = data_store
self.stop_words = stop_words
def _tokenize_and_filter(self, text: Iterator[str]) -> Iterator[str]:
...
def _top_n(self, items: List[int], n: int) -> List[int]:
...
def insert(self, doc: Document):
for text in (doc.body, doc.title):
for token in self._tokenize_and_filter(text):
self.data_store.insert(token, doc)
def search(self, keywords: Iterator[str], n: int) -> Iterator[Document]: # TODO: overload the type.
candidate_ids = list()
for token in self._tokenize_and_filter(keywords):
candidate_ids += datastore.get_ids(token)
top_ids = self._top_n(candidate_ids, n)
return map(self.data_store.get_doc, top_ids)
if __name__ == "__main__":
with ... as pgconn:
datastore = PostgresDataStore(pgconn)
google = SearchEngine(datastore)
docs = [
Document(1, "cat", "The cat utility reads files sequentially..."),
Document(2, "grep", "The grep utility searches any given input files..."),
Document(3, "sed", "The sed utility reads the specified files,,,")
]
_ = [google.insert(d) for d in docs]
for doc in google.search("utility that reads files", 2):
print(doc.id, doc.title)
|
#
# @lc app=leetcode id=23 lang=python3
#
# [23] Merge k Sorted Lists
#
# https://leetcode.com/problems/merge-k-sorted-lists/description/
#
# algorithms
# Hard (33.24%)
# Total Accepted: 356.4K
# Total Submissions: 1.1M
# Testcase Example: '[[1,4,5],[1,3,4],[2,6]]'
#
# Merge k sorted linked lists and return it as one sorted list. Analyze and
# describe its complexity.
#
# Example:
#
#
# Input:
# [
# 1->4->5,
# 1->3->4,
# 2->6
# ]
# Output: 1->1->2->3->4->4->5->6
#
#
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
## Time limit exceed
# class Solution:
# def mergeKLists(self, lists: List[ListNode]) -> ListNode:
# lst = list(filter(None,lists))
# if not lst:
# return None
# lists = lst
# dummyhead = ListNode(0)
# cur = dummyhead
# while lists:
# valuelst = [node.val for node in lists]
# for index,value in enumerate(valuelst):
# if value == min(valuelst):
# cur.next = lists[index]
# cur = cur.next
# lists[index]=lists[index].next
# if not lists[index]:
# lists.pop(index)
# break
# return dummyhead.next
## Very long time: recursion
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if not lists:
return None
if len(lists)==1:
return lists[0]
lst1 = lists[0]
lst2 = self.mergeKLists(lists[1:])
dummyhead = ListNode(0)
cur = dummyhead
while lst1 and lst2:
if lst1.val < lst2.val:
cur.next = lst1
lst1=lst1.next
else:
cur.next = lst2
lst2=lst2.next
cur=cur.next
if not lst1 or not lst2:
cur.next = lst1 if lst1 else lst2
return dummyhead.next
## Iteration: very slow
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
import functools
if not lists:
return None
if len(lists)==1:
return lists[0]
head = functools.reduce(self.merge2,lists)
return head
def merge2(self,lst1,lst2):
dummyhead = ListNode(0)
cur = dummyhead
while lst1 and lst2:
if lst1.val < lst2.val:
cur.next = lst1
lst1=lst1.next
else:
cur.next = lst2
lst2=lst2.next
cur=cur.next
if not lst1 or not lst2:
cur.next = lst1 if lst1 else lst2
return dummyhead.next
## Sort numbers
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if not lists:
return None
if len(lists)==1:
return lists[0]
value=[]
for node in lists:
while node:
value.append(node.val)
node = node.next
dummyhead = ListNode(0)
cur = dummyhead
for val in sorted(value):
cur.next = ListNode(val)
cur = cur.next
return dummyhead.next
## PriorityQueue
# O(Nlogk)
# TypeError '<' not supported between instances of 'ListNode' and 'ListNode':
# This error occurs because ListNode definition does not include __lt__ method.
# To avoid this error, we can use a wrapper class with __lt__ method for ListNode.
# https://leetcode.com/problems/merge-k-sorted-lists/solution/
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
class Wrapper():
def __init__(self, node):
self.node = node
def __lt__(self,other):
return self.node.val < other.node.val
from queue import PriorityQueue
dummy = ListNode(0)
cur = dummy
pq = PriorityQueue()
for node in lists:
if node:
pq.put(Wrapper(node))
while not pq.empty():
node = pq.get().node
cur.next = node
cur = cur.next
node = node.next
if node:
pq.put(Wrapper(node))
return dummy.next
## Divide and conquer
# O(Nlogk)
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if not lists:
return None
if len(lists)==1:
return lists[0]
for i in range(len(lists)//2):
lists[2*i]=self.merge2(lists[2*i],lists[2*i+1])
lists = lists[::2]
return self.mergeKLists(lists)
def merge2(self,lst1,lst2):
dummyhead = ListNode(0)
cur = dummyhead
while lst1 and lst2:
if lst1.val < lst2.val:
cur.next = lst1
lst1=lst1.next
else:
cur.next = lst2
lst2=lst2.next
cur=cur.next
if not lst1 or not lst2:
cur.next = lst1 if lst1 else lst2
return dummyhead.next
## Heap
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
from heapq import heappush, heappop
heap = []
for node in lists:
while node:
heappush(heap,node.val)
node = node.next
dummy = ListNode(0)
cur = dummy
while heap:
cur.next = ListNode(heappop(heap))
cur = cur.next
return dummy.next
|
#
# @lc app=leetcode id=50 lang=python3
#
# [50] Pow(x, n)
#
# https://leetcode.com/problems/powx-n/description/
#
# algorithms
# Medium (27.58%)
# Total Accepted: 293.7K
# Total Submissions: 1.1M
# Testcase Example: '2.00000\n10'
#
# Implement pow(x, n), which calculates x raised to the power n (x^n).
#
# Example 1:
#
#
# Input: 2.00000, 10
# Output: 1024.00000
#
#
# Example 2:
#
#
# Input: 2.10000, 3
# Output: 9.26100
#
#
# Example 3:
#
#
# Input: 2.00000, -2
# Output: 0.25000
# Explanation: 2^-2 = 1/2^2 = 1/4 = 0.25
#
#
# Note:
#
#
# -100.0 < x < 100.0
# n is a 32-bit signed integer, within the range [−2^31, 2^31 − 1]
#
#
## Recursion
# class Solution:
# def myPow(self, x: float, n: int) -> float:
# if n ==0:
# return 1
# elif n == 1:
# return x
# elif n <0:
# return self.myPow(1/x,-n)
# else:
# return self.myPow(x*x,int(n/2))*(x if n%2 else 1)
##
# class Solution:
# def myPow(self, x: float, n: int) -> float:
# if n ==0:
# return 1
# elif n <0:
# return 1/self.myPow(x,-n)
# else:
# result = 1
# powern = x
# for i in bin(n)[::-1]:
# if i == 'b':
# return result
# elif i == '1':
# result *= powern
# powern *= powern
##
class Solution:
def myPow(self, x: float, n: int) -> float:
return x**n
# s=Solution()
# print(s.myPow(8.84372,-5)-pow(8.84372,-5))
# print(s.myPow(-2,5))
# print((-2)**5)
# print(s.myPow(2,5))
# print(s.myPow(8.84372,-5))
# # # # print(list(map(lambda x:s.myPow(8.84372, -x)-pow(8.84372, -x),range(10))))
|
#
# @lc app=leetcode id=1006 lang=python3
#
# [1006] Clumsy Factorial
#
# https://leetcode.com/problems/clumsy-factorial/description/
#
# algorithms
# Medium (55.22%)
# Total Accepted: 4.8K
# Total Submissions: 8.6K
# Testcase Example: '4'
#
# Normally, the factorial of a positive integer n is the product of all
# positive integers less than or equal to n. For example, factorial(10) = 10 *
# 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.
#
# We instead make a clumsy factorial: using the integers in decreasing order,
# we swap out the multiply operations for a fixed rotation of operations:
# multiply (*), divide (/), add (+) and subtract (-) in this order.
#
# For example, clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1. However,
# these operations are still applied using the usual order of operations of
# arithmetic: we do all multiplication and division steps before any addition
# or subtraction steps, and multiplication and division steps are processed
# left to right.
#
# Additionally, the division that we use is floor division such that 10 * 9 / 8
# equals 11. This guarantees the result is an integer.
#
# Implement the clumsy function as defined above: given an integer N, it
# returns the clumsy factorial of N.
#
#
#
# Example 1:
#
#
# Input: 4
# Output: 7
# Explanation: 7 = 4 * 3 / 2 + 1
#
#
# Example 2:
#
#
# Input: 10
# Output: 12
# Explanation: 12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1
#
#
#
#
# Note:
#
#
# 1 <= N <= 10000
# -2^31 <= answer <= 2^31 - 1 (The answer is guaranteed to fit within a 32-bit
# integer.)
#
#
#
class Solution:
def clumsy(self, N: int) -> int:
result = 0
n = N
while(N>0):
minus = 0
if N == n:
minus = 1
if N >=4:
result -= int(N*(N-1)/(N-2))-(N-3)
N = N-4
elif N ==3:
result -=int( N*(N-1)/(N-2))
N = N-3
elif N ==2:
result -= N*(N-1)
N=N-2
elif N ==1:
result -= N
N=N-1
result = result*(-1)*minus
return result
## Recursion
class Solution:
def clumsy(self, N: int) -> int:
def caltail(n):
if n == 1: return -1
if n == 2: return -2
if n == 3: return -6
if n == 4: return -5
return caltail(n - 4) - n * (n - 1) // (n - 2) + (n - 3)
if N == 1: return 1
if N == 2: return 2
if N == 3: return 6
if N == 4: return 7
return N * (N - 1) // (N - 2) + N - 3 + caltail(N - 4)
## Test
S=Solution()
print(S.clumsy(10))
|
#
# @lc app=leetcode id=61 lang=python3
#
# [61] Rotate List
#
# https://leetcode.com/problems/rotate-list/description/
#
# algorithms
# Medium (26.55%)
# Total Accepted: 179.7K
# Total Submissions: 676K
# Testcase Example: '[1,2,3,4,5]\n2'
#
# Given a linked list, rotate the list to the right by k places, where k is
# non-negative.
#
# Example 1:
#
#
# Input: 1->2->3->4->5->NULL, k = 2
# Output: 4->5->1->2->3->NULL
# Explanation:
# rotate 1 steps to the right: 5->1->2->3->4->NULL
# rotate 2 steps to the right: 4->5->1->2->3->NULL
#
#
# Example 2:
#
#
# Input: 0->1->2->NULL, k = 4
# Output: 2->0->1->NULL
# Explanation:
# rotate 1 steps to the right: 2->0->1->NULL
# rotate 2 steps to the right: 1->2->0->NULL
# rotate 3 steps to the right: 0->1->2->NULL
# rotate 4 steps to the right: 2->0->1->NULL
#
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
### 可能是对的的答案但是超过time limit 了,考虑两个edge case:
### [1] 0
### [1,2,3] 20000000
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if not head:
return None
if not k:
return head
fast = head
while fast:
fast = fast.next
k-=1
if not k:
if not fast:
return head
else:
break
if not fast:
fast = head
slow = head
while fast.next:
fast = fast.next
slow = slow.next
fast.next = head
newhead = slow.next
slow.next = None
return newhead
## Solution
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if not head or not head.next:
return head
if not k:
return head
cur = head
lenth = 1
while cur.next:
cur = cur.next
lenth += 1
steps = k%lenth
if not steps:
return head
else:
cur.next = head
for _ in range(lenth-steps-1):
head=head.next
newhead = head.next
head.next = None
return newhead
|
import traceback
from datetime import datetime
class Player():
def __init__(self, data):
"""Takes a dict converted from the JSON response by the API and wraps
the player data within an object.
:param data: The player data from the API's response.
:type data: dict
"""
self.name = data['name']
self.position = data['position']
self.jersey_number = data['jerseyNumber']
self.date_of_birth = datetime.strptime(data['dateOfBirth'],
'%Y-%m-%d').date()
self.nationality = data['nationality']
self.contract_until = datetime.strptime(data['contractUntil'],
'%Y-%m-%d').date()
self.market_value = data['marketValue']
|
class Three_Vecter:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def __add__(self, n):
r = Three_Vecter()
r.x = self.x + n.x
r.y = self.y + n.y
r.z = self.z + n.z
return r
def __sub__(self, n):
r = Three_Vecter()
r.x = self.x - n.x
r.y = self.y - n.y
r.z = self.z - n.z
return r
def __mul__(self, n):
r = Three_Vecter()
r.x = self.x * n
r.y = self.y * n
r.z = self.z * n
return r
def __truediv__(self, n):
r = Three_Vecter()
r.x = self.x / n
r.y = self.y / n
r.z = self.z / n
return r
def __floordiv__(self, n):
r = Three_Vecter()
r.x = self.x // n
r.y = self.y // n
r.z = self.z // n
return r
def show(self):
print((self.x, self.y, self.z))
if __name__ == '__main__':
v1 = Three_Vecter(1, 2, 3)
v2 = Three_Vecter(4, 5, 6)
v3 = v1+v2
v3.show()
v4 = v1-v2
v4.show()
v5 = v1*3
v5.show()
v6 = v1/2
v6.show()
'''三要素: 封装继承和多态'''
|
import random
class Card:
"""The responisibility of this class:
--draw the card
--validate the user's guess
--determine if correct
--put a score to the round
Attributes:
--last card: interger of last card drawn
--current card: interger of current card drawn
--current card type: string that indicates card type
--stored guess: sotring the last gues made
"""
def __init__(self):
"""The class constructor.
Declares and initializes instance attributes.
args: self(Card): instance of Card"""
self.last_card = 0
self.current_card = 0
self.current_card_type = ''
self.stored_guess = ''
def draw_card(self):
"""Determines what the card will be.
args: self(Card): instance of Card
"""
self.current_card = random.randint(1, 13)
card_types = ('spade', 'heart', 'diamond', 'club')
self.current_card_type = random.choice(card_types)
def valid_user_guess(self, hi_lo):
"""Stores the guess from the interface into an attribute.
Preforms additional validation on input.
args: self(Card): instance of Card
Returns bool: True on valid input, False on invalid input
"""
if len(hi_lo) > 1 or len(hi_lo) == 0:
return False
hi_lo = hi_lo.lower()
if (not hi_lo == 'h') and (not hi_lo == 'l'):
return False
if type(hi_lo) is not str:
return False
# All validation checks passed, store it
self.stored_guess = hi_lo
return True
def check_user_guess(self):
"""See if the user's guess is correct.
args: self(Card): instance of Card
Returns bool: True if correct, False if incorrect
"""
if self.stored_guess == "h" and self.current_card > self.last_card:
return True
elif self.stored_guess == "l" and self.current_card < self.last_card:
return True
else:
return False
def rotate_to_last(self):
self.last_card = self.current_card
def mod_score(self):
"""This determines points for individual rounds.
args: self(Card): instance of Card
returns: Points of the round."""
if self.check_user_guess():
points = 100
elif not self.check_user_guess():
points = -75
return points
def pretty_card(self):
"""Customize look of the card.
args: self(Card): instance of Card
returns: Picture of the card and description of the card drawn."""
card_types = {
'spade': 0x1f0a0,
'heart': 0x1f0b0,
'diamond': 0x1f0c0,
'club': 0x1f0d0
}
card_val = {
1: 'Ace',
2: '2',
3: '3',
4: '4',
5: '5',
6: '6',
7: '7',
8: '8',
9: '9',
10: '10',
11: 'Jack',
12: 'Queen',
13: 'King'
}
pretty_val = card_val[self.current_card]
unicode_val = card_types[self.current_card_type] + self.current_card
return f'{chr(unicode_val)} ({pretty_val} of {self.current_card_type.title()}s)'
|
a = 2
b = 3
print(a * b)
print(a ** b)
print(a // b)
print(a / b)
print(a - b)
print(a + b)
|
def triangleArea():
height = int(input("Enter triangle height : "))
base = int(input("Enter triangle base : "))
area = (height * base) / 2
print("Area of triangle is {}". format(area))
triangleArea() |
def strReverse():
fname = input("Enter your first name : ")
lname = input("Enter your last name : ")
rev_fname = fname[::-1]
rev_lname = lname[::-1]
print(rev_fname+" "+rev_lname)
strReverse() |
import sqlite3 as lite
class DatabaseManage(object):
def __init__(self):
global con
try:
con = lite.connect("course.db")
with con:
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS course(Id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, description TEXT, price TEXT, is_private BOOLEAN NOT NULL DEFAULT 1)")
except Exception:
print("Unable to create DB!")
# TODO : Insert data
def insert_data(self, data):
try:
with con:
cur = con.cursor()
cur.execute("INSERT INTO course(name, description, price, is_private) VALUES (?,?,?,?)", data)
return True
except Exception:
return False
# TODO : Fetch data
def fetch_data(self):
try:
with con:
cur = con.cursor()
cur.execute("SELECT * FROM course")
return cur.fetchall()
except Exception:
return False
# TODO : Delete data
def delete_data(self, id):
try:
with con:
cur = con.cursor()
sql = "DELETE FROM course WHERE Id = ?"
cur.execute(sql, [id])
return True
except Exception:
return False
# TODO : User interface
def main():
db = DatabaseManage()
print("*"*40)
print("\n :: COURSE MANAGEMENT :: \n")
print("*"*40)
print("\n")
print("#"*40)
print("\n :: User Manual :: \n")
print("#"*40)
print("\n")
print("Press 1. Insert new course \n")
print("Press 2. Show all courses \n")
print("Press 3. Delete course (Enetr course id) \n")
print("#"*40)
print("\n")
choice = input("\n Enter your choice: ")
if choice == "1":
name = input("Enter course name : ")
description = input("Enter course description : ")
price = input("Enter course price : ")
is_private = input("Is this course is private (0/1) : ")
if db.insert_data([name, description, price, is_private]):
print("Course added successfully")
else:
print("Oops Something is wrong")
elif choice == "2":
print("\n :: Course List :: \n")
for index, item in enumerate(db.fetch_data()):
print("Sl no " + str(index + 1))
print("Course Id " + str(item[0]))
print("Course name " + str(item[1]))
print("Course description " + str(item[2]))
print("Course price " + str(item[3]))
private = "Yes" if item[4] else "No"
print("Is private " + str(private))
print("\n")
elif choice == "3":
id = input("Enter course id to delete : ")
if db.delete_data(id):
print("Course deleted successfully")
else:
print("Oops Something is wrong")
else:
print("\n Bad Choice")
if __name__ == "__main__":
main() |
import re
string = "Hello my name is gaurav sanas, I am 27 years old"
match = re.search("27", string)
if match:
print("match found at position : ", match.start())
else:
print("not found")
# case sensitive if we used small h it will not match
# ^ start with
match2 = re.search("^Hello", string)
if match2:
print("match found")
else:
print("not found")
# Ends with used $
match3 = re.search("old$", string)
if match3:
print("match found")
else:
print("not found")
# start with and Ends with used ^ $
match4 = re.search("[^Hello.*old$]", string)
if match4:
print("match found")
else:
print("not found")
# findall()
match5 = re.findall("a", string)
if match5:
print("match found")
else:
print("not found")
|
from datetime import date, time, datetime
from math import floor
DAYS_PER_YEAR = 365
class Decalander:
MONTHS_PER_YEAR = 10
DAYS_PER_MONTH = floor(DAYS_PER_YEAR / MONTHS_PER_YEAR)
def __init__(self, year: int, ordinal: int):
self.year = year
self.ordinal = ordinal
def __str__(self):
dpm = Decalander.DAYS_PER_MONTH
month = self.ordinal // dpm + 1
if month == 11:
month = "c" # stands for TODO
day = self.ordinal % dpm + 1
return "{}-{}-{}".format(self.year, month, day)
@staticmethod
def today():
return Decalander.from_gregorian(date.today())
@ staticmethod
def from_gregorian(greg: date):
# special case, our leap day is the last day
if greg.month == 2 and greg.day == 29:
year_ordinal = 365
else:
year_ordinal = (date(1999, greg.month, greg.day) -
date(1999, 1, 1)).days
return Decalander(greg.year, year_ordinal)
TIME_FORMAT = "%H:%M:%S"
MIDNIGHT = datetime.strptime("00:00:00", TIME_FORMAT)
GREG_SECONDS_PER_DAY = 24*60*60
class Decatime:
HOURS_PER_DAY = 10
MINUTES_PER_HOUR = 100
SECONDS_PER_MINUTE = 100
SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR
SECONDS_PER_DAY = SECONDS_PER_HOUR * HOURS_PER_DAY
RATIO = SECONDS_PER_DAY/GREG_SECONDS_PER_DAY
def __init__(self, seconds_am: int):
self.seconds_am = seconds_am*Decatime.RATIO
def __str__(self):
seconds = self.seconds_am % Decatime.SECONDS_PER_MINUTE
minutes = (self.seconds_am //
Decatime.SECONDS_PER_MINUTE) % Decatime.MINUTES_PER_HOUR
hours = self.seconds_am // Decatime.SECONDS_PER_HOUR
return "{:>1d}:{:>02d}:{:>02d}".format(int(hours), int(minutes), int(seconds))
@staticmethod
def now():
return Decatime.from_greg_time(datetime.now())
@ staticmethod
def from_greg_time(greg: datetime):
time_am = (greg - MIDNIGHT)
seconds_after_midnight = time_am.seconds
seconds_after_midnight += time_am.microseconds / 1e6
return Decatime(seconds_after_midnight)
if __name__ == "__main__":
dates = [date(2000, 1, 1), date(2000, 12, 31),
date(1989, 12, 14), date(1992, 12, 14),
date(1991, 5, 25), date(2000, 2, 29)]
for d in dates:
print("gregorian: {}, decalendar: {}".format(
d, Decalander.from_gregorian(d)))
now = datetime.now()
times = [
datetime.strptime("00:00:00", TIME_FORMAT),
datetime.strptime("12:00:00", TIME_FORMAT),
datetime.strptime("23:59:59", TIME_FORMAT),
now
]
for t in times:
print("gregorian: {}, decitime: {}".format(
t, Decatime.from_greg_time(t)))
|
# Python program to find largest number in a list
# List of numbers
list = [13, 10, 25, 31, 56, 80, 95, 110, 250, -2, -7]
# Sorting the list
list.sort()
# Printing numbers in the list
print("The Numbers from the list is: ", list)
# Printing the first largest number in the list
print("The first largest number is:", list[-1])
# Printing the second largest number in the list
print("The second largest number is:", list[-2])
# Printing the last largest number in the list
print("The smallest number is:", list[3])
# Using list comprehension
# Print even number from list
even_num = [num for num in list if num % 2 == 0]
print("Even number from list is: ", even_num)
# Using list comprehension
# Print Odd number from list
odd_num = [oddnum for oddnum in list if oddnum % 2 == 1]
print("Odd number from list is: ", odd_num)
|
import helper
import authorization
import alexa_device
__author__ = "NJC"
__license__ = "MIT"
__version__ = "0.2"
def user_input_loop(alexa_device):
""" This thread initializes a voice recognition event based on user input. This function uses command line
input for interacting with the user. The user can start a recording, or quit if desired.
This is currently the "main" thread for the device.
"""
# While the stop event is not set
while True:
# Prompt user to press enter to start a recording, or q to quit
text = input("Press enter anytime to start recording (or 'q' to quit).")
# If 'q' is pressed
if text == 'q':
# Set stop event and break out of loop
alexa_device.close()
break
# If enter was pressed (and q was not)
# Get raw audio from the microphone
alexa_device.user_initiate_audio()
if __name__ == "__main__":
# Load configuration file (contains the authorization for the user and device information)
config = helper.read_dict('config.dict')
# Check for authorization, if none, initialize and ask user to go to a website for authorization.
if 'refresh_token' not in config:
print("Please go to http://localhost:5000")
authorization.get_authorization()
config = helper.read_dict('config.dict')
# Create alexa device
alexa_device = alexa_device.AlexaDevice(config)
user_input_loop(alexa_device)
print("Done")
|
a = [3, 4, 5]
b = a
# assign the variable "a" to a new list without changing "b"
a = [i + 3 for i in a]
b = a[:] # even better way to copy a list
print (a)
print(b)
|
# Elaborar um programa que apresente o valor da conversão em dólar lido em real.
real = float(input('Quantos reais deseja converter? '))
price = float(input('Qual o valor da cotação do dolar? '))
print(f'R${real} convertido em dolares é igual a R${real / price}')
|
"""
Elaboar um programa que faça a leitura de 4 valores inteiros. Ao final, apresentar o resultado do produto do
primeiro com o terceiro e a soma do segundo com o quarto
"""
a = int(input('Digite o primeiro valor: '))
b = int(input('Digite o segundo valor: '))
c = int(input('Digite o terceiro valor: '))
d = int(input('Digite o quarto valor: '))
print(f'O produto de {a} e {c} é igual a {a * c}')
print(f'A soma de {b} e {d} é igual a {b + d}')
|
"""
Ler uma temperatura em Fahrenheit e apresentá-la convertida em Celsius.
C = (F - 32) * (5 / 9)
"""
F = float(input('Entre com uma temperatura em Fahrenheit: '))
C = (F - 32) * (5 / 9)
print('%s graus Fahrenheit são %.2f graus Celsius' % (F, C))
|
from random import * # So that we can have random numbers.
def main():
mum = "Eileen"
dad = "Sydney"
wife = "Laura"
place = "Sydney"
print(id(mum))
print("Hi, Mom")
print(id(dad))
print(id(place))
main()
# Note that the ids of dad and place are identical.
# This is an example of Python's 'interning'.
|
class Queue:
def __init__(self):
self.items = []
def enqueue(self, value):
self.items.insert(0, value)
def deq(self):
return self.items.pop()
def isEmpty(self):
return (len(self.items) == 0)
def size(self):
return (len(self.items))
if __name__ == '__main__':
main()
|
def gcd(m,n):
while m %n != 0 :
oldm = m
oldn = n
m = oldn
n = oldm%oldn
return n
m = int(input("Enter 1st int: "))
n = int(input("Enter 2nd int: "))
print(gcd(m,n))
|
from math import log10
from tkinter import IntVar, Spinbox
class SDTShowSpinbox(Spinbox):
def __init__(self, master=None, sdt=None, show_cnt=1, command=None):
self.sdt = sdt
# Initialize Variables
self.curr_show = IntVar()
self.curr_show.set(1)
self.show_cnt = show_cnt
width = 2 * int(log10(self.show_cnt))
Spinbox.__init__(self, master,
from_=1, to=self.show_cnt, increment=1,
command=command,
textvariable=self.curr_show,
width=width)
# Bind FocusOut event to update the show number when the user leaves
# the spinbox (which intuitively means that the user has edited the
# number to satisfy their desire)
self.bind("<FocusOut>", self._enter_spinbox)
# Bind MouseWheel event to scroll the spinbox when the user scrolls
# their mousewheel
self.bind("<MouseWheel>", self._scroll_spinbox)
# Bind Return event to update the show number when the user presses
# the enter key (which intuitively means that the user has edited the
# number to satisfy their desire)
self.bind("<Return>", self._enter_spinbox)
# Sets up the spinbox to verify that only numbers are being entered
# into the spinbox. This function must be called every time that a
# spinbox action takes place to ensure that it continues to stay
# linked appropriately.
self._setup_validate()
def get_show_num(self):
return self.curr_show.get()
def reconfigure_show_cnt(self, new_show_cnt):
width = 2 * int(log10(new_show_cnt))
self.configure(to=new_show_cnt)
self.configure(width=width)
self.show_cnt = new_show_cnt
self.set_show_num(self.curr_show.get())
def set_show_num(self, show_num=1):
if(self.show_cnt > 1):
self.curr_show.set(show_num - 1)
self.invoke(element="buttonup")
elif(self.show_cnt == 1):
# This is necessary because when show_cnt == 1, then the bounds of
# the Spinbox don't work properly
self.curr_show.set(1)
# Function must be called after the text variable is changed because
# .set() disconnects the validate function
self._setup_validate()
def _enter_spinbox(self, event):
self.set_show_num(show_num=self.curr_show.get())
def _scroll_spinbox(self, event):
increment = event.delta // 120
new_value = self.curr_show.get() + increment - 1
self.set_show_num(show_num=new_value)
def _setup_validate(self):
validatecommand = self.register(self._validate_input)
self.configure(validate="all", validatecommand=(validatecommand, "%S"))
def _validate_input(self, input_value):
return input_value.isdigit()
|
vegetables = [
{"name": "eggplant"},
{"name": "tomato"},
{"name": "corn"},
]
print(vegetables)
import csv
with open('veggies.csv', 'w') as f:
writer= csv.writer(f)
writer.writerow(['name','length'])
for veggie in vegetables:
#i want the name of the veg
vegetable_name = veggie['name']
veggie_name_length = len(veggie['name'])
#write those to CSV
row = [vegetable_name, veggie_name_length]
writer.writerow(row) |
#加 +
print(1+1)
# 减 -
print(1-1)
#乘 *
print(2*2)
#除 /
print(9/3)
#取余%
print(2%3)
a = 10
b = 30
print(a+b-a)
# 字符串 列表 元组
#字符串
s = '1111'
d = '2222'
print(s+d )
# 列表
l = [1,2,3,4]
k = [5,6,7,8]
print(l+k)
# 元组
t = (1,2,3,4,)
y = (3,5,8,)
print(t+y)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#__title__ = ''
#__author__ = 'tiangy'
#__mtime__ = '2019/9/5'
'''
i =1
while(判断条件):
循环体
i =i+1
'''
for i in range(1,101,1):
print (i)
i = 1
while(i < 101):
print (i)
i = i +1
# for 循环
'''
range(0,10,1) = [1,2,3,4,5,6,7,8,9]
range(0,10,2) = [1,3,5,7,9]
for i in range(0,10,1):
代码块
'''
for i in range(10):
print(i)
# while
for i in range(1,10,2):
print(i)
for i in range(1,100,2):
print(i)
# 求出100以内的奇数
for i in range(1,100):
if(i%2 == 1):
print(i)
# 终止循环 break
# 跳过本次循环 continue
# 100以内 到5就终止
for i in range(100):
if(i == 5):
break
print(i)
# 100以内 到5就跳过
for i in range(100):
if(i%5 == 0):
continue
print(i)
# 1000以内 到3就终止
for i in range(50):
if(i == 3):
break
print(i)
# 求出 1+2+3+...100 的和
# 方法一
a = 0
for i in range(1,101):
a = a + i
print(a)
# 方法二
# 求出 100! 1*2*3*4...*100
# 打印出九九乘法表(循环嵌套)
# 冒泡排序 |
import sys
'''
This module is print function package to decoration for string
'''
class ZeroIndexError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class OverIndexError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class CheckIndex:
def __init__(self, index, l_list):
self.index = index
self.l_list = l_list
def check(self):
if self.index <=0:
raise ZeroIndexError("ZeroIndexError: should input over zero. Plese check index")
if self.index > len(self.l_list):
raise OverIndexError("OverIndexError: list index out of range")
def print_with_ab(string):
"""
This is a function to print asterisk border line around the string
"""
print('*'* (len(string) + 4))
print('* ' + string + ' *')
print('*'* (len(string) + 4))
def print_with_dlb(string):
"""
This is a function to print double line border line around the string
"""
print('='* (len(string) + 4))
print('= ' + string + ' =')
print('='* (len(string) + 4))
def print_list_value(s, index=None):
"""
This is a fucntion to find string value and index number in the string
"""
str_list = s.split()
if index != None:
try:
CheckIndex(index, str_list).check()
if index == 1:
print(f'The {index}st value is " {str_list[index-1]} "')
elif index == 2:
print(f'The {index}nd value is " {str_list[index-1]} "')
else:
print(f'The {index}th value is " {str_list[index-1]} "')
except ZeroIndexError as e:
print(e); exit()
except OverIndexError as e:
print(e); exit()
else:
index = 0
for val in str_list:
if index == 0:
print(f'[ {val} ] is the {index+1}st value in string')
elif index == 1:
print(f'[ {val} ] is the {index+1}nd value in string')
else:
print(f'[ {val} ] is the {index+1}th value in string')
index = index + 1
if __name__ == '__main__':
l = len(sys.argv)-1
s = sys.argv[1]
functions = {'-a': print_with_ab, '-d': print_with_dlb,'-s': print_list_value}
if l == 1:
print(s)
elif l == 2:
opt = sys.argv[2]
if opt == '-a' or opt =='-d' or opt =='-s':
opt = sys.argv[2]
func = functions[opt]
func(s)
else:
func = functions['-a']
func(s)
else:
func = functions['-s']
func(s, int(sys.argv[3])) |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 16 00:42:38 2020
@author: RogelioTESI
"""
class Reversa:
"""Iterador para recorrer una secuencia de atrás para adelante."""
def __init__(self,datos):
self.datos = datos
self.indice = len(datos)
def __iter__(self):
return self
def __next__(self):
if self.indice == 0:
raise StopIteration()
self.indice = self.indice - 1
return self.datos[self.indice]
for elemento in Reversa([1,2,3,4]):
print(elemento)
lista = [1,2,3]
it = iter(lista)
print(next(it))
print(next(it))
print(next(it))
print(next(it)) |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 22 01:03:21 2020
Multiplicacion
@author: RogelioTESI
"""
a = input("Ingresa un numero: ")
b = input("Ingresa otro numero: ")
a = int(a)
b = int(b)
c = a*b
print("El resultado es: ", c)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 7 00:25:32 2018
@author: Liv d'Aliberti
"""
#The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
#Find the sum of all the primes below two million.
#In solving this problem, I learned about this thing called
#the Sieve of Eratosthenes which is apparently a "trick" for
#finding prime numbers. It finds primes by iteratively
#marking as composite the multiples of each prime, starting
#with 2. The multiples of a given prime are generated as a
#sequence of numbers starting from that prime. See this link
#to see what I learned:
#https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
def primes_less_than(divisor):
"""
Input: Integer
Output: Integer
Purpose: Create a function that finds all primes less than 2,000,000
and returns the sum of all primes less than 2,000,000
"""
potential_primes_set = set(range(2, divisor))
multiples = set()
primes = set()
for i in potential_primes_set:
if i not in multiples:
primes.add(i)
for j in range(i*2, divisor, i):
multiples.add(j)
return(sum(primes))
#The solution for this particular problem is 142,913,828,922
|
""" Определим слова в хэштеге.
Дана строка, начинается с # и содержит набор слов соединенных в одну строку без пробелов.
Срока описана в стиле camelCase, то есть первое слово начинается с прописной буквы, а каждое следующее с заглавной.
Например: #приветКакДела, #меняЗовутЕгорМнеМногоЛет и тд.
Необходимо посчитать количество слов в строке и вывести количество этих слов
65-90 - заглавные лат. буквы, 1040-1071 - русские заглавные (а в ASCII 192-223, лол)
"""
n = input()
count = 0
for i in n:
if i == '#':
count +=1
elif 65 <= ord(i) <= 90 or 1040 <= ord(i) <= 1071:
count += 1
print('Всего слов в хэш-теге: ', count)
#print(ord('А'),ord('Я')) #1040 1071 |
""" Реализовать функцию map, принимающей два аргумента:
список и произвольную арифметическую функцию.
Функция map должна возвращать новый список,
элементы которого являются результатом функции func.
Пусть будет функция, возводящая число в куб (в 3-ю степень числа)
"""
def func3s(x):
return x**3
def map(x: list, a):
for i, val in enumerate(x):
x[i] = a(val)
print(x) |
""" Дан файл с расписанием занятий на неделю.
Помимо названия предмета в нем также указано лекция это,
или практическое занятие, или лабораторная работа.
В одной строке может быть указаны только один предмет с информацией о нем.
Посчитать, сколько за неделю проходит практических занятий,
лекций и лабораторных работ.
"""
d = {'П': 0, 'ЛР': 0, 'Л': 0} #Практика, лаб работы, лекции
with open('input1.txt', 'r') as fin:
for line in fin.readlines():
lst = line.split()
if len(lst) > 1:
d[lst[len(lst)-1]]+= 1
print('Итого:\nЛекций: ', d['Л'], '\nПракт. занятий: ', d['П'], '\nЛаб. работ: ', d['ЛР']) |
import os
def manualInput(question):
answer = input(question + "(y/n): ").lower().strip()
print("")
while not(answer == "y" or answer == "yes" or \
answer == "n" or answer == "no"):
print("Введите y или n")
answer = input(question + "(y/n):").lower().strip()
print("")
if answer[0] == "y":
return True
else:
return False
# Перевести в 10 систему
def decimalConversion(number, base):
try:
decimalNumber = int(number, base)
except Exception:
print("Ошибка в файле входных данных. Первый элемент в строке должен быть целым числом в системе счисления с базой от 2 до 16")
exit(1)
else:
return decimalNumber
# Перевести цифры в буквы для систем с количеством цифр > 10
def digitConversion(digit):
if digit < 10:
return str(digit)
else:
return chr(ord('A') + digit - 10)
# Перевести число из 10 системы в желаемую
def nthBaseConversion(number, base):
if number < 0:
return '-' + nthBaseConversion(-number, base)
else:
(result, remainder) = divmod(number, base)
if result > 0:
return nthBaseConversion(result, base) + digitConversion(remainder)
return digitConversion(remainder)
# main
while True:
try:
name1 = input("Введите имя файла с исходными данными ")
f = open(name1)
if os.stat(name1).st_size == 0:
raise Exception
except FileNotFoundError:
print("Ошибка. Файл не существует")
except Exception:
print("Ошибка. Файл пуст")
else:
f.close()
break
name2 = input("Введите имя файла с для записи результатов ")
if manualInput("Обновить файл с исходными данными?"):
H1 = input("1 число ")
P1 = input("База системы счисления 1 числа ")
H2 = input("2 число ")
P2 = input("База системы счисления 2 числа ")
numbers = open(name1, "w")
print(H1, P1, file=numbers)
print(H2, " ", P2, file=numbers)
numbers.close()
else:
pass
number, base = [], []
numbers = open(name1)
for line in numbers:
row = line.split()
number.append(row[0])
try:
base.append(int(row[1]))
except Exception:
print("Ошибка в файле входных данных. Второе число строки после пробела должно быть целым.")
exit(1)
numbers.close()
try:
x = decimalConversion(number[0], base[0])
y = decimalConversion(number[1], base[1])
except Exception:
print("Ошибка в файле входных данных. Файл должен содержать 2 строки")
exit(1)
else:
sum10 = x + y
print("x = ", x, "; y =", y, "; sum10 = ", sum10, "\n")
sumA = nthBaseConversion(sum10, base[0])
sumB = nthBaseConversion(sum10, base[1])
# print("Сумма в ", base[0], "системе счисления = ", sumA)
# print("Сумма в ", base[1], "системе счисления = ", sumB)
output = open(name2, "w")
for i in base:
sumi = nthBaseConversion(sum10, base[base.index(i)])
print("Сумма в ", i, "системе счисления = ", sumi)
print("Сумма в ", i, "системе счисления = ", sumi, file = output)
output.close()
|
#Backtracking-2
#Problem1 : https://leetcode.com/problems/subsets/
#All test cases passed on Leetcode
#Time Complexity: O(2^n) -Exponential
#Space Complexity: O(n) for Backtracking
class Solution:
def __init__(self):
self.result=[]
#Approach used :backtracking
#Update the same list we call backtracking each time and whenever we have to append the result,we create a copy of the list and add.
def backtrack(self,nums,temp,start):
#cloning a list by using the builtin function list()
self.result.append(list(temp))
for i in range(start,len(nums)):
#action
temp.append(nums[i])
#recurse
self.backtrack(nums,temp,i+1)
#backtrack
temp.pop()
def subsets(self, nums: List[int]) -> List[List[int]]:
#edge cases
if not nums or len(nums)==0:
return result
#call backtrack function
self.backtrack(nums,[],0)
return self.result
|
import numpy as np
import matplotlib.pyplot as plt
# calculate Euclidean distance
def euclidean_distance(x1, x2):
scale_x1 = x1 * 100
scale_x2 = x2 * 100
return np.sqrt(np.sum(np.power(scale_x1 - scale_x2, 2)))
# Initial centroids with random samples
def init_centroids(data, k):
num_samples, dim = data.shape
centroids = np.zeros((k, dim))
for i in range(k):
index = int(np.random.uniform(0, num_samples))
centroids[i] = data[index]
return centroids
# K-means clusters
def k_means(data, k):
print("K-means clustering...")
print("Data shape for K-means:", data.shape)
if data.ndim == 1:
raise Exception("Reshape your data either using array.reshape(-1, 1) if your data has a single feature "
"or array.reshape(1, -1) if it contains a single sample.")
num_samples = data.shape[0]
# First column stores which cluster this sample belongs to,
# Second column stores the error between this sample and its centroid
cluster_assignment = np.zeros((num_samples, 2))
cluster_changed = True
# Step 1: init centroids
centroids = init_centroids(data, k)
print("Centroids initialization:")
print(centroids)
# show_cluster(data, k, cluster_assignment[:, 0], centroids, title="K-means, initial centroids")
num_iterations = 0
while cluster_changed:
cluster_changed = False
# for each sample
for j in range(num_samples):
min_distance = 100000.0
min_index = 0
# for each centroid
# Step 2: find the centroid who is closest
for i in range(k):
distance = euclidean_distance(data[j], centroids[i])
if distance < min_distance:
min_distance = distance
min_index = i
# Step 3: update its cluster
if cluster_assignment[j, 0] != min_index:
cluster_changed = True
cluster_assignment[j] = min_index, np.power(min_distance, 2)
# Step 4: update centroids
for i in range(k):
points_in_cluster = data[np.nonzero(cluster_assignment[:, 0] == i)[0]]
if len(points_in_cluster) > 0:
centroids[i] = np.mean(points_in_cluster, axis=0)
title = "K-means, #iter:" + num_iterations.__str__()
print(title)
print(centroids)
# show_cluster(data, k, cluster_assignment[:, 0], centroids, title=title)
num_iterations += 1
# show_cluster(data, k, cluster_assignment[:, 0], title="eigen_space")
return centroids, cluster_assignment[:, 0]
|
#************************** CS421: Assignment 7 **************
#
# Most of the implementation for the cryptoquote algorithm is done
#
# You only need to implement section 5.
#
# Lines from 28 and 35 reflect different test cases.
# Start with simple test cases and progress to the bigger test cases
#
# Use pythontutor.com to implement so that you can visualize how your lists and variables are changing.
# Save the complete implementation to a file called "a_cryptoquote.py" and submit the file to Google Classroom
#
# How to save the code from PythonTutor to a file?
# Select the entire code (Ctrl + A)
# Copy the entire code (Ctrl + C)
# Open notepad or any other editor you use to write text files.
# Paste the entire code (Ctrl + V)
# Save the code to a file (Ctrl +S)
# ************************************************************
# Get the quote. This is the input.
#We will have different test cases
# start from simple test cases
# only when simple test cases are passing, go the next test case
quote = "aaaa"
quote = "abab"
quote = "ab ab"
quote = "abc abc abc"
quote = "abc! abc? abc@gmail.com"
quote = "Siva Jasthi"
quote = "An eye for an eye makes the whole world blind!"
quote = "An eye for an eye makes the whole world blind! - Mahatma Gandhi"
# Once all the above test cases are passing
# we can ask the user for inputting the quote
# At that time, we can ask the user for the input
#quote = input("Enter a quotation: ")
# [1] I need a list of all letters from the input quote
#https://stackoverflow.com/questions/4978787/how-to-split-a-string-into-an-array-of-characters-in-python
# since cryptoquotes deal with only upper case letters
# let us make a temporary string to hold the upper-cased quote
quote_upper = quote.upper()
#convert quote_upper into a list
quote_list = list(quote_upper)
# create a temporary quote_list_temp for holding the swaps
quote_list_temp = list(quote_list)
print(quote_list_temp)
#print what we got so far
print("This is the input quote")
print(quote)
print("This is the upper cased quote")
print(quote_upper)
print("This is the list of characters in the quote")
print(quote_list)
# [2] We need an alphabet list which is ordered
# a,b,c,...z
# How do I create a ordered list of alphabest?
#https://www.geeksforgeeks.org/python-ways-to-initialize-list-with-alphabets/
#import the string module
import string
# initializing empty list
ordered_list = []
# using string module for filling alphabets
# Since all cryptograms are not case sensitive,
# let us go with upper case
ordered_list = list(string.ascii_uppercase)
# printing the ordered list
print ("Ordered Alphabet List : ")
print(ordered_list)
# [3]. We need a randomized list
# How do I randomize this ordered list
# so that I can maintain the mapping
# between original (ordered) and the randomized list
import random
# make a copy of the original list
random_list = list(ordered_list);
#using the raondom module to shuffle (randomize) the input list
random.shuffle(random_list);
print ("Shuffled Alphabet List : ")
print(random_list)
# All you code goes between BEGIN and END lines.
# BEGIN ============= Student Code ============
#[4] We will now create the crypto quote
# per the psedo-code given below
# we now have these four lists
# quote_list
# quote_lit_temp
# ordered_list
# random_list
#
# Our algorithm depends on all these lists
#
#Once the for loop is done,
#we will have quote_list_temp reflecting the cryptoquote
# we need to keep track of the position
# at which we are doing the substitution
q_pos = -1
for x in quote_list:
# bump up the position for the character
# this is the character we are currently processing
q_pos = q_pos + 1
# we need to swap only the characters
# symbols and characters can be ignored
if (x in ordered_list):
# if we are here, it means that we are processing a character
# find out where this character is in the ordered alphabet list
# the x_pos should be between 0 and 25
x_pos = ordered_list.index(x)
# Now find out our mapping letter for the substitution
y_char = random_list[x_pos]
# Now do the swap in the quote_list_temp
quote_list_temp[q_pos] = y_char
# print the quote_list_temp
print("Here is quote list temp after the substitutions: ")
print(quote_list_temp)
# END ============== Student Code ============
#5. We need to convert the quote_list_temp (the cryptoquote) to a string
# How do I convert a list into a string?
# see https://www.geeksforgeeks.org/jin-function-python/
# Variables for holding the final crypto quote
# We are joining the list into a single string
crypto= crypto.join(quote_list_temp)
#6. We need to show one hint to the users.
# Since quote_list_temp contains the cryptic character
# and the quote_list contains the original character
# We can simply show the first character mapping from both the lists
hint = "Hint => " + quote_list_temp[0] + " = " + quote_list[0]
# All previous print statements can be commended
# once the program is working.
#6 Now print all the variables in the end
# to verify that our algorithm is working
#print the quote
print("========== Your quote: ============ ")
print(quote)
#print the crypto
print("========== Crypto quote: ============ ")
print(crypto)
print("Hint: ", hint)
|
from turtle import *
speed(-1)
def draw_square(l,colour):
for i in range(4):
color(str(colour))
forward(l)
left(90)
for i in range(30):
draw_square(i*5,"red")
left(17)
penup()
forward(i * 2)
pendown()
|
def numero_to_letras(numero):
indicador = [("", ""), ("MIL", "MIL"), ("MILLON", "MILLONES"), ("MIL", "MIL"), ("BILLON", "BILLONES")]
entero = int(numero)
decimal = int(round((numero - entero) * 100))
# print 'decimal : ',decimal
contador = 0
numero_letras = ""
while entero > 0:
a = entero % 1000
if contador == 0:
en_letras = convierte_cifra(a, 1).strip()
else:
en_letras = convierte_cifra(a, 0).strip()
if a == 0:
numero_letras = en_letras + " " + numero_letras
elif a == 1:
if contador in (1, 3):
numero_letras = indicador[contador][0] + " " + numero_letras
else:
numero_letras = en_letras + " " + indicador[contador][0] + " " + numero_letras
else:
numero_letras = en_letras + " " + indicador[contador][1] + " " + numero_letras
numero_letras = numero_letras.strip()
contador = contador + 1
entero = int(entero / 1000)
numero_letras = numero_letras + " Pesos"
#print('numero: ', numero)
print(numero_letras)
def convierte_cifra(numero, sw):
lista_centana = ["", ("CIEN", "CIENTO"), "DOSCIENTOS", "TRESCIENTOS", "CUATROCIENTOS", "QUINIENTOS", "SEISCIENTOS",
"SETECIENTOS", "OCHOCIENTOS", "NOVECIENTOS"]
lista_decena = ["", (
"DIEZ", "ONCE", "DOCE", "TRECE", "CATORCE", "QUINCE", "DIECISEIS", "DIECISIETE", "DIECIOCHO", "DIECINUEVE"),
("VEINTE", "VEINTI"), ("TREINTA", "TREINTA Y "), ("CUARENTA", "CUARENTA Y "),
("CINCUENTA", "CINCUENTA Y "), ("SESENTA", "SESENTA Y "),
("SETENTA", "SETENTA Y "), ("OCHENTA", "OCHENTA Y "),
("NOVENTA", "NOVENTA Y ")
]
lista_unidad = ["", ("UN", "UNO"), "DOS", "TRES", "CUATRO", "CINCO", "SEIS", "SIETE", "OCHO", "NUEVE"]
centena = int(numero / 100)
decena = int((numero - (centena * 100)) / 10)
unidad = int(numero - (centena * 100 + decena * 10))
#print("centena: ",centena, "decena: ",decena,'unidad: ',unidad)
texto_centena = ""
texto_decena = ""
texto_unidad = ""
# Validad las centenas
texto_centena = lista_centana[centena]
if centena == 1:
if (decena + unidad) != 0:
texto_centena = texto_centena[1]
else:
texto_centena = texto_centena[0]
# Valida las decenas
texto_decena = lista_decena[decena]
if decena == 1:
texto_decena = texto_decena[unidad]
elif decena > 1:
if unidad != 0:
texto_decena = texto_decena[1]
else:
texto_decena = texto_decena[0]
if decena != 1:
texto_unidad = lista_unidad[unidad]
if unidad == 1:
texto_unidad = texto_unidad[sw]
return "%s %s %s" % (texto_centena, texto_decena, texto_unidad)
numero_to_letras(100000) |
# Task_1. Написати скрипт, який з двох введених чисел визначить, яке з них більше, а яке менше.
a = int(input("Введіть число "))
b = int(input("Введіть число "))
if a == b:
print("Числа {0} і {1} рівні".format(a, b))
elif a <= b:
мін_зн, макс_зн = a, b
print("Число {0} - мінімальне число , а число {1} - максимальне число".format(мін_зн, макс_зн))
else:
мін_зн, макс_зн = b, a
print("Число {0} - мінімальне число , а число {1} - максимальне число".format(мін_зн, макс_зн))
print()
# Task_2. Написати скрипт, який перевірить чи введене число парне чи непарне і вивести відповідне повідомлення.
num = int(input("Enter a number: "))
if num % 2 == 0:
print("The number {0} is even".format(num))
else:
print("The number {0} is odd".format(num))
print()
# Task_3. Написати скрипт, який обчислить факторіал введеного числа.
n = int(input('Введіть число: '))
factorial = 1
for i in range(1, n + 1):
factorial *= i
print('Факторіал числа {} становить'.format(n), factorial)
print()
|
#Task
#Given an integer, , perform the following conditional actions:
#If is odd, print Weird
#If is even and in the inclusive range of to , print Not Weird
#If is even and in the inclusive range of to , print Weird
#If is even and greater than , print Not Weird
#Complete the stub code provided in your editor to print whether or not is weird.
#Input Format
#A single line containing a positive integer,Constraints.
#Output Format
#Print Weird if the number is weird; otherwise, print Not Weird.
#Sample Input 0
## 3
#Sample Output 0
##Weird
#Sample Input 1
##24
##Sample Output 1
##Not Weird
##Explanation
##Sample Case 0: is odd and odd numbers are weird, so we print Weird.
##Sample Case 1: and is even, so it isn't weird. Thus, we print Not Weird.
#!/bin/python3
import sys
N = int(input().strip())
if N % 2 == 1:
print('Werid')
elif N < 5:
print(' Not Werid')
elif N <= 20:
print('Werid')
else:
print('Not Weird')
|
#!/usr/bin/env python3
#sheinkhant
def prime_checker(number):
is_prime = True
for i in range(2, number - 1):
if number % i == 0:
is_prime = False
if is_prime:
print("It's a prime number.")
else:
print("It's not a prime number.")
n = int(input("Check this number: "))
prime_checker(number=n) |
#!/usr/bin/env python3
#sheinkhant
for i in range(1,101):
if i % 3 == 0 and i % 5 == 0:
print("FuzzBuzz")
elif i % 3 == 0:
print("Fuzz")
elif i % 5 == 0:
print("Buzz")
else:
print(i) |
def move(_1,_2):
_2.append(_1.pop(-1))
print(a,b,c)
def toh(disks,source,dest,aux):
if disks==1:
move(source,dest)
else:
toh(disks-1,source,aux,dest)
move(source,dest)
toh(disks-1,aux,dest,source)
# def tower(disks,source,dest,aux):
# if disks==1:
# print(f'move {source} to {dest}')
# else:
# tower(disks-1,source,aux,dest)
# print(f'move {source} to {dest}')
# tower(disks-1,aux,dest,source)
a=[5,4,3,2,1]
b=[]
c=[]
toh(5,a,c,b) |
from graph import Graph,Edge
from dijkstra import dijkstra_target
g=Graph([1,2,3,4,5,6,7,8,9,10]) # Create graph with 10 houses
g.add_edge(Edge(1,2,cost=3))
g.add_edge(Edge(2,3,cost=4))
g.add_edge(Edge(3,4,cost=2))
g.add_edge(Edge(4,5,cost=3))
g.add_edge(Edge(5,6,cost=5))
g.add_edge(Edge(6,7,cost=4))
g.add_edge(Edge(7,1,cost=2))
g.add_edge(Edge(1,10,cost=3))
g.add_edge(Edge(10,9,cost=4))
g.add_edge(Edge(9,2,cost=3))
g.add_edge(Edge(9,3,cost=3))
g.add_edge(Edge(5,3,cost=4))
g.add_edge(Edge(9,5,cost=2))
g.add_edge(Edge(8,5,cost=3))
g.add_edge(Edge(8,9,cost=3))
g.add_edge(Edge(8,10,cost=4))
g.add_edge(Edge(10,7,cost=4))
g.add_edge(Edge(8,7,cost=5))
g.add_edge(Edge(10,2,cost=2))
g.add_edge(Edge(6,8,cost=3))
for i in range(1,11):
pass
# Second idea:
# Algorithm:
# find_minimum_roads(map):
# for a graph of nodes (houses) joined by edges (roads) with a cost
# determine the minimum total cost of roads that need be created to join all of the houses
# and the roads that should be constructed to meet this minimum
#
# total <- 0
# finished <- False
# while:
# distances <- dict
# for each node on map:
# calculate the minimum distance from this node to each other node
# store these values in distances
#
# shortest <- lowest non-zero value in distances
# if there are no non-zero values:
# end while
#
# for each key in distances:
# if value of this key = shortest:
# get the path taken from the first node to the second
# add the cost of each edge on this path to total
# set the cost of each edge on this path to zero
# end for
#
# return total,roads with cost = 0
total=0
while True:
distances={}
for node in g.nodes:
distances.update({(node.ident,i):dijkstra_target(g,node.ident,i,'dist') for i in range(1,11)})
dists=[value for value in distances.values() if value>0]
if dists:
shortest=min(dists)
else:
break
for key in distances:
if distances[key]==shortest:
p=dijkstra_target(g,key[0],key[1],'path')
for node in p:
if node.prev:
total+=g.get_edge(node.ident,node.prev.ident).cost
g.get_edge(node.ident,node.prev.ident).cost=0
break
for edge in g.edges:
if edge.cost==0:
print(f'{edge.a}--{edge.b}: Paved')
print(f'Total = {total}')
# # First idea:
# # Algorithm:
# # find_minimum_roads(map):
# # for a graph of nodes (houses) joined by edges (roads) with a cost
# # determine the minimum total cost of roads that need be created
# # and the roads that should be constructed to meet this minimum
# #
# # let total = 0
# # let source node = node of the highest degree
# # for each house:
# # find the shortest path from source to the house
# # let p equal a list of edges equal this path
# # for each edge in p:
# # add the cost of this edge to total
# # set the cost of this edge to 0
# #
# # return total,roads with cost 0
# print(g)
# total=0
# for i in range(1,11):
# p=dijkstra_target(g,9,i)
# for node in p:
# if node.prev:
# total+=g.get_edge(node.ident,node.prev.ident).cost
# g.get_edge(node.ident,node.prev.ident).cost=0
# for edge in g.edges:
# print(str(edge))
# print(total) |
def quick_sort(l):
if len(l) in [0, 1]:
return l
p = l[0]
smaller = []
larger = []
for e in l[1:]:
if e < p:
smaller.append(e)
else:
larger.append(e)
return quicksort(smaller) + [p] + quicksort(larger)
def count_quick_sort(l):
if len(l) in [0, 1]:
return l, 1
p = l[0]
smaller = []
larger = []
steps = 0
for e in l[1:]:
steps += 1
if e < p:
smaller.append(e)
else:
larger.append(e)
left, s = count_quick_sort(smaller)
steps += s
right, s = count_quick_sort(larger)
steps += s
return (left + [p] + right), steps
from random import randint
print(count_quick_sort([randint(0, 2000) for _ in range(100000)])[1])
|
class Scientist():
def __init__(self, born, died):
self.born = born
self.died = died
def simultaneously_alive(A, B):
if A.died <= B.born or B.died <= A.born:
return False
return True
def max_alive(S):
most_living = 0
currently_living = []
scientists = sorted(S, key = lambda s: s.born)
for s in scientists:
for o in currently_living:
if not simultaneously_alive(s, o):
currently_living.remove(o)
currently_living.append(s)
most_living = max(most_living, len(currently_living))
return most_living
S = [
Scientist(1950, 1980),
Scientist(1940, 1990),
Scientist(1930, 1970),
Scientist(1980, 2019)
]
print(max_alive(S)) |
import os
from abc import ABCMeta
from abc import abstractmethod
class base_data(object):
def __init__(self, is_training):
__metaclass__=ABCMeta
print("base_data init")
self._is_training = is_training
@abstractmethod
def __call__(self, *args, **kwargs):
print("base_data call")
# callable的意义在哪里? 封装整个对象初始化的过程,返回一个对象,外部调用对象,根据不同的输入来改变对象的内部属性或行为
pass
|
# coding: utf-8
"""
Reverse Complement
Autor:
Colaborador:
Guido Luz Percú (guidopercu@gmail.com)
Tipo:
bioinformatics
Descrição:
Converte uma sequência de DNA em seu complemento, isto é, inverte a string e troca A por T, T por A, C por G e G por C.
Complexidade:
?
Dificuldade:
facil
Licenca:
MIT
"""
def reverse_complement(genoma):
dicionario = {"A": "T", "T": "A", "C": "G", "G": "C"}
complemento_reverso = [dicionario[x] for x in genoma[::-1]]
return "".join(complemento_reverso)
print(reverse_complement('ATCG')) # CGAT
|
# -*- coding: utf-8 -*-
"""
Algoritmo de Aho-Corasick.
Autor:
Alfred Aho and Margaret Corasick (1975)
Colaborador:
Pedro Arthur Duarte (JEdi)
pedroarthur.jedi@gmail.com
Tipo:
multi pattern string matching
finite automate-based
Descrição:
Dado um conjunto de padrões, esse algoritmo constrói uma máquina de estados
finitos de forma que seja possível buscá-los no texto de entrada em tempo
linearmente proporcional ao tamanho dessa última. Para isso, o algoritmo de
Aho-Corasick utiliza uma estrutura de dados semelhante as Tries, porém com
nós adicionais que evitam a necessidade de backtracking. Esse nós
adicionais representam o maior prefixo comum presente entre os padrões.
Complexidade:
O(⅀m) de pré-processamento, onde "m" é o tamanho do padrão
O(n) de busca, onde "n" é o tamanho do texto de entrada
Dificuldade:
média (?)
Referências:
https://en.wikipedia.org/wiki/Aho-Corasick_algorithm
Licença:
GPLv3
"""
class AhoCoraski(dict):
failTransition = None
isTerminal = False
def __init__(self, patternList=None, thenBuild=False):
if patternList is not None:
self.add(patternList)
if thenBuild is True:
self.build()
def add(self, pattern):
if isinstance(pattern, list):
for w in pattern:
self.add(w)
return self
currentState = self
for c in pattern:
if c not in currentState:
currentState[c] = AhoCoraski()
currentState = currentState[c]
currentState.isTerminal = pattern
return self
def build(self):
queue = [ self ]
while len(queue) > 0:
current = queue.pop(0)
for transition, next in current.iteritems():
state = current.failTransition
while state is not None and transition not in state:
state = state.failTransition
if state is not None:
next.failTransition = state[transition]
else:
next.failTransition = self
queue.append(next)
return self
def match(self, subject):
output = [ ]
current = self
if isinstance(subject, list):
for s in subject:
output += self.match(s)
return output
for c in subject:
if c in current:
current = current[c]
else:
current = current.failTransition
while current is not None and c not in current:
current = current.failTransition
if current is not None:
current = current[c]
else:
current = self
if current.isTerminal is not False:
output.append(current.isTerminal)
return output
patternList = [ 'he', 'she', 'his', 'her', 'show', 'shall', 'hall', ]
print AhoCoraski(patternList, True).match("This phrase shall match")
|
# -*- encoding: utf-8 -*-
"""
Cálculo da raíz quadrada através do método de Newton-Raphson
Autor:
Isaac Newton e Joseph Raphson
Colaborador:
Alysson Oliveira (lssn.oliveira@gmail.com)
Tipo:
math
Descrição:
Método interativo para estimar as raízes de funções e pode ser aplicado
a para o cálculo de rais quadrada.
Complexidade:
?
Dificuldade:
fácil
Referências: (opcional)
https://pt.wikipedia.org/wiki/M%C3%A9todo_de_Newton-Raphson
https://courses.csail.mit.edu/6.006/fall11/rec/rec12_newton.pdf
http://www.iaps.org.in/journal/index.php/journaliaps/article/view/161/146
Guttag, John V. Introduction to Computation and Programming Using \
Python. MIT Press. 2013. ISBN 978-0-262-52500-8
"""
def newton_raphson_sqrt(n, precisao=0.001, debug=False):
"""
n: Valor que se deseja obter a raíz
precisao: Valor de precisão (ex.: 0.01)
debug: Quando True mostra os chutes até que a precisão seja satisfeita
"""
chute = 0.5 * n
while abs(chute * chute - n) >= precisao:
if debug:
print(' Chute:', chute)
chute = chute - (((chute**2) - n) / (2 * chute))
return chute
# Testando a função
for i in 49, 64:
print('Calculando raíz de {}'.format(i))
print('Resultado: {}'.format(newton_raphson_sqrt(i)))
print(35 * '=')
for i in 81, 100:
print('Calculando raíz de {}'.format(i))
print('Resultado: {}'.format(newton_raphson_sqrt(i, 0.01, True)))
print(35 * '=')
|
# -*- encoding: utf-8 -*-
"""
Binary Heap
Autor:
M. D. ATKINSON, J. R. SACK, N. SANTORO, and T. STROTHOTT
Colaborador:
Juan Lopes (me@juanlopes.net)
Tipo:
data-structures
Descrição:
Implementação de priority queue usando uma binary min-heap.
Complexidade:
Inserção: O(log n)
Remoção: O(log n)
Obter mínimo: O(1)
Dificuldade:
Fácil
Referências: (opcional)
http://en.wikipedia.org/wiki/Binary_heap
"""
class BinaryHeap:
def __init__(self, V = []):
self.V = [None] + list(V)
self.heapify()
def heapify(self):
for i in range(self.count()/2, 0, -1):
self.bubble_down(i)
def count(self):
return len(self.V) - 1
def top(self):
return (self.V[1] if self.count() > 0 else None)
def push(self, value):
self.V.append(value)
self.bubble_up(self.count())
def pop(self):
if self.count() == 0: return None
value = self.V[1]
self.V[1] = self.V[-1]
self.V.pop()
self.bubble_down(1)
return value
def pop_all(self):
while self.count() > 0:
yield self.pop()
def bubble_up(self, n):
while n != 1 and self.less(n, n/2):
self.swap(n, n/2)
n /= 2
def bubble_down(self, n):
while self.less(n*2, n) or self.less(n*2+1, n):
c = self.min(n*2, n*2+1)
self.swap(n, c)
n = c
def less(self, a, b):
if a>self.count(): return False
if b>self.count(): return True
return self.V[a]<self.V[b]
def min(self, a, b):
return (a if self.less(a,b) else b)
def swap(self, a, b):
self.V[a], self.V[b] = self.V[b], self.V[a]
heap = BinaryHeap()
heap.push(10)
heap.push(2)
heap.push(5)
heap.push(-100)
print heap.pop() #-100
print heap.pop() #2
print heap.pop() #5
print heap.pop() #10
print
print 'Heap sort'
V = [10, 2, 5, -100]
print V, '->', list(BinaryHeap(V).pop_all())
|
# -*- coding: utf-8 -*-
"""
Algoritmo de Bellman-Ford.
Autor:
Richard Bellman & Lester R. Ford Jr. (1958)
Colaborador:
Pedro Arthur Duarte (JEdi)
pedroarthur.jedi@gmail.com
Tipo:
graph
shortest path on directed graphs with negative weighted edges
Descrição:
O algoritmo de Bellman-Ford determina o caminho mais curto de origem única
em grafos com arestas de pesos negativos. Para grafos sem arestas negativas,
o algoritmo de Dijkstra apresenta melhor desempenho.
Complexidade:
O(V*E), onde 'V' é a cardinalidade o conjunto de vértices e 'E' a
cardinalidade do conjunto de arestas.
Dificuldade:
media
Referências:
http://en.wikipedia.org/wiki/Bellman-Ford_algorithm
Licença:
GPLv3
"""
from sys import maxint
class NegativeWeightCycleError(Exception):
pass
class Vertex:
'''
Abstração de vértice para a implementação através de lista de adjacência;
estão inclusos atributos extras para a implementação do algoritmo
'''
def __init__(self, label, distance, predecessors=None):
self.label = label
self.distance = distance
self.predescessor = None
def __repr__(self):
return str(self.label)
class Edge:
'''
Abstração de aresta para a implementação através de lista de adjacência
'''
def __init__(self, source, destination, weight):
self.src = source
self.dst = destination
self.wht = weight
class Graph:
'''
Abstração de grafo para a implementação através de lista de adjacência.
'''
def __init__(self, graph=None):
'''
Caso seja passada uma matriz de adjacência, essa é transformada numa
lista de adjacência.
'''
self.vertex = { }
self.edges = [ ]
if graph == None:
return
for i in xrange(0, len(graph)):
for j in xrange(0, len(graph)):
if graph[i][j] == None:
continue
self.addEdge(i, j, graph[i][j])
def addEdge(self, source, destination, weight):
if source not in self.vertex:
self.vertex[source] = Vertex(source, maxint)
if destination not in self.vertex:
self.vertex[destination] = Vertex(destination, maxint)
self.edges.append(
Edge(self.vertex[source], self.vertex[destination], weight))
class BellmanFord:
def __init__(self, g):
self.graph = g
def adjacencyMatrixShortestPath(self, source, destination):
'''Implementação através de matriz de adjacência'''
# Etapa de inicialização: todas as distâncias são definidas como
# infinitas para que sejam então atualizadas durante a relaxação
self.distances = [ maxint for s in self.graph ]
self.distances[source] = 0
# Arranjo auxiliar para que possamos reconstruir o menor caminho
self.predecessors = [ 0 for s in self.graph ]
# Para cada v em V:
for i in xrange(0, len(self.graph)):
# Para cada e em E
# Aqui, devido ao uso da matriz de adjacência, precisamos
# utilizar dois laços "para" (for) de forma que possamos
# percorrer todas as aresta
for u in xrange(0, len(self.graph)):
for v in xrange(0, len(self.graph)):
if self.graph[u][v] == None:
continue
# Etapa de "relaxação" do grafo
if self.distances[u] + self.graph[u][v] < self.distances[v]:
self.distances[v] = self.distances[u] + self.graph[u][v]
self.predecessors[v] = u
# Verificação da existência de círculos negativos
for u in xrange(0, len(self.graph)):
for v in xrange(0, len(self.graph)):
if self.graph[u][v] == None:
continue
if self.distances[u] + self.graph[u][v] < self.distances[v]:
raise NegativeWeightCycleError
# lista de saída; índice -1 indica o custo total do menor caminho
output = [ self.distances[destination] ]
# Reconstruindo o menor caminho através do predecessor do destino
while True:
output.insert(0, destination)
if destination == source:
break
else:
destination = self.predecessors[destination]
# Crianças, não façam isso em casa.
return output[:-1], output[-1]
def adjacencytListShortestPath(self, source, destination):
'''
Implementação através de lista de adjacência;
Funcionalmente, o mesmo código acima. Porém, bem mais limpo e menos
devorador de memória. Adequado para matrizes esparsas.
'''
source, destination = (self.graph.vertex[source],
self.graph.vertex[destination])
# A etapa de inicialização está parcialmente implícita no construtor
# da classe Vertex. Assim, precisamos apenas atualizar o valor de
# distância do nó origem.
source.distance = 0
for _ in self.graph.vertex:
for e in self.graph.edges:
if e.src.distance + e.wht < e.dst.distance:
e.dst.distance = e.src.distance + e.wht
e.dst.predescessor = e.src
for e in self.graph.edges:
if e.src.distance + e.wht < e.dst.distance:
raise NegativeWeightCycleError
output = [ destination.distance ]
while True:
output.insert(0, destination)
if destination == source:
break
else:
destination = destination.predescessor
return output[:-1], output[-1]
'''
Matriz de adjacência; None pode ser utilizado para representar a inexistência
de arestas entre dois vértices.
'''
graph = [
[7, 6, 8, 3, 5, 3, 2, 7, 1, 2, ],
[0, 5, 2, 9, 1, 6, 2, 9, 9, 7, ],
[6, 8, 7, 5, 8, 5, 7, 9, 8, 2, ],
[6, 9, 7, 5, 8, 9, 8, 6, 3, 4, ],
[0, 4, 8, 1, 6, 5, 8, 0, 7, 9, ],
[2, 3, 3, 9, 9, 0, 0, 3, 0, 4, ],
[7, 8, 0, 7, 7, 2, 9, 6, 0, 8, ],
[3, 3, 5, 4, 8, 8, 8, 4, 4, 0, ],
[9, 7, 2, 5, 0, 5, 4, 9, 0, 3, ],
[6, 1, 8, 6, 6, 6, 1, 6, 7, 9, ],
]
# Calculando o menor caminho através da matriz
print BellmanFord(graph).adjacencyMatrixShortestPath(0,9)
# Calculando o menor caminho através da lista
print BellmanFord(Graph(graph)).adjacencytListShortestPath(0,9)
|
# -*- encoding: utf-8 -*-
"""
* Sequência de Fibonacci
*
* Autor:
* Felipe Djinn <felipe@felipedjinn.com.br>
* Colaborador:
* Bruno Lara Tavares <bruno.exz@gmail.com>
* Dilan Nery <dnerylopes@gmail.com>
* Tipo:
* math
* Descrição:
* Na matemática, os Números de Fibonacci são uma sequência definida como recursiva.
* O algoritmo recursivo que define a série aplica-se, na prática, conforme a regra sugere:
* começa-se a série com 0 e 1; a seguir, obtém-se o próximo número de Fibonacci somando-se
* os dois anteriores e, assim, sucessiva e infinitamente.
* Complexidade:
* O(n)
* Referências:
* http://pt.wikipedia.org/wiki/N%C3%BAmero_de_Fibonacci
*
"""
def fibonacci(nesimo):
c, n1, n2 = 0, 0, 1
while c < nesimo:
n1, n2 = n2, n1 + n2
c += 1
return n2
for nesimo in range(100):
print fibonacci(nesimo)
|
# encoding: utf-8
"""
Permutation
Autor:
Fabian Stedma
Colaborador:
Bruno Gabriel dos Santos (bruno.gsantos89@gmail.com)
Tipo:
math
Descrição:
Calcula o número de combinações distintas que são possíveis de serem formadas por um array numérico.
Complexidade:
O(n!)
Dificuldade:
medio
Referências:
[1] https://en.wikipedia.org/wiki/Permutation#Algorithms_to_generate_permutations
"""
def permutation(input_data, temp_data, position):
if position == len(input_data):
print ''.join(str(temp_data))
else:
for i in xrange(len(input_data)):
is_same = False
for j in xrange(position):
if temp_data[j] == input_data[i]:
is_same = True
if not is_same:
if len(temp_data) <= i:
temp_data.append(input_data[i])
else:
temp_data[position] = input_data[i]
permutation(input_data, temp_data, position+1)
permutation([1,2,3], [], 0)
|
# coding: utf-8
'''
Array Sum
Autor:
?
Colaborador:
Dayvid Victor (victor.dvro@gmail.com)
Descricao:
Esse programa recebe como parametro uma lista
e retorna a soma dos elementos desta lista.
Complexidade:
O(n)
Dificuldade:
facil
Licenca:
GPL
'''
def arraysum(l, key = lambda a, b: a + b):
s = 0
for e in l:
s = key(s,e)
return s
if __name__ == '__main__':
l1 = [1,2,3,4,5,6,7,8,9,10]
l2 = [-4,-3,-2,-1,0,1,2,3,4]
print arraysum(l1)
print arraysum(l2)
|
from typing import List
from unittest import TestCase
class TestFilterOddNumbers(TestCase):
""" This test case filters odd numbers from a given sequence """
def test_with_basic_algorithm(self) -> None:
""" Test checks if odd numbers are filtered with basic algorithm """
odds: List[...] = list()
for n in range(1, 6):
if n % 2 != 0:
odds.append(n)
self.assertListEqual(odds, [1, 3, 5])
def test_with_list_comprehension(self):
""" Test checks if odd numbers are filtered with list comprehension """
self.assertListEqual([n for n in range(1, 6) if n % 2 != 0], [1, 3, 5])
def test_with_filter_function(self) -> None:
""" Test checks if odd numbers are filtered with 'filter' function """
def check_odds(n: int) -> bool:
if not n % 2:
return False
return True
self.assertListEqual(list(filter(check_odds, range(1, 6))), [1, 3, 5])
class TestFilterEvenNumbers(TestCase):
""" This test case filters even numbers from a given sequence """
def test_with_basic_algorithm(self) -> None:
""" Test checks if even numbers are filtered with basic algorithm """
odds: List[...] = list()
for n in range(1, 6):
if n % 2 == 0:
odds.append(n)
self.assertListEqual(odds, [2, 4])
def test_with_list_comprehension(self):
""" Test checks if even numbers are filtered with list comprehension """
self.assertListEqual([n for n in range(1, 6) if n % 2 == 0], [2, 4])
def test_with_filter_function(self) -> None:
""" Test checks if even numbers are filtered with 'filter' function """
def check_evens(n: int) -> bool:
if n % 2:
return False
return True
self.assertListEqual(list(filter(check_evens, range(1, 6))), [2, 4])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.