blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
f805fcf8ca04dc8d23d6b0e2f27351b19d922c29 | owendeng90/python_learn | /python学习/20191020_for星号输出1.py | 865 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/10/20 11:48
# @Author : owen
# @Site :
# @File : 20191020_for星号输出1.py
# @Software: PyCharm Community Edition
# @Code thought
#类型3
numrows=1
while numrows <=6:
print('')
numcolumns=6
while numcolumns >0:
if numcolumns<=numrows:
print(numcolumns,end=' ')
else:
print(' ',end=' ')
numcolumns-=1
numrows += 1
#类型2
numrows=6
while numrows >=0:
print('')
numcolumns=1
while numcolumns <=6:
if numcolumns<=numrows:
print(numcolumns,end=' ')
numcolumns+=1
numrows -= 1
#类型1
numrows=1
while numrows <=6:
print('')
numcolumns=1
while numcolumns <=6:
if numcolumns<=numrows:
print(numcolumns,end=' ')
numcolumns+=1
numrows += 1 |
554f27076bba32f42f26bc791bc362d88bb3e223 | owendeng90/python_learn | /python学习/20191020_整数金字塔.py | 665 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/10/20 11:48
# @Author : owen
# @Site :
# @File : 20191020_for星号输出1.py
# @Software: PyCharm Community Edition
# @Code thought
num = int(input("请输入任意整数(1-15)\n"))
for numrows in range(1,num+1):
print('')
for numcolumns in range(1,2*num):
if numcolumns>=num-(numrows-1) and numcolumns<=num+(numrows-1):
if numcolumns==num:
print(1,end=' ')
elif numcolumns<num:
print(6-numcolumns+1, end=' ')
else:
print(numcolumns-6+1, end=' ')
else:
print(' ',end=' ') |
dd96f05dc6a33e705b1f88fad871384a55dbb5b5 | tomassabol/ivo_turtleproject | /pong_game.py | 2,801 | 3.734375 | 4 | import turtle
# screen config
screen = turtle.Screen()
screen.title("Pong game")
screen.bgcolor("black")
screen.setup(width=1000, height=600)
# left pad
left_pad = turtle.Turtle()
left_pad.speed(0)
left_pad.color("white")
left_pad.shape("square")
left_pad.shapesize(stretch_wid=6, stretch_len=2)
left_pad.penup()
left_pad.goto(-400, 0)
# right pad
right_pad = turtle.Turtle()
right_pad.speed(0)
right_pad.color("white")
right_pad.shape("square")
right_pad.shapesize(stretch_wid=6, stretch_len=2)
right_pad.penup()
right_pad.goto(400, 0)
# ball
ball = turtle.Turtle()
ball.speed(30)
ball.shape("circle")
ball.color("white")
ball.penup()
ball.goto(0, 0)
ball.dx = 5
ball.dy = -5
# score
left_player = 0
right_player = 0
# display score
score = turtle.Turtle()
score.speed(0)
score.color("white")
score.penup()
score.hideturtle()
score.goto(0, 260)
score.write("Left_player : 0 Right_player: 0", align="center", font=("SF", 24, "normal"))
# move pads vertically
def move_leftpad_up():
y = left_pad.ycor()
y += 20
left_pad.sety(y)
def move_leftpad_down():
y = left_pad.ycor()
y -= 20
left_pad.sety(y)
def move_rightpad_up():
y = right_pad.ycor()
y += 20
right_pad.sety(y)
def move_rightpad_down():
y = right_pad.ycor()
y -= 20
right_pad.sety(y)
# key bind
screen.listen()
screen.onkeypress(move_leftpad_up, "w")
screen.onkeypress(move_leftpad_down, "s")
screen.onkeypress(move_rightpad_up, "Up")
screen.onkeypress(move_rightpad_down, "Down")
while True:
screen.update()
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
# Checking borders
if ball.ycor() > 280:
ball.sety(280)
ball.dy *= -1
if ball.ycor() < -280:
ball.sety(-280)
ball.dy *= -1
if ball.xcor() > 500:
ball.goto(0, 0)
ball.dy *= -1
left_player += 1
score.clear()
score.write("Left_player : {} Right_player: {}".format(
left_player, right_player), align="center",
font=("Courier", 24, "normal"))
if ball.xcor() < -500:
ball.goto(0, 0)
ball.dy *= -1
right_player += 1
score.clear()
score.write("Left_player : {} Right_player: {}".format(
left_player, right_player), align="center",
font=("Courier", 24, "normal"))
# Paddle ball collision
if (ball.xcor() > 360 and ball.xcor() < 370) \
and (ball.ycor() < right_pad.ycor() + 40
and ball.ycor() > right_pad.ycor() - 40):
ball.setx(360)
ball.dx *= -1
if (ball.xcor() < -360 and ball.xcor() > -370)\
and (ball.ycor() < left_pad.ycor() + 40
and ball.ycor() > left_pad.ycor() - 40):
ball.setx(-360)
ball.dx *= -1
|
76760bc59e273a7589abec7fdea5eca25c4961e9 | lolpatrol/Advent-of-Code-2018 | /Day5.py | 589 | 3.53125 | 4 | import string
def part1(data):
reduced = []
for letter in data:
if reduced and abs(ord(letter) - ord(reduced[-1])) == 32:
reduced.pop()
else:
reduced.append(letter)
return len(reduced)
def part2(data):
smallest = len(data)
for letter in string.ascii_lowercase:
temp = data.replace(letter, '').replace(letter.upper(), '')
smallest = min(part1(temp), smallest)
return smallest
data = open('day5_input.txt').read().strip()
ans1 = part1(data)
ans2 = part2(data)
print('Part 1: ', ans1, '\nPart 2: ', ans2)
|
876942c68f9f07c1f7cfca1580fce89d25b761d3 | brendend/AutomateTheBoringStuff | /calc100.py | 108 | 3.515625 | 4 | total = 0
for I in range(101):
total = total + I
print('The calculated value is ' + (str(total)) + '.')
|
e21f0a7925825ae1496db0b0b2be3a90e89a03bc | arthurckl/ABC | /jogo_revisao.py | 3,106 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 3 14:29:27 2015
@author: Arthur
Game Rock-Paper-Scissors-Spock-Lizard:
With the old rules of Rock-Paper-Scissors, but now there are
two more options, Spock and Lizard.
"""
import random
A = ["rock","paper","scissors","spock","lizard"]
B = {"rock":["paper","lizard","spock","scissors"],
"paper":["scissors","rock","lizard","spock"],
"scissors":["rock","paper","spock","lizard"],
"lizard":["rock","spock","scissors","paper"],
"spock":["lizard","rock","paper","scissors"]};
answer = str(input(("Hello!, how about we play Rock-Paper-Scissors-Spock-Lizard?\n"+
"If you want to, type 'yes', if not... type 'no'\n" +
"Anytime you want to quit in the middle of the game, just type 'quit'\n"))).lower()
def decision(answer):
if answer == "yes":
print("Alright! Let's play! \n Good Luck champs")
return True
elif answer == "no":
print ("Ok then, bye")
return False
else:
print("Type correctly please, I didn't understand")
answer = str(input("*"))
return decision(answer)
w = decision(answer)
while w == True:
user_point = 0
computer_point = 0
while user_point != 3 or computer_point != 3:
if user_point == 3 or computer_point == 3:
break
else:
user_choice = str(input("Your turn:")).lower()
computer_choice = random.choice(A)
if user_choice == computer_choice:
user_point == 0 and computer_point == 0
print("It's a draw")
elif user_choice in A:
for key,value in B.items():
for i in range(len(value)):
if user_choice == key and value[i] == computer_choice:
if i % 2 == 0:
computer_point += 1
print ("I won this round,%s beats %s" % (computer_choice,
user_choice))
if user_point > 0:
user_point -= 1
else:
user_point += 1
print ("You won this round,%s beats %s" % (user_choice,
computer_choice))
if computer_point > 0:
computer_point -= 1
print("Your points:",user_point,"\nComputer points:",computer_point)
else:
print("There's no option for such thing!Choose correctly this time.")
if user_point == 3:
print("You win!Very Good!")
else:
print("You lose!What a loser haha!")
x = str(input("Do you want to play again? \n"+
"Type 'yes' if you want to, or 'no' if you don't want to \n")).lower()
if x == "yes":
print("Again?! Great!")
w = True
else:
w = False
print("See you later!")
|
ec541b14059808cf538ba11ffa9645488d70f4f4 | BuseMelekOLGAC/GlobalAIHubPythonHomework | /HANGMAN.py | 1,602 | 4.1875 | 4 | print("Please enter your name:")
x=input()
print("Hello,"+x)
import random
words = ["corona","lung","pain","hospital","medicine","doctor","ambulance","nurse","intubation"]
word = random.choice(words)
NumberOfPrediction = 10
harfler = []
x = len(word)
z = list('_' * x)
print(' '.join(z), end='\n')
while NumberOfPrediction > 0:
y = input("Guess a letter:")
if y in words:
print("Please don't tell the letter that you've guessed before!")
continue
elif len(y) > 1:
print("Please just enter one letter!!!")
continue
elif y not in word:
NumberOfPrediction -= 1
print("Misestimation.You have {} prediction justification last!".format(NumberOfPrediction))
else:
for i in range(len(word)):
if y == word[i]:
print("Correct Guess!")
z[i] = y
words.append(y)
print(' '.join(z), end='\n')
answer = input("Do you still want to guesss all of the word? ['yes' or 'no'] : ")
if answer == "yes":
guess = input("You can guess all of the word then : ")
if guess == word:
print("Congrats!You know right!!!")
break
else:
NumberOfPrediction -= 1
print("Misestimation! You have {} prediction justification last".format(NumberOfPrediction))
if NumberOfPrediction== 0:
print("Oh no,you don't have any prediction justification.You lost the game.Your hangman is hanged hahah!")
break |
7468cd814c2d83c6ccc40ce5fd700f5bde47ad41 | Yury31/yury-siarhey | /lesson4.4_siarhey.py | 337 | 3.75 | 4 | try:
x = int(input('Insert the number >> '))
except ValueError:
print('Wrong value! Bye-bye!!')
quit()
while True:
print('If you wanna kB press #1')
print('Or press #2 for bytes!')
break
y = int(input('>> '))
if y == 1:
print(x*1024, 'kB')
elif y == 2:
print(x/1024, 'b')
else:
print('ERROAARRR!!')
|
6520609ec4b3bc30a6d61abc23a092b112bd1062 | MindCC/ml_homework | /Lab02/Answer/TSPInstance.py | 3,097 | 3.53125 | 4 | import math
from os import path
import numpy as np
import matplotlib.pyplot as plt
class TSPInstance:
'''
file format:
city number
best known tour length
list of city position (index x y)
best known tour (city index starts from 1)
'''
def __init__(self, file_name):
self.__file_name = file_name
with open(file_name, mode='r') as file_handle:
d = file_handle.readline()
self.__city_number = int(d)
d = file_handle.readline()
self.__best_known_tour_length = int(d)
self.__city_position = []
for city in range(self.citynum):
d = file_handle.readline()
d = d.split()
self.__city_position.append((int(d[1]),int(d[2])))
tour = []
d = file_handle.readline()
while d == "": #skip empty lines
d = file_handle.readline()
for city in range(self.citynum):
d = file_handle.readline()
tour.append(int(d)-1)
self.__best_tour = tuple(tour)
@property
def citynum(self):
return self.__city_number
@property
def optimalval(self):
return self.__best_known_tour_length
@property
def optimaltour(self):
return self.__best_tour
def __getitem__(self, n):
return self.__city_position[n]
def get_distance(self, n, m):
'''
返回城市n和城市m之间的距离
'''
c1 = self[n]
c2 = self[m]
dist = (c1[0]-c2[0])**2 + (c1[1]-c2[1])**2
return int(math.sqrt(dist)+0.5)
def evaluate(self, tour):
'''
返回访问路径tour的路径长度
'''
dist = []
for i in range(len(tour)-1):
dist.append(self.get_distance(tour[i],tour[i+1]))
else:
dist.append(self.get_distance(tour[-1],tour[0]))
return sum(dist)
def plot_tour(self, solution):
'''
画出访问路径solution
'''
x = np.zeros(self.citynum+1)
y = np.zeros(self.citynum+1)
for i, city in enumerate(solution):
x[i] = self[city][0]
y[i] = self[city][1]
city = solution[0]
x[-1] = self[city][0]
y[-1] = self[city][1]
plt.plot(x, y, linewidth = 2)
##plt.scatter(x, y)
font = {'family': 'serif',
'color': 'black',
'weight': 'normal',
'size': 9,
}
for i, city in enumerate(solution):
plt.text(x[i],y[i],str(int(city+1)), fontdict=font)
plt.show()
if __name__=="__main__":
file_name = path.dirname(__file__) + "/01eil51.txt"
instance = TSPInstance(file_name)
print(instance.citynum)
print(instance.optimalval)
print(instance.evaluate(instance.optimaltour))
print(instance.optimaltour)
print(instance[0])
print(instance.get_distance(0,1))
instance.plot_tour(instance.optimaltour)
|
cc0b8ef1943eb8b6b5b42870be3387bbde4f8001 | MindCC/ml_homework | /Lab02/Question/lab2_Point.py | 2,008 | 4.46875 | 4 | # -*- coding: cp936 -*-
'''
ID:
Name:
'''
import math
class Point:
'''
Define a class of objects called Point (in the two-dimensional plane).
A Point is thus a pair of two coordinates (x and y).
Every Point should be able to calculate its distance
to any other Point once the second point is specified.
άƽϵPoint㣩Point2xy
Pointʵּ2֮ķdistanceTo( Point )
'''
def __init__(self, x, y):
self.__x = x
self.__y = y
def distance_to(self, other):
'''
㲢selfother֮ľ
'''
# sqrt(x^2+y^2)
return math.sqrt((self.__x - other.__x) ** 2 + (self.__y - other.__y) ** 2)
def __str__(self):
'''
صַʾ(x,y)
'''
return '(%d,%d)' % (self.__x, self.__y)
class Line:
'''
Define a class of objects called Line. Line(ߣ
Every Line is a pair of two Points. Line2
Lines are created by passing two Points to the Line constructor.
A Line object must be able to report its length,
which is the distance between its two end points.
'''
def __init__(self, p1, p2):
self.__p1 = p1
self.__p2 = p2
def length(self):
'''
ʾߵ2֮ľ
'''
return self.__p1.distance_to(self.__p2)
def __str__(self):
'''
ߵַʾ(x1,y1)--(x2,y2)
'''
return str(self.__p1) + '--' + str(self.__p2)
if __name__ == "__main__":
p1 = Point(0, 3)
print(p1)
assert str(p1) == "(0,3)"
p2 = Point(4, 0)
print(p2)
assert str(p2) == "(4,0)"
print(p1.distance_to(p2)) # should be 5.0
line1 = Line(p1, p2)
print(line1)
assert str(line1) == "(0,3)--(4,0)"
print(line1.length()) # should be 5.0
print(Line(Point(0, 0), Point(1, 1)).length())
|
0b57a9545507ed95c6f205e680e6436645fffc68 | jacareds/Unis | /2020.4_Atv2_Exer5.py | 278 | 4.25 | 4 | #Escreva uma função que:
#a) Receba uma frase como parâmetro.
#b) Retorne uma nova frase com cada palavra com as letras invertidas.
def inverText(text):
inversor = (text)
print(inversor[::-1])
entradInput = str(input("Digite uma frase: "))
inverText(entradInput)
|
01b1090b01fa027571889fe82558817034faffc9 | Hdwig/Math | /Lesson_3.2.1.py | 368 | 3.609375 | 4 | import numpy as np
import matplotlib.pyplot as plt
import math
a = 10
a2 = a ** 2
b = 2
b2 = b ** 2
xm = []
xp = []
yp = []
ym = []
for i in np.linspace(-10, 10, 1000):
x1 = i
xp.append(x1)
yp.append(math.sqrt(b2 - (x1 ** 2 * b2) / a2))
ym.append(-math.sqrt(b2 - (x1 ** 2 * b2) / a2))
plt.plot(xp, yp)
plt.plot(xp, ym)
plt.xlabel("x")
plt.ylabel("y")
|
5b8b45455631739e209fb0e92c057826e523cc66 | pesanteur/google_flight_api | /google_flight/querybuilder.py | 434 | 3.8125 | 4 | import json
with open('airports.json') as data_file:
data = json.load(data_file)
def get_iata_num(location):
"Get IATA number for a given city."
# TODO: Make thi sbetter so it can find cities with similar names or find multiple airports in the same city
for i in data:
city = data[i]['city']
if location == city:
iata = data[i]['iata']
else:
continue
return iata
|
838a748326aaac421224ae0ccb3e61363269c924 | AnimatedRNG/splash-2016-conway | /snowflake.py | 2,373 | 3.546875 | 4 | #!/bin/env python3
from life_renderer import LifeWindow
from random import randint
ROWS, COLS = 100, 100
cells = [[]]
def printall():
global cells
for i in range(ROWS):
for j in range(COLS):
if cells[i][j] > 0:
print((i, j, cells[i][j]))
def setup(life_window):
global cells
cells = [[0 for r in range(COLS)] for c in range(ROWS)]
cells[ROWS // 3 - 1][COLS // 2 - 1] = 1
life_window.clear_grid()
def loop(life_window):
life_window.clear_grid()
global cells
final_cells = [row[:] for row in cells]
# Uncomment next line for strange undiscovered fractal
#final_cells = cells[:]
for i in range(ROWS):
for j in range(COLS):
cell = (i, j)
neighbor_num = 0
for neighbor in list(__get_neighbors__(cell, cells, True).values()):
if neighbor > 0:
neighbor_num += 1
if neighbor_num == 1 or neighbor_num == 3 or neighbor_num == 6 or cells[i][j] > 0:
final_cells[i][j] = cells[i][j] % 8 + 1
else:
final_cells[i][j] = 0
print("Performed automata calculations.")
cells = final_cells
for i in range(ROWS):
for j in range(COLS):
if cells[i][j] > 0:
life_window.create_cell(i, j, value = cells[i][j])
print('Added cells')
def __get_macroblock__(pos, cells):
neighbor_sum = 0
neighbors = list(__get_neighbors__(pos, cells, False).values())
for neighbor in neighbors:
neighbor_sum += neighbor
return neighbor_sum // len(neighbors)
def __get_neighbors__(pos, cells, only_living = False):
positions = []
even_row, odd_row, even_col, odd_col = pos[0] % 2 == 0, pos[0] % 2 == 1, pos[1] % 2 == 0, pos[1] % 2 == 1
if ((even_row and even_col) or (odd_row and even_col)):
positions = [(pos[0] - 1, pos[1]), (pos[0] + 1, pos[1]), (pos[0], pos[1] - 1), \
(pos[0], pos[1] + 1), (pos[0] + 1, pos[1] - 1), (pos[0] + 1, pos[1] + 1)]
else:
positions = [(pos[0] - 1, pos[1]), (pos[0] + 1, pos[1]), (pos[0], pos[1] - 1), \
(pos[0], pos[1] + 1), (pos[0] - 1, pos[1] - 1), (pos[0] - 1, pos[1] + 1)]
new_positions = []
for p in positions:
if not (p[0] < 0 or p[0] >= ROWS or p[1] < 0 or p[1] >= COLS):
new_positions.append(p)
positions = new_positions
neighbors = {}
for p in positions:
if cells[p[0]][p[1]] > 0:
neighbors[p] = cells[p[0]][p[1]]
elif not only_living:
neighbors[p] = 0
return neighbors
life_window = LifeWindow(ROWS, COLS, setup = setup, loop = loop, hexagonal = True) |
edfbde378792e76035957665b102df3c7b59ad05 | HyunaShin/AlgorithmStudy | /coding_interview_conquer/bfs.py | 1,126 | 3.921875 | 4 | vertex_list = ["A", "B", "C", "D", "E", "F", "G"]
edge_list = [(0,1), (1,2), (1,3), (3,4), (4,5), (1,6)]
graphs = (vertex_list, edge_list)
def bfs(graph , start):
'''
너비 우선 탐색은 queue를 활용한 탐색법이다.
방법은 다음과 같다.
1. 시작 노드를 정한다.
2. 노드를 큐에 넣는다.
3. dequeue한다. --> dequeue한 노드의 인접 노드를 queue에 넣는다.이 때 이미 방문한 노드는 무시한다.
4. dequeue한 노드를 visited에 넣는다.
응용하면, 최단 경로를 구할 때 쓴다.
'''
vertex_list, edge_list = graph
visited_list = []
queue = [start]
adjacency_list = [[] for vertex in vertex_list]
for edge in edge_list:
adjacency_list[edge[0]].append(edge[1])
while queue:
current = queue.pop(0)
# current = queue.pop()
for neighbor in adjacency_list[current]:
if neighbor not in visited_list:
queue.append(neighbor)
# queue.insert(0,neighbor)
visited_list.append(current)
return visited_list
print(bfs(graphs,0))
|
55337a14b3c2b6a3b77a54fcb77281f34f754566 | geluso/learn-programming-programming-board-games | /03-grid-games/02-battleship/battleship-py/battleship_board_displayer.py | 1,612 | 3.671875 | 4 | from util import direction_to_dx_dy
def display_board(board):
print()
print("Ships left:")
print("X: 2[ ] 3[ ] 3[ ] 4[ ] 5[ ]")
print("O: 2[ ] 3[ ] 3[ ] 4[ ] 5[ ]")
print()
print(" 1 2 3 4 5 6 7 8 9 ")
rows = list("ABCDEFGH")
for letter, row in zip(rows, board):
line = letter + " "
line += " ".join(row) + " " + letter
print(line)
def display_placement_preview(player, ship, irow, icol, direction):
print()
print("Ships left:")
print("X: 2[ ] 3[ ] 3[ ] 4[ ] 5[ ]")
print("O: 2[ ] 3[ ] 3[ ] 4[ ] 5[ ]")
print()
print(" 1 2 3 4 5 6 7 8 9 ")
is_valid = True
# set
dx, dy = direction_to_dx_dy(direction)
for n in range(ship.size):
drow = irow + dy * n
dcol = icol + dx * n
if not player.ship_placements.is_valid(drow, dcol):
is_valid = False
elif player.ship_placements.board[drow][dcol] != ".":
is_valid = False
player.ship_placements.board[drow][dcol] = "X"
else:
player.ship_placements.board[drow][dcol] = str(ship.size)
rows = list("ABCDEFGH")
for letter, row in zip(rows, player.ship_placements.board):
line = letter + " "
line += " ".join(row) + " " + letter
print(line)
# unset
for n in range(ship.size):
drow = irow + dy * n
dcol = icol + dx * n
if player.ship_placements.is_valid(drow, dcol):
player.ship_placements.board[drow][dcol] = "."
return is_valid
|
3864ed6af4d0e73cb8d67a6441188e47d56518a9 | geluso/learn-programming-programming-board-games | /02-card-games/03-poker/00-hand-detection/ranking.py | 1,805 | 3.5625 | 4 | class Rank:
def __init__(self):
pass
def rank(self):
"""Stuff
hand is an array of five Cards
"""
hands = [
self.is_royal_flush, self.is_straight_flush,
self.is_four_of_a_kind, self.is_full_house, self.is_flush,
self.is_straight, self.is_three_of_a_kind, self.is_two_pair,
self.is_pair, self.is_high_card
]
for hand in hands:
if hand():
return hand(self.hand)
if is_royal_flush():
pass
class RoyalFlush(Rank):
def is_royal_flush(self):
if self.is_straight_flush() and self.faces[0][0] == 'A':
return True
return False
class StraightFlush:
def is_straight_flush(self):
if self.is_straight() and self.is_flush():
return True
return False
class FourOfAKind:
def is_four_of_a_kind(self):
if self.faces[0][1] == 4:
return True
return False
class FullHouse:
def is_full_house(self):
if self.faces[0][1] == 3 and self.faces[1][1] == 2:
return True
return False
class Flush:
def is_flush(self):
if self.suits[0][1] == 5:
return True
return False
class Straight:
def is_straight(self):
pass
class ThreeOfAKind:
def is_three_of_a_kind(self):
if self.faces[0][1] == 3:
return True
return False
class TwoPair:
def is_two_pair(self):
if self.faces[0][1] == 2 and self.faces[1][1] == 2:
return True
return False
class Pair:
def is_pair(self):
if self.faces[0][1] == 2:
return True
return False
class HighCard:
def is_high_card(self):
return self.high_card
|
85814d21f5ab1f57385cad9a4317f74c64e5ce70 | geluso/learn-programming-programming-board-games | /02-card-games/03-poker/00-hand-detection/card.py | 1,051 | 3.546875 | 4 | SPADES = 'spades'
CLUBS = 'clubs'
DIAMONDS = 'diamonds'
HEARTS = 'hearts'
SUITS = [SPADES, CLUBS, DIAMONDS, HEARTS]
FACES = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A']
class Card:
def __init__(self, face, suit):
self.face = face
self.suit = suit
@classmethod
def from_str(cls, str):
face = str[0]
suit = str[1]
if suit == 'S':
return Card(face, SPADES)
elif suit == 'C':
return Card(face, CLUBS)
elif suit == 'D':
return Card(face, DIAMONDS)
elif suit == 'H':
return Card(face, HEARTS)
def __gt__(self, other):
if self.face == other.face:
suits = [SPADES, CLUBS, DIAMONDS, HEARTS]
rank_self = suits.index(self.suit)
rank_other = suits.index(other.suit)
else:
faces = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"]
rank_self = faces.index(self.face)
rank_other = faces.index(other.face)
return rank_self > rank_other
|
09157861238e085199b31fd12f1df22076e3a0ea | Mizoguchi-Yuhei/udemy-kame-python | /input.py | 889 | 3.953125 | 4 | # input(): ユーザーの入力した値(文字列)を取得する
# age = input("何歳ですか?")
# print("あなたは{}歳です。".format(age))
age = int(input("何歳ですか?"))
# age = int(age)
casino_age = 18
game_text = """プレイするゲームを選択してください。
1: ルーレット
2: ブラックジャック
3: ポーカー
"""
if age >= casino_age:
print("どうぞカジノにお入りください。")
game = input(game_text)
if game == "1":
print("あなたはルーレットを選びました。")
elif game == "2":
print("あなたはブラックジャックを選びました。")
elif game == "3":
print("あなたはポーカーを選びました。")
else:
print("1~3を選んでください。")
else:
print("{}歳未満の方はカジノに入れません。".format(casino_age)) |
e2259e34e5a91d547e72dd1c516a745cf64faa1e | Mizoguchi-Yuhei/udemy-kame-python | /string_basic.py | 269 | 3.53125 | 4 | # 文字列(String)
print("Hello World!!")
print('1')
print("I'm fine.")
print('I"m fine.')
print("""
Hello world!!
How are you doing?
""")
print("Hello \nworld")
print("Hello \tworld")
print("back slash n: \\n")
print('I\'m fine')
print("hello" + "world" + "!!") |
cc1fc1f9c827d29495d1d0b8849d2520467af3a6 | Mizoguchi-Yuhei/udemy-kame-python | /range.py | 360 | 3.984375 | 4 | # range(start, stop, step)
# for i in range(1, 7):
# for i in range(1, 7, 1):
# print(i)
for i in range(7):
print(i)
# for i in range(4, 13, 2)
# print(i)
for _ in range(10):
print("hello")
for i in range(1, 51):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i) |
dc7c432deb82bf1f07e3f6e2b0632fb515c5ed62 | DiegoAyalaH/Mision-04 | /Rectangulos.py | 1,626 | 4.25 | 4 | #Nombre Diego Armando Ayala Hernández
#Matrícula A01376727
#resumen del programa: Obtiene los datos de dos rectangulos y te da el area y el perimetor de ambos
#Calcula el área de un rectángulo
def calcularArea(altura, ancho):
area = altura * ancho
return area
#Calcula el perímetro de un rectángulo
def calcularPerimetro(altura, ancho):
perimetro = (2 * altura) + (2 * ancho)
return perimetro
#Te dice cual de las dos áreas es mayor o si son iguales
def decirCualMayorArea(areaUno,areaDos):
if areaUno > areaDos:
return "El primer rectángulo es mayor"
elif areaUno < areaDos:
return "El segundo rectángulo es mayor"
return "Los rectangulos son iguales"
#Función main: recibe las dimensiones, te da el área y perímetro de los ambos rectángulos. También te dice cual es mayor o si son iguales
def main():
print("Escribe las dimensiones del primer rectángulo")
alturaUno = int(input("Altura: "))
anchoUno = int(input("Ancho: "))
print()
print("Escribe las dimensiones del segundo rectángulo")
alturaDos = int(input("Altura: "))
anchoDos = int(input("Ancho: "))
perimetro1 = calcularPerimetro(alturaUno, anchoUno)
perimetro2 = calcularPerimetro(alturaDos, anchoDos)
areaUno = calcularArea(alturaUno, anchoUno)
areaDos = calcularArea(alturaDos, anchoDos)
mayorArea = decirCualMayorArea(areaUno, areaDos)
print("Primer rectángulo")
print("Área : ", (areaUno))
print("Perímetro : ", (perimetro1))
print("Segundo rectángulo")
print("Área ", (areaDos))
print("Perímetro ", (perimetro2))
print(mayorArea)
|
c0bb13e71c4175bd2d6f5b509e437caa2dbf41cd | adrian-popa/fundamentals-of-programming | /Assignment05-07/src/domain/grade.py | 1,097 | 3.734375 | 4 | class Grade:
"""
Grade domain class
"""
def __init__(self, assignment_id, student_id, grade=None):
"""
Constructor for grade domain class
assignment_id - The assignment's ID (integer)
student_id - The student's ID (integer)
grade - The grade's value (integer)
"""
self.__assignment_id = assignment_id
self.__student_id = student_id
self.__grade = grade
def __eq__(self, other):
return self.__assignment_id == other.__assignment_id and self.__student_id == other.__student_id
def get_assignment_id(self):
return self.__assignment_id
def get_student_id(self):
return self.__student_id
def get_grade(self):
return self.__grade
def __str__(self):
format = 'Assignment ID: ' + str(self.__assignment_id) + ', student ID: ' + str(self.__student_id) + ', '
if self.__grade is None:
return format + 'ungraded'
else:
return format + 'grade: ' + str(self.__grade)
def __repr__(self):
return str(self)
|
3066c478740dd4d5974e7e0209a5c99f90f421ce | adrian-popa/fundamentals-of-programming | /tests/Hammurabi/src/validators/game_validator.py | 1,444 | 3.53125 | 4 | from controllers.controller_exception import ControllerError
class GameValidator:
@staticmethod
def validate_turn(situation, acres_to_buy_sell, units_to_feed_population, acres_to_plant):
land_price = situation.get_land_price()
grain_stocks = situation.get_grain_stocks()
if acres_to_buy_sell * land_price > grain_stocks:
raise ControllerError("You cannot buy more land than you have grain for.")
acres_of_land = situation.get_acres_of_land()
if acres_of_land + acres_to_buy_sell < 0:
raise ControllerError("You cannot sell more land than you have.")
acres_of_land = acres_of_land + acres_to_buy_sell
grain_stocks = grain_stocks - acres_to_buy_sell * land_price
if units_to_feed_population < 0:
raise ControllerError("You cannot feed people a negative number of units.")
if units_to_feed_population > grain_stocks:
raise ControllerError("You cannot feed people with grain you do not have.")
grain_stocks = grain_stocks - units_to_feed_population
if acres_to_plant < 0:
raise ControllerError("You cannot plant a negative number of acres.")
if acres_to_plant > acres_of_land:
raise ControllerError("You cannot plant more acres than you have.")
if acres_to_plant > grain_stocks:
raise ControllerError("You cannot plant grain that you do not have.")
|
33b31428f2451f5acd5e148e01ea18db564f540f | adrian-popa/fundamentals-of-programming | /Assignment05-07/out/production/Assignment05-07/controllers/student_controller.py | 2,169 | 3.578125 | 4 | from domain.student import Student
class StudentController:
"""
Student controller class
"""
def __init__(self, student_validator, student_repository):
"""
Constructor for student controller class
student_validator - The student validator for validating a student
student_repository - The student repository for CRUD operations on students
"""
self.__student_validator = student_validator
self.__student_repository = student_repository
def create_student(self, name, group, student_id=None):
"""
Method for creating a student
name - The student's name (string)
group - The student's group (integer)
"""
student = Student(student_id, name, group)
self.__student_validator.validate(student)
self.__student_repository.add(student)
return self.__student_repository.get_all()[-1].get_student_id()
def update_student(self, student_id, name, group):
"""
Method for updating a student
student_id - The student's ID (integer)
name - The student's name (string)
group - The student's group (integer)
"""
student = Student(student_id, name, group)
self.__student_validator.validate(student)
self.__student_repository.update(student_id, student)
def delete_student(self, student_id, should_decrement=False):
"""
Method for deleting a student
student_id - The student's ID (integer)
"""
self.__student_repository.delete(student_id, should_decrement)
def get_student(self, student_id):
return self.__student_repository.get(student_id)
def retrieve_students(self):
"""
Method for retrieving all students
output: an array of students from the repository
"""
return self.__student_repository.get_all()
def retrieve_students_by_group(self, group):
"""
Method for retrieving all students by a given group
output: an array of students from the repository
"""
return self.__student_repository.get_by_group(group)
|
f6c77714d04c741fda5667435f26fc15d161a268 | room77/py77 | /pylib/util/math/errors.py | 654 | 3.890625 | 4 | """
Math function related errors
"""
__author__ = "Kar Epker, karepker@gmail.com"
__copyright__ = "Room 77, Inc. 2013"
class NotDefinedError(Exception):
"""Error to raise when the operation is not defined"""
def __init__(self, operation, arg_dict):
"""Builds a not defined error
Args:
operation (string): The operation that was undefined (e.g. mean)
arg_dict (dict): A dict of args given to the function that wants to raise
this error
"""
self.operation = operation
self.arg_dict = arg_dict
def __str__(self):
return "operation %s is not defined with arguments %s!" % (
self.operation, str(self.arg_dict))
|
f98807412c2d9a098f5830c012e2b66cc561e844 | leztien/utilities | /datasets/make_3D_S_shape_out_of_2D_data.py | 1,001 | 3.5 | 4 |
def make_3D_S_shape_out_of_2D_data(data):
import numpy as np
assert isinstance(data, np.ndarray) and data.ndim == 2, "wrong input data"
X = data
t = (X[:,0] - X[:,0].mean()) * np.pi * 3
x = np.sin(t)
y = (np.cos(t)-1) * np.sign(t)
z = X[:,-1]
X = np.vstack([x,y,z]).T
# rotate and scale
n = 1 / (2 ** 0.5)
T = [[n, -n, -n],
[n, n, -n],
[n, 0, n]]
#X = np.matmul(T, X.T).T
X += np.abs(X.min(axis=0))
return X
def main():
import matplotlib.pyplot as plt, mpl_toolkits.mplot3d
from myutils.datasets import draw_random_pixels_from_image #, make_3D_S_shape_out_of_2D_data
X, y = draw_random_pixels_from_image("HELLO", n_points=1500)
X_3D = make_3D_S_shape_out_of_2D_data(X)
sp = plt.subplot(111, projection='3d')
sp.scatter(*X_3D.T, c=y, cmap=plt.cm.viridis)
sp.set(xlabel="x-axis", ylabel="y-axis", zlabel="z-axis")
plt.show()
if __name__=="__main__":main() |
2bd760b8f685c2483606200f2d2161363f50e21e | leztien/utilities | /ml/utility_functions_from_project001.py | 27,850 | 3.5625 | 4 |
class Coord:
def __init__(self, hours, minutes=None):
minutes = minutes or 0
assert -180 <= hours <= 180, "bar hours provided"
assert 0 <= minutes < 60, "bad mintes provided"
self.hours, self.minutes = hours, minutes
def __str__(self):
s = "{:>02}{}{:>02}{}".format(self.hours, chr(176), self.minutes, chr(8242))
return s
def __repr__(self):
return self.__str__()
def __float__(self):
minutes = self.minutes / 60
f = (abs(self.hours) + minutes) * (-1 if self.hours<0 else 1)
return f
def __add__(self, other):
if isinstance(other,int):
totalminutes = (abs(self.hours)*60 + self.minutes) * (-1 if self.hours<0 else 1)
totalminutes += other
h,m = divmod(abs(totalminutes), 60)
h *= -1 if totalminutes<0 else 1
ins = self.__class__(h,m)
return ins
elif isinstance(other,self.__class__):
return NotImplemented
else: raise NotImplementedError
def __sub__(self, other):
return self.__add__(-other)
def __radd__(self, other):
return self.__add__(other)
def __rsub__(self, other):
return self.__add__(-other)
def __iadd__(self, other):
if isinstance(other,int):
totalminutes = (abs(self.hours)*60 + self.minutes) * (-1 if self.hours<0 else 1)
totalminutes += other
h,m = divmod(abs(totalminutes), 60)
h *= -1 if totalminutes<0 else 1
self.hours, self.minutes = h,m
return self
elif isinstance(other,self.__class__):
return NotImplemented
else: raise NotImplementedError
def __isub__(self, other):
return self.__iadd__(-other)
@classmethod
def fromstring(cls, string):
from re import compile
pt = compile(r"(-?\d{1,2})%s(\d{1,2})" % chr(176))
m = pt.match(string.strip())
if m:
t = m.groups()
if all(s.lstrip('-').isdecimal() for s in t):
h,m = (int(n) for n in t)
ins = cls(h,m)
return(ins)
raise ValueError("parsing failed")
#################END OF OORD CLASS###########################################################
def make_data(m=100):
import numpy as np, pandas as pd
rs = np.random.RandomState(0)
#FEATURE x1 and x2 (latitude, longitude)
hamburg = [Coord.fromstring(s) for s in "53°33 10°00".split()]
latitude_longitude = rs.uniform([-20,-20], [20,20], (m,2)).astype(int).astype(object)
nd = hamburg + latitude_longitude
vectorized_float = np.vectorize(float)
nd = vectorized_float(nd).astype(np.float16).round(2) #feature x1, x2
mean_dist = (((nd - [float(e) for e in hamburg]) **2).sum(axis=1)**0.5).mean() #to be used as: if > dist
is_outside_citycenter = (((nd - [float(e) for e in hamburg]) **2).sum(axis=1)**0.5) > mean_dist
x1,x2 = nd.T
f12 = np.abs(rs.normal(loc=nd.mean(), scale=nd.std(), size=m))
#FEATURE x3 (site side length in meters)
x3 = rs.normal(loc=10, scale=3, size=m).round(1)
x3[x3<=0] = 3
f3 = np.abs(rs.normal(loc=x3.mean(), scale=x3.std(), size=m))
#FEATURE x4 (total costs of the site)
price_per_meter = rs.normal(loc=10000, scale=2000, size=m)
x4 = (x3 * price_per_meter).round()
f4 = np.abs(rs.normal(loc=x4.mean(), scale=x4.std(), size=m)).round()
#FEATURE (rating)
x5 = rs.choice(['A','B','C'], m, replace=True)
#DATAFRAME
pd.options.display.precision=2
df = pd.DataFrame({'latitude':x1.round(2), 'longitude':np.round(x2,2),
'side length':x3, 'site costs':x4, 'rating':x5,
'f12':f12, 'f3':f3, 'f4':f4}).round(2)
X = np.vstack([is_outside_citycenter, x3**3, x4/x3, pd.factorize(x5)[0]]).T
EE = X.mean(axis=0) #Expected values
MX = EE.max()
weights = MX / EE
weights *= [-1, 1, -1, 1]
y = (X * weights).sum(axis=1)
y = X @ weights #same
θ = np.array([np.abs(y.min()), *weights]).round(2).astype(np.float16)
y += np.abs(y.min())
mask = y>0
X,y,df = (arr[mask] for arr in (X,y,df))
from sklearn.linear_model import LinearRegression
md = LinearRegression().fit(X,y)
print("score:::", md.score(X,y))
print(X)
print(y)
#np.save("X", X)
#np.save("y", y)
print(mean_dist)
#APPEND THE TARGET TO DATAFRAME
df['profit'] = y
return df
###############END OF MAKE DATA#######################################
def add_outliers(a, p=None, copy=True, random_state=None):
from numpy.random import RandomState, randint, randn
from numpy import quantile, abs, logical_or, setdiff1d
if copy: a = a.copy()
p = p or 0.05; assert isinstance(p, float) and 0<p<1,"error1"
rs = RandomState(random_state or randint(0, int(1e6)))
Q1,Q3 = quantile(a, q=[0.25, 0.75])
IQR = Q3 - Q1
LB = Q1 - IQR*1.5
UB = Q3 + IQR*1.5
nxOriginalOutliers = logical_or(a<LB,a>UB).nonzero()[0]
how_many = int(round(len(a)*p,0)) - len(nxOriginalOutliers)
nx = set(range(len(a))) - set(nxOriginalOutliers)
nx = rs.choice(list(nx), replace=False, size=how_many)
nx = setdiff1d(nx, nxOriginalOutliers)
add_outliers.original_outliers = nxOriginalOutliers.tolist()
add_outliers.added_outliers = []
if len(nx)==0 or how_many<1:
from warnings import warn
warn("No outliers were added", Warning)
return a
nxL,nxU = nx[:how_many//2], nx[how_many//2:]
a[nxL] = LB - abs(randn(len(a[nxL]))*(a.std()/1.5))
a[nxU] = UB + abs(randn(len(a[nxU]))*(a.std()/1.5))
add_outliers.added_outliers = nx.tolist()
Q1,Q3 = quantile(a, q=[0.25, 0.75])
IQR = Q3 - Q1
LB = Q1 - IQR*1.5
UB = Q3 + IQR*1.5
add_outliers.actual_outliers = logical_or(a<LB,a>UB).sum()
return a
def add_outliers_to_matrix(mx, columns=None, p=None): #mx is passes by ref
columns = columns or range(mx.shape[-1])
if not hasattr(columns, '__len__'): columns = [columns,]
p = p if hasattr(p,'__len__') else [p,]*len(columns)
assert len(columns)==len(p),"error10"
for j,p in zip(columns,p):
mx[:,j] = add_outliers(mx[:,j], p, copy=True)
return(mx) #if nothing is return the passed in mx will still be modified
#========================================================================================
def makedata(m=100, n_target_categories=None, add_nans=False, add_noise=False, add_outliers=False, return_csv_filepath=True, random_seed=None):
import numpy as np # e.g. filepath = makedata(1000, return_csv_filepath=True, add_nans=0.01, add_noise=True, add_outliers=True)
import scipy.stats
from pandas import DataFrame, factorize, Categorical
rs = np.random.RandomState(random_seed or 0)
#FEATURE x1 (side-length)
probs = rs.randint(5,21, size=10)
probs = probs / probs.sum()
x1 = rs.choice([*range(1,11)], p=probs, size=m, replace=True)
#FEATURE x2 (thickness)
multinomail = scipy.stats.multinomial(m, [0.1, 0.2, 0.3, 0.25, 0.15])
counts = multinomail.rvs(1)[0].tolist()
l = [[n,]*k for n,k in zip(range(5,11), counts)] #vizualize the distribution here
l = sum(l,[])
import random
random.shuffle(l)
x2 = (np.array(l) + x1**2*0.05).round(1)
#FEATURE x3 (total >>> ratio) in $
a = rs.normal(loc=100, scale=25, size=m)
x3 = (a * x1).round(2)
#FEATURE x4 (yes/no = 50/50)
x4 = rs.choice(['no','yes'], size=m, replace=True)
#FEATURE x5 (garde)
x5 = scipy.stats.binom.rvs(n=2, p=0.5, size=m)
x5 = np.array(list("CBA"))[x5]
#FAKE FEATURE x6
x6 = x1 * x2
x6 = rs.normal(loc=x6.mean(), scale=x6.std(), size=m).round(2)
#FAKE FEATURE x7
x7 = np.abs(rs.normal(loc=x3.mean(), scale=x3.std(), size=m)).round(2)
#TARGET
f1 = x1**2
f2 = x1**2*x2
f3 = x3/x1
f4 = np.abs(factorize(x4)[0]-1).astype(np.uint8)
f5 = Categorical(x5, ordered=True).reorder_categories(list("CBA")).rename_categories([0,1,2]).astype(np.uint8)
X = np.vstack([f1,f2,f3,f4,f5]).T
μμ = X.mean(axis=0)
mx = μμ.max()
θ = mx / μμ
y = (X @ θ).round(2) + (rs.randn(m) if add_noise else 0)
#ADD OUTLIERS
if add_outliers:
add_outliers = globals()['add_outliers']
x2 = add_outliers(x2, p=0.03, random_state=rs.get_state()[1][0]) #assume erronious measurement
y = add_outliers(y, p=0.03, random_state=rs.get_state()[1][0]+1) #assume erronious measurement
#IF CATEGORICAL TARGET
if n_target_categories:
assert isinstance(n_target_categories,int)and(2<=n_target_categories<=100),"bad categories, must be int"
from numpy import linspace,digitize
breaks = linspace(y.min(), y.max()+0.001, n_target_categories+1)
y = digitize(y, breaks) - 1
#DATAFRAME
df = DataFrame({'length':x1,'thickness':x2,'total':x3,'yes/no':x4,'grade':x5,
'feature6':x6, 'feature7':x7, 'target':y})
#ADD NAN'S
if add_nans:
p = add_nans if isinstance(add_nans, float) else 0.01
subset = slice(None),slice(1,None,None)
def indeces_for_random_nan_cells(df, p=0.1, subset=None):
from numpy import dtype, uint8, zeros, random
subset = subset or (slice(None),slice(None))
m,n = df.shape
dtype = dtype([('row', uint8), ('col', 'uint8')])
nd = zeros(shape=(m,n), dtype=dtype)
[nd[i].__setitem__('row', i) for i in range(m)]
[nd[:,j].__setitem__('col', j) for j in range(n)]
nd = nd[subset]
k = int(round(nd.size * p)) # number of cells to fill up with nan's
nx = random.choice(nd.size, replace=False, size=k)
nx = nd.ravel()[nx]
nx = [tuple(t) for t in nx]
return(nx)
nx = indeces_for_random_nan_cells(df, p, subset)
[df.iloc.__setitem__(t, np.nan) for t in nx]
if return_csv_filepath:
import os, time
DIR = os.environ.get('TEMP')
FILENAME = "temp_" + time.strftime("%Y%m%d%H%M%S") + ".csv"
fullfilename = os.path.join(DIR, FILENAME)
df.to_csv(fullfilename, index=False)
del df
return fullfilename
return(df)
#=============================================================================================
def prepare_data_and_split_into_X_y(df, recursive_elimination=True, columns=None) -> ('df','y'): # returns a df with the X-values and the target y-variable
from utility import OutliersRemover, DropTargetNans
from sklearn.pipeline import Pipeline
columns = columns or [1,2,5,6,7]
outliersremover = OutliersRemover(columns=columns, recursive_elimination=recursive_elimination)
droptargetnans = DropTargetNans()
pl = Pipeline([('outliersremover', outliersremover), ('droptargetnans', droptargetnans)])
dfOutliersAndNansRemoved = pl.fit_transform(df)
dfX = dfOutliersAndNansRemoved.iloc[:,:-1]
y = ytrue = dfOutliersAndNansRemoved['target'].values
return(dfX,y)
#========================================================================================
from sklearn.base import BaseEstimator, TransformerMixin
class Subsetter(BaseEstimator, TransformerMixin):
def __init__(self, columns=None, if_df_return_values=False, astype_float=False):
self.columns = columns or slice(None)
self._if_df_return_values = if_df_return_values
self.astype_float = astype_float
def fit(self, X, *args, **kwargs):
return self
def transform(self, X, *args, **kwargs):
from pandas import DataFrame
from numpy import ndarray, matrix, float64
if type(X)in(ndarray,matrix):
X = X[:,self.columns]
elif isinstance(X, DataFrame):
df = X
from numbers import Integral
if hasattr(self.columns, '__iter__') and all(isinstance(n,Integral) for n in self.columns):
df = df.iloc[:,self.columns]
else:
df = df[self.columns]
if not self._if_df_return_values: return df
else: X = df.values
else: raise TypeError("unforseen error / not supported type")
X = X.astype(float64) if self.astype_float else X
return X
#======================================================================================
from sklearn.base import BaseEstimator, TransformerMixin
class RatioFeatures(BaseEstimator, TransformerMixin):
def __init__(self, column_pairs=None, return_ratio_only=False, if_df_return_values=False): # when usind in a pipeline, sklearn might not like *args
self.column_pairs = column_pairs or [(0,1),]
self.return_ratio_only = return_ratio_only
self.if_df_return_values = if_df_return_values
@property
def column_pairs(self):
return self.__column_pairs
@column_pairs.setter
def column_pairs(self, new):
assert hasattr(new, '__iter__'),"must be iterable"
def unravel(it):
l = list()
for e in it:
if hasattr(e, "__len__") and type(e) is not str: l.extend(unravel(e))
else: l.append(e)
return l
a = unravel(new)
assert len(a)>=2,"error1"
assert len(a)%2==0, "error2"
assert all(isinstance(e,int) for e in a) or all(isinstance(e, str) for e in a), "error3"
new = [(a[i],a[i+1]) for i in range(0, len(a)-1, 2)]
self.__column_pairs = new
self.__unraveled_column_pairs = a #for inner purposes
def fit(self, X, y=None, *args, **kwargs):
a = self.__unraveled_column_pairs
if isinstance(a[0], int):
from numpy import ndarray, matrix; from pandas import DataFrame
assert type(X) in (ndarray,matrix) or (isinstance(X, DataFrame)and self.if_df_return_values),"error4"
assert min(a)>=0 and max(a)<X.shape[-1],"error5"
elif isinstance(a[0], str):
from pandas import DataFrame
df = X
assert isinstance(df, DataFrame),"error6"
assert all(s in df.columns.values for s in a),"error7"
else: raise TypeError("unforseen error")
return self
def transform(self, X, y=None, *args, **kwargs):
from numpy import ndarray, hstack, nan, isinf
from pandas import DataFrame, concat
if isinstance(X, DataFrame) and self.if_df_return_values and isinstance(self.__unraveled_column_pairs[0], int):
X = X.values
self.fit(X) # in order to catch possible errors when transforming new data
new_features = []
if isinstance(X, ndarray): #np.matrix is not yet implemented
for ix1,ix2 in self.column_pairs:
a1,a2 = (arr.astype('f') for arr in (X[:,ix1],X[:,ix2] ))
new_feature = a1/a2
new_feature[isinf(new_feature)] = nan
new_features.append(new_feature[:,None])
if self.return_ratio_only: return hstack([*new_features])
else: return hstack([X, *new_features])
elif isinstance(X,DataFrame):
df = X
for ix1,ix2 in self.column_pairs:
new_feature = df[ix1] / df[ix2]
#TODO: Devision by Zero
new_feature.name = df[ix1].name + ' / ' + df[ix2].name
new_features.append(new_feature)
if self.return_ratio_only: return concat([*new_features], axis=1)
else: return concat([df,*new_features], axis=1)
else: raise TypeError("your type is not implemented")
raise Exception("unforseen error")
#=====================================================================================
from sklearn.base import BaseEstimator, TransformerMixin
class RatioFeaturesSimple(BaseEstimator, TransformerMixin):
def __init__(self, column_pairs=None, return_ratio_only=False, if_df_return_values=False): # when usind in a pipeline, sklearn might not like *args
self.column_pairs = column_pairs
self.return_ratio_only = return_ratio_only
self.if_df_return_values = if_df_return_values
def fit(self, X, y=None, *args, **kwargs):
return self
def transform(self, X, y=None, *args, **kwargs):
from numpy import ndarray, hstack, nan, isinf
from pandas import DataFrame, concat
if isinstance(X, DataFrame) and self.if_df_return_values and isinstance(self.__unraveled_column_pairs[0], int):
X = X.values
new_features = []
if isinstance(X, ndarray): #np.matrix is not yet implemented
for ix1,ix2 in self.column_pairs:
a1,a2 = (arr.astype('f') for arr in (X[:,ix1],X[:,ix2] ))
new_feature = a1/a2
new_feature[isinf(new_feature)] = nan
new_features.append(new_feature[:,None])
if self.return_ratio_only: return hstack([*new_features])
else: return hstack([X, *new_features])
elif isinstance(X,DataFrame):
df = X
for ix1,ix2 in self.column_pairs:
new_feature = df[ix1] / df[ix2]
#TODO: Devision by Zero
new_feature.name = df[ix1].name + ' / ' + df[ix2].name
new_features.append(new_feature)
if self.return_ratio_only: return concat([*new_features], axis=1)
else: return concat([df,*new_features], axis=1)
else: raise TypeError("your type is not implemented")
#=====================================================================================
from sklearn.base import BaseEstimator,TransformerMixin
class Scaler(BaseEstimator,TransformerMixin):
"""allows to scale or not to scale - for grid-search"""
def __init__(self, scaler, scale=False):
self.scaler = scaler # user must pass in a scaler like sklearn-MinMaxScaler()
self.scale = scale
def fit(self, X, y=None, *args):
if self.scale:
self.scaler.fit(X)
return self
def transform(self, X, y=None, *args):
if self.scale:
X = self.scaler.transform(X)
return X
#======================================================================================
def splitdata(df):
sr = df['target']
breaks = sr.quantile([0, 0.25, 0.5, 0.75, 1.0]).values
from numpy import digitize
f = digitize(sr.values, breaks)
from sklearn.model_selection import train_test_split
dfTrain,dfTest = train_test_split(df, test_size=0.2, stratify=f)
#pickle
dfTrain.to_pickle(r"trainset_dataframe.pkl")
dfTest.to_pickle(r"testset_dataframe.pkl")
splitdata.train = r"trainset_dataframe.pkl"
splitdata.test = r"testset_dataframe.pkl"
return(dfTrain,dfTest)
#===================================================================================
def outlier_indeces(a, return_boolean_mask=False):
from numpy import quantile, logical_or, nonzero
Q1,Q3 = quantile(a, q=[0.25,0.75])
IQR = Q3-Q1
LB = Q1-IQR*1.5
UB = Q3+IQR*1.5
mask = logical_or(a<LB, a>UB)
if return_boolean_mask: return mask
nx = nonzero(mask)[0]
return nx
#===================================================================================
from numpy import isnan, quantile, ndarray, floating, float64, array
from numexpr import evaluate
def outlier_bounds(a): # get outlier bounds by recursive outlier elimination
if not isinstance(a, ndarray): a = array(a, dtype=float64)
if not issubclass(a.dtype.type, floating): a = a.astype(float64)
a = a[~isnan(a)]
Q1,Q3 = quantile(a, q=[0.25,0.75])
IQR = Q3-Q1
LB,UB = Q1-IQR*1.5, Q3+IQR*1.5
mask = evaluate("(a<LB) | (a>UB)") #outliers
if int(mask.sum()): return(outlier_bounds(a[~mask]))
return(LB,UB) #this is in effect the else-block
#====================================================================================
from sklearn.base import BaseEstimator, TransformerMixin
class OutliersRemover(BaseEstimator, TransformerMixin):
def __init__(self, columns=None, recursive_elimination=False):
self.columns = columns or []
self.recursive_elimination = recursive_elimination
assert isinstance(columns,list),"must be a list"
def fit(self, X, y=None, *args, **kwargs):
from pandas import DataFrame
from numpy import empty
if isinstance(X, DataFrame): X = X.values
bounds = empty(shape=(2, len(self.columns)), dtype='float64')
for j,column in enumerate(self.columns):
bounds[:,j] = self._outlier_bounds(X[:,column])
self.LB, self.UB = bounds #lower and upper bounds
return self
def transform(self, X, y=None, *args, **kwargs):
from pandas import DataFrame
from numpy import logical_and
from numexpr import evaluate
self.X = X #keep the original input data for later
X = X.iloc[:, self.columns].values if isinstance(X, DataFrame) else X[:,self.columns]
LB,UB = self.LB, self.UB
#MASK = (X <= LB)|(X >= UB); MASK = np.logical_or(X<=LB, X.__ge__(UB)) #same
MASK = evaluate("(X<=LB)|(X>=UB)") # X = subset MASK = 2D mask-array denoting outliers
self.mask = logical_and.reduce(~MASK, axis=1) # non-outliers
self.X = self.X.iloc[self.mask,:] if isinstance(self.X, DataFrame) else self.X[self.mask,:]
self.number_of_outliers_removed = X.shape[0] - self.X.shape[0]
self.outliers_index = (~self.mask).nonzero()[0]
del X, self.mask
return self.X
from numpy import isnan, quantile, ndarray, floating, float64, array, empty
from numexpr import evaluate
def _outlier_bounds(self, a): # get outlier bounds by recursive outlier elimination
if not isinstance(a, ndarray): a = array(a, dtype=float64)
if not issubclass(a.dtype.type, floating): a = a.astype(float64)
mask = isnan(a)
if mask.any(): a = a[~mask]
Q1,Q3 = quantile(a, q=[0.25,0.75])
IQR = Q3-Q1
LB,UB = Q1-IQR*1.5, Q3+IQR*1.5
if self.recursive_elimination:
mask = evaluate("(a<LB) | (a>UB)") #outliers
if int(mask.sum()):
return(self._outlier_bounds(a[~mask]))
return(LB,UB) #this is in effect the else-block
#=========================================================================================================
from sklearn.base import BaseEstimator, TransformerMixin
class DropTargetNans(BaseEstimator, TransformerMixin):
def __init__(self, target=None):
self.target = target or -1
def fit(self, X, y=None, *args, **kwargs):
return self
def transform(self, X, y=None, *args, **kwargs):
from numpy import ndarray, matrix
from pandas import DataFrame
if isinstance(X, DataFrame):
df = X
self.target = self.target if isinstance(self.target,str) else df.columns.values[self.target]
df = df.dropna(subset=[self.target])
return(df)
if type(X) in (ndarray,matrix):
from numpy import isnan
from numbers import Integral
assert isinstance(self.target, Integral),"must be int"
mask = ~isnan(X[:,self.target])
X = X[mask,:]
return X
else: raise TypeError("not implemented")
#==================================================================================================
from sklearn.base import BaseEstimator, TransformerMixin
class Transformer(BaseEstimator, TransformerMixin):
def __init__(self, hyperparameter=None):
self.hyperparameter = hyperparameter or [(0,1),(2,3)]
@property
def hyperparameter(self):
return self.__hyperparameter
@hyperparameter.setter
def hyperparameter(self, new):
from numbers import Integral
b = hasattr(new, '__len__') and all(hasattr(e, '__len__')and len(e)==2 and all(isinstance(n,Integral) and n>=0 for n in e) for e in new)
if not b: raise ValueError("hyperparameter must be of format [(0,1),(2,3), ...]")
self.__hyperparameter = new
def fit(self, X, y=None, *args, **kwargs):
return self
def transform(self, X, y=None, *args, **kwargs):
return X
#=========================================================================================
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import PolynomialFeatures
class PolynomialExpansion(BaseEstimator, TransformerMixin):
"""returns only the polynomially expanded features, but not the original (input) features"""
def __init__(self, degree=2, with_interactions=True):
self.degree = degree
self.with_interactions = with_interactions
def fit(self, X, y=None, *args):
return self
def transform(self, X, y=None, *args):
poly = PolynomialFeatures(degree=self.degree, interaction_only=not self.with_interactions, include_bias=False)
XX = poly.fit_transform(X)
XX = XX[:, X.shape[1]:]
self.names = poly.get_feature_names()[X.shape[1]:]
del poly
return XX
#====================================================================================
from sklearn.base import BaseEstimator,TransformerMixin
class CorrelationFeatureSelector(BaseEstimator,TransformerMixin):
def __init__(self, k_best=None, proportion=None):
self.k_best, self.proportion = k_best, proportion
self.nx = None
def fit(self, X, y, *args):
n = self.k_best or int(round(self.proportion*X.shape[1]))
assert isinstance(n, int)and n<X.shape[1],"error1"
from numpy import corrcoef, c_
r = corrcoef(c_[X,y].T).round(3)[:-1,-1] #r = correlation coefficients
self.nx = r.argsort()[:-(n+1):-1]
return self
def transform(self, X, y=None, *args):
if self.nx is None: raise Exception("you must fit the model first")
return X[:,self.nx]
#=====================================================================================
def discretize(a, bins=3): # bins = number of equal bins
from math import ceil # equivelent to numpy.digitize(a, bins=breaks)
mn,mx = min(a), max(a) # equivelent to pandas.cut(a, bins=3)
nx = [ceil((n-mn)/(mx-mn)*bins) for n in a]
nx[0] = nx[1]
return nx #Note discretization depends on the range of the array
#====================================================================================
|
f5ba37f91a469a245113b30d1a37e8ad171ab278 | chensxb97/Homework_2 | /postingList.py | 2,445 | 3.609375 | 4 | import math
class ListNode:
# Initialisation
def __init__(self, doc_id=None):
self.doc_id = int(doc_id) # docId
self.next = None # Points to next node
self.skip_to = None # Points to skipped node
class postingList:
# Initialisation
def __init__(self, postingStr=None):
self.head = None
self.tail = None
self.length = 0
self.has_skips = False
# Populate postingList
if postingStr != None:
if type(postingStr) == str: # Input argument of type: string
doc_ids = [int(i) for i in postingStr.split()]
for doc_id in doc_ids:
self.insert(ListNode(doc_id))
elif type(postingStr) == list or type(postingStr) == set: # Input argument of type: list or set
for doc_id in postingStr:
self.insert(ListNode(doc_id))
else:
print('Input posting is not in the correct structure.')
# Insertion at back of list
def insert(self, node):
if self.head == None:
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail = node
self.length += 1
# Convert object to string
def convertToString(self):
result = ''
cur = self.head
while cur != None:
result += str(cur.doc_id) + ' '
cur = cur.next
result = result.rstrip()
return result
# Gets node via search index
def getNode(self, index):
cur = self.head
while index > 0:
cur = cur.next
index -= 1
return cur
# Calculates skip interval based on the postingList length
def skipInterval(self):
return math.floor(math.sqrt(self.length))
# Sets the skip pointer of node1 to node2
def skip(self, idx1, idx2):
node1 = self.getNode(idx1)
node2 = self.getNode(idx2)
node1.skip_to = node2
# Adds skips
def addSkips(self):
if self.has_skips == False:
node1 = 0
skips = self.skipInterval()
node2 = skips
while node2 < self.length:
self.skip(node1, node2)
node1 = node2
node2 += skips
self.has_skips = True
else:
print('Posting list already added skips')
return self
|
97cc951bd585348f99f30d9b2cf56e6d42b2117e | ankitandel/list.py | /list10.py | 318 | 3.796875 | 4 | # # Q: How to find all pairs in an array of integers whose sum is equal to the given number?
# number = 30
# n = [10, 11, 12, 13, 14, 17, 18, 19]
# i=0
# a=[]
# while i<len(n):
# j=4
# while j<len(n):
# if n[i]+n[j]==number:
# a.append([n[i],n[j]])
# j=j+1
# i=i+1
# print(a)
|
2a91ea52ab877f3587a8f869648828006f61054c | GrayWizard12345/PythonGUI | /Starter.py | 1,520 | 3.546875 | 4 | from Customer import Customer
from Order import Order
from Product import Product
from Staff import Staff
from Store import Store
if __name__ == "__main__":
c1 = Customer("01223", "Peter Parker", "Qo'yliq", 2.2, "90-932-75-98", ["Silver", 'Gold'])
c2 = Customer("01223", "Sherlock Holmes", "Backer street", 31415, "90-987-65-43", ["Regular", 'VIP'])
store = Store('U1510375', "John's Mall", "Ziyolar-9", "90-123-45-67")
staff1 = Staff("0", "02213", "Uncle Ben", "Manager")
staff2 = Staff("1", "45646", "Aunt May", "Cashier")
staff3 = Staff('2', "12345", "John Doe", "Owner")
p1 = Product(69, "Cucumber", "Fresh and long cucumber", 69.69, 666)
p2 = Product(666, "Tomatoes", "Red and plump", 12.14, 314)
order = Order(store, c1, staff2)
print(store)
print()
print(c1)
print()
print(c2)
print()
print(staff1)
print()
print(staff2)
print()
ans = 0
while ans != "yes":
print("Are you ready to make an order? (type yes or no):")
ans = input()
if ans == "no":
print("Okay, type yes when you'll be ready!")
while ans != 'done':
print("Currently there are only 2 products:\n"
"1. Cucumber\n"
"2. Tomatoes\n"
"Which one do you want to by?: (type 1 or 2 or 'done' to proceed)")
ans = input()
if ans == '1':
order.add_product(p1)
if ans == '2':
order.add_product(p2)
print("\tHere is your receipt:\n")
order.print_receipt()
|
7bbd3d5da5ee6272f1228623e0383e2cb7b3d755 | RedKnite5/Junk | /file_ops.py | 1,140 | 3.671875 | 4 | #!C:\Users\RedKnite\AppData\Local\Programs\Python\Python38\python
# file_ops.py
class File(object):
def __init__(self, filename=None):
self.filename = filename
if self.filename is not None:
try:
with open(self.filename, "r") as f:
self.text = f.read()
except FileNotFoundError:
self.text = ""
with open(self.filename, "x"):
pass
else:
self.text = ""
def set_filename(self, filename):
self.filename = filename
def __str__(self):
return f"file({self.filename})"
def __add__(self, other):
return self.text + str(other)
def __iadd__(self, other):
with open(self.filename, "w") as f:
f.write(self.text + str(other))
self.text += str(other)
def clear(self):
with open(self.filename, "w"):
pass
def read(self):
return self.text
def readlines(self):
return text.split("\n")
def append(self, string):
with open(self.filename, "a") as f:
f.write(string)
self.text += string
def insert(self, string, index=0):
pass
if __name__ == "__main__":
a = File("text.txt")
a += "Hello!"
|
e7cfc9650e8567b3e3b49c88b1d5ac82fb822f90 | RedKnite5/Junk | /euler66.py | 1,220 | 3.5 | 4 | from itertools import count
from math import isqrt, sqrt, isclose
from fractions import Fraction
def is_square(n):
if isinstance(n, Fraction):
num, denom = n.as_integer_ratio()
if denom != 1:
return False
n = num
if isqrt(n)**2 == n:
return True
return False
def minimal_sol(D: int) -> int | None:
# check if square
if is_square(D):
return None
start = 2
if D == 61:
start = 1_000_000 * 352
for x in count(start):
if x % 1_000_000 == 0:
print(x / 1_000_000, D)
y_2 = Fraction(x * x - 1) / D
if is_square(y_2):
return x
def linear_approx(D: int, start: int) -> int:
sqrt_D = D**.5
for x in count(start):
y = x * sqrt_D
if y > 6000:
print(y)
exit()
if isclose(y, round(y), abs_tol=1e-7):
print("%.99g" % y, y == round(y))
y_2 = Fraction(x * x - 1) / D
if is_square(y_2):
return x
def main() -> None:
maximal_min = (2, 3)
for D in range(2, 1001):
x = linear_approx(D, 2)
if x is None:
continue
if x > maximal_min[1]:
maximal_min = (D, x)
print("New max: ", maximal_min)
D, x = maximal_min
print(f"{D = } {x = }")
if __name__ == "__main__":
main()
|
55ec148f1b65c4a82e959125decb4e5091756ed5 | RedKnite5/Junk | /graph_calc_obj.py | 2,351 | 3.546875 | 4 | import math
from math import e
import tkinter as tk
import list_functions as li
# python graph_calc.py
class graph(object):
def __init__(self,func,
scr_width=400,scr_height=400,
xmin=-5,xmax=5,ymin=-5,ymax=5):
def axis(x,y): return(0)
def y1(x,y): return(eval(func))
xfunc = [axis,y1]
yfunc = [axis]
fields = []
root = tk.Tk()
def close():
root.quit()
screen = tk.Canvas(root,width=scr_width,height=scr_height)
screen.pack()
close = tk.Button(root,text="Close",command=close)
close.pack()
for i in xfunc:
density = 1000
x = xmin
k = 0
while x < xmax:
xrang = xmax-xmin
yrang = ymax-ymin
x += xrang/density
try:
y = i(x,0)
slope = (i(x,0)-i(x-.0001,0))/.0001
density = int((400*math.fabs(slope))+500)
if y > ymax or y < ymin:
density = 2000
a = (x-xmin)*scr_width/xrang
b = scr_height -( (y-ymin)*scr_height/yrang)
screen.create_line(a,b,a+1,b)
k += 1
except: pass
for i in yfunc:
density = 1000
y = ymin
k = 0
while y < ymax:
xrang = xmax-xmin
yrang = ymax-ymin
y += yrang/density
x = i(y,0)
slope = (i(y,0)-i(y-.0001,0))/.0001
density = int((400*math.fabs(slope))+1000)
if x > xmax or x < xmin:
density = 2000
a = (x-xmin)*scr_width/xrang
b = scr_height -( (y-ymin)*scr_height/yrang)
screen.create_line(a,b,a+1,b)
k += 1
'''
for i in fields:
field_density = 30
for k in range(int(field_density)):
for h in range(int(field_density)):
xrang = xmax-xmin
yrang = ymax-ymin
x = (h+((xmin+xmax)/2 - field_density/2))*xrang/field_density
y = (k+((ymin+ymax)/2 - field_density/2))*yrang/field_density
slope = i(x,y)
a = (x-xmin)*scr_width/xrang
b = scr_height - (y-ymin)*scr_height/yrang
slope_line_len = slope*(30/(1+slope**4))**.5
try:
c = math.fabs(slope_line_len/slope)
except:
c = slope_line_len
d = slope_line_len*slope
print("")
print(b,d,b-d,b+d)
print(round(((4*c*c)+(4*d*d))**.5))
print("C: ",c," D: ",d)
screen.create_line(a+c,b-d,a-c,b+d)
'''
root.update()
|
5a8ee88c65b580dcd9efcf73014edb50bffb8bad | RedKnite5/Junk | /euler34.py | 672 | 3.8125 | 4 | # euler34.py
# Find the sum of all numbers which are equal to the sum of the factorial of their digits.
# 1 and 2 dont count since theyre totals only contain 1 value and are not "sums"
max = 362880
def fact(n: int) -> int:
if n < 0:
raise ValueError("negative value for factorial")
result: int = 1
for i in range(1, n+1):
result *= i
return result
facts = {str(d): fact(d) for d in range(10)}
def fact_digit_sum(n: int) -> int:
total: int = 0
for d in str(n):
total += facts[d]
return total
def main() -> None:
total = sum(n for n in range(3, max) if fact_digit_sum(n) == n)
print(f"{total = }")
if __name__ == "__main__":
main()
|
6b0abedebad8e88acf45541bd32b8f127ec5835f | RedKnite5/Junk | /calculus.py | 1,964 | 3.8125 | 4 | # calculus.py
def make_int(i):
if i.is_integer():
return int(i)
else:
return i
class vector(object):
def __init__(self, i=0, j=0, k=0):
self.i = i
self.j = j
self.k = k
def __repr__(self):
return f"vector{self.i, self.j, self.k}"
def __str__(self):
return f"{self.i}i + {self.j}j + {self.k}k"
def __mul__(self, s):
if not isinstance(s, vector):
self.i *= s
self.j *= s
self.k *= s
return self
else:
raise ValueError("Can not scale vectors by other vectors")
def __rmul__(self, s):
if not isinstance(s, vector):
self.i *= s
self.j *= s
self.k *= s
return self
else:
raise TypeError("Can not scale vectors by other vectors")
def __truediv__(self, s):
if not isinstance(s, vector):
self.i = make_int(self.i / s)
self.j = make_int(self.j / s)
self.k = make_int(self.k / s)
else:
raise TypeError("Can not divide vectors")
def __add__(self, v):
if isinstance(v, vector):
return vector(self.i + v.i, self.j + v.j, self.k + v.k)
else:
raise TypeError(f"Can not add type: {type(v)} to vectors")
def __sub__(self, v):
if isinstance(v, vector):
return vector(self.i - v.i, self.j - v.j, self.k - v.k)
else:
raise TypeError(f"Can not subtract type: {type(v)} to vectors")
def magnitude(self):
return (self.i * self.i + self.j * self.j + self.k * self.k) ** .5
def unitize(self):
self /= self.magnitude()
def dot(self, v):
if isinstance(v, vector):
return self.i * v.i + self.j * v.j + self.k * v.k
else:
raise TypeError(f"Can no dot {type(v)}")
def cross(self, v):
if isinstance(v, vector):
return vector(
self.j * v.k - self.k * v.j,
self.k * v.i - self.i * v.k,
self.i * v.j - self.j * v.i)
else:
raise TypeError(f"Can no cross {type(v)}")
v = vector(1, 0, 0)
u = vector(0, 1, 0)
print(u.cross(v))
|
3d4f7563471852e9ed616b8728ed2e07f1ce6fbe | aakriti04/Spirograph | /main.py | 515 | 3.515625 | 4 | from turtle import Turtle, Screen
import random
tiny = Turtle()
screen = Screen()
screen.colormode(255)
tiny.speed("fastest")
def get_color():
red = random.randint(0, 255)
green = random.randint(0, 255)
blue = random.randint(0, 255)
return red, green, blue
def draw_spirograph(size_of_gap):
for i in range(int(360 / size_of_gap)):
tiny.pencolor(get_color())
tiny.circle(100)
tiny.setheading(tiny.heading() + size_of_gap)
draw_spirograph(10)
screen.exitonclick()
|
7244d3d09c25bf82950579505c3b33985413a0fc | datalin/sql | /sqlud.py | 397 | 3.84375 | 4 | import sqlite3
with sqlite3.connect("new.db") as connection:
cursor = connection.cursor()
cursor.execute("UPDATE population SET population = 9000000 WHERE city = 'New York City' ")
cursor.execute("DELETE FROM population WHERE city ='Boston' ")
print "\n NEW DATA: \n"
cursor.execute("SELECT * FROM population")
rows = cursor.fetchall()
for row in rows:
print row[0], row[1], row[2] |
86006d8fcf42dee17b4f7a9e0121cb30e547fe04 | Havfar/Tsinghua-ML | /code/decision-tree/decision_tree_our.py | 8,420 | 4.03125 | 4 | # For Python 2 / 3 compatability
from __future__ import print_function
from csv import reader
from math import sqrt
import pandas as pd
# Loading data
def load_csv(filename):
dataset = list()
with open(filename, 'r') as file:
csv_reader = reader(file)
for row in csv_reader:
if not row:
continue
dataset.append(row)
return dataset
# get training data
filename = 'train.csv'
test_filename = 'test.csv'
filename_dir = 'input/'
dataset = load_csv(filename_dir + filename)
testdata = load_csv(filename_dir + test_filename)
smaller_dataset = dataset[1:5000]
testdata = testdata
training_data = smaller_dataset
# Column labels.
# These are used only to print the tree.
header = dataset[0]
def unique_vals(rows, col):
"""Find the unique values for a column in a dataset."""
return set([row[col] for row in rows])
def class_counts(rows):
"""Counts the number of each type of example in a dataset."""
counts = {} # a dictionary of label -> count.
for row in rows:
# in our dataset format, the label is always the last column
label = row[-1]
if label not in counts:
counts[label] = 0
counts[label] += 1
return counts
def class_counts_mnist(rows):
counts = {}
for row in rows:
# First entry in row is label
label = row[0]
if label not in counts:
counts[label] = 0
counts[label] += 1
#print("==> Counts:", counts)
return counts
def is_numeric(value):
"""Test if a value is numeric."""
return isinstance(value, int) or isinstance(value, float)
class Question:
"""A Question is used to partition a dataset.
This class just records a 'column number' (e.g., 0 for Color) and a
'column value' (e.g., Green). The 'match' method is used to compare
the feature value in an example to the feature value stored in the
question. See the demo below.
"""
def __init__(self, column, value):
self.column = column
self.value = value
def match(self, example):
# Compare the feature value in an example to the
# feature value in this question.
val = example[self.column]
if is_numeric(val):
return val >= self.value
else:
return val == self.value
def __repr__(self):
# This is just a helper method to print
# the question in a readable format.
condition = "=="
if is_numeric(self.value):
condition = ">="
return "Is %s %s %s?" % (
header[self.column], condition, str(self.value))
def partition(rows, question):
true_rows, false_rows = [], []
for row in rows:
if question.match(row):
true_rows.append(row)
else:
false_rows.append(row)
return true_rows, false_rows
def gini(rows):
counts = class_counts_mnist(rows)
impurity = 1
for lbl in counts:
prob_of_lbl = counts[lbl] / float(len(rows))
impurity -= prob_of_lbl**2
return impurity
def info_gain(left, right, current_uncertainty):
"""Information Gain.
The uncertainty of the starting node, minus the weighted impurity of
two child nodes.
"""
p = float(len(left)) / (len(left) + len(right))
return current_uncertainty - p * gini(left) - (1 - p) * gini(right)
def find_best_split(rows):
best_gain = 0 # keep track of the best information gain
best_question = None # keep train of the feature / value that produced it
current_uncertainty = gini(rows)
n_features = len(rows[0]) - 1 # number of columns
print("n_features:", n_features)
for col in range(1,n_features): # for each feature
print("==> finding split for column:", col)
# for each iteration this is the set of all values of a specific column, eg, All pixels number 0
values = set([row[col] for row in rows]) # unique values in the column
#print("Values:", values)
for val in values: # for each value
# Create a question object for each val under a column, holding the val and the col number
#print("Creating question with col:", col, "value:", val)
question = Question(col, val)
# try splitting the dataset
true_rows, false_rows = partition(rows, question)
# Skip this split if it doesn't divide the
# dataset.
if len(true_rows) == 0 or len(false_rows) == 0:
continue
# Calculate the information gain from this split
gain = info_gain(true_rows, false_rows, current_uncertainty)
# You actually can use '>' instead of '>=' here
# but I wanted the tree to look a certain way for our
# toy dataset.
if gain >= best_gain:
best_gain, best_question = gain, question
return best_gain, best_question
class Leaf:
"""A Leaf node classifies data.
This holds a dictionary of class (e.g., "Apple") -> number of times
it appears in the rows from the training data that reach this leaf.
"""
def __init__(self, rows):
self.predictions = class_counts_mnist(rows)
class Decision_Node:
"""A Decision Node asks a question.
This holds a reference to the question, and to the two child nodes.
"""
def __init__(self,
question,
true_branch,
false_branch):
self.question = question
self.true_branch = true_branch
self.false_branch = false_branch
def build_tree(rows, treecounter):
print("Treecounter:", treecounter)
# Try partitioing the dataset on each of the unique attribute,
# calculate the information gain,
# and return the question that produces the highest gain.
gain, question = find_best_split(rows)
# Base case: no further info gain
# Since we can ask no further questions,
# we'll return a leaf.
if gain == 0:
return Leaf(rows)
# If we reach here, we have found a useful feature / value
# to partition on.
true_rows, false_rows = partition(rows, question)
# Recursively build the true branch.
true_branch = build_tree(true_rows, treecounter+1)
# Recursively build the false branch.
false_branch = build_tree(false_rows, treecounter+1)
# Return a Question node.
# This records the best feature / value to ask at this point,
# as well as the branches to follow
# dependingo on the answer.
return Decision_Node(question, true_branch, false_branch)
def print_tree(node, spacing=""):
# Base case: we've reached a leaf
if isinstance(node, Leaf):
print (spacing + "Predict", node.predictions)
return
# Print the question at this node
print (spacing + str(node.question))
# Call this function recursively on the true branch
print (spacing + '--> True:')
print_tree(node.true_branch, spacing + " ")
# Call this function recursively on the false branch
print (spacing + '--> False:')
print_tree(node.false_branch, spacing + " ")
def classify(row, node):
# Base case: we've reached a leaf
if isinstance(node, Leaf):
return node.predictions
# Decide whether to follow the true-branch or the false-branch.
# Compare the feature / value stored in the node,
# to the example we're considering.
if node.question.match(row):
return classify(row, node.true_branch)
else:
return classify(row, node.false_branch)
def leaf_pred(counts):
if len(counts.keys()) == 1:
for key in counts.keys():
return key
else:
return "error"
def print_leaf(counts):
"""A nicer way to print the predictions at a leaf."""
total = sum(counts.values()) * 1.0
probs = {}
for lbl in counts.keys():
probs[lbl] = str(int(counts[lbl] / total * 100)) + "%"
return probs
if __name__ == '__main__':
my_tree = build_tree(training_data, 0)
print_tree(my_tree)
predictions = []
for row in testdata[1:]:
predictions.append(leaf_pred(classify(row, my_tree)))
print(len(predictions))
len(testdata)
# Create submission file
df_sub = pd.DataFrame(list(range(1,len(testdata))))
df_sub.columns = ["ImageID"]
df_sub["Label"] = predictions
df_sub.to_csv("output/decision_tree.csv",index=False)
|
9a01cd1953741d28f9420ade66e1bc98d5228679 | invokerkael918/BinaryTree-Divide-ConquerTraverse | /Binary Tree Inorder Traversal.py | 1,291 | 3.875 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: A Tree
@return: Inorder in ArrayList which contains node values.
"""
def inorderTraversal(self, root):
# write your code here
if not root:
return []
stack = []
result = []
node = root
while node:
stack.append(node)
node = node.left
while stack:
currNode = stack.pop()
result.append(currNode.val)
if currNode.right:
currNode = currNode.right
while currNode:
stack.append(currNode)
currNode = currNode.left
return result
class Solution2:
"""
@param root: A Tree
@return: Inorder in ArrayList which contains node values.
"""
def inorderTraversal(self, root):
# write your code here
result = []
self.traverse(root, result)
return result
def traverse(self, root, result):
if not root:
return
self.traverse(root.left, result)
result.append(root.val)
self.traverse(root.right, result)
|
a78e54197d5ebfea796d1d7bc9529c7bceb76c50 | RockMiin/Deep_Learning | /chapter04/test.py | 1,322 | 3.515625 | 4 | import numpy as np
from dataset.mnist import load_mnist
from network import TwoLayerNet
(x_train, y_train), (x_test, y_test)= load_mnist(normalize=True, one_hot_label=True)
# 손실함수값을 담는 리스트
train_loss_list= []
train_acc_list= []
test_acc_list= []
# 하이퍼 파라미터
iters_num= 100 # 반복 횟수
train_size= x_train[0].size # 784
batch_size= 10
learning_rate= 0.1
iter_per_epoch= max(train_size/ batch_size, 1)
# 신경망
network= TwoLayerNet(input_size=784, hidden_size=50, output_size=10)
print("learning start")
for i in range(iters_num):
print('start')
# 미니 배치 값 추출
batch_mask= np.random.choice(train_size, batch_size)
x_batch= x_train[batch_mask]
y_batch= y_train[batch_mask]
grad= network.numerical_gradient(x_batch, y_batch)
for key in ('W1', 'b1', 'W2', 'b2'):
network.params[key] -=learning_rate*grad[key]
loss= network.loss(x_batch, y_batch)
print('epoch :', i, 'loss :', loss)
train_loss_list.append(loss)
if i% iter_per_epoch== 0:
train_acc= network.accuracy(x_train, y_train)
test_acc= network.accuracy(x_test, y_test)
train_acc_list.append(train_acc)
test_acc_list.append(test_acc)
print("train acc:", str(train_acc), "test acc:", str(test_acc))
print('end') |
d29faa39dec07a25caa6383e0ecbe35edebbb4c5 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/minimumDominoRotationsForEqualRow.py | 2,392 | 4.4375 | 4 | """
Minimum Domino Rotations For Equal Row
In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the i-th domino, so that A[i] and B[i] swap values.
Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same.
If it cannot be done, return -1.
Example 1:
Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2]
Output: 2
Explanation:
The first figure represents the dominoes as given by A and B: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
Example 2:
Input: A = [3,5,1,2,3], B = [3,6,3,3,4]
Output: -1
Explanation:
In this case, it is not possible to rotate the dominoes to make one row of values equal.
"""
"""
Greedy
Time: O(N) since here one iterates over the array
Space: O(1)
"""
class Solution:
def minDominoRotations(self, A: List[int], B: List[int]) -> int:
def check(x):
"""
Return min number of swaps
if one could make all elements in A or B equal to x.
Else return -1.
"""
# how many rotations should be done
# to have all elements in A equal to x
# and to have all elements in B equal to x
rotations_a = rotations_b = 0
for i in range(n):
# rotations coudn't be done
if A[i] != x and B[i] != x:
return -1
# A[i] != x and B[i] == x
elif A[i] != x:
rotations_a += 1
# A[i] == x and B[i] != x
elif B[i] != x:
rotations_b += 1
# min number of rotations to have all
# elements equal to x in A or B
return min(rotations_a, rotations_b)
n = len(A)
rotationsA = check(A[0]) # If one could make all elements in A or B equal to A[0]
rotationsB = check(B[0]) # If one could make all elements in A or B equal to B[0]
if rotationsA != -1 and rotationsB != -1:
return min(rotationsA, rotationsB)
elif rotationsA == -1:
return rotationsB
else:
return rotationsA
|
e7fe8ffa16f0c95d77d5949aa4b352a1646dfb3b | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/trappingRainWater.py | 1,647 | 4.03125 | 4 | """
Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
"""
"""
DP
Time and Space: O(N)
Find maximum height of bar from the left end upto an index i in the array left_max.
Find maximum height of bar from the right end upto an index i in the array right_max.
Iterate over the \text{height}height array and update ans:
Add min(max_left[i],max_right[i])−height[i] to ans
"""
class Solution:
def trap(self, height: List[int]) -> int:
arr = []
left, right = 0, 0
water = 0
for h in height:
left = max(left, h)
arr.append(left)
for idx, h in enumerate(reversed(height)):
right = max(right, h)
water += min(arr[len(height)-1-idx], right) - h
return water
class Solution:
def trap(self, height: List[int]) -> int:
res = 0
arrLeft = []
currLeft = 0
for i in range(1, len(height)):
currLeft = max(currLeft, height[i-1])
arrLeft.append(currLeft)
currRight = 0
for i in range(len(height)-2, -1, -1):
currRight = max(currRight, height[i+1])
res += max(min(arrLeft[i], currRight) - height[i], 0)
return res
|
9d8447d6a6385f032da37a4722b0c7dc2c11bc11 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/repeatingCharacters.py | 1,068 | 3.90625 | 4 | """
Twitch Words
You are given a word like hellloooo print all the repeating character index and the number of time it is has been repeated.
Example 1:
Input: "hellloooo"
Output: [[2, 3], [5, 4]]
Explanation: hellloooo has l and o as repeating characters so return index of l which is at 2
and the number of times it has been repeated is 3. Same goes for O.
Example 2:
Input: "leetcodeee"
Output: [[1, 2], [7, 3]]
Follow-up:
What if you need to print the repeated character as well?
Example 1:
Input: "hellloooo"
Output : [['l', 3], ['o', 4]]
Example 2:
Input: "leetcodeee"
Output: [['e', 5]]
"""
"""
Time: O(N)
Space: O(1)
"""
def repeatingCharacters(s):
res = []
index, count = -1, 1
for i in range(1, len(s)+1):
if len(s) == i or (count > 1 and s[i-1] != s[i]):
res.append([index, count])
index = -1
count = 1
elif s[i-1] == s[i]:
count += 1
if index < 0:
index = i-1
return res
if __name__ == '__main__':
assert repeatingCharacters('hellloooo') == [[2, 3], [5, 4]]
assert repeatingCharacters('leetcodeee') == [[1, 2], [7, 3]]
|
136566eb89b6ed018b35c1bb28b513ce5950a76b | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/wordBreakII.py | 2,812 | 4 | 4 | """
Word Break II
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:
Input:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
Output:
[
"cats and dog",
"cat sand dog"
]
Example 2:
Input:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
Output:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
Explanation: Note that you are allowed to reuse a dictionary word.
Example 3:
Input:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
Output:
[]
"""
"""
DFS
1.Every time, we check whether s starts with a word. If so, we check whether the substring s[len(word):] starts with a word, etc.
2.resultOfTheRest keeps calling until we hit the last word. If the last word is in the dict, we append it to res.
The last word is 'dog ==> 'res = [ "dog"]
3. This time, we skip "else," since we fulfill the condition " if len(word) == len(s)." We store it in memo: {'dog': ['dog']}
4.Then we return to "resultOfTheRest = self.helper(s[len(word):], wordDict, memo)"
s = "sanddog" because we start with "cat" (cat is the first word in the dict) and "cat" leads to "sand".
resultOfTheRest = ["dog"]
word = "sand"
item = "sand dog"
res = ["sand dog"]
memo ={'dog': ['dog'], "sanddog":["sand dog"] }
Why do we need memo?
We always recurse to the last word in the string and backtrack, so storing all possible combinations of the substring in the memo saves time for the next iteration of the whole string. For example, "catsanddog," if we don't store "dog," then we have to iterate through the dictionary. This is very DP.
Time: O(n^3) size of recursion is n^2 and we go through n results
Space: O(n^3)
"""
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
def dfs(s, wordDict, memo):
if s in memo:
return memo[s]
if not s:
return []
res = []
for word in wordDict:
if not s.startswith(word):
continue
if len(word) == len(s):
res.append(word)
else:
remains = dfs(s[len(word):], wordDict, memo)
for remain in remains:
remain = '{} {}'.format(word, remain)
res.append(remain)
memo[s] = res
return memo[s]
memo = dict()
return dfs(s, wordDict, memo)
|
f944d895524acc3acf080981610859f6e31c75c3 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/salaryAdjustment.py | 1,616 | 4.09375 | 4 | """
Give an array of salaries. The total salary has a budget. At the beginning, the total salary of employees is larger than the budget. It is required to find the number k, and reduce all the salaries larger than k to k, such that the total salary is exactly equal to the budget.
Example 1:
Input: salaries = [100, 300, 200, 400], budget = 800
Output: 250
Explanation: k should be 250, so the total salary after the reduction 100 + 250 + 200 + 250 is exactly equal to 800.
You can assume that solution always exists.
"""
def budgetize(sals, budget):
i = len(sals) - 1
count = 1 # counts how many high salaries we are converting to k
while i >= 0:
# sort salaries so you can cherrypick highest sals and start replacing them with k
sorted_sals = sorted(sals)
# find the sum of all the salaries except the highest one(s)
# as i decreases, this array will reduce in size i.e. we will exclude highest and second highest sal in
# next iteration, then highest , second highest and third highest in next and so on..
sum_of_sals_excluding_highest = sum(sorted_sals[:i])
# find k by substracting this sum from the budget..
k = (budget - sum_of_sals_excluding_highest)/count
if max(sorted_sals[:i]) > k: # this means there are still salries higher than k...
i -= 1 # reduce i to now convert the next highest salary..
count += 1 # increase by one since now another high salary will be converted to k..
else:
return k
if __name__ == '__main__':
assert budgetize([100,200,300,400], 800) == 250 |
870b254cc9b82fa75a0df58708004055f2473bba | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/allPossibleFullBinaryTrees.py | 2,125 | 3.859375 | 4 | """
All Possible Full Binary Trees
A full binary tree is a binary tree where each node has exactly 0 or 2 children.
Return a list of all possible full binary trees with N nodes. Each element of the answer is the root node of one possible tree.
Each node of each tree in the answer must have node.val = 0.
You may return the final list of trees in any order.
Example 1:
Input: 7
Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]
Explanation:
Note:
1 <= N <= 20
"""
Note:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
"""
Intuition and Algorithm
Let FBT(N) be the list of all possible full binary trees with NN nodes.
Every full binary tree TT with 3 or more nodes, has 2 children at its root. Each of those children left and right are themselves full binary trees.
Thus, for N≥3, we can formulate the recursion: FBT(N)= [All trees with left child from FBT(x) and right child from FBT(N−1−x), for all x].
Also, by a simple counting argument, there are no full binary trees with a positive, even number of nodes.
Finally, we should cache previous results of the function FBT so that we don't have to recalculate them in our recursion.
Time: O(2^N)
Space: O(2^N)
"""
class Solution:
def allPossibleFBT(self, N: int) -> List[TreeNode]:
memo = {0: [], 1: [TreeNode(0)]} # base cases
def generate(N):
if N not in memo:
ans = []
for x in range(N): # the left subtree size
y = N - 1 - x # the right subtree size
for left in generate(x):
for right in generate(y):
bns = TreeNode(0)
bns.left = left
bns.right = right
ans.append(bns)
memo[N] = ans
return memo[N]
generate(N)
return memo[N]
|
6ac38a5d92a978a72312502672b7af1d803df468 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/sequenceReconstruction.py | 2,202 | 3.953125 | 4 | """
Sequence Reconstruction
Check whether the original sequence org can be uniquely reconstructed from the sequences in seqs. The org sequence is a permutation of the integers from 1 to n, with 1 ≤ n ≤ 104. Reconstruction means building a shortest common supersequence of the sequences in seqs (i.e., a shortest sequence so that all sequences in seqs are subsequences of it). Determine whether there is only one sequence that can be reconstructed from seqs and it is the org sequence.
Example 1:
Input:
org: [1,2,3], seqs: [[1,2],[1,3]]
Output:
false
Explanation:
[1,2,3] is not the only one sequence that can be reconstructed, because [1,3,2] is also a valid sequence that can be reconstructed.
Example 2:
Input:
org: [1,2,3], seqs: [[1,2]]
Output:
false
Explanation:
The reconstructed sequence can only be [1,2].
Example 3:
Input:
org: [1,2,3], seqs: [[1,2],[1,3],[2,3]]
Output:
true
Explanation:
The sequences [1,2], [1,3], and [2,3] can uniquely reconstruct the original sequence [1,2,3].
Example 4:
Input:
org: [4,1,5,2,6,3], seqs: [[5,2,6,3],[4,1,5,2]]
Output:
true
"""
"""
BFS/Topoligical sort
There should only be 1 starting node each level
Reconstruct
Time: O(N) N = number of sequence
"""
class Solution:
def sequenceReconstruction(self, org: List[int], seqs: List[List[int]]) -> bool:
children = collections.defaultdict(set)
parents = collections.defaultdict(set)
nodes = set()
for s in seqs:
for i in range(len(s)):
nodes.add(s[i])
if i > 0:
parents[s[i]].add(s[i-1])
if i < len(s)-1:
children[s[i]].add(s[i+1])
stack = [n for n in nodes if len(parents[n]) == 0]
count = len(stack)
ans = []
while count == 1:
curr = stack.pop()
count -= 1
ans.append(curr)
nodes.remove(curr)
for child in children[curr]:
parents[child].remove(curr)
if len(parents[child]) == 0:
stack.append(child)
count += 1
return not nodes and ans == org
|
1b399e72edc812253cacad330840ed59cf0194c9 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/diameterOfBinaryTree.py | 1,290 | 4.3125 | 4 | """
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
"""
Time Complexity: O(N). We visit every node once.
Space Complexity: O(N), the size of our implicit call stack during our depth-first search.
"""
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if not root:
return 0
self.res = 0
self.depth(root)
return self.res-1 # -1 because length is defined as the number of edges
def depth(self, node):
if not node:
return 0
left = self.depth(node.left)
right = self.depth(node.right)
self.res = max(self.res, left+right+1)
return max(left, right) + 1
|
c46566508ff155387fd425d0150ec3b83306fbb6 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/largestValuesFromLabels.py | 1,796 | 3.78125 | 4 | """
Largest Values From Labels
We have a set of items: the i-th item has value values[i] and label labels[i].
Then, we choose a subset S of these items, such that:
|S| <= num_wanted
For every label L, the number of items in S with label L is <= use_limit.
Return the largest possible sum of the subset S.
Example 1:
Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1
Output: 9
Explanation: The subset chosen is the first, third, and fifth item.
Example 2:
Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2
Output: 12
Explanation: The subset chosen is the first, second, and third item.
Example 3:
Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1
Output: 16
Explanation: The subset chosen is the first and fourth item.
Example 4:
Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2
Output: 24
Explanation: The subset chosen is the first, second, and fourth item.
Note:
1 <= values.length == labels.length <= 20000
0 <= values[i], labels[i] <= 20000
1 <= num_wanted, use_limit <= values.length
"""
"""
Heapq
Time: O(nlog(n))
Space: O(n)
"""
class Solution:
def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int:
rating = []
for label, value in zip(labels, values):
rating.append((-value, label))
res = 0
count = 0
heapq.heapify(rating)
used = dict()
while count < num_wanted and rating:
value, label = heapq.heappop(rating)
used[label] = used.get(label, 0) + 1
if used[label] > use_limit:
continue
count += 1
res += -value
return res
|
19b5899f53bd94583c8b4208db2c5b3982020b55 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/greatestCommonDivisorOfStrings.py | 1,331 | 3.984375 | 4 | """
Greatest Common Divisor of Strings
For strings S and T, we say "T divides S" if and only if S = T + ... + T (T concatenated with itself 1 or more times)
Return the largest string X such that X divides str1 and X divides str2.
Example 1:
Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
Example 2:
Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
Example 3:
Input: str1 = "LEET", str2 = "CODE"
Output: ""
Note:
1 <= str1.length <= 1000
1 <= str2.length <= 1000
str1[i] and str2[i] are English uppercase letters.
"""
"""
Time & space: O(n ^ 2)
due to slicing
If longer string starts with shorter string, cut off the common prefix part of the longer string; repeat till one is empty, then the other is gcd string;
If the longer string does NOT start with the shorter one, there is no gcd string.
can reduce to O(n1 + n2)
"""
class Solution(object):
def gcdOfStrings(self, str1, str2):
"""
:type str1: str
:type str2: str
:rtype: str
"""
if len(str1) == len(str2):
return str1 if str1 == str2 else ''
else:
if len(str1) < len(str2):
str1, str2 = str2, str1
if str1[:len(str2)] == str2:
return self.gcdOfStrings(str1[len(str2):], str2)
else:
return ''
|
f490e6054c9d90343cab89c810ca2c649d8138fe | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/mergeIntervals.py | 1,167 | 4.125 | 4 | """
Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
"""
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
"""
Time: O(nlogn)
Space: O(n)
"""
class Solution:
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
start, end, result = [], [], []
for interval in intervals:
st, en = interval.start, interval.end
start.append(st)
end.append(en)
start.sort()
end.sort()
i = 0
while i < len(intervals):
st = start[i]
while i < len(intervals) - 1 and start[i + 1] <= end[i]:
i += 1
en = end[i]
result.append([st, en])
i += 1
return result
|
b7a8bfe774a497d709c6198f3b895d71793aa724 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/palindromeNumber.py | 3,458 | 3.875 | 4 | """
Palindrome Number
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
"""
"""
Approach 1: Revert half of the number
Intuition
The first idea that comes to mind is to convert the number into string, and check if the string is a palindrome, but this would require extra non-constant space for creating the string which is not allowed by the problem description.
Second idea would be reverting the number itself, and then compare the number with original number, if they are the same, then the number is a palindrome. However, if the reversed number is larger than int.MAX, we will hit integer overflow problem.
Following the thoughts based on the second idea, to avoid the overflow issue of the reverted number, what if we only revert half of the int number? After all, the reverse of the last half of the palindrome should be the same as the first half of the number, if the number is a palindrome.
For example, if the input is 1221, if we can revert the last part of the number "1221" from "21" to "12", and compare it with the first half of the number "12", since 12 is the same as 12, we know that the number is a palindrome.
Let's see how we could translate this idea into an algorithm.
Algorithm
First of all we should take care of some edge cases. All negative numbers are not palindrome, for example: -123 is not a palindrome since the '-' does not equal to '3'. So we can return false for all negative numbers.
Now let's think about how to revert the last half of the number. For number 1221, if we do 1221 % 10, we get the last digit 1, to get the second to the last digit, we need to remove the last digit from 1221, we could do so by dividing it by 10, 1221 / 10 = 122. Then we can get the last digit again by doing a modulus by 10, 122 % 10 = 2, and if we multiply the last digit by 10 and add the second last digit, 1 * 10 + 2 = 12, it gives us the reverted number we want. Continuing this process would give us the reverted number with more digits.
Now the question is, how do we know that we've reached the half of the number?
Since we divided the number by 10, and multiplied the reversed number by 10, when the original number is less than the reversed number, it means we've processed half of the number digits.
"""
"""
Time: O(log_10(N)) as we are dividing the input by 10 every iteration
Space: O(1)
"""
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0 or (x%10 == 0 and x != 0): # if the last digit is 0 and x is not 0, it is also an edge case
return False
revertedNumber = 0
while x > revertedNumber:
revertedNumber = revertedNumber*10 + x%10
x //= 10
print(x, revertedNumber)
return x == revertedNumber or x == revertedNumber//10
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
x = str(x)
left, right = 0, len(x)-1
while left < right:
if x[left] != x[right]:
return False
left+=1
right-=1
return True
|
5d2924c98c659b1b8bfb2914f8927e7e5f0d504c | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/MaxSubarraySum.py | 341 | 3.5 | 4 | class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
curr_sum = max_sum = nums[0]
for n in nums[1:]:
curr_sum = max(curr_sum + n, n)
max_sum = max(max_sum, curr_sum)
return max_sum |
5199c8a527f6cd7843f617dbe28c46ab0b6aa697 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/encodeAndDecodeTinyURL.py | 3,302 | 4.125 | 4 | """
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
Approach:
Random Numbers
Generate a random integer to be used as the code. In case the generated code happens to be already mapped to some previous \text{longURL}longURL, we generate a new random integer to be used as the code. The data is again stored in a HashMap to help in the decoding process.
**Performance Analysis**
The number of URLs that can be encoded is limited by the range of \text{int}int.
The average length of the codes generated is independent of the \text{longURL}longURL's length, since a random integer is used.
The length of the URL isn't necessarily shorter than the incoming \text{longURL}longURL. It is only dependent on the relative order in which the URLs are encoded.
Since a random number is used for coding, again, as in the previous case, the number of collisions could increase with the increasing number of input strings, leading to performance degradation.
Determining the encoded URL isn't possible in this scheme, since we make use of random numbers.
"""
import random
import string
"""
This code is not very scalable, but it works well within the scope of this problem ;). It generates a random 6 character string and checks if it exists in dict values. But once the dict becomes extremely large our while loop in encode will become very slow. This may be improved by dynamically increasing the string length returned by generate_shortUrl as it detects the number of values in our dict.
"""
class Codec:
def __init__(self):
# dict to store all longUrl to shortUrl mappings
self.long_to_short = dict()
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
# Test if mapping already exists
if longUrl in self.long_to_short.keys():
return self.long_to_short[longUrl]
# Generate random 6 character string for tinyUrl
def generate_shortUrl():
all_chars = string.ascii_letters + string.digits
shortUrl = "".join(random.choice(all_chars) for x in range(6))
return shortUrl
# Keep generating new shortUrl till it finds one that doesn't exist in our dict
shortUrl = generate_shortUrl()
while shortUrl in self.long_to_short.values():
shortUrl = generate_shortUrl()
# map
self.long_to_short[longUrl] = shortUrl
return shortUrl
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL.
:type shortUrl: str
:rtype: str
"""
# Simple mapping
for k, v in self.long_to_short.items():
if v == shortUrl:
return k
return None
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))
|
c408d4bc98627857f1b0a39810c517ff0b8259b9 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/nonOverlappingIntervals.py | 5,138 | 4.125 | 4 | """
Non-overlapping Intervals
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [[1,2],[1,2],[1,2]]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Example 3:
Input: [[1,2],[2,3]]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
Note:
You may assume the interval's end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.
"""
"""
The Greedy approach just discussed was based on choosing intervals greedily based on the starting points. But in this approach, we go for choosing points greedily based on the end points. For this, firstly we sort the given intervals based on the end points. Then, we traverse over the sorted intervals. While traversing, if there is no overlapping between the previous interval and the current interval, we need not remove any interval. But, if an overlap exists between the previous interval and the current interval, we always drop the current interval.
Case 1:
The two intervals currently considered are non-overlapping:
In this case, we need not remove any interval and for the next iteration the current interval becomes the previous interval.
Case 2:
The two intervals currently considered are overlapping and the starting point of the later interval falls before the starting point of the previous interval:
In this case, as shown in the figure below, it is obvious that the later interval completely subsumes the previous interval. Hence, it is advantageous to remove the later interval so that we can get more range available to accommodate future intervals. Thus, previous interval remains unchanged and the current interval is updated.
Case 3:
The two intervals currently considered are overlapping and the starting point of the later interval falls before the starting point of the previous interval:
In this case, the only opposition to remove the current interval arises because it seems that more intervals could be accommodated by removing the previous interval in the range marked by A. But that won't be possible as can be visualized with a case similar to Case 3a and 3b shown above. But, if we remove the current interval, we can save the range B to accommodate further intervals. Thus, previous interval remains unchanged and the current interval is updated.
To explain how it works, again we consider every possible arrangement of the intervals.
Time complexity : O(nlog(n)). Sorting takes O(nlog(n)) time.
Space complexity : O(1). No extra space is used.
"""
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
if len(intervals) == 0:
return 0
intervals.sort(key = lambda x: x[1])
end = intervals[0][1]
count = 1
for i in range(1, len(intervals)):
if intervals[i][0] >= end:
end = intervals[i][1]
count += 1
return len(intervals) - count
"""
Case 1:
The two intervals currently considered are non-overlapping:
In this case, we need not remove any interval and we can continue by simply assigning the prevprev pointer to the later interval and the count of intervals removed remains unchanged.
Case 2:
The two intervals currently considered are overlapping and the end point of the later interval falls before the end point of the previous interval:
In this case, we can simply take the later interval. The choice is obvious since choosing an interval of smaller width will lead to more available space labelled as AA and BB, in which more intervals can be accommodated. Hence, the prevprev pointer is updated to current interval and the count of intervals removed is incremented by 1.
Case 3:
The two intervals currently considered are overlapping and the end point of the later interval falls after the end point of the previous interval:
In this case, we can work in a greedy manner and directly remove the later interval.
"""
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
if len(intervals) == 0:
return 0
intervals.sort(key = lambda x: x[0])
end = intervals[0][1]
prev, count = 0, 0
for i in range(1, len(intervals)):
if intervals[prev][1] > intervals[i][0]: # if previous ends after current start
if intervals[prev][1] > intervals[i][1]: # if prevous ends after current end
prev = i # make the current one the new prev as prev is removed as it is a larger interval and removing it will allow more intervals to be fitted in
count += 1 # update count due to overlapping
else:
prev = i # update prev to current and count of intervals don't change
return count
|
66edbdf3dde7da846d5ca7217b0fa65ded787ade | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/powXN.py | 1,432 | 4.0625 | 4 | """
Implement pow(x, n), which calculates x raised to the power n (x^n).
"""
"""
Not allowed??
"""
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
return x**n
class Solution:
def myPow(self, x: float, n: int) -> float:
if n < 0:
x = 1/x
n = -n
ans = 1
for i in range(n):
ans *= x
return ans
"""
Fast Power Recursive
Time: O(log n), each time we apply the formulat, n is reduced by half.
Space: O(log n) storing log n number of result
if n is even, we can use the formula (x^n)^2 = x^(2n)
if n is odd, we can use A*A*x
"""
class Solution(object):
def myPow(self, x, n):
x = 1/x if n < 0 else x
n = -n if n < 0 else n
return self.fastPow(x, n)
def fastPow(self, x, n):
if n == 0:
return 1.0
half = self.fastPow(x, n/2)
if not n%2:
return half * half
return half*half*x
class Solution:
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n == 0:
return 1
elif n < 1:
return 1 / (self.myPow(x, -n))
if n % 2:
return x * self.myPow(x, n - 1)
else:
return self.myPow(x * x, n / 2)
|
eb9c67b2716252cfa33d63aa9a818fe25c332daa | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/minDepthBinaryTree.py | 1,813 | 4.03125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
queue = [(root, 1)]
while queue:
node, level = queue.pop(0)
if not node.left and not node.right:
return level
if node.left:
queue.append((node.left, level+1))
if node.right:
queue.append((node.right, level+1))
"""
Recursive
Time complexity : we visit each node exactly once, thus the time complexity is O(N), where NN is the number of nodes.
Space: O(N) if unbalanced tree
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
if not root.left and not root.right:
return 1
min_depth = float('inf')
for c in [root.left, root.right]:
if c:
min_depth = min(min_depth, self.minDepth(c))
return min_depth+1
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
if not root.left or not root.right:
return self.minDepth(root.left) + self.minDepth(root.right) + 1
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
|
d86c8afbca66bd1b0731b02fbb2c1bbf551c2615 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/reverseLinkedList.py | 2,118 | 4.21875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
new_head = None
while head:
head.next, head, new_head = new_head, head.next, head
return new_head
class Solution:
# @param {ListNode} head
# @return {ListNode}
def reverseList(self, head):
return self._reverse(head)
def _reverse(self, node, prev=None):
if not node:
return prev
n = node.next
node.next = prev
return self._reverse(n, node)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
"""
Iterative
Time: O(n)
Space: O(1)
"""
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
prev = None
curr = head
while curr is not None:
nextTemp = curr.next
curr.next = prev
prev = curr
curr = nextTemp
return prev
"""
Recursive
The recursive version is slightly trickier and the key is to work backwards. Assume that the rest of the list had already been reversed, now how do I reverse the front part? Let's assume the list is: n1 → … → nk-1 → nk → nk+1 → … → nm → Ø
Assume from node nk+1 to nm had been reversed and you are at node nk.
n1 → … → nk-1 → nk → nk+1 ← … ← nm
We want nk+1’s next node to point to nk.
So,
nk.next.next = nk;
Be very careful that n1's next must point to Ø. If you forget about this, your linked list has a cycle in it. This bug could be caught if you test your code with a linked list of size 2.
Time: O(n)
Space: O(n) due to stack space
"""
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
p = self.reverseList(head.next)
head.next.next = head
head.next = None
return p
|
111b0a0257a9e197a4d20f5c0576bfd6cf0d854a | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Dice Challenge/poker_dice.py | 7,402 | 3.84375 | 4 | '''
A program that simulates the poker dice game. http://en.wikipedia.org/wiki/Poker_dice
Functions:
play(): randomly gives a hand and the dice can be kept by either inputting all or ALL or any current card. Nothing is kept otherwise.
Simulate(): Shows the probability of each type of hand given the number of times played.
Written by Benny Hwang 17/08/2017
'''
from random import randint
def roll_dice(dices):
dice_list = sorted(dices)
dice_dict = {0:'Ace',1:'King',2:'Queen',3:'Jack',4:'10',5:'9'}
roll = []
for d in dice_list:
roll.append(dice_dict[d])
print("The roll is: " + str(roll[0]) + " " + str(roll[1]) + " " + str(roll[2]) + " " + str(roll[3]) + " "+ str(roll[4]))
repeated = []
num = []
for i in dice_list:
if i not in repeated:
num.append(dice_list.count(i))
repeated.append(i)
single = False
pairs = False
tri = False
quad = False
penta = False
ones = []
double = []
triple = []
quadriple = []
pentagon = []
for i in num:
if i == 1:
single = True
ones.append(i)
if i == 2:
pairs = True
double.append(i)
if i == 3:
tri = True
triple.append(i)
if i == 4:
quad = True
quadriple.append(i)
if i == 5:
penta = True
pentagon.append(i)
if single:
if len(ones) == 5:
if dice_list == list(range(min(dice_list),max(dice_list)+1)):
print("It is a Straight")
else:
print("It is a Bust")
if pairs:
if len(double) == 1 and tri == False:
print("It is a One pair")
if len(double) == 2:
print("It is a Two pair")
if tri:
if pairs == False:
print("It is a Three of a kind")
if pairs == True:
print("It is a Full house")
if penta:
print("It is a Five of a kind")
if quad:
print("It is a Four of a kind")
return roll
def roll_dice2(dices):
dice_list = sorted(dices)
dice_dict = {0:'Ace',1:'King',2:'Queen',3:'Jack',4:'10',5:'9'}
roll = []
for d in dice_list:
roll.append(dice_dict[d])
repeated = []
num = []
for i in dice_list:
if i not in repeated:
num.append(dice_list.count(i))
repeated.append(i)
single = False
pairs = False
tri = False
quad = False
penta = False
FiveOfaKind = 0
FourOfaKind = 0
FullHouse = 0
Straight = 0
ThreeOfaKind = 0
Two_pair = 0
One_pair = 0
Bust = 0
ones = []
double = []
triple = []
quadriple = []
pentagon = []
for i in num:
if i == 1:
single = True
ones.append(i)
if i == 2:
pairs = True
double.append(i)
if i == 3:
tri = True
triple.append(i)
if i == 4:
quad = True
quadriple.append(i)
if i == 5:
penta = True
pentagon.append(i)
if single:
if len(ones) == 5:
if dice_list == list(range(min(dice_list),max(dice_list)+1)):
Straight += 1
else:
Bust += 1
if pairs:
if len(double) == 1 and tri == False:
One_pair += 1
if len(double) == 2:
Two_pair += 1
if tri:
if pairs == False:
ThreeOfaKind += 1
if pairs == True:
FullHouse += 1
if penta:
FiveOfaKind += 1
if quad:
FourOfaKind += 1
return tuple([roll,FiveOfaKind,FourOfaKind,FullHouse,Straight,ThreeOfaKind,Two_pair,One_pair,Bust])
def play():
get_out = False
rN = 2
dice1 = randint(0,5)
dice2 = randint(0,5)
dice3 = randint(0,5)
dice4 = randint(0,5)
dice5 = randint(0,5)
dices = [dice1,dice2,dice3,dice4,dice5]
while get_out == False:
roll = roll_dice(dices)
num_dict = {2:'second', 3:'third'}
if rN >3:
break
roll_num = num_dict[rN]
rN += 1
roll_copy = roll.copy()
#print(roll_copy)
To_use = []
valid = False
while valid == False:
user_input = input('Which dice do you want to keep for the ' +str(roll_num) + ' roll? ')
if user_input == 'all' or user_input == 'All':
print('Ok, done.')
get_out = True
break
else:
in_list = user_input.split(' ')
#print(in_list)
valid = True
for i in in_list:
#print(i)
if i != '' and i not in roll_copy:
if valid == True:
print('That is not possible, try again!')
valid = False
roll_copy = roll.copy()
To_use = []
elif i in roll_copy:
roll_copy.remove(i)
#print(roll_copy)
To_use.append(i)
#print(To_use)
if len(To_use) == 5:
print('Ok, done.')
get_out = True
break
if get_out == False:
reverse_dice_dict = {'Ace':0,'King':1,'Queen':2,'Jack':3,'10':4,'9':5}
hold_dice = []
for i in To_use:
dice_num = reverse_dice_dict[i]
hold_dice.append(dice_num)
while len(hold_dice)<5:
hold_dice.append(randint(0,5))
dices = hold_dice
return
def simulate(n):
reverse_dice_dict = {'Ace':0,'King':1,'Queen':2,'Jack':3,'10':4,'9':5}
FiveOfaKind = 0
FourOfaKind = 0
FullHouse = 0
Straight = 0
ThreeOfaKind = 0
Two_pair = 0
One_pair = 0
Bust = 0
x = 1
while x <= n:
dice1 = randint(0,5)
dice2 = randint(0,5)
dice3 = randint(0,5)
dice4 = randint(0,5)
dice5 = randint(0,5)
dices = [dice1,dice2,dice3,dice4,dice5]
result = roll_dice2(dices)
FiveOfaKind = FiveOfaKind + result[1]
FourOfaKind = FourOfaKind + result[2]
FullHouse = FullHouse + result[3]
Straight = Straight + result[4]
ThreeOfaKind = ThreeOfaKind + result[5]
Two_pair = Two_pair + result[6]
One_pair = One_pair + result[7]
Bust = Bust + result[8]
x+=1
Total = FiveOfaKind+FourOfaKind+FullHouse+Straight+ThreeOfaKind+Two_pair+One_pair+Bust
print('Five of a kind : ' + str('%.2f' % (100*FiveOfaKind/Total))+'%')
print('Four of a kind : ' + str('%.2f' % (100*FourOfaKind/Total))+'%')
print('Full house : ' + str('%.2f' % (100*FullHouse/Total))+'%')
print('Straight : ' + str('%.2f' % (100*Straight/Total))+'%')
print('Three of a kind: ' + str('%.2f' % (100*ThreeOfaKind/Total))+'%')
print('Two pair : ' + str('%.2f' % (100*Two_pair/Total))+'%')
print('One pair : ' + str('%.2f' % (100*One_pair/Total))+'%')
return
|
2b6b64ed41e1ed99a4e8a12e1e6ab53e6a9596ef | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/shortestWayToFormString.py | 7,619 | 3.78125 | 4 | """
Shortest Way to Form String
From any string, we can form a subsequence of that string by deleting some number of characters (possibly no deletions).
Given two strings source and target, return the minimum number of subsequences of source such that their concatenation equals target. If the task is impossible, return -1.
"""
"""
Binary Search
Create mapping from each source char to the indices in source of that char.
Iterate over target, searching for the next index in source of each char. Return -1 if not found.
Search is by binary search of the list of indices in source of char.
If the next index in source requires wrapping around to the start of source, increment result count.
Time: O(n log m) for source of length m and target of length n.
Space: O(m)
The idea is to create an inverted index that saves the offsets of where each character occurs in source. The index data structure is represented as a hashmap, where the Key is the character, and the Value is the (sorted) list of offsets where this character appears. To run the algorithm, for each character in target, use the index to get the list of possible offsets for this character. Then search this list for next offset which appears after the offset of the previous character. We can use binary search to efficiently search for the next offset in our index.
Example with source = "abcab", target = "aabbaac"
The inverted index data structure for this example would be:
inverted_index = {
a: [0, 3] # 'a' appears at index 0, 3 in source
b: [1, 4], # 'b' appears at index 1, 4 in source
c: [2], # 'c' appears at index 2 in source
}
Initialize i = -1 (i represents the smallest valid next offset) and loop_cnt = 1 (number of passes through source).
Iterate through the target string "aabbaac"
a => get the offsets of character 'a' which is [0, 3]. Set i to 1.
a => get the offsets of character 'a' which is [0, 3]. Set i to 4.
b => get the offsets of character 'b' which is [1, 4]. Set i to 5.
b => get the offsets of character 'b' which is [1, 4]. Increment loop_cnt to 2, and Set i to 2.
a => get the offsets of character 'a' which is [0, 3]. Set i to 4.
a => get the offsets of character 'a' which is [0, 3]. Increment loop_cnt to 3, and Set i to 1.
c => get the offsets of character 'c' which is [2]. Set i to 3.
We're done iterating through target so return the number of loops (3).
The runtime is O(M) to build the index, and O(logM) for each query. There are N queries, so the total runtime is O(M + N*logM). M is the length of source and N is the length of target. The space complexity is O(M), which is the space needed to store the index.
"""
class Solution:
def shortestWay(self, source: str, target: str) -> int:
index = collections.defaultdict(list)
for i, s in enumerate(source):
index[s].append(i)
res = 0
i = 0 # next index of source to check
for t in target:
if t not in index:
return -1 # cannot make target if char not in source
indices = index[t]
j = bisect.bisect_left(indices, i)
if j == len(indices): # index in char_indices[c] that is >= i
res += 1 # wrap around to beginning of source
j = 0
i = indices[j] + 1 # next index in source
return res if i == 0 else res + 1 # add 1 for partial source
def shortestWay(self, source: str, target: str) -> int:
inverted_index = collections.defaultdict(list)
for i, ch in enumerate(source):
inverted_index[ch].append(i)
loop_cnt = 1
i = -1
for ch in target:
if ch not in inverted_index:
return -1
offset_list_for_ch = inverted_index[ch]
# bisect_left(A, x) returns the smallest index j s.t. A[j] >= x. If no such index j exists, it returns len(A).
j = bisect.bisect_left(offset_list_for_ch, i)
if j == len(offset_list_for_ch):
loop_cnt += 1
i = offset_list_for_ch[0] + 1
else:
i = offset_list_for_ch[j] + 1
return loop_cnt
"""
DP
The main idea behind this code is also to build up an inverted index data structure for the source string and then to greedily use characters from source to build up the target. In this code, it's the dict array. Each character is mapped to an index where it is found at in source. In this code, dict[i][c - 'a'] represents the earliest index >= i where character c occurs in source.
For example, if source = "xyzy", then dict[0]['y' - 'a'] = 1 but dict[2]['y'-'a'] = 3.
Also a value of -1, means that there are no occurrences of character c after the index i.
So, after this inverted data structure is built (which took O(|Σ|*M) time). We iterate through the characters of our target String. The idxOfS represents the current index we are at in source.
For each character c in target, we look for the earliest occurrence of c in source using dict via dict[idxOfS][c - 'a']. If this is -1, then we have not found any other occurrences and hence we need to use a new subsequence of S.
Otherwise, we update idxOfS to be dict[idxOfS][c - 'a'] + 1 since we can only choose characters of source that occur after this character if we wish to use the same current subsequence to build the target.
dict[idxOfS][c-'a'] = N - 1 is used as a marker value to represent that we have finished consuming the entire source and hence need to use a new subsequence to continue.
(I would highly recommend reading @Twohu's examples of how to use the inverted index data structure to greedily build target using the indexes. They go into much more detail).
At the end, the check for (idxOfS == 0? 0 : 1) represents whether or not we were in the middle of matching another subsequence. If we were in the middle of matching it, then we would need an extra subsequence count of 1 since it was never accounted for.
"""
class Solution:
def shortestWay(self, source: str, target: str) -> int:
if len(set(target) - set(source)) > 0:
return -1
m = len(source)
move = [[-1]*26 for _ in range(m)]
move[0] = [source.find(chr(c)) + 1 for c in range(ord('a'), ord('a') + 26)]
for i in range(-1, -m, -1):
move[i] = list(map(lambda x: x+1, move[i+1]))
move[i][ord(source[i]) - 97] = 1
i = 0
for c in target:
i += move[i%m][ord(c)-ord('a')]
return i//m + (i%m > 0)
"""
Greedy
Time: O(MN)
"""
class Solution(object):
def shortestWay(self, source, target):
def match(st):#match source from st index of target
idx=0#idx of source
while idx<len(source) and st<n:
if source[idx]==target[st]:
st+=1
idx+=1
else:
idx+=1
return st
n=len(target)
source_set=set(source)
for ch in target:
if ch not in source_set:
return -1
#match one by one,match string until cannot match anymore.
st=0
count=0
while st<n:
st=match(st)
count+=1
return count
class Solution:
def shortestWay(self, source: str, target: str) -> int:
def inc():
self.cnt += 1
return 0
self.cnt = i = 0
for t in target:
i = source.find(t, i) + 1 or source.find(t, inc()) + 1
if not i:
return -1
return self.cnt + 1
|
c6858af5e5805807fd78b699f4f819cf5cd97e04 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/nextPremutation.py | 2,120 | 3.984375 | 4 | """
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
"""
"""
Time: O(n), worse case two scan of the array, but sort is nlog(n), better apprace is to use swap at the end since we already know it is in ascending order when we scan from right to left.
Space: O(1)
"""
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i = len(nums)-2
# find the first decreasing element
while i >= 0 and nums[i+1] <= nums[i]:
i -= 1
# while scaning from right to left, we know it is in increasing order
# so we swap the number just larger than the decreasing element with the decreasing
# element, then reverse the order of everything from the decreasing element
if i>= 0:
j = len(nums)-1
while j >= 0 and nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
# place those number in ascending order
nums[i+1:] = sorted(nums[i+1:])
class Solution:
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if not nums or len(nums) == 1:
return
pointer = len(nums)-2
while pointer >= 0:
if nums[pointer] < nums[pointer+1]:
break
pointer -= 1
if pointer < 0:
nums.sort()
return
pointer2 = pointer + 1
while pointer2 < len(nums) and nums[pointer] < nums[pointer2]:
pointer2 += 1
nums[pointer2-1], nums[pointer] = nums[pointer], nums[pointer2-1]
nums[pointer+1:] = sorted(nums[pointer+1:])
|
43bd43a6f6c2a296ed72646400a862eea2307131 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/stringCombinations.py | 623 | 3.9375 | 4 | """
Given a string s consisting of 0, 1 and ?. The question mark can be either 0 or 1. Find all possible combinations for the string.
Example 1:
Input: s = "001?"
Output: ["0010", "0011"]
"""
def get_string_combinations(s):
res = []
def get_strings(s, res, idx):
if idx == len(s):
res.append(s)
return
if idx < len(s) and s[idx] == '?':
get_strings(s[:idx] + '0' + s[idx+1:], res, idx+1)
get_strings(s[:idx] + '1' + s[idx+1:], res, idx+1)
else:
get_strings(s, res, idx+1)
get_strings(s, res, 0)
return res
if __name__ == '__main__':
assert get_string_combinations('001?') == ["0010", "0011"] |
99e25be34833e876da74bb6f53a62edf745be9a5 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/sortedSquares.py | 2,053 | 4.25 | 4 | """
Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Example 2:
Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Note:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A is sorted in non-decreasing order.
"""
"""
Time Complexity: O(N log N), where N is the length of A.
Space Complexity: O(N).
"""
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
return sorted(x*x for x in A)
"""
Approach 2: Two Pointer
Intuition
Since the array A is sorted, loosely speaking it has some negative elements with squares in decreasing order, then some non-negative elements with squares in increasing order.
For example, with [-3, -2, -1, 4, 5, 6], we have the negative part [-3, -2, -1] with squares [9, 4, 1], and the positive part [4, 5, 6] with squares [16, 25, 36]. Our strategy is to iterate over the negative part in reverse, and the positive part in the forward direction.
Algorithm
We can use two pointers to read the positive and negative parts of the array - one pointer j in the positive direction, and another i in the negative direction.
Now that we are reading two increasing arrays (the squares of the elements), we can merge these arrays together using a two-pointer technique.
Time Complexity: O(N), where N is the length of A.
Space Complexity: O(N).
"""
class Solution(object):
def sortedSquares(self, A):
N = len(A)
# i, j: negative, positive parts
j = 0
while j < N and A[j] < 0:
j += 1
i = j - 1
ans = []
while 0 <= i and j < N:
if A[i]**2 < A[j]**2:
ans.append(A[i]**2)
i -= 1
else:
ans.append(A[j]**2)
j += 1
while i >= 0:
ans.append(A[i]**2)
i -= 1
while j < N:
ans.append(A[j]**2)
j += 1
return ans
|
323ec56c71b0abfb505751145e4eb236d68b5881 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/zigzagLevelOrderTraversal.py | 1,252 | 3.859375 | 4 | """
Binary Tree Zigzag Level Order Traversal
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
"""
Time: O(N)
Space: O(N) where N are number of nodes
"""
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
result = []
if not root:
return result
queue = collections.deque([(root, 1)])
levels = collections.defaultdict(list)
# odd number level is left to right and even number is right to left
while queue:
node, level = queue.popleft()
levels[level].append(node.val)
if node.left:
queue.append((node.left, level+1))
if node.right:
queue.append((node.right, level+1))
for lv in sorted(levels.keys()):
if lv%2:
result.append(levels[lv])
else:
result.append(levels[lv][::-1])
return result
|
29a9492d7b810fdf13731fe2679265b616095d7d | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/shortestPathInBinaryMatrix.py | 1,670 | 4.0625 | 4 | """
Shortest Path In Binary Matrix
n an N by N square grid, each cell is either empty (0) or blocked (1).
A clear path from top-left to bottom-right has length k if and only if it is composed of cells C_1, C_2, ..., C_k such that:
Adjacent cells C_i and C_{i+1} are connected 8-directionally (ie., they are different and share an edge or corner)
C_1 is at location (0, 0) (ie. has value grid[0][0])
C_k is at location (N-1, N-1) (ie. has value grid[N-1][N-1])
If C_i is located at (r, c), then grid[r][c] is empty (ie. grid[r][c] == 0).
Return the length of the shortest such clear path from top-left to bottom-right. If such a path does not exist, return -1.
Example 1:
Input: [[0,1],[1,0]]
Output: 2
Example 2:
Input: [[0,0,0],[1,1,0],[1,1,0]]
Output: 4
Note:
1 <= grid.length == grid[0].length <= 100
grid[r][c] is 0 or 1
"""
"""
BFS
Time: O(N)
Space: O(N)
"""
class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
directions = [(1, 1), (1, 0), (-1, 0), (-1, 1), (-1, -1), (0, 1), (0, -1), (1, -1)]
if not len(grid) or not len(grid[0]):
return 0
if grid[0][0] == 1:
return -1
n = len(grid)
queue = collections.deque([(0, 0, 1)])
visited = set()
while queue:
i, j, d = queue.popleft()
if i == n - 1 and j == n - 1:
return d
for di, dj in directions:
ni, nj = i + di, j + dj
if 0 <= ni < n and 0 <= nj < n and grid[ni][nj] == 0:
grid[ni][nj] = 1
queue.append((ni, nj, d+1))
return -1
|
949196289694e00c9ca8e7381786a1cd91cdaf7c | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/nextGreaterElementII.py | 2,687 | 3.84375 | 4 | """
Next Greater Element II
Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number.
Example 1:
Input: [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number;
The second 1's next greater number needs to search circularly, which is also 2.
Note: The length of given array won't exceed 10000.
"""
"""
Stack
Time and Space: O(N)
This approach makes use of a stack. This stack stores the indices of the appropriate elements from numsnums array. The top of the stack refers to the index of the Next Greater Element found so far. We store the indices instead of the elements since there could be duplicates in the nums array. The description of the method will make the above statement clearer.
We start traversing the numsnums array from right towards the left. For an element nums[i] encountered, we pop all the elements stack[top] from the stack such that stack[top] ≤ nums[i]. We continue the popping till we encounter a stack[top] satisfying stack[top] > nums[i]nums[stack[top]]>nums[i]. Now, it is obvious that the current stack[top] only can act as the Next Greater Element for nums[i](right now, considering only the elements lying to the right of nums[i]).
If no element remains on the top of the stack, it means no larger element than nums[i] exists to its right. Along with this, we also push the index of the element just encountered(nums[i]), i.e. ii over the top of the stack, so that nums[i](or stack[top]) now acts as the Next Greater Element for the elements lying to its left.
We go through two such passes over the complete nums array. This is done so as to complete a circular traversal over the numsnums array. The first pass could make some wrong entries in the resres array since it considers only the elements lying to the right of nums[i], without a circular traversal. But, these entries are corrected in the second pass.
"""
class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
res = [-1 for _ in range(len(nums))]
stack = []
for i in range(2*len(nums)-1, -1, -1):
while stack and nums[stack[-1]] <= nums[i%len(nums)]:
stack.pop()
res[i%len(nums)] = -1 if not stack else nums[stack[-1]]
stack.append(i%len(nums))
return res
|
35f9c64ca063b6ba46c8145462fb67afc6a32076 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/numberOfSubsets.py | 878 | 3.5 | 4 | """
For a given list of integers and integer K, find the number of non-empty subsets S such that min(S) + max(S) <= K.
Example 1:
nums = [2, 4, 5, 7]
k = 8
Output: 5
Explanation: [2], [4], [2, 4], [2, 4, 5], [2, 5]
Example 2:
nums = [1, 4, 3, 2]
k = 8
Output: 15
Explanation: 16 (2^4) - 1 (empty set) = 15
Example 3:
nums = [2, 4, 2, 5, 7]
k = 10
Output: 27
Explanation: 31 (2^5 - 1) - 4 ([7], [5, 7], [4, 5, 7], [4, 7]) = 27
Expected O(n^2) time solution or better.
"""
# Sliding Window O(nlog(n))
def countSubsets(nums, k):
nums.sort()
count = 0
low, high = 0, len(nums)-1
while low <= high:
if nums[low] + nums[high] > k:
high -= 1
else:
count += 2 ** (high - low)
low += 1
return count
if __name__ == '__main__':
assert countSubsets([2, 4, 5, 7], 8) == 5
assert countSubsets([1, 4, 3, 2], 8) == 15
assert countSubsets([2, 4, 2, 5, 7], 10) ==27
|
e932cecd4084f2d7cef0faa06e792dab7ef590ad | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/binaryTreeLongestConsecutiveSequence.py | 2,493 | 3.953125 | 4 | """
Binary Tree Longest Consecutive Sequence
Given a binary tree, find the length of the longest consecutive sequence path.
The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
"""
Top Down DFS
Time: O(n) traverse n nodes
Space: O(n) recursion stack space
"""
class Solution:
def longestConsecutive(self, root: TreeNode) -> int:
self.res = 0
def dfs(node, parent, length):
if not node:
return
length = length + 1 if parent.val + 1 == node.val else 1
self.res = max(self.res, length)
dfs(node.left, node, length)
dfs(node.right, node, length)
dfs(root, root, 0)
return self.res
class Solution:
def longestConsecutive(self, root: TreeNode) -> int:
self.res = 0
if not root:
return self.res
self.getPath(root, root.val, 1)
return self.res
def getPath(self, node, parentVal, length):
if not node:
self.res = max(self.res, length)
return
if node.val == parentVal + 1:
length += 1
self.res = max(self.res, length)
self.getPath(node.left, node.val, length)
self.getPath(node.right, node.val, length)
else:
self.getPath(node.left, node.val, 1)
self.getPath(node.right, node.val, 1)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def longestConsecutive(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
self.max_consec = 0
self.helper(root, self.max_consec, root.val + 1)
return self.max_consec
def helper(self, root, consec, target):
if not root:
return
if root.val == target:
consec += 1
else:
consec = 1
self.max_consec = max(self.max_consec, consec)
self.helper(root.right, consec, root.val + 1)
self.helper(root.left, consec, root.val + 1)
|
f325cecbb91df5d05bd766a8099a2ccd236759f8 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/twoSumSortedInput.py | 608 | 3.640625 | 4 | class Solution:
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
left, right = 0, len(numbers)-1
while left < right:
if numbers[left] + numbers[right] == target:
return [left+1, right+1]
elif numbers[left] + numbers[right] < target:
left += 1
else:
right -= 1
# alternative is to just do binary search but not faster because
# you do the search for each number potentially O(n log n)
|
33e938d5592965fa2c772c5c958ced297ee18955 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/flipEquivalentBinaryTree.py | 1,531 | 4.1875 | 4 | """
Flip Equivalent Binary Trees
For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees.
A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations.
Write a function that determines whether two binary trees are flip equivalent. The trees are given by root nodes root1 and root2.
"""
"""
There are 3 cases:
If root1 or root2 is null, then they are equivalent if and only if they are both null.
Else, if root1 and root2 have different values, they aren't equivalent.
Else, let's check whether the children of root1 are equivalent to the children of root2. There are two different ways to pair these children.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
"""
Time Complexity: O(min(N_1, N_2)) where N_1, N_2N are the lengths of root1 and root2.
Space Complexity: O(min(H_1, H_2)) are the heights of the trees of root1 and root2.
"""
class Solution:
def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:
if root1 is None and root2 is None:
return True
if not root1 or not root2 or root1.val != root2.val:
return False
return (self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.right, root2.right)) or (self.flipEquiv(root1.left, root2.right) and self.flipEquiv(root1.right, root2.left))
|
31c90567097d5ecabe0986d29a642950b5487b85 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/ArrayIndexAndElementEquality.py | 469 | 3.875 | 4 | def index_equals_value_search(arr):
'''
for i in range(len(arr)):
if i == arr[i]:
return i
return -1
'''
if len(arr) == 1:
if arr[0] == 0:
return 0
start, end = 0, len(arr) - 1
while start <= end:
mid = (start + end) // 2
if mid == arr[mid]:
return mid
elif arr[mid] > mid:
end = mid - 1
elif arr[mid] < mid:
start = mid + 1
return -1 |
8da53bbfcfdf16380d8b4c2620a6509ae8ff6ad6 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/maximumProductSubarray.py | 1,399 | 4.0625 | 4 | """
Maximum Product Subarray
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
"""
"""
O(N)
Let max or min result from A[0] to A[k] be MAX[k] or MIN[k]
The max result from A[0] to A[i] can only come from:
Decision 1. discard previous result, restart at A[i]
Decision 2. take A[i], MAX[i] = MAX[i-1] * A[i]
Decision 3. this is the most tricky part: A[i] can be negative, then MAX[i-1] * A[i] is negative (suppose MAX[i-1] is positive). Or a more complicated case: MIN[i-1] and MAX[i-1] are both negative, and A[i] is negative too, so that we need to take MIN[i-1] * A[i] into consideration.
Same thing to min result from A[0] to A[i].
"""
class Solution:
def maxProduct(self, nums: List[int]) -> int:
r = nums[0]
Max = [r]
Min = [r]
for i, num in enumerate(nums[1:]):
if num >= 0:
Max.append(max(num, Max[i] * num))
Min.append(min(num, Min[i] * num))
else:
Max.append(max(num, Min[i] * num))
Min.append(min(num, Max[i] * num))
return max(Max)
|
302f7ed1d4569abaf417efddff2c2b1721146207 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/maxStack.py | 2,794 | 4.25 | 4 | """
Max Stack
Design a max stack that supports push, pop, top, peekMax and popMax.
push(x) -- Push element x onto stack.
pop() -- Remove the element on top of the stack and return it.
top() -- Get the element on the top.
peekMax() -- Retrieve the maximum element in the stack.
popMax() -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one.
Example 1:
MaxStack stack = new MaxStack();
stack.push(5);
stack.push(1);
stack.push(5);
stack.top(); -> 5
stack.popMax(); -> 5
stack.top(); -> 1
stack.peekMax(); -> 5
stack.pop(); -> 1
stack.top(); -> 5
Note:
-1e7 <= x <= 1e7
Number of operations won't exceed 10000.
The last four operations won't be called when stack is empty.
"""
"""
A regular stack already supports the first 3 operations and max heap can take care of the last two. But the main issue is when popping an element form the top of one data structure how can we efficiently remove that element from the other. We can use lazy removal (similar to Approach #2 from 480. Sliding Window Median) to achieve this is in average O(log N) time.
"""
class MaxStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.maxHeap = []
self.toPop_heap = {} #to keep track of things to remove from the heap
self.toPop_stack = set() #to keep track of things to remove from the stack
def push(self, x):
"""
:type x: int
:rtype: void
"""
heapq.heappush(self.maxHeap, (-x,-len(self.stack)))
self.stack.append(x)
def pop(self):
"""
:rtype: int
"""
self.top()
x = self.stack.pop()
key = (-x,-len(self.stack))
self.toPop_heap[key] = self.toPop_heap.get(key,0) + 1
return x
def top(self):
"""
:rtype: int
"""
while self.stack and len(self.stack)-1 in self.toPop_stack:
x = self.stack.pop()
self.toPop_stack.remove(len(self.stack))
return self.stack[-1]
def peekMax(self):
"""
:rtype: int
"""
while self.maxHeap and self.toPop_heap.get(self.maxHeap[0],0):
x = heapq.heappop(self.maxHeap)
self.toPop_heap[x] -= 1
return -self.maxHeap[0][0]
def popMax(self):
"""
:rtype: int
"""
self.peekMax()
x,idx = heapq.heappop(self.maxHeap)
x,idx = -x,-idx
self.toPop_stack.add(idx)
return x
# Your MaxStack object will be instantiated and called as such:
# obj = MaxStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.peekMax()
# param_5 = obj.popMax()
|
27b36d5fd37abd73621928e149440a7522da2afc | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Heap/preferred_heap.py | 2,929 | 3.90625 | 4 | # Randomly generates N distinct integers with N provided by the user,
# inserts all these elements into a priority queue, and outputs a list
# L consisting of all those N integers, determined in such a way that:
# - inserting the members of L from those of smallest index of those of
# largest index results in the same priority queue;
# - L is preferred in the sense that the last element inserted is as large as
# possible, and then the penultimate element inserted is as large as possible, etc.
#
# Written by Benny Hwang 27/10/2017
import sys
from random import seed, sample
from priority_queue_adt import *
def reset_pq(original):
tempQ = PriorityQueue()
for e in original[1: ]:
tempQ.insert(e)
pq = tempQ
return pq
def remove_largest_possible( target_index,testQ):
global pq
for index in reversed(target_index):
if index == 1:
val = pq.delete()
pq.insert(val)
if pq._data[ : len(pq) + 1] == testQ:
pq.delete()
return val
pq = reset_pq(testQ)
while index//2:
parent_index = index//2
pq._data[parent_index], pq._data[index] = pq._data[index], pq._data[parent_index]
index = index//2
val = pq.delete()
possible_new = pq._data[ : len(pq) + 1]
pq.insert(val)
if pq._data[ : len(pq) + 1] == testQ:
pq = reset_pq(possible_new)
return val
pq = reset_pq(testQ)
def get_route_to_root(current_last_pos):
target_index = []
target_index.append(current_last_pos)
while current_last_pos//2:
current_last_pos = current_last_pos//2
target_index.append(current_last_pos)
return target_index
def preferred_sequence():
perferred_order = []
while len(perferred_order)!= len(L):
testQ = pq._data[ : len(pq) + 1]
current_last_pos = len(pq._data[ : len(pq) + 1])-1
target_index = get_route_to_root(current_last_pos)
val = remove_largest_possible( target_index,testQ)
perferred_order.append(val)
return perferred_order[::-1]
try:
for_seed, length = [int(x) for x in input('Enter 2 nonnegative integers, the second one '
'no greater than 100: '
).split()
]
if for_seed < 0 or length > 100:
raise ValueError
except ValueError:
print('Incorrect input (not all integers), giving up.')
sys.exit()
seed(for_seed)
L = sample(list(range(length * 10)), length)
pq = PriorityQueue()
for e in L:
pq.insert(e)
print('The heap that has been generated is: ')
print(pq._data[ : len(pq) + 1])
print('The preferred ordering of data to generate this heap by successsive insertion is:')
print(preferred_sequence())
|
98e45ace3d4486913d547c1f6234b4a2a202f512 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/maximumSumOfN-aryTree.py | 1,472 | 3.890625 | 4 | """
Given an N-ary tree and the weight of each edge represented in the value at the child node, now we are pouring water from root node and it gradually coming down through each node traversing one by one. Now time taken by the water to come from parent to child node was written by the value at child node and also root.value = 0 as time taken by root to get wet is 0 sec. Now you need to find the total time required by all nodes to get wet.
Example
0
3. 2. 4
5 6
We are pouring water from root node-
1)Time required to go to 1st child is 3
2)Time required to go to 2nd child is 2
3)Time required to go to 3rd child is 4
4)Time required to go to 1st child of node "3" is 5+3=8
5)Time required to go to 2nd child of node "3" is 3+6=9
So total time required by all node to get wet is 9.
"""
import collections
class TreeNode:
def __init__(self, val):
self.val = val
self.children = None
def water_tower(root):
queue = collections.deque([(node, 0) for node in root.children])
max_sum = 0
while queue:
node, curr_sum = queue.popleft()
curr_sum += node.val
max_sum = max(max_sum, curr_sum)
if not node.children:
continue
for child in node.children:
queue.append((child, curr_sum))
return max_sum
if __name__ == '__main__':
left = TreeNode(3)
left.children = [TreeNode(5), TreeNode(6)]
center = TreeNode(2)
right = TreeNode(4)
root = TreeNode(0)
root.children = [left, center, right]
assert water_tower(root) == 9
|
be4b1f82b684b71f01d76c32b573b96b6d07b658 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/nextGreaterElementIII.py | 2,171 | 3.703125 | 4 | """
Next Greater Element III
Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive 32-bit integer exists, you need to return -1.
Example 1:
Input: 12
Output: 21
Example 2:
Input: 21
Output: -1
"""
"""
Time: O(N)
Space: O(N)
In this case as well, we consider the given number nn as a character array aa. First, we observe that for any given sequence that is in descending order, no next larger permutation is possible. For example, no next permutation is possible for the following array:
[9, 5, 4, 3, 1]
We need to find the first pair of two successive numbers a[i] and a[i−1], from the right, which satisfy a[i]>a[i−1]. Now, no rearrangements to the right of a[i−1] can create a larger permutation since that subarray consists of numbers in descending order. Thus, we need to rearrange the numbers to the right of a[i−1] including itself.
Now, what kind of rearrangement will produce the next larger number? We want to create the permutation just larger than the current one. Therefore, we need to replace the number a[i-1] with the number which is just larger than itself among the numbers lying to its right section, say a[j].
We swap the numbers a[i-1]and a[j]. We now have the correct number at index i-1. But still the current permutation isn't the permutation that we are looking for. We need the smallest permutation that can be formed by using the numbers only to the right of a[i−1]. Therefore, we need to place those numbers in ascending order to get their smallest permutation.
"""
class Solution:
def nextGreaterElement(self, n: int) -> int:
s = list(map(int, str(n)))
i = len(s)-1
while i-1>=0 and s[i] <= s[i-1]:
i -= 1
if i==0:
return -1
j = i
while j+1 < len(s) and s[j+1] > s[i-1]:
j += 1
s[i-1], s[j] = s[j], s[i-1]
s[i:] = reversed(s[i:])
ret = int(''.join(map(str, s)))
return ret if ret<=((1<<31)-1) else -1
|
7a10218d23278cfce1aa3f24e1a12b473a257d4d | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/timeBasedKeyValueStore.py | 4,155 | 3.6875 | 4 | """
Time Based Key-Value Store
Create a timebased key-value store class TimeMap, that supports two operations.
1. set(string key, string value, int timestamp)
Stores the key and value, along with the given timestamp.
2. get(string key, int timestamp)
Returns a value such that set(key, value, timestamp_prev) was called previously, with timestamp_prev <= timestamp.
If there are multiple such values, it returns the one with the largest timestamp_prev.
If there are no values, it returns the empty string ("").
Example 1:
Input: inputs = ["TimeMap","set","get","get","set","get","get"], inputs = [[],["foo","bar",1],["foo",1],["foo",3],["foo","bar2",4],["foo",4],["foo",5]]
Output: [null,null,"bar","bar",null,"bar2","bar2"]
Explanation:
TimeMap kv;
kv.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1
kv.get("foo", 1); // output "bar"
kv.get("foo", 3); // output "bar" since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 ie "bar"
kv.set("foo", "bar2", 4);
kv.get("foo", 4); // output "bar2"
kv.get("foo", 5); //output "bar2"
Example 2:
Input: inputs = ["TimeMap","set","set","get","get","get","get","get"], inputs = [[],["love","high",10],["love","low",20],["love",5],["love",10],["love",15],["love",20],["love",25]]
Output: [null,null,null,"","high","high","low","low"]
Note:
All key/value strings are lowercase.
All key/value strings have length in the range [1, 100]
The timestamps for all TimeMap.set operations are strictly increasing.
1 <= timestamp <= 10^7
TimeMap.set and TimeMap.get functions will be called a total of 120000 times (combined) per test case.
Accepted
19,382
Submissions
37,704
"""
"""
HashMap + Binary search
Time: Set is O(1), Get is O(logN)
Space: O(N)
"""
class TimeMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.store = collections.defaultdict(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self.store[key].append((timestamp, value))
def get(self, key: str, timestamp: int) -> str:
if not len(self.store[key]):
return ''
i = bisect.bisect(self.store[key], (timestamp, chr(ord('z'))))
return self.store[key][i-1][1] if i else ''
class TimeMap:
def __init__(self):
self._dic = defaultdict(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self._dic[key].append((value, timestamp,))
def get(self, key: str, timestamp: int) -> str:
if key in self._dic:
li = self._dic[key]
l, r = 0, len(self._dic[key]) - 1
if li[l][1] > timestamp:
return ""
elif li[r][1] <= timestamp:
return li[r][0]
else:
while l <= r:
mid = l + (r - l) // 2
if li[mid][1] == timestamp:
return li[mid][0]
if li[mid][1] < timestamp:
l = mid + 1
else:
r = mid - 1
return li[r][0]
return ""
class TimeMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.store = collections.defaultdict(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self.store[key].append((timestamp, value))
def get(self, key: str, timestamp: int) -> str:
if key not in self.store:
return ''
arr = self.store[key]
left, right = 0, len(arr)-1
while left <= right:
mid = (left+right)//2
if arr[mid][0] == timestamp:
return arr[mid][1]
elif arr[mid][0] < timestamp:
left = mid + 1
else:
right = mid - 1
return arr[right][1] if right >= 0 else ''
# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp)
|
39c5c28985e46e9266410896dc041f0948ea46d7 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/permutationSequence.py | 2,125 | 4.0625 | 4 | """
Permutation Sequence
The set [1,2,3,...,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note:
Given n will be between 1 and 9 inclusive.
Given k will be between 1 and n! inclusive.
Example 1:
Input: n = 3, k = 3
Output: "213"
Example 2:
Input: n = 4, k = 9
Output: "2314"
"""
"""
For permutations of n, the first (n-1)! permutations start with 1, next (n-1)! ones start with 2, ... and so on. And in each group of (n-1)! permutations, the first (n-2)! permutations start with the smallest remaining number, ...
take n = 3 as an example, the first 2 (that is, (3-1)! ) permutations start with 1, next 2 start with 2 and last 2 start with 3. For the first 2 permutations (123 and 132), the 1st one (1!) starts with 2, which is the smallest remaining number (2 and 3). So we can use a loop to check the region that the sequence number falls in and get the starting digit. Then we adjust the sequence number and continue.
Time: O(n) because n<= 9
"""
class Solution:
def getPermutation(self, n: int, k: int) -> str:
numbers = [i for i in range(1, n+1)]
permutation = ''
k -= 1 # Because to get the k-th sequence, you only need to perform (k-1) transformation, as number is initialized as range(1, n+1) which is already the 1st term.
while n > 0:
n -= 1
# get the index of current digit
index, k = divmod(k, math.factorial(n))
permutation += str(numbers[index])
# remove handled number
numbers.remove(numbers[index])
return permutation
def getPermutation(self, n, k):
nums = [str(i) for i in range(1, n+1)]
fact = [1] * n
for i in range(1,n):
fact[i] = i*fact[i-1]
k -= 1
ans = []
for i in range(n, 0, -1):
id = k / fact[i-1]
k %= fact[i-1]
ans.append(nums[id])
nums.pop(id)
return ''.join(ans)
|
f09ae78531c516afc4a4177bdf9f2bdbf537d043 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/verifyPreorderSequenceInBinarySearchTree.py | 2,086 | 3.8125 | 4 | """
Verify Perorder Sequence In Binary Search Tree
Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.
You may assume each number in the sequence is unique.
Consider the following binary search tree:
5
/ \
2 6
/ \
1 3
Example 1:
Input: [5,2,6,1,3]
Output: false
Example 2:
Input: [5,2,1,3,6]
Output: true
Follow up:
Could you do it using only constant space complexity?
"""
"""
Using Binary Tree's property and stack
We keep updating the lower bound
Time: O(N)
Space: O(N)
"""
class Solution(object):
def verifyPreorder(self, preorder):
"""
:type preorder: List[int]
:rtype: bool
"""
stack = []
lower = -float('inf')
for x in preorder:
if x < lower:
return False
while stack and x > stack[-1]:
lower = stack.pop()
stack.append(x)
return True
"""
Time: O(N)
Space: O(1)
Preorder array can be reused as the stack thus achieve O(1) extra space, since the scanned items of preorder array is always more than or equal to the length of the stack.
At any point, we need to figure out the lower bound for all the values yet to be seen or processed. Now how would be manage that? Visualize a BST.
Initially that lower bound is -INF.
You start pushing all the left most values into a stack. When you find preorder[i] > preorder[i-1], it indicates a right child. We now want to find the predecessor of this right child. The predecessor will serve as new lower bound.
How do we find predecessor? Keep popping till you preorder[i] > st[-1].
"""
class Solution(object):
def verifyPreorder(self, preorder):
# stack = preorder[:i], reuse preorder as stack
lower = -1 << 31
i = 0
for x in preorder:
if x < lower:
return False
while i > 0 and x > preorder[i - 1]:
lower = preorder[i - 1]
i -= 1
preorder[i] = x
i += 1
return True
|
437e273c80d1f452066000556fde65871de49a3e | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/findCommonCharacters.py | 1,908 | 4.03125 | 4 | """
Find Common Characters
Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.
You may return the answer in any order.
Example 1:
Input: ["bella","label","roller"]
Output: ["e","l","l"]
Example 2:
Input: ["cool","lock","cook"]
Output: ["c","o"]
"""
class Solution:
def commonChars(self, A: List[str]) -> List[str]:
check = set(A[0])
result = [[l] * min([a.count(l) for a in A]) for l in check]
return sorted([i for e in result for i in e])
from collections import Counter
class Solution:
def commonChars(self, A: List[str]) -> List[str]:
my_list, res = [], []
for v in A:
my_list.append(Counter(v))
for key in my_list[0]:
times = my_list[0][key]
for e in my_list[1:]:
times = min(times, e[key])
for _ in range(times):
res.append(key)
return res
class Solution:
def commonChars(self, A: List[str]) -> List[str]:
output = []
for letter in set(min(A)):
count = 100
for word in A:
count = min(count, word.count(letter))
while count > 0:
count -= 1
output.append(letter)
return output
class Solution:
def commonChars(self, A: List[str]) -> List[str]:
if not A:
return []
letters = set()
for word in A:
for letter in word:
letters.add(letter)
repeats = []
for l in letters:
occurance = min([word.count(l) for word in A])
repeats.extend([l]*occurance)
return repeats
|
0e980363de2eb7407209395ab2b9ba73aaaa1f23 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Linked Lists/linked_list_adt.py | 6,118 | 3.953125 | 4 | # Written by Eric Martin and modified by Benny Hwang
'''
A Linked List abstract data type
'''
from copy import deepcopy
class Node:
def __init__(self, value = None):
self.value = value
self.next_node = None
class LinkedList:
def __init__(self, L = None, key = lambda x: x):
self.key = key
if L is None:
self.head = None
return
if not len(L[: 1]):
self.head = None
return
node = Node(L[0])
self.head = node
for e in L[1: ]:
node.next_node = Node(e)
node = node.next_node
def print(self, separator = ', '):
if not self.head:
return
nodes = []
node = self.head
while node:
nodes.append(str(node.value))
node = node.next_node
print(separator.join(nodes))
def duplicate(self):
if not self.head:
return
node = self.head
node_copy = Node(deepcopy(node.value))
L = LinkedList(key = self.key)
L.head = node_copy
node = node.next_node
while node:
node_copy.next_node = Node(deepcopy(node.value))
node_copy = node_copy.next_node
node = node.next_node
return L
def __len__(self):
length = 0
node = self.head
while node:
length += 1
node = node.next_node
return length
def apply_function(self, function):
node = self.head
while node:
node.value = function(node.value)
node = node.next_node
def is_sorted(self):
node = self.head
while node and node.next_node:
if self.key(node.value) > self.key(node.next_node.value):
return False
node = node.next_node
return True
def extend(self, L):
if not L.head:
return
if not self.head:
self.head = L.head
return
node = self.head
while node.next_node:
node = node.next_node
node.next_node = L.head
def reverse(self):
if not self.head:
return
node = self.head.next_node
self.head.next_node = None
while node:
next_node = node.next_node
node.next_node = self.head
self.head = node
node = next_node
def recursive_reverse(self):
if not self.head or not self.head.next_node:
return
node = self.head
while node.next_node.next_node:
node = node.next_node
last_node = node.next_node
node.next_node = None
self.recursive_reverse()
last_node.next_node = self.head
self.head = last_node
def index_of_value(self, value):
index = 0
node = self.head
while node:
if node.value == value:
return index
index += 1
node = node.next_node
return -1
def value_at(self, index):
if index < 0:
return
node = self.head
while node and index:
node = node.next_node
index -= 1
if node:
return node.value
return
def prepend(self, value):
if not self.head:
self.head = Node(value)
return
head = self.head
self.head = Node(value)
self.head.next_node = head
def append(self, value):
if not self.head:
self.head = Node(value)
return
node = self.head
while node.next_node:
node = node.next_node
node.next_node = Node(value)
def insert_value_at(self, value, index):
new_node = Node(value)
if not self.head:
self.head = new_node
return
if index <= 0:
new_node.next_node = self.head
self.head = new_node
return
node = self.head
while node.next_node and index > 1:
node = node.next_node
index -= 1
next_node = node.next_node
node.next_node = new_node
new_node.next_node = next_node
def insert_value_before(self, value_1, value_2):
if not self.head:
return False
if self.head.value == value_2:
self.insert_value_at(value_1, 0)
return True
node = self.head
while node.next_node and node.next_node.value != value_2:
node = node.next_node
if not node.next_node:
return False
new_node = Node(value_1)
new_node.next_node = node.next_node
node.next_node = new_node
return True
def insert_value_after(self, value_1, value_2):
if not self.head:
return False
node = self.head
while node and node.value != value_2:
node = node.next_node
if not node:
return False
new_node = Node(value_1)
new_node.next_node = node.next_node
node.next_node = new_node
return True
def insert_sorted_value(self, value):
new_node = Node(value)
if not self.head:
self.head = new_node
return
if value <= self.key(self.head.value):
new_node.next_node = self.head
self.head = new_node
return
node = self.head
while node.next_node and value > self.key(node.next_node.value):
node = node.next_node
new_node.next_node = node.next_node
node.next_node = new_node
def delete_value(self, value):
if not self.head:
return False
if self.head.value == value:
self.head = self.head.next_node
return True
node = self.head
while node.next_node and node.next_node.value != value:
node = node.next_node
if node.next_node:
node.next_node = node.next_node.next_node
return True
return False
|
0e23639a8c4185493a53e157cc41df4f4543e086 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Linked Lists/extended_linked_list_adt.py | 1,132 | 3.5625 | 4 | '''
Written by Benny Hwang 12/09/2017
Extends the module, linked_list_adt by adding a remove duplicate value feature
'''
from linked_list_adt import *
class ExtendedLinkedList(LinkedList):
def __init__(self, L = None):
# The super keyword allows it to inherit the class used in the argumet (LinkedList) in this case
super().__init__(L)
def remove_duplicates(self):
# If empty list, return
if not self.head:
return
# Start from head
current_node = self.head
# set a node and move through the list comparing each node to the current node
while current_node:
# node to compare
node = current_node
while node.next_node:
# If a duplicate is found
if node.next_node.value == current_node.value:
# delink the next node and connect the next next node
node.next_node = node.next_node.next_node
else:
node = node.next_node
current_node = current_node.next_node
|
01b4259cf50c44ed8412415a550c3a67a150c065 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/treap.py | 2,635 | 3.984375 | 4 | """
A binary tree has the binary search tree property (BST property) if, for every node, the keys in its left subtree are smaller than its own key, and the keys in its right subtree are larger than its own key. It has the heap property if, for every node, the keys of its children are all smaller than its own key. You are given a set of binary tree nodes (i, j) where each node contains an integer i and an integer j. No two i values are equal and no two j values are equal. We must assemble the nodes into a single binary tree where the i values obey the BST property and the j values obey the heap property. If you pay attention only to the second key in each node, the tree looks like a heap, and if you pay attention only to the first key in each node, it looks like a binary search tree.
Example 1:
Input: [(1, 6), (3, 7), (2, 4)]
Output:
(3, 7)
/
(1, 6)
\
(2, 4)
Example 2:
Input: [(1, 4), (8, 5), (3, 6), (10, -1), (4, 7)]
Output:
(4, 7)
/ \
(3, 6) (8, 5)
/ \
(1, 4) (10, -1)
You can assume that a solution always exists.
"""
# https://leetcode.com/discuss/interview-question/363945/google-special-binary-tree
class TreeNode:
def __init__(self, x, y):
self.left = self.right = None
self.key1, self.key2 = x, y
def checkBST(node):
if node is None: return True
l, r = node.left, node.right
while l and l.right: l = l.right
while r and r.left: r = r.left
l_val = l.key1 if l else -float('inf')
r_val = r.key1 if r else float('inf')
return l_val < node.key1 < r_val and checkBST(node.left) and checkBST(node.right)
def checkHeap(node):
if node is None: return True, -float('inf')
chk_l, val_l = checkHeap(node.left)
chk_r, val_r = checkHeap(node.right)
chk = node.key2 > max(val_l, val_r) and chk_l and chk_r
val = max(node.key2, val_l, val_r)
return chk, val
def specialBinaryTree(pairs):
# Sort according to second value
pairs.sort(key=lambda x: x[1], reverse=True)
def helper(pairs):
if not pairs: return None
# Create root node
x0, y0 = pairs[0]
node = TreeNode(x0, y0)
# Split left and right according to first value
node.left = helper([(x, y) for x, y in pairs if x < x0])
node.right = helper([(x, y) for x, y in pairs if x > x0])
return node
return helper(pairs)
pairs = [(1, 6), (3, 7), (2, 4)]
root = specialBinaryTree(pairs)
print(checkBST(root), checkHeap(root)[0])
paris = [(1, 4), (8, 5), (3, 6), (10, -1), (4, 7)]
root = specialBinaryTree(pairs)
print(checkBST(root), checkHeap(root)[0]) |
5851ff675353f950e8a9a1c730774a35ab54b8db | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/stringConversion.py | 2,321 | 4.25 | 4 | """
Given 2 strings s and t, determine if you can convert s into t. The rules are:
You can change 1 letter at a time.
Once you changed a letter you have to change all occurrences of that letter.
Example 1:
Input: s = "abca", t = "dced"
Output: true
Explanation: abca ('a' to 'd') -> dbcd ('c' to 'e') -> dbed ('b' to 'c') -> dced
Example 2:
Input: s = "ab", t = "ba"
Output: true
Explanation: ab -> ac -> bc -> ba
Example 3:
Input: s = "abcdefghijklmnopqrstuvwxyz", t = "bcdefghijklmnopqrstuvwxyza"
Output: false
Example 4:
Input: s = "aa", t = "cd"
Output: false
Example 5:
Input: s = "ab", t = "aa"
Output: true
Example 6:
Input: s = "abcdefghijklmnopqrstuvwxyz", t = "bbcdefghijklmnopqrstuvwxyz"
Output: true
Both strings contain only lowercase English letters.
"""
"""
Time Complexity: O(s)
Space Complexity: O(s)
This seems like those mapping problems of one string to another on steroids. After we modify a certain letter, the new letter for that group may be the same as a later letter in s. So we'd want to use a placeholder for certain mappings, but at what point do we run out of placeholders? Definitely when we're using all 26 letters, but is that the only time? It seems like it's very hard to prove that, given all the potential overlaps of mappings that may occur.
If that is the reality though, I'd say as long as we can map every letter in s to the same letter in b, and as long as there aren't 26 letters (or if there are 26 letters, the strings must be identical), then we can do the conversion...
"""
def convert(s, t):
if len(s) != len(t):
return False
if s == t:
return True
dict_s = {} # match char in s and t
unique_t = set() # count unique letters in t
for i in range(len(s)):
if (s[i] in dict_s):
if dict_s[s[i]] != t[i]:
return False
else:
dict_s[s[i]] = t[i]
unique_t.add(t[i])
if len(dict_s) == 26:
return len(unique_t) < 26
return True
if __name__ == '__main__':
assert convert('abca', 'dced') == True
assert convert('ab', 'ba') == True
assert convert('abcdefghijklmnopqrstuvwxyz', 'bcdefghijklmnopqrstuvwxyza') == False
assert convert('aa', 'cd') == False
assert convert('ab', 'aa') == True
assert convert('abcdefghijklmnopqrstuvwxyz', 'bbcdefghijklmnopqrstuvwxyz') == True
|
82189015651e918670a0685bed581e262098dd6d | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/compareStrings.py | 1,763 | 4.09375 | 4 | """
Compare String
One string is strictly smaller than another when the frequency of occurrence of the smallest
character in the string is less than the frequency of the occurrence of the
smallest character in the comparison string.
For example, string "abcd" is smaller than string "aaa" because the smallest
character in "abcd" is "a" with a frequency of 1, and the smallest character
in "aaa" is also "a", but with a frequency of 3. In another example, string "a"
is samller than string "bb" because the smallest character in "a" is "a" with a
frequency of 1, and the smallest character in "bb" is "b" with a frequency of 2.
Write a function that given string A (which contains M strings delimited by ',')
and string B (which contains N strings delimited by ','), returns an array C of N
integers. For 0 <= J < N, values of C[j] specify the number of strings in A which
are strictly smaller than the comparision Jth string in B.
"""
import collections
import bisect
def binarySearch(arr, val):
left, right = 0, len(arr)
while left < right:
mid = (left + right) // 2
if arr[mid] >= val:
right = mid
else:
left = mid + 1
return left
def compareStrings(A, B):
stringA = A.split(',')
stringB = B.split(',')
lowest_As = []
for strA in stringA:
counts = collections.Counter(strA)
lowest_As.append(counts[sorted(counts.keys())[0]])
lowest_As.sort()
res = []
for strB in stringB:
counts = collections.Counter(strB)
lowest_B = counts[sorted(counts.keys())[0]]
res.append(binarySearch(lowest_As, lowest_B)) # or use bisect to find the left insertion index => res.append(bisect.bisect_left(lowest_As, lowest_B))
print(res)
return res
if __name__ == '__main__':
assert compareStrings("abcd,aabc,bd", "aaa,aa") == [3, 2]
|
ad7585865f7d924975f5f44cb9dd5bd857215f55 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/ReverseVowelsOfAString.py | 1,513 | 4.09375 | 4 | """
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: "hello"
Output: "holle"
Example 2:
Input: "leetcode"
Output: "leotcede"
Note:
The vowels does not include the letter "y".
"""
# Time O(n), Space: O(n)
class Solution:
def reverseVowels(self, s: str) -> str:
if not s:
return s
left, right = 0, len(s)-1
letters = list(s)
vowels = {'a', 'e', 'i', 'o', 'u'}
while left < right:
while left < len(s) and letters[left].lower() not in vowels:
left += 1
while right >= 0 and letters[right].lower() not in vowels:
right -= 1
if left < right:
letters[left], letters[right] = letters[right], letters[left]
left += 1
right -= 1
return ''.join(letters)
class Solution:
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
s = list(s)
vowels = set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'])
i, j = 0, len(s)-1
while i < j:
if s[i] not in vowels:
i += 1
if s[j] not in vowels:
j -= 1
if s[i] in vowels and s[j] in vowels:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
return ''.join(s)
|
de1cdd7c24ce9e56af7baaf562ad915960eb246d | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/uniquePaths.py | 1,433 | 4.15625 | 4 | """
Unique Paths
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
"""
"""
DP (recursion is 2^n)
Time: O(m*n)
Space: O(m*n) => can be reduced to just storing one row to O(n) space
"""
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[0 for _ in range(m)] for _ in range(n)]
dp[0][0] = 1
for i in range(n):
for j in range(m):
if i == 0 or j == 0:
dp[i][j] = 1
else:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[-1][-1]
"""
Math Way
"""
# math C(m+n-2,n-1)
def uniquePaths1(self, m, n):
if not m or not n:
return 0
return math.factorial(m+n-2)/(math.factorial(n-1) * math.factorial(m-1))
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
grid = [[1 for i in range(m)] for _ in range(n)]
for i in range(n):
for j in range(m):
if not i or not j:
continue
grid[i][j] = grid[i - 1][j] + grid[i][j - 1]
return grid[n - 1][m - 1]
|
8cb2c5f1e33742337cdb1495c6d2f13e169d481a | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/binarySearchTreeIterator.py | 5,505 | 4.15625 | 4 | """
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Note:
next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
You may assume that next() call will always be valid, that is, there will be at least a next smallest number in the BST when next() is called.
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
"""
Time: hasnext: O(1)
next: O(N)
Space: O(h), for stack
Controlled recursion or do an inoder traversal then use pointer with array
Controlled recursion uses less space
1. Initialize an empty stack S which will be used to simulate the inorder traversal for our binary search tree. Note that we will be following the same approach for inorder traversal as before except that now we will be using our own stack rather than the system stack. Since we are using a custom data structure, we can pause and resume the recursion at will.
2. consider a helper function that we will be calling again and again in the implementation. This function, called _inorder_left will essentially add all the nodes in the leftmost branch of the tree rooted at the given node root to the stack and it will keep on doing so until there is no left child of the root node.
For a given node root, the next smallest element will always be the leftmost element in its tree. So, for a given root node, we keep on following the leftmost branch until we reach a node which doesn't have a left child and that will be the next smallest element. For the root of our BST, this leftmost node would be the smallest node in the tree. Rest of the nodes are added to the stack because they are pending processing. Try and relate this with a dry run of a simple recursive inorder traversal and things will make a bit more sense.
3. The first time next() function call is made, the smallest element of the BST has to be returned and then our simulated recursion has to move one step forward i.e. move onto the next smallest element in the BST. The invariant that will be maintained in this algorithm is that the stack top always contains the element to be returned for the next() function call. However, there is additional work that needs to be done to maintain that invariant. It's very easy to implement the hasNext() function since all we need to check is if the stack is empty or not. So, we will only focus on the next() call from now.
4. When a next() function is called, move back up one stack and check all of its right node's left child and add them to stack
"""
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
self._leftmost_inorder(root)
def _leftmost_inorder(self, root):
while root:
self.stack.append(root)
root = root.left
def next(self):
"""
@return the next smallest number
:rtype: int
"""
top = self.stack.pop()
if top.right:
self._leftmost_inorder(top.right)
return top.val
def hasNext(self):
"""
@return whether we have a next smallest number
:rtype: bool
"""
return len(self.stack) > 0
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
# Definition for a binary tree node
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
self.curr = root
def hasNext(self):
"""
:rtype: bool
"""
return True if self.stack or self.curr else False
def next(self):
"""
:rtype: int
"""
while self.curr:
self.stack.append(self.curr)
self.curr = self.curr.left
self.curr = self.stack.pop()
val = self.curr.val
self.curr = self.curr.right
return val
# Your BSTIterator will be called like this:
# i, v = BSTIterator(root), []
# while i.hasNext(): v.append(i.next())
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator:
def __init__(self, root: TreeNode):
self.root = root
self.nodes = []
self.dfs(root)
self.pointer = 0
def dfs(self, node):
if not node:
return
self.dfs(node.left)
self.nodes.append(node)
self.dfs(node.right)
def next(self) -> int:
"""
@return the next smallest number
"""
if self.hasNext():
res = self.nodes[self.pointer]
self.pointer += 1
return res.val
def hasNext(self) -> bool:
"""
@return whether we have a next smallest number
"""
return self.pointer < len(self.nodes)
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
|
e81fb3440413a2ca42df459fec604df7d2aad8b8 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/largestSubarrayLengthK.py | 1,764 | 4.1875 | 4 | """
Largest Subarray Length K
Array X is greater than array Y if the first non matching element in both
arrays has a greater value in X than Y.
For example:
X = [1, 2, 4, 3, 5]
Y = [1, 2, 3, 4, 5]
X is greater than Y because the first element that does not match is larger in X.
and if
A = [1, 4, 3, 2, 5] and K = 4, the result is
[4, 3, 2, 5]
"""
# my interpretation is that we can look at all the possible starting indices for a starting array and compare the first value. All elements are unique (distinct), so one value within an array will always be larger or smaller than another--giving us the largest subarray if we just compare that first index.
# if A is all unique
"""
Time: O(N), space: O(1)
"""
def solution(a, k):
# store the first starting index for a subarray as the largest since len(a) will be <= k
first_idx = 0
for x in range(1, len(a)-k+1): # check indices where a subarray of size k can be made
# replace the largest first index if a larger value is found
first_idx = x if a[first_idx] < a[x] else first_idx
return a[first_idx:first_idx+k]
def solution2(a, k):
first_idx = 0
for x in range(1, len(a) - k + 1):
# compare values at each index for the would be sub arrays
for i in range(k):
# replace the largest index and break out of the inner loop is larger value is found
if a[first_idx + i] <= a[x + i]:
first_idx = x
break
# if the current stored largest subarray is larger than the current subarray, move on
else:
break
return a[first_idx:first_idx+k]
if __name__ == '__main__':
assert solution(a=[1, 4, 3, 2, 5], k=4) == [4, 3, 2, 5]
assert solution2(a=[1, 4, 3, 2, 5], k=4) == [4, 3, 2, 5]
assert solution2(a=[1, 4, 4, 2, 5], k=4) == [4, 4, 2, 5]
|
d8776c41083583c02c3fdc6ff3605cca4eea94af | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Dice Challenge/pivoting_die.py | 4,498 | 4.125 | 4 | '''
Consider a board similar to the one below
7 8 9 10
6 1 2 11
5 4 3
However, imagine it as being infinite. A die is initially placed at 1 and can only
move to the next consecutive number (e.g 1 to 2, 2 to 3...)
Prompts the user for a natural number N at least equal to 1, and outputs the numbers at the top, the front and the right after the die has been moved to cell N.
Written by Benny Hwang 13/08/2017
'''
import math
def move_right(Current_faces):
Top_old = Current_faces[0]
Right_old = Current_faces[2]
Bottom_old = Current_faces[3]
Left_old = Current_faces[5]
Top_new = Left_old
Front_new = Current_faces[1]
Right_new = Top_old
Bottom_new = Right_old
Back_new = Current_faces[4]
Left_new = Bottom_old
Current_faces = [Top_new, Front_new, Right_new, Bottom_new, Back_new, Left_new]
return Current_faces
def move_left(Current_faces):
Top_old = Current_faces[0]
Right_old = Current_faces[2]
Bottom_old = Current_faces[3]
Left_old = Current_faces[5]
Top_new = Right_old
Front_new = Current_faces[1]
Right_new = Bottom_old
Bottom_new = Left_old
Back_new = Current_faces[4]
Left_new = Top_old
Current_faces = [Top_new, Front_new, Right_new, Bottom_new, Back_new, Left_new]
return Current_faces
def move_forward(Current_faces):
Top_old = Current_faces[0]
Front_old = Current_faces[1]
Bottom_old = Current_faces[3]
Back_old = Current_faces[4]
Top_new = Back_old
Front_new = Top_old
Right_new = Current_faces[2]
Bottom_new = Front_old
Back_new = Bottom_old
Left_new = Current_faces[5]
Current_faces = [Top_new, Front_new, Right_new, Bottom_new, Back_new, Left_new]
return Current_faces
def move_back(Current_faces):
Top_old = Current_faces[0]
Front_old = Current_faces[1]
Bottom_old = Current_faces[3]
Back_old = Current_faces[4]
Top_new = Front_old
Front_new = Bottom_old
Right_new = Current_faces[2]
Bottom_new = Back_old
Back_new = Top_old
Left_new = Current_faces[5]
Current_faces = [Top_new, Front_new, Right_new, Bottom_new, Back_new, Left_new]
return Current_faces
if __name__ == '__main__':
N = False
while N == False:
N = input("Enter the desired goal cell number: ")
if not N.isdigit():
print('Incorrect value, try again')
N = False
elif int(N) <1:
print('Incorrect value, try again')
N = False
N = int(N)
Top = 3
Front = 2
Right = 1
Bottom = 4
Back = 5
Left = 6
Current_faces = [Top, Front, Right, Bottom, Back, Left]
Square_size = []
if N > 1:
for i in range(1, N, 2):
if i**2 <= N:
i_copy = i
Square_size.append(i**2)
else:
i = 1;
Square_size.append(i)
if N not in Square_size:
val = (i_copy+2)**2
Square_size.append(val)
Cell = int(1)
for i in Square_size:
if Cell < N & Cell==1:
Current_faces = move_right(Current_faces)
Cell += 1
max_dir_step = int(math.sqrt(i) - 1)
if max_dir_step == 0:
max_dir_step == 1
steps = 0
while steps < max_dir_step-1 and Cell < N:
Current_faces = move_forward(Current_faces)
steps += 1
Cell += 1
steps = 0
while steps < max_dir_step and Cell < N:
Current_faces = move_left(Current_faces)
steps += 1
Cell += 1
steps = 0
while steps < max_dir_step and Cell < N:
Current_faces = move_back(Current_faces)
steps += 1
Cell += 1
steps = 0
while steps < max_dir_step+1 and Cell < N:
Current_faces = move_right(Current_faces)
steps += 1
Cell += 1
Top = Current_faces[0]
Front = Current_faces[1]
Right = Current_faces[2]
Bottom = Current_faces[3]
Back = Current_faces[4]
Left = Current_faces[5]
print('On cell ' + str(N) + ', ' + str(Top) + ' is at the top, ' + str(Front) + ' at the front, and ' + str(Right) + ' on the right.')
|
887127a0daa40d6f832475eb5ff8d5976e056510 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/addTwoNumbers.py | 3,988 | 3.625 | 4 | """
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
"""
The pseudocode is as following:
Initialize current node to dummy head of the returning list.
Initialize carry to 00.
Initialize pp and qq to head of l1l1 and l2l2 respectively.
Loop through lists l1l1 and l2l2 until you reach both ends.
Set xx to node pp's value. If pp has reached the end of l1l1, set to 00.
Set yy to node qq's value. If qq has reached the end of l2l2, set to 00.
Set sum = x + y + carry.
Update carry = sum/10.
Create a new node with the digit value of (summod10) and set it to current node's next, then advance current node to next.
Advance both pp and qq.
Check if carry = 1, if so append a new node with digit 11 to the returning list.
Return dummy head's next node.
Time complexity : O(max(m,n)). Assume that mm and nn represents the length of l1l1 and l2l2 respectively, the algorithm above iterates at most max(m,n) times.
Space complexity : O(max(m,n)). The length of the new list is at most max(m,n)+1.
"""
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode, c=0) -> ListNode:
val = l1.val + l2.val + c
c = val //10
ret = ListNode(val%10)
if l1.next != None or l2.next != None or c!= 0:
if l1.next == None:
l1.next = ListNode(0)
if l2.next == None:
l2.next = ListNode(0)
ret.next = self.addTwoNumbers(l1.next, l2.next, c)
return ret
"""
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
temp = ListNode(0)
dummy = temp
carry = 0
while l1 and l2:
new = l1.val + l2.val + carry
if new >= 10:
carry = 1
new = new % 10
else:
carry = 0
newNode = ListNode(new)
temp.next = newNode
temp = temp.next
l1 = l1.next
l2 = l2.next
while l1:
new = l1.val + carry
if new >= 10:
carry = 1
new = new % 10
else:
carry = 0
newNode = ListNode(new)
temp.next = newNode
temp = temp.next
l1 = l1.next
while l2:
new = l2.val + carry
if new >= 10:
carry = 1
new = new % 10
else:
carry = 0
newNode = ListNode(new)
temp.next = newNode
temp = temp.next
l2 = l2.next
if carry:
newNode = ListNode(1)
temp.next = newNode
return dummy.next
|
368549e62f1c5994ae9030d43a1b518167425b74 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/2KeysKeyboard.py | 2,034 | 3.796875 | 4 | """
2 Keys Keyboard
Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step:
Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
Paste: You can paste the characters which are copied last time.
Given a number n. You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to get n 'A'.
Example 1:
Input: 3
Output: 3
Explanation:
Intitally, we have one character 'A'.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.
Note:
The n will be in the range [1, 1000].
"""
"""
Prime Factorization
Intuition
We can break our moves into groups of (copy, paste, ..., paste). Let C denote copying and P denote pasting. Then for example, in the sequence of moves CPPCPPPPCP, the groups would be [CPP][CPPPP][CP].
Say these groups have lengths g_1, g_2, .... After parsing the first group, there are g_1 'A's. After parsing the second group, there are g_1 * g_2 'A's, and so on. At the end, there are g_1 * g_2 * ... * g_n 'A's.
We want exactly N = g_1 * g_2 * ... * g_n. If any of the g_i are composite, say g_i = p * q, then we can split this group into two groups (the first of which has one copy followed by p-1 pastes, while the second group having one copy and q-1 pastes).
Such a split never uses more moves: we use p+q moves when splitting, and pq moves previously. As p+q <= pq is equivalent to 1 <= (p-1)(q-1), which is true as long as p >= 2 and q >= 2.
Algorithm By the above argument, we can suppose g_1, g_2, ... is the prime factorization of N, and the answer is therefore the sum of these prime factors.
Time: O(N)
Space: O(1)
"""
class Solution:
def minSteps(self, n: int) -> int:
ans = 0
d = 2
while n > 1:
while n%d == 0:
ans += d
n /= d
d += 1
return ans
|
2b4e64d837993111fde673235c80dc26e3ded912 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/reconstructItinerary.py | 2,112 | 4.375 | 4 | """
Reconstruct Itinerary
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
Note:
If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
All airports are represented by three capital letters (IATA code).
You may assume all tickets form at least one valid itinerary.
Example 1:
Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]
Example 2:
Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"].
But it is larger in lexical order.
"""
"""
DFS
Time: O(N) where N is number of tickets
Note: sort in reverse first so we can have the graph to contain the smallest lexical order
so we can guarantee the lexical order of the itinerary can be as good as possible
"""
class Solution:
# Iterative
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
graph = collections.defaultdict(list)
for src, dest in sorted(tickets, reverse=True):
graph[src].append(dest)
res = []
stack = ['JFK']
while stack:
while graph[stack[-1]]:
stack.append(graph[stack[-1]].pop())
res.append(stack.pop())
return res[::-1]
# Recursive
def findItinerary(self, tickets):
targets = collections.defaultdict(list)
for a, b in sorted(tickets)[::-1]:
targets[a] += b,
route = []
def visit(airport):
while targets[airport]:
visit(targets[airport].pop())
route.append(airport)
visit('JFK')
return route[::-1]
|
7192024a408d165666ad4f10f7b53b965ce4c769 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/minStack.py | 2,110 | 3.96875 | 4 | """
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
"""
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.minStack = []
def push(self, x: int) -> None:
self.stack.append(x)
if not self.minStack or self.minStack[-1] >= x:
self.minStack.append(x)
def pop(self) -> None:
if self.stack:
minVal = self.stack.pop()
if minVal == self.minStack[-1]:
self.minStack.pop()
def top(self) -> int:
return self.stack[-1] if self.stack else None
def getMin(self) -> int:
return self.minStack[-1] if self.minStack else None
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
class MinStack(object):
def __init__(self):
self.stack = []
def push(self, x):
self.stack.append((x, min(self.getMin(), x)))
def pop(self):
self.stack.pop()
def top(self):
if self.stack:
return self.stack[-1][0]
def getMin(self):
if self.stack:
return self.stack[-1][1]
return sys.maxint
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x: int) -> None:
self.stack.append((x, min(self.getMin(), x)))
def pop(self) -> None:
self.stack.pop()
def top(self) -> int:
return self.stack[-1][0]
def getMin(self) -> int:
if not self.stack:
return float('inf')
return self.stack[-1][1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
|
a5ecd1c97f54dbab3f1500677c6230da91ce45ad | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/minimumAbsoluteDifferenceBetweenServerLoads.py | 1,446 | 3.671875 | 4 | """
There are some processes that need to be executed. Amount of a load that process causes on a server that runs it, is being represented by a single integer. Total load caused on a server is the sum of the loads of all the processes that run on that server. You have at your disposal two servers, on which mentioned processes can be run. Your goal is to distribute given processes between those two servers in the way that, absolute difference of their loads will be minimized.
Given an array of n integers, of which represents loads caused by successive processes, return the minimum absolute difference of server loads.
Example 1:
Input: [1, 2, 3, 4, 5]
Output: 1
Explanation:
We can distribute the processes with loads [1, 2, 4] to the first server and [3, 5] to the second one,
so that their total loads will be 7 and 8, respectively, and the difference of their loads will be equal to 1.
"""
# maximise one to be the half of total
def solution(processes):
max_load = sum(processes)
total = max_load // 2
dp = [[0 for i in range(len(processes))] for j in range(total)]
for i in range(1, total + 1):
if i >= processes[0]:
dp[i-1][0] = processes[0]
for idx, item in enumerate(processes):
for w in range(2, total+1):
if w-1 < item:
dp[w-1][idx] = dp[w-1][idx-1]
else:
dp[w - 1][idx] = max(dp[w - 1][idx - 1], dp[w - item - 1][idx - 1] + item)
best = dp[total - 1][len(processes) - 1]
return max_load - 2*best |
30672bb5dbe790fbbee64a49dcbff2727b344140 | lokeshpopuri21/data-structures-and-algorithms-coursera | /great common divisor.py | 168 | 3.546875 | 4 | a, b = [int(i) for i in input().split()]
def computeGCD(a, b):
while(b):
a, b = b, a % b
return a
print (computeGCD(a,b))
|
610bd5c83000ceb978178c651c3eafd8711aaf51 | asteraceae/comp363TetrisProject | /tetrismain.py | 26,267 | 3.546875 | 4 | import pygame
import sys
from random import randrange as rand
#Board configuration and block size (which can be changed to create different board dimensions: default is a square board 25x25)
blocksize = 30
columnnum = 20
rownum = 25
maxfps = 60
#create a list of the colors (using the RBG color system)
colors = [
(0, 0, 0), #black
(255, 85, 85), #red
(255, 140, 50 ), #orange
(239, 212, 89 ), #yellow
(100, 200, 115), #light green
(50, 120, 52 ), #dark green
(44, 177, 238 ), #blue
(120, 108, 245), #purple
(1, 5, 28) #dark grey (used for the background)
]
# Define the shapes of the single pieces using "0" for blank spaces in the pieces (T, S, Z, J, L, I, O)
tetris_shapes = [
[[1, 1, 1],
[0, 1, 0]], #T shape
[[0, 2, 2],
[2, 2, 0]], #S shape
[[3, 3, 0],
[0, 3, 3]], #Z shape
[[4, 0, 0],
[4, 4, 4]], #J shape
[[0, 0, 5],
[5, 5, 5]], #L Shape
[[6, 6, 6, 6]], #I shape
[[7, 7],
[7, 7]] #O Shape
]
#create a definition to create a new board
def new_board():
board = [
[ 0 for x in range(columnnum) ]
for y in range(rownum)
]
board += [[ 1 for x in range(columnnum)]]
return board
#create a definition to remove a row from the board
def remove_row(board, row):
del board[row]
return [[0 for i in range(columnnum)]] + board
#create a function to join the matrices
def join_matrices(mat1, mat2, mat2_offset):
offsetx, offsety = mat2_offset
for cy, row in enumerate(mat2):
for cx, val in enumerate(row):
mat1[cy+offsety-1 ][cx+offsetx] += val
return mat1
#create a definition to check and see if collisions occurred
def check_collision(board, shape, offsetval):
offsetx, offsety = offsetval
for cy, row in enumerate(shape):
for cx, cell in enumerate(row):
try:
if cell and board[ cy + offsety ][ cx + offsetx ]:
return True
except IndexError:
return True
return False
#create a definition to rotate the pieces
def rotate_clockwise(piece):
return [
[ piece[y][x] for y in range(len(piece)) ]
for x in range(len(piece[0]) - 1, -1, -1)
]
#use this class to run the Tetris game
class TetrisGame(object):
#start by initializing the game as well as the width, height, background
#grid, font size, and screen
def __init__(self, mainscreens):
pygame.init()
pygame.key.set_repeat(250,25)
self.width = 800
self.height = 951
self.mainscreens = mainscreens
self.rowlim = blocksize*columnnum
self.bground_grid = [[ 8 if x%2==y%2 else 0
for x in range(columnnum)] for y in range(rownum)]
self.default_font = pygame.font.Font(
pygame.font.get_default_font(), 25)
self.screen = pygame.display.set_mode((self.width, self.height))
pygame.event.set_blocked(pygame.MOUSEMOTION)
#when choosing the piece, make it a random choice
self.next_piece = tetris_shapes[rand(len(tetris_shapes))]
self.next_piece2 = tetris_shapes[rand(len(tetris_shapes))]
self.next_piece3 = tetris_shapes[rand(len(tetris_shapes))]
self.next_piece4 = tetris_shapes[rand(len(tetris_shapes))]
self.init_game()
#create a definition to setup a new piece
def new_piece(self):
self.piece = self.next_piece[:]
self.next_piece = self.next_piece2
self.next_piece2 = self.next_piece3
self.next_piece3 = self.next_piece4
self.next_piece4 = tetris_shapes[rand(len(tetris_shapes))]
self.piece_x = int(columnnum / 2 - len(self.piece[0])/2)
self.piece_y = 0
if check_collision(self.board,
self.piece,
(self.piece_x, self.piece_y)):
self.gameover = True
#create a definition to initialize the game (board, pieces, levels, scores, etc)
def init_game(self):
self.board = new_board()
self.new_piece()
self.level = 1
self.score = 0
self.lines = 0
pygame.time.set_timer(pygame.USEREVENT+1, 1000)
#create a function to display messages on the screen
def disp_msg(self, message, toparea):
x,y = toparea
for line in message.splitlines():
self.screen.blit(
self.default_font.render(
line,
False,
(255,255,255),
(22, 29, 72)),
(x,y))
y+=14
#create a function to display the message in the center of the screen
def center_msg(self, message):
for i, line in enumerate(message.splitlines()):
messageimage = self.default_font.render(line, False,
(255,255,255), (22, 29, 72))
messagecenter_x, messagecenter_y = messageimage.get_size()
messagecenter_x //= 2
messagecenter_y //= 2
self.screen.blit(messageimage, (
self.width // 2-messagecenter_x,
self.height // 2-messagecenter_y+i*22))
#create a function to draw the matrix (including the offset values)
def draw_matrix(self, matrix, offsetval):
offsetx, offsety = offsetval
for y, row in enumerate(matrix):
for x, val in enumerate(row):
if val:
pygame.draw.rect(
self.screen,
colors[val],
pygame.Rect(
(offsetx+x) *
blocksize,
(offsety+y) *
blocksize,
blocksize,
blocksize),0)
def add_cl_lines(self, n):
linescores = [0, 40, 100, 300, 1200]
self.lines += n
self.score += linescores[n] * self.level
if self.lines >= self.level*6:
self.level += 1
newdelay = 1000-50*(self.level-1)
newdelay = 100 if newdelay < 100 else newdelay
pygame.time.set_timer(pygame.USEREVENT+1, newdelay)
#create a function to move the piece
def move(self, xchange):
if not self.gameover and not self.paused:
new_x = self.piece_x + xchange
if new_x < 0:
new_x = 0
if new_x > columnnum - len(self.piece[0]):
new_x = columnnum - len(self.piece[0])
if not check_collision(self.board,
self.piece,
(new_x, self.piece_y)):
self.piece_x = new_x
#create a function to drop the piece, check for collisions
def drop(self, auto):
if not self.gameover and not self.paused:
self.score += 1 if auto else 0
self.piece_y += 1
if check_collision(self.board,
self.piece,
(self.piece_x, self.piece_y)):
self.board = join_matrices(self.board, self.piece,
(self.piece_x, self.piece_y))
self.new_piece()
cleared_rows = 0
while True:
for i, row in enumerate(self.board[:-1]):
if 0 not in row:
self.board = remove_row(self.board, i)
cleared_rows += 1
break
else:
break
self.add_cl_lines(cleared_rows)
return True
return False
#create a function to instantly drop the piece
def insta_drop(self):
if not self.gameover and not self.paused:
while(not self.drop(True)):
pass
#create a function to rotate a piece if up arrow is pushed
def rotate_piece(self):
if not self.gameover and not self.paused:
new_piece = rotate_clockwise(self.piece)
if not check_collision(self.board,new_piece,(self.piece_x, self.piece_y)):
self.piece = new_piece
#create a function to pause the game (use it when the "p" key is pressed)
def toggle_pause(self):
self.paused = not self.paused
#create function to quit the game
def quit(self):
self.center_msg("Ending the game!")
pygame.display.update()
sys.exit()
#create a function to start the game (gameover = False)
def start_game(self):
if self.gameover:
self.init_game()
self.gameover = False
#create a function to run the game (include the clock, what the different keys
#represent, and how to pause game and display things)
def run(self):
#create a dictionary for the possible moves: up, down, left, right,
#p, escape, return, and space (and their coordinate code calls)
keyslist = {
'SPACE': self.start_game,
'LEFT': lambda:self.move(-1), #moving left is negative
'RIGHT': lambda:self.move(+1),
'UP': self.rotate_piece,
'DOWN': lambda:self.drop(True),
'a': lambda: self.move(-1), # moving left is negative
'd': lambda: self.move(+1),
'w': self.rotate_piece,
's': lambda: self.drop(True),
'p': self.toggle_pause,
'ESCAPE': self.quit,
'RETURN': self.insta_drop
}
#start the game with gameover as false (until they lose) and pause as false
self.gameover = False
self.paused = False
clocktime = pygame.time.Clock()
while 1:
self.screen.fill((22, 29, 72))
image = pygame.image.load('resources/TetrisBanner.png') # get tetris banner
self.screen.blit(image, (-96, 799)) # paste banner on screen
mx, my = pygame.mouse.get_pos() # get mouse points
self.skip_button = pygame.Rect((620, 730, 171, 65))
self.end_button = pygame.Rect((620, 827, 171, 65))
if self.skip_button.collidepoint((mx, my)): # if button clicked, go to game screen
if self.click:
self.gameover = True
pass # to be added in double player
if self.end_button.collidepoint((mx, my)): # if button clicked, go to game screen
if self.click:
self.mainscreens.name_screen()
pass
pygame.draw.rect(self.screen, (22, 29, 72), self.skip_button) # draw skip button
pygame.draw.rect(self.screen, (22, 29, 72), self.end_button) # draw end button
self.skip_button = pygame.image.load('resources/SkipButton.png') # overlay button image
self.screen.blit(self.skip_button, (615, 730))
self.end_button = pygame.image.load('resources/EndButton.png') # overlay button image
self.screen.blit(self.end_button, (615, 827))
#GAMEOVER
if self.gameover:
self.screen.fill((22, 29, 72))
image = pygame.image.load('resources/GameOver.png') # get game over banner
self.screen.blit(image, (0, 205)) # paste banner on screen
end_button = pygame.image.load('resources/EndButton.png') # overlay button image
self.screen.blit(end_button, (615, 827))
self.center_msg("""\n\n Score: %d \n\n To start a new game, press SPACE""" % self.score)
else:
#PAUSE
if self.paused:
self.center_msg("Game has been paused.")
else:
#IF NOT GAMEOVER/PAUSE
pygame.draw.line(self.screen,
(255,255,255),
(self.rowlim+1, 0),
(self.rowlim+1, self.height-1))
self.disp_msg("Next:", (self.rowlim+blocksize, 3))
self.disp_msg("\n Score: %d" % (self.score), (self.rowlim+blocksize, blocksize*21))
self.draw_matrix(self.bground_grid, (0,0))
self.draw_matrix(self.board, (0,0))
self.draw_matrix(self.piece, (self.piece_x, self.piece_y))
self.draw_matrix(self.next_piece, (columnnum + 1, 2))
self.draw_matrix(self.next_piece2, (columnnum + 1, 5))
self.draw_matrix(self.next_piece3, (columnnum + 1, 8))
self.draw_matrix(self.next_piece4, (columnnum + 1, 11))
pygame.display.update()
#create movements for the various key events (pause, up, down, quit, etc)
self.click = False
for event in pygame.event.get():
if event.type == pygame.USEREVENT+1:
self.drop(False)
elif event.type == pygame.QUIT:
self.quit()
elif event.type == pygame.KEYDOWN:
for key in keyslist:
if event.key == eval("pygame.K_"
+key):
keyslist[key]()
if event.type == pygame.MOUSEBUTTONDOWN: # if mouse clicked, click is true
if event.button == 1:
self.click = True
#set the clock to tick with the maxfps given in the beginning
clocktime.tick(maxfps)
class TetrisGame2Player(object):
#start by initializing the game as well as the width, height, background
#grid, font size, and screen
def __init__(self, mainscreens):
pygame.init()
pygame.key.set_repeat(250,25)
self.width = 800
self.height = 951
self.mainscreens = mainscreens
self.rowlim = blocksize*columnnum
self.bground_grid = [[ 8 if x%2==y%2 else 0
for x in range(columnnum)] for y in range(rownum)]
self.default_font = pygame.font.Font(
pygame.font.get_default_font(), 25)
self.screen = pygame.display.set_mode((self.width, self.height))
pygame.event.set_blocked(pygame.MOUSEMOTION)
# when choosing the piece, make it a random choice
self.next_piece = tetris_shapes[rand(len(tetris_shapes))]
self.next_piece2 = tetris_shapes[rand(len(tetris_shapes))]
self.next_piece3 = tetris_shapes[rand(len(tetris_shapes))]
self.next_piece4 = tetris_shapes[rand(len(tetris_shapes))]
self.gametwo = False
self.init_game()
# create a definition to setup a new piece
def new_piece(self):
self.piece = self.next_piece[:]
self.next_piece = self.next_piece2
self.next_piece2 = self.next_piece3
self.next_piece3 = self.next_piece4
self.next_piece4 = tetris_shapes[rand(len(tetris_shapes))]
self.piece_x = int(columnnum / 2 - len(self.piece[0]) / 2)
self.piece_y = 0
if check_collision(self.board,
self.piece,
(self.piece_x, self.piece_y)):
self.gameover = True
#create a definition to initialize the game (board, pieces, levels, scores, etc)
def init_game(self):
self.board = new_board()
self.new_piece()
self.level = 1
self.score = 0
self.lines = 0
pygame.time.set_timer(pygame.USEREVENT+1, 1000)
#create a function to display messages on the screen
def disp_msg(self, message, toparea):
x,y = toparea
for line in message.splitlines():
self.screen.blit(
self.default_font.render(
line,
False,
(255,255,255),
(22, 29, 72)),
(x,y))
y+=14
#create a function to display the message in the center of the screen
def center_msg(self, message):
for i, line in enumerate(message.splitlines()):
messageimage = self.default_font.render(line, False,
(255,255,255), (22, 29, 72))
messagecenter_x, messagecenter_y = messageimage.get_size()
messagecenter_x //= 2
messagecenter_y //= 2
self.screen.blit(messageimage, (
self.width // 2-messagecenter_x,
self.height // 2-messagecenter_y+i*22))
#create a function to draw the matrix (including the offset values)
def draw_matrix(self, matrix, offsetval):
offsetx, offsety = offsetval
for y, row in enumerate(matrix):
for x, val in enumerate(row):
if val:
pygame.draw.rect(
self.screen,
colors[val],
pygame.Rect(
(offsetx+x) *
blocksize,
(offsety+y) *
blocksize,
blocksize,
blocksize),0)
def add_cl_lines(self, n):
linescores = [0, 40, 100, 300, 1200]
self.lines += n
self.score += linescores[n] * self.level
if self.lines >= self.level*6:
self.level += 1
newdelay = 1000-50*(self.level-1)
newdelay = 100 if newdelay < 100 else newdelay
pygame.time.set_timer(pygame.USEREVENT+1, newdelay)
#create a function to move the piece
def move(self, xchange):
if not self.gameover and not self.paused:
new_x = self.piece_x + xchange
if new_x < 0:
new_x = 0
if new_x > columnnum - len(self.piece[0]):
new_x = columnnum - len(self.piece[0])
if not check_collision(self.board,
self.piece,
(new_x, self.piece_y)):
self.piece_x = new_x
#create a function to drop the piece, check for collisions
def drop(self, auto):
if not self.gameover and not self.paused:
self.score += 1 if auto else 0
self.piece_y += 1
if check_collision(self.board,
self.piece,
(self.piece_x, self.piece_y)):
self.board = join_matrices(self.board, self.piece,
(self.piece_x, self.piece_y))
self.new_piece()
cleared_rows = 0
while True:
for i, row in enumerate(self.board[:-1]):
if 0 not in row:
self.board = remove_row(self.board, i)
cleared_rows += 1
break
else:
break
self.add_cl_lines(cleared_rows)
return True
return False
#create a function to instantly drop the piece
def insta_drop(self):
if not self.gameover and not self.paused:
while(not self.drop(True)):
pass
#create a function to rotate a piece if up arrow is pushed
def rotate_piece(self):
if not self.gameover and not self.paused:
new_piece = rotate_clockwise(self.piece)
if not check_collision(self.board,new_piece,(self.piece_x, self.piece_y)):
self.piece = new_piece
#create a function to pause the game (use it when the "p" key is pressed)
def toggle_pause(self):
self.paused = not self.paused
#create function to quit the game
def quit(self):
self.center_msg("Ending the game!")
pygame.display.update()
sys.exit()
#create a function to start the game (gameover = False)
def start_game(self):
if self.gameover:
if self.gametwo == False:
self.gametwo = True
elif self.gametwo == True:
self.gametwo = False
self.init_game()
self.gameover = False
#create a function to run the game (include the clock, what the different keys
#represent, and how to pause game and display things)
def run(self):
#create a dictionary for the possible moves: up, down, left, right,
#p, escape, return, and space (and their coordinate code calls)
keyslist = {
'SPACE': self.start_game,
'LEFT': lambda:self.move(-1), #moving left is negative
'RIGHT': lambda:self.move(+1),
'UP': self.rotate_piece,
'DOWN': lambda:self.drop(True),
'a': lambda: self.move(-1), # moving left is negative
'd': lambda: self.move(+1),
'w': self.rotate_piece,
's': lambda: self.drop(True),
'p': self.toggle_pause,
'ESCAPE': self.quit,
'RETURN': self.insta_drop
}
#start the game with gameover as false (until they lose) and pause as false
self.gameover = False
self.paused = False
p1score = 0
p2score = 0
clocktime = pygame.time.Clock()
while 1:
self.screen.fill((22, 29, 72))
image = pygame.image.load('resources/TetrisBanner.png') # get tetris banner
self.screen.blit(image, (-96, 799)) # paste banner on screen
mx, my = pygame.mouse.get_pos() # get mouse points
self.skip_button = pygame.Rect((620, 730, 171, 65))
self.end_button = pygame.Rect((620, 827, 171, 65))
if self.skip_button.collidepoint((mx, my)): # if button clicked, go to game screen
if self.click:
self.gameover = True
pass # to be added in double player
if self.end_button.collidepoint((mx, my)): # if button clicked, go to game screen
if self.click:
self.mainscreens.name_screen()
pass
pygame.draw.rect(self.screen, (22, 29, 72), self.skip_button) # draw skip button
pygame.draw.rect(self.screen, (22, 29, 72), self.end_button) # draw end button
self.skip_button = pygame.image.load('resources/SkipButton.png') # overlay button image
self.screen.blit(self.skip_button, (615, 730))
self.end_button = pygame.image.load('resources/EndButton.png') # overlay button image
self.screen.blit(self.end_button, (615, 827))
#GAMEOVER
if self.gameover:
self.screen.fill((22, 29, 72))
if self.gametwo == False:
self.center_msg("""\n\n Score: %d \n\n When Player 2 is ready, press SPACE""" % self.score)
image = pygame.image.load('resources/GameOver2.png') # get tetris banner
self.screen.blit(image, (0, 205)) # paste banner on screen
end_button = pygame.image.load('resources/EndButton.png') # overlay button image
self.screen.blit(end_button, (615, 827))
elif self.gametwo == True:
p2score = self.score
self.screen.fill((22, 29, 72))
image = pygame.image.load('resources/GameOver3.png') # get tetris banner
self.screen.blit(image, (0, 205)) # paste banner on screen
end_button = pygame.image.load('resources/EndButton.png') # overlay button image
self.screen.blit(end_button, (615, 827))
if p1score > p2score:
self.center_msg("""\n\nPlayer 1 Wins! \n\nP1 Score: %d \nP2 Score: %d\n\n To start a new 2 player game, press SPACE""" % (p1score, p2score))
self.winscore = p1score
elif p2score > p1score:
self.center_msg("""\n\nPlayer 2 Wins! \n\nP1 Score: %d \nP2 Score: %d\n\n To start a brand new 2 player game, press SPACE""" % (p1score, p2score))
self.winscore = p2score
else:
#PAUSE
if self.paused:
self.center_msg("Game has been paused.")
else:
#IF NOT GAMEOVER/PAUSE
pygame.draw.line(self.screen,
(255,255,255),
(self.rowlim+1, 0),
(self.rowlim+1, self.height-1))
self.disp_msg("Next:", (self.rowlim+blocksize,3))
self.disp_msg("\n Score: %d" % self.score, (self.rowlim+blocksize, blocksize*21))
self.draw_matrix(self.bground_grid, (0,0))
self.draw_matrix(self.board, (0,0))
self.draw_matrix(self.piece, (self.piece_x, self.piece_y))
self.draw_matrix(self.next_piece, (columnnum+1, 2))
self.draw_matrix(self.next_piece2, (columnnum + 1, 5))
self.draw_matrix(self.next_piece3, (columnnum + 1, 8))
self.draw_matrix(self.next_piece4, (columnnum + 1, 11))
pygame.display.update()
#create movements for the various key events (pause, up, down, quit, etc)
self.click = False
for event in pygame.event.get():
if event.type == pygame.USEREVENT+1:
self.drop(False)
elif event.type == pygame.QUIT:
self.quit()
elif event.type == pygame.KEYDOWN:
for key in keyslist:
if event.key == eval("pygame.K_"
+key):
keyslist[key]()
if event.type == pygame.MOUSEBUTTONDOWN: # if mouse clicked, click is true
if event.button == 1:
self.click = True
#set the clock to tick with the maxfps given in the beginning
clocktime.tick(maxfps)
#then run the Tetris App in the main screen
if __name__ == '__main__':
tetris = TetrisGame()
tetris.run()
|
670d62ffcdf05c898777d8876f11695b8df377b1 | godumuyiwa/numericalcompute | /simpleiterationfor.py | 378 | 3.734375 | 4 | def simpleiterusingfor(a):
x = a
for loops in range (1,101):
#using a for loop without any accuracy set
x_new = (2*x**2 + 3)/5
print(loops, x_new)
if abs(x_new - x) <0.00001:
break
else:
x = x_new
print(f"The number of iteration is {loops} and the root is {x_new}")
simpleiterusingfor(0)
|
7ccb8e1436ad8be419b257510e198e5054ced8d2 | AliHaddad/Text-Analysis | /analyser.py | 3,138 | 4.03125 | 4 | import codecs
def normalize(s):
"""
(str) -> str
Given a string, return a copy of that string with
all alphabetical characters turned lowercase and
all special characters removed and replaced with a space.
>>> normalize("Hey! How are you? I'm fine. ;D")
'hey how are you i m fine d'
"""
new_string = ''
for ch in s:
if ch.isalpha():
new_string = new_string + ch.lower()
elif ch == ' ':
new_string = new_string + ' '
else:
new_string = new_string + ' '
return new_string.strip()
def get_sentiment_scores(filename):
"""
(str) -> dict
Given the name of a file which contains a list of words
and their positive and negative weights, return a dictionary
storing this information as follows:
- the keys in the dict are the words
- the values associated with each key is a tuple of two floats,
where the first element is the positivity weight of this word,
and the second element is the negativity weight of this word
"""
d = {}
L = []
f = codecs.open(filename, "r", "utf-8")
for line in f:
if not line.startswith('#'):
x = line.strip()
x = line.split('\t')
key = x[2][:-1]
pos = x[0]
neg = x[1]
d[key] = (pos, neg)
sentiment_scores = d
return sentiment_scores
pass
def fix_file(filename):
''' (str -> list)
Adjusts the file to return a list of the words in the file.
'''
f = codecs.open(filename, "r", "utf-8")
L = []
final_string = ''.join(L)
for line in f:
L.append(normalize(line.strip()))
final_string = ''.join(L)
return final_string.split(' ')
def analyze_file(filename, sentiment_scores):
"""
(str, dict) -> tuple of three floats
Given a filename and a dict of sentiment scores, analyze the contents
of the file and figure out its total positivity, negativity and sentiment.
Return this in a tuple of floats where the first element is the total
positivity score as a ratio to total number of words in the file, the
second element is the total negativity as a ratio to total words, and
the third element is the total sentiment.
"""
i = 0
p = 0
n = 0
string_list = fix_file(filename)
while i < len(string_list):
if string_list[i] in sentiment_scores:
tup = sentiment_scores.get(string_list[i])
p = (p) + float(tup[0]) * 100
n = (n) + float(tup[1]) * 100
i = i + 1
else:
i = i + 1
return ((p) / (len(string_list)), (n) / (len(string_list)), (p / (len(string_list)) - n / (len(string_list))))
if __name__ == "__main__":
sentiment_scores = get_sentiment_scores("sentiment_scores.txt")
while True:
filename = input("Enter a filename: ")
pos, neg, total = analyze_file(filename, sentiment_scores)
print("Total positivity score: {:.3f}, \nTotal negativity score: {:.3f}, \nTotal sentiment score: {:.3f}".format(pos, neg, total))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.