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
|
---|---|---|---|---|---|---|
405f28e905884cfdd2c11810b27c76f69cc636b9 | nueadkie/cs362-inclass-activity-4 | /wordcount.py | 287 | 3.875 | 4 | def calc(input_string):
# Special case for empty string, or if just whitespace.
if len(input_string.strip()) == 0:
return 0
words = 1
# Remove any trailing and leading whitespace.
for char in input_string.strip():
if char == ' ':
words += 1
return words
|
08a4f34357da5a7063177e4996aa8cadf5c318c6 | hendritedjo/python_exercise | /exercise-list.py | 1,573 | 3.75 | 4 |
#1
hari = ['senin','selasa','rabu','kamis','jumat','sabtu','minggu']
try:
inputhari = input("Masukkan hari : ")
inputangka = int(input("Masukkan jumlah : "))
inputhari = inputhari.lower()
if (inputhari not in hari):
print("Nama hari yang anda masukkan salah")
else:
sisa = inputangka % 7
if (hari.index(inputhari)+sisa) > 6:
sisa = sisa + hari.index(inputhari) - 7
elif (hari.index(inputhari)+sisa < 0):
sisa = sisa + hari.index(inputhari) + 7
print("Hari ini hari {}. {} hari lagi adalah hari {}".format(inputhari.capitalize(),str(inputangka),hari[sisa].capitalize()))
except:
print("Jumlah yang anda masukkan salah")
'''
#2
kalimat = input("Masukkan kalimat : ")
for a in kalimat:
if a in ["0","1","2","3","4","5","6","7","8","9"]:
print("Tidak menerima angka")
break
else:
kalimat = kalimat.split()
if kalimat.isalpha():
for a in kalimat:
print(a[::-1], end=" ")
print("")
else:
#3
kata1 = input("Masukkan kata : ")
for a in kata1:
if a in ["0","1","2","3","4","5","6","7","8","9"]:
print("Tidak menerima angka")
break
else:
if kata1.isalpha():
kata2 = kata1[::-1]
if kata1.lower() == kata2.lower():
print("Kata tersebut {} merupakan Palindrome".format(kata1))
else:
print("Kata tersebut {} bukan merupakan Palindrome".format(kata1))
else:
print("Tidak menerima di luar alphabet")
''' |
33ab245a6da86e5d0d8c4e51d47762afa12f85a4 | hendritedjo/python_exercise | /exam-listspinner.py | 434 | 3.78125 | 4 | #Soal 2
list1 = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
def counterClockwise(num):
num1 = [[a for a in range(num[0][3], num[3][3]+1, 4)],
[a for a in range(num[0][2], num[3][2]+1, 4)],
[a for a in range(num[0][1], num[3][1]+1, 4)],
[a for a in range(num[0][0], num[3][0]+1, 4)]]
return num1
print(counterClockwise(list1)) |
a7ff689d33dad699ac7e270958cf4d841afb5453 | cathyxinxyz/Capstone_project_2 | /Top_K_terms.py | 3,289 | 3.515625 | 4 | # function to plot the top k most frequent terms in each class
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
import seaborn as sns
def Top_K_ngrams(k, ngram, df, text_col, class_col):
vect=TfidfVectorizer(ngram_range=(ngram,ngram))
vect.fit(df[text_col])
tfidf_df=pd.DataFrame(vect.transform(df[text_col]).toarray())
tfidf_df.columns=vect.get_feature_names()
top_K_ngrams_by_class=dict()
for v in df[class_col].value_counts().index:
freq_in_class=tfidf_df[df[class_col]==v].sum(axis=0).sort_values(ascending=False)
frac_in_class=freq_in_class/freq_in_class.sum()
top_K_ngrams_by_class[v]=frac_in_class[:k].index
print ('the top {} frequent {}-gram terms for class {}:'.format(k,ngram, v))
sns.barplot(y=frac_in_class[:k].index, x=frac_in_class[:k])
plt.ylabel('{}-gram terms'.format(ngram))
plt.xlabel('fraction')
plt.show()
return top_K_ngrams_by_class
# function to plot the top k most frequent nouns in each class
from nltk.tag.perceptron import PerceptronTagger
def Top_K_nouns(k, df, text_col, class_col, plot=False):
vect=TfidfVectorizer()
vect.fit(df[text_col])
tfidf_df=pd.DataFrame(vect.transform(df[text_col]).toarray())
tfidf_df.columns=vect.get_feature_names()
tfidf_T=tfidf_df.transpose()
tagger = PerceptronTagger()
tfidf_T['pos']=tagger.tag(tfidf_T.index)
tfidf_T=tfidf_T[tfidf_T['pos'].apply(lambda tup:tup[1] in ['NN','NNP','NNS','NNPS'])]
tfidf_df=tfidf_T.drop(['pos'], axis=1).transpose()
top_k_by_class=dict()
for v in df[class_col].value_counts().index:
freq_in_class=tfidf_df[df[class_col]==v].sum(axis=0).sort_values(ascending=False)
frac_in_class=freq_in_class/freq_in_class.sum()
top_k_by_class[v]=frac_in_class[:k].index
if plot:
print ('the top {} frequent nouns for class {}:'.format(k,v))
plt.figure(figsize=(5, 10))
sns.barplot(y=frac_in_class[:k].index, x=frac_in_class[:k])
plt.xlabel('fraction')
plt.show()
return (top_k_by_class)
from nltk.tag.perceptron import PerceptronTagger
def Top_K_verbs(k, df, text_col, class_col, plot=False):
vect=TfidfVectorizer()
vect.fit(df[text_col])
tfidf_df=pd.DataFrame(vect.transform(df[text_col]).toarray())
tfidf_df.columns=vect.get_feature_names()
tfidf_T=tfidf_df.transpose()
tagger = PerceptronTagger()
tfidf_T['pos']=tagger.tag(tfidf_T.index)
tfidf_T=tfidf_T[tfidf_T['pos'].apply(lambda tup:tup[1] in ['VB','VBD','VBG','VBN'])]
tfidf_df=tfidf_T.drop(['pos'], axis=1).transpose()
top_k_by_class=dict()
for v in df[class_col].value_counts().index:
freq_in_class=tfidf_df[df[class_col]==v].sum(axis=0).sort_values(ascending=False)
frac_in_class=freq_in_class/freq_in_class.sum()
top_k_by_class[v]=frac_in_class[:k].index
if plot:
print ('the top {} frequent nouns for class {}:'.format(k,v))
plt.figure(figsize=(5, 10))
sns.barplot(y=frac_in_class[:k].index, x=frac_in_class[:k])
plt.xlabel('fraction')
plt.show()
return (top_k_by_class) |
4557143f73a37747a488bf808e8814b888c2e169 | jerome-gingras/Advent-of-code-2015 | /day9/day9.py | 982 | 3.53125 | 4 | from itertools import permutations
import sys
f = open("C:\\Dev\\Advent-of-code-2015\\day9\\input.txt", "r")
line = f.readline()
cities = set()
distances = dict()
while line != "":
(source, _, destination, _, distance) = line.split()
cities.add(source)
cities.add(destination)
if source in distances:
distances[source][destination] = int(distance)
else:
distances[source] = dict([(destination, int(distance))])
if destination in distances:
distances[destination][source] = int(distance)
else:
distances[destination] = dict([(source, int(distance))])
line = f.readline()
shortest_path = sys.maxint
longest_path = 0
for items in permutations(cities):
distance = sum(map(lambda x, y: distances[x][y], items[:-1], items[1:]))
shortest_path = min(shortest_path, distance)
longest_path = max(longest_path, distance)
print "Shortest path is " + str(shortest_path)
print "Longuest path is " + str(longest_path) |
8c75b7197feda25b715d4f2d0641e7e02cffa1e4 | Alexionder/TheLifeOfAlex | /Exploration time/items.py | 1,183 | 3.890625 | 4 | class Sword():
def __init__(self, durability, strength, name):
self.durability = durability
self.strength = strength
self.name = name
def inspect(self):
print "This sword has " + str(self.durability) + " durability and " + str(self.strength) + " strength."
class Axe():
def __init__(self, durability, strength, name):
self.durability = durability
self.strength = strength
self.name = name
def inspect(self):
print "This axe has " + str(self.durability) + " durability and " + str(self.strength) + " strength."
class HPbottle():
def __init__(self, amount):
self.amount = amount
if amount < 15:
self.name = "weak health potion"
elif amount < 30:
self.name = "moderate health potion"
else:
self.name = "strong health potion"
def inspect(self):
print "This potion can heal you for " + str(self.amount) + "."
class Food():
def __init__(self, amount, name):
self.amount = amount
self.name = name
def inspect(self):
print "This food can satisfy you hunger for " + str(self.amount) + "."
|
6d52f092b0a8d34724125240a931caf789b0870a | AsleyR/Tic-Tac-Toe-Game---Python | /TTT2.py | 11,984 | 4 | 4 | from tkinter import *
#Note: Add choice to be X or O for PvC
new_gamemode = False
play_as_O = False
player = ""
computer = "X"
x = 0 #General purpose variable for operations
board = {0: " ", 2: " ", 3: " ",
4: " ", 5: " ", 6: " ",
7: " ", 8: " ", 9: " "}
def turn():
global computer
global player
global x
x = x + 1
if new_gamemode == False:
if (x % 2) == 0:
player = "O"
else:
player = "X"
elif new_gamemode == True and play_as_O == False:
computer = "O"
player = "X"
elif new_gamemode == True and play_as_O == True:
computer = "X"
player = "O"
return player
#Left as a debug tool
def print_board():
print(board[0] + "|" + board[2] + "|" + board[3])
print("-+-+-")
print(board[4] + "|" + board[5] + "|" + board[6])
print("-+-+-")
print(board[7] + "|" + board[8] + "|" + board[9])
print("\n")
def free_space(position):
if board[position] == " ":
return True
else:
return False
def place_mark(position, mark):
if free_space(position) == True:
board[position] = mark
print_board()
if check_win() and who_won(mark):
if winner_label["text"] == "":
winner_label["text"] = mark + " Wins!"
print(mark + " WINS!")
if check_draw() == True:
if winner_label["text"] == "":
winner_label["text"] = "Draw!"
print("DRAW!")
else:
print("Space is used.")
def check_draw():
for key in board.keys():
if (board[key] == " "):
return False
return True
def check_win():
#Check horizontal
if board[0] == board[2] and board[0] == board[3] and board[0] != " ":
return True
elif board[4] == board[5] and board[4] == board[6] and board[4] != " ":
return True
elif board[7] == board[8] and board[7] == board[9] and board[7] != " ":
return True
#Check vertical
elif board[0] == board[4] and board[0] == board[7] and board[0] != " ":
return True
elif board[2] == board[5] and board[2] == board[8] and board[2] != " ":
return True
elif board[3] == board[6] and board[3] == board[9] and board[3] != " ":
return True
#Check diagonal
elif board[0] == board[5] and board[0] == board[9] and board[0] != " ":
return True
elif board[3] == board[5] and board[3] == board[7] and board[3] != " ":
return True
else:
return False
def who_won(mark):
#Check horizontal
if board[0] == board[2] and board[0] == board[3] and board[0] == mark:
return True
elif board[4] == board[5] and board[4] == board[6] and board[4] == mark:
return True
elif board[7] == board[8] and board[7] == board[9] and board[7] == mark:
return True
#Check vertical
elif board[0] == board[4] and board[0] == board[7] and board[0] == mark:
return True
elif board[2] == board[5] and board[2] == board[8] and board[2] == mark:
return True
elif board[3] == board[6] and board[3] == board[9] and board[3] == mark:
return True
#Check diagonal
elif board[0] == board[5] and board[0] == board[9] and board[0] == mark:
return True
elif board[3] == board[5] and board[3] == board[7] and board[3] == mark:
return True
else:
return False
#I don't know why, but board is sorted like 0, 2, 3, 4.... Had to rename board[1] to board[0]
# to avoid KeyErrors
def computer_move():
best_score = -800
best_move = 0
for key in board.keys():
if (free_space(key) == True):
board[key] = computer
score = minimax(0, False)
board[key] = " "
if (score > best_score):
best_score = score
best_move = key
if best_move == 0 and free_space(best_move) == True:
btn1.config(text=computer, bg="grey70", state=DISABLED)
elif best_move == 2 and free_space(best_move) == True:
btn2.config(text=computer, bg="grey70", state=DISABLED)
elif best_move == 3 and free_space(best_move) == True:
btn3.config(text=computer, bg="grey70", state=DISABLED)
elif best_move == 4 and free_space(best_move) == True:
btn4.config(text=computer, bg="grey70", state=DISABLED)
elif best_move == 5 and free_space(best_move) == True:
btn5.config(text=computer, bg="grey70", state=DISABLED)
elif best_move == 6 and free_space(best_move) == True:
btn6.config(text=computer, bg="grey70", state=DISABLED)
elif best_move == 7 and free_space(best_move) == True:
btn7.config(text=computer, bg="grey70", state=DISABLED)
elif best_move == 8 and free_space(best_move) == True:
btn8.config(text=computer, bg="grey70", state=DISABLED)
elif best_move == 9 and free_space(best_move) == True:
btn9.config(text=computer, bg="grey70", state=DISABLED)
place_mark(best_move, computer)
return
def minimax(depth, isMaximizing):
if (who_won(computer)):
return 1
elif (who_won(player)):
return -1
elif (check_draw()):
return 0
if (isMaximizing):
best_score = -800
for key in board.keys():
if (free_space(key) == True):
board[key] = computer
score = minimax(depth + 1, False)
board[key] = " "
if (score > best_score):
best_score = score
return best_score
else:
best_score = 800
for key in board.keys():
if (free_space(key) == True):
board[key] = player
score = minimax(depth + 1, True)
board[key] = " "
if (score < best_score):
best_score = score
return best_score
def comp_turn():
if new_gamemode == True:
computer_move()
def reset():
global x
x = 0
for i in board.keys(): #i is a random variable
board[i] = " "
print_board()
winner_label["text"] = ""
btn1.config(text="", bg="lightgrey", state=NORMAL)
btn2.config(text="", bg="lightgrey", state=NORMAL)
btn3.config(text="", bg="lightgrey", state=NORMAL)
btn4.config(text="", bg="lightgrey", state=NORMAL)
btn5.config(text="", bg="lightgrey", state=NORMAL)
btn6.config(text="", bg="lightgrey", state=NORMAL)
btn7.config(text="", bg="lightgrey", state=NORMAL)
btn8.config(text="", bg="lightgrey", state=NORMAL)
btn9.config(text="", bg="lightgrey", state=NORMAL)
def click1():
turn()
if new_gamemode == True:
place_mark(0, player)
comp_turn()
else:
place_mark(0, player)
btn1["text"] = player
btn1["state"] = DISABLED
btn1["bg"] = "grey70"
def click2():
turn()
if new_gamemode == True:
place_mark(2, player)
comp_turn()
else:
place_mark(2, player)
btn2["text"] = player
btn2["state"] = DISABLED
btn2["bg"] = "grey70"
def click3():
turn()
if new_gamemode == True:
place_mark(3, player)
comp_turn()
else:
place_mark(3, player)
btn3["text"] = player
btn3["state"] = DISABLED
btn3["bg"] = "grey70"
def click4():
turn()
if new_gamemode == True:
place_mark(4, player)
comp_turn()
else:
place_mark(4, player)
btn4["text"] = player
btn4["state"] = DISABLED
btn4["bg"] = "grey70"
def click5():
turn()
if new_gamemode == True:
place_mark(5, player)
comp_turn()
else:
place_mark(5, player)
btn5["text"] = player
btn5["state"] = DISABLED
btn5["bg"] = "grey70"
def click6():
turn()
if new_gamemode == True:
place_mark(6, player)
comp_turn()
else:
place_mark(6, player)
btn6["text"] = player
btn6["state"] = DISABLED
btn6["bg"] = "grey70"
def click7():
turn()
if new_gamemode == True:
place_mark(7, player)
comp_turn()
else:
place_mark(7, player)
btn7["text"] = player
btn7["state"] = DISABLED
btn7["bg"] = "grey70"
def click8():
turn()
if new_gamemode == True:
place_mark(8, player)
comp_turn()
else:
place_mark(8, player)
btn8["text"] = player
btn8["state"] = DISABLED
btn8["bg"] = "grey70"
def click9():
turn()
if new_gamemode == True:
place_mark(9, player)
comp_turn()
else:
place_mark(9, player)
btn9["text"] = player
btn9["state"] = DISABLED
btn9["bg"] = "grey70"
def new_game():
reset()
if play_as_O == True:
pvc2()
def pvp():
global new_gamemode
global play_as_O
new_gamemode = False
play_as_O = False
reset()
#Player go first and plays as X
def pvc1():
global new_gamemode
global play_as_O
new_gamemode = True
play_as_O = False
reset()
#Player go second and plays as O
def pvc2():
global new_gamemode
global play_as_O
reset()
new_gamemode = True
play_as_O = True
turn()
comp_turn()
print_board()
window = Tk()
window.title("Tic Tac Toe")
window.geometry("300x300")
window.resizable(False, False)
window.columnconfigure(0, weight=1)
main_label = Label(text="Tic Tac Toe", pady= 10, font=("Helvetica", 15))
main_label.pack()
frameM = Frame(window)
frameM.pack()
frame1 = Frame(window)
frame1.pack()
frame2 = Frame(window)
frame2.pack()
frame3 = Frame(window)
frame3.pack()
btn1 = Button(frame1, text="", bg="lightgrey", width= 8, pady= 15, font=("Helvetica", 10), command=click1)
btn1.pack(side=LEFT)
btn2 = Button(frame1, text="", bg="lightgrey", width= 8, pady= 15, font=("Helvetica", 10), command=click2)
btn2.pack(side=LEFT)
btn3 = Button(frame1, text="", bg="lightgrey", width= 8, pady= 15, font=("Helvetica", 10), command=click3)
btn3.pack(side=LEFT)
btn4 = Button(frame2, text="", bg="lightgrey", width= 8, pady= 15, font=("Helvetica", 10), command=click4)
btn4.pack(side=LEFT)
btn5 = Button(frame2, text="", bg="lightgrey", width= 8, pady= 15, font=("Helvetica", 10), command=click5)
btn5.pack(side=LEFT)
btn6 = Button(frame2, text="", bg="lightgrey", width= 8, pady= 15, font=("Helvetica", 10), command=click6)
btn6.pack(side=LEFT)
btn7 = Button(frame3, text="", bg="lightgrey", width= 8, pady= 15, font=("Helvetica", 10), command=click7)
btn7.pack(side=LEFT)
btn8 = Button(frame3, text="", bg="lightgrey", width= 8, pady= 15, font=("Helvetica", 10), command=click8)
btn8.pack(side=LEFT)
btn9 = Button(frame3, text="", bg="lightgrey", width= 8, pady= 15, font=("Helvetica", 10), command=click9)
btn9.pack(side=LEFT)
winner_label = Label(text="", fg="red", pady= 10, font=("Helvetica", 13))
winner_label.pack()
menu_bar = Menu(frameM)
window.config(menu = menu_bar)
game_menu = Menu(menu_bar, tearoff=0)
option_menu = Menu(menu_bar, tearoff=0)
change_sign_menu = Menu(option_menu, tearoff=0)
menu_bar.add_cascade(label="Game", menu=game_menu)
menu_bar.add_cascade(label="Options", menu=option_menu)
game_menu.add_command(label="New Game", command=new_game)
game_menu.add_separator()
game_menu.add_command(label="Exit", command=window.quit)
option_menu.add_command(label="PvP", command=pvp)
option_menu.add_cascade(label="PVC", menu=change_sign_menu)
change_sign_menu.add_command(label="Play as X", command=pvc1)
change_sign_menu.add_command(label="Play as O", command=pvc2)
window.mainloop() |
fa7ee8f13255f1ceda3e28c58c427c84bf81817f | LionrChen/GraphFeaturesExtraction | /graph/graph.py | 7,797 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'ChenSir'
__mtime__ = '2019/7/16'
# code is far away from bugs with the god animal protecting
I love animals. They taste delicious.
┏┓ ┏┓
┏┛┻━━━┛┻┓
┃ ┃
┃ ┳┛ ┗┳ ┃
┃ ┻ ┃
┗━┓ ┏━┛
┃ ┗━━━┓
┃神兽保佑 ┣┓
┃ 永无BUG! ┏┛
┗┓┓┏━━┳┓┏┛
┃┫┫ ┃┫┫
┗┻┛ ┗┻┛
"""
from graphBase import GraphBase
from node import Node
from edge import Edge
class Graph(GraphBase):
def __init__(self, directed=False, weighted=False):
super().__init__(directed, weighted)
def add_node(self, value):
try:
new_node = Node(value)
self.nodes[value] = new_node
return new_node
except:
print("Invalid vertex id '{}', may be exits.".format(value))
def add_nodes(self, node_list):
for node_name in node_list:
new_node = Node(node_name)
try:
self.nodes[node_name] = new_node
except:
print("Invalid vertex id '{}', may be exits.".format(node_name))
def add_edge(self, sour, terg):
try:
if not self.weighted:
new_edge = Edge(False, sour, terg)
self.edges.append(new_edge)
self.update(new_edge)
except:
print("The edge already exits.")
def add_weight_edge(self, weight, sour, terg):
try:
if self.weighted:
new_edge = Edge(weight, sour, terg)
self.edges.append(new_edge)
self.update(new_edge)
except:
print("The edge already exits.")
def add_edges(self, edges):
""" Example to [(from, to)]
"""
for edge in edges:
try:
if not self.weighted:
new_edge = Edge(False, edge[0], edge[1])
self.edges.append(new_edge)
self.update(new_edge)
except:
print("The edge already exits.")
def update(self, edge):
self.nodes.get(edge.head).indegree += 1
self.nodes.get(edge.tail).outdegree += 1
self.nodes.get(edge.tail).nexts.append(edge.head)
self.nodes.get(edge.tail).edges.append(edge)
def subgraph(self, nodes):
""" Here nodes is list about node's value.
"""
new_graph = Graph()
for node_key in nodes:
node = Node(self.nodes.get(node_key).value)
neighbors = list(set(self.nodes.get(node_key).nexts).intersection(set(nodes)))
node.nexts = neighbors
new_graph.nodes[node_key] = node
return new_graph
def jaccard_coefficient(self, node1, node2):
""" This coefficient use to measure the ratio between the number of two node's
common neighbors and them total neighbors.
"""
first_node = self.nodes.get(node1).nexts
second_node = self.nodes.get(node2).nexts
common_friends = list(set(first_node).intersection(set(second_node)))
division = first_node.__len__() + second_node.__len__()
if division is not 0:
return format(common_friends.__len__() / division, '.6f')
def total_neighbors(self, node1, node2):
""" If node1 and node2 are exits, them total neighbors are the add between the
node1 and node2.
"""
first_node = self.nodes.get(node1).nexts
second_node = self.nodes.get(node2).nexts
print("The number of total neighbors of Node {} and {} is {}.".format(node1, node2,
first_node.__len__() + second_node.__len__()))
return first_node.__len__() + second_node.__len__()
def preference_attachment(self, node1, node2):
""" the probability that two users yield an association in certain period of
time is proportional to the product of the number of one user's neighborhoods
and that of another's neighborhoods.
"""
first_node = self.nodes.get(node1).nexts
second_node = self.nodes.get(node2).nexts
print("The score of preference attachment of Node {} and {} is {}.".format(node1, node2,
first_node.__len__() * second_node.__len__()))
return first_node.__len__() * second_node.__len__()
def friend_measure(self, node1, node2):
""" the more connections their neighborhoods have with each other, the higher the
chances the two users are connected in a social network.
"""
first_node = self.nodes.get(node1).nexts
second_node = self.nodes.get(node2).nexts
F_fm = 0
for node_key in first_node:
x_node = self.nodes.get(node_key)
for node_key_sec in second_node:
# y_node = self.nodes.get(node_key_sec)
if node_key is not node_key_sec and node_key_sec not in x_node.nexts:
F_fm += 1
print("The score of friend measure of Node {} and {} is {}.".format(node1, node2, F_fm))
return F_fm
def SCC_graph(graph):
""" calculate the number of strongly connected components within neighborhood-subgraph.
First generate 1-dimensional neighborhood-subgraph with source and target node.
a sample of graph, use dict to store graph.
G = {
'a': {'b', 'c'},
'b': {'d', 'e', 'i'},
'c': {'d'},
'd': {'a', 'h'},
'e': {'f'},
'f': {'g'},
'g': {'e', 'h'},
'h': {'i'},
'i': {'h'}
}
"""
nodes = graph.nodes
# reverse graph
def reverse_graph(nodes):
re_graph = dict()
for key in nodes.keys():
node = nodes.get(key)
node.reset_attr()
re_graph[key] = node
# reverse edge
for key in nodes.keys():
for nei in nodes[key].nexts:
re_graph[nei].nexts.append(key)
return re_graph
# gain a sequence sorted by time
def topo_sort(nodes):
res = []
S = set()
# Depth-first traversal/search
def dfs(nodes, u):
if u in S:
return
S.add(u)
for v in nodes[u].nexts:
if v in S:
continue
dfs(nodes, v)
res.append(u)
# check each node was leave out
for u in nodes.keys():
dfs(nodes, u)
res.reverse()
return res
# gain singe strongly connected components with assigns start node
def walk(nodes, s, S=None):
if S is None:
s = set()
Q = []
P = dict()
Q.append(s)
P[s] = None
while Q:
u = Q.pop()
for v in nodes[u].nexts:
if v in P.keys() or v in S:
continue
Q.append(v)
P[v] = P.get(v, u)
return P
# use to record the node of strongly connected components
seen = set()
# to store scc
scc = []
GT = reverse_graph(nodes)
for u in topo_sort(nodes):
if u in seen:
continue
C = walk(GT, u, seen)
seen.update(C)
scc.append(sorted(list(C.keys())))
print("The number of strongly connected components of graph is {}.".format(scc.__len__()))
return scc
|
67fe9255295af578c9721b7847299ebe185cf5b8 | Pasquale-Silv/Improving_Python | /Python Programming language/DataCampPractice/Personal_programs/Input_E_rapprString.py | 676 | 4.34375 | 4 | # La funzione input(...) restituisce un tipo stringa, anche se viene passato un numero int o float
# Puoi rappresentare una stringa concatenata in diversi modi:
# 1- Concatenandola con + e convertendo i numeri con str() ----> 'numero: ' + str(3.6)
# 2- Utilizzando la virgola( , ) come separatore tra stringhe e numeri o altre stringhe: 'numero' , ':' , 5
# 3- Mediante Formatted-String Literal ----> f"Il numero è { 5 }"
print('numero: ' + str(3.6))
print('numero', ':', 5)
print(f"Il numero è { 5 }")
print(f"numero uno: { 10 }, numero2: { 22 }, loro somma: { 10 + 22 } \n")
prova = input('Inserisci qualcosa: \n')
print(f"Hai inserito '{ prova }', complimenti!'") |
7de1ba91ebbb95ade3f54e652560b2c65369b1e3 | Pasquale-Silv/Improving_Python | /Python Programming language/DataCampPractice/Corso_CISCO_netacad/Strings_in_Python/s8_center_method.py | 720 | 4.25 | 4 | # The one-parameter variant of the center() method makes a copy of the original string,
# trying to center it inside a field of a specified width.
# The centering is actually done by adding some spaces before and after the string.
# Demonstrating the center() method
print('[' + 'alpha'.center(10) + ']')
print('[' + 'Beta'.center(2) + ']')
print('[' + 'Beta'.center(4) + ']')
print('[' + 'Beta'.center(6) + ']')
# The two-parameter variant of center() makes use of the character from the second argument,
# instead of a space. Analyze the example below:
print('[' + 'gamma'.center(20, '*') + ']')
s1 = "Pasquale".center(30)
print(s1)
print("length:", len(s1))
s2 = "Pasquale Silvestre".center(50, "-")
print(s2)
print(len(s2))
|
27598f79de97818823527e23f3969c27959f8702 | Pasquale-Silv/Improving_Python | /Python Programming language/DataCampPractice/Corso_CISCO_netacad/Strings_in_Python/s15_split.py | 617 | 4.46875 | 4 | # The
# split()
# method does what it says - it splits the string and builds a list of all detected substrings.
# The method assumes that the substrings are delimited by whitespaces - the spaces don't take part in the operation,
# and aren't copied into the resulting list.
# If the string is empty, the resulting list is empty too.
# Demonstrating the split() method
print("phi chi\npsi".split())
# Note: the reverse operation can be performed by the join() method.
print("-------------------------")
# Demonstrating the startswith() method
print("omega".startswith("meg"))
print("omega".startswith("om"))
|
0c10af8575d97394bbcb9c2363a82fe424df2bd0 | Pasquale-Silv/Improving_Python | /Python Programming language/DataCampPractice/Corso_CISCO_netacad/integers_octal_exadecimal.py | 1,053 | 4.53125 | 5 | # If an integer number is preceded by an 0O or 0o prefix (zero-o),
# it will be treated as an octal value. This means that the number must contain digits taken from the [0..7] range only.
# 0o123 is an octal number with a (decimal) value equal to 83.
print(0o123)
# The second convention allows us to use hexadecimal numbers.
# Such numbers should be preceded by the prefix 0x or 0X (zero-x).
# 0x123 is a hexadecimal number with a (decimal) value equal to 291. The print() function can manage these values too.
print(0x123)
print(4 == 4.0)
print(.4)
print(4.)
# On the other hand, it's not only points that make a float. You can also use the letter e.
# When you want to use any numbers that are very large or very small, you can use scientific notation.
print(3e8)
print(3E8)
# The letter E (you can also use the lower-case letter e - it comes from the word exponent)
# is a concise record of the phrase times ten to the power of.
print("----------------------------------------------------------")
print(0.0000000000000000000001)
print(1e-22)
|
212a0b661d06ce21a27e70d775accdbddb3a8b1e | Pasquale-Silv/Improving_Python | /Python Programming language/DataCampPractice/Corso_CISCO_netacad/number_literals.py | 907 | 3.703125 | 4 | # Python 3.6 has introduced underscores in numeric literals,
# allowing for placing single underscores between digits and after base specifiers for improved readability.
# This feature is not available in older versions of Python.
"""
If you'd like to quickly comment or uncomment multiple lines of code,
select the line(s) you wish to modify and use the following keyboard shortcut:
CTRL + / -------------------------> (Windows)
or
CMD + / ------------------- ---> (Mac OS).
It's a very useful trick, isn't it?
"""
print(11_111_111 * 2)
print(11111111)
print(11_111_111)
print("/" == "/") # Col 7 e non
print("------------------------------------")
leg_a = float(input("Input first leg length: "))
leg_b = float(input("Input second leg length: "))
hypo = (leg_a**2 + leg_b**2) ** .5
print("Hypotenuse length is", hypo)
print("Concateno:", 33, hypo, 3.33, True)
|
fd80e5cecb0c723cf52c16e6b112648476b37388 | Pasquale-Silv/Improving_Python | /Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part1/Nested_Functions/NestedFunc1.py | 548 | 4.1875 | 4 | # Define three_shouts
def three_shouts(word1, word2, word3):
"""Returns a tuple of strings
concatenated with '!!!'."""
# Define inner
def inner(word):
"""Returns a string concatenated with '!!!'."""
return word + '!!!'
# Return a tuple of strings
return (inner(word1), inner(word2), inner(word3))
# Call three_shouts() and print
print(three_shouts('a', 'b', 'c'))
print()
tupla_prova = three_shouts('Pasquale', 'Ignazio', 'Laura')
print(tupla_prova)
var1, var2, var3 = tupla_prova
print(var1, var2, var3) |
15d42320cb2c5217991e7b6202330c9e5e5fa414 | Pasquale-Silv/Improving_Python | /Python Programming language/DataCampPractice/Corso_CISCO_netacad/Strings_in_Python/s7.py | 458 | 4.4375 | 4 | # Demonstrating the capitalize() method
print('aBcD'.capitalize())
print("----------------------")
# The endswith() method checks if the given string ends with the specified argument and returns True or False,
# depending on the check result.
# Demonstrating the endswith() method
if "epsilon".endswith("on"):
print("yes")
else:
print("no")
t = "zeta"
print(t.endswith("a"))
print(t.endswith("A"))
print(t.endswith("et"))
print(t.endswith("eta"))
|
ada5381cdf4e7ce76bd87b681ea3e233ab83fbc2 | Pasquale-Silv/Improving_Python | /Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part1/Part_III/reduce_and_LambdaFunc.py | 439 | 3.9375 | 4 | # Import reduce from functools
from functools import reduce
# Create a list of strings: stark
stark = ['robb', 'sansa', 'arya', 'brandon', 'rickon']
# Use reduce() to apply a lambda function over stark: result
result = reduce(lambda item1, item2: item1 + item2, stark)
# Print the result
print(result)
listaNum = [3, 5, 2, 10]
somma = reduce(lambda x, y: x + y, listaNum) # Printa la somma di tutti i numeri della lista
print(somma) |
a959f8c5d7ec65d50fea6f6ca640524a04e13501 | Pasquale-Silv/Improving_Python | /Python Programming language/DataCampPractice/Regular_Expressions_in_Python/Positional_String_formatting/Positional_formatting1.py | 812 | 4.15625 | 4 | # positional formatting ------> .format()
wikipedia_article = 'In computer science, artificial intelligence (AI), sometimes called machine intelligence, ' \
'is intelligence demonstrated by machines, ' \
'in contrast to the natural intelligence displayed by humans and animals.'
my_list = []
# Assign the substrings to the variables
first_pos = wikipedia_article[3:19].lower()
second_pos = wikipedia_article[21:44].lower()
# Define string with placeholders
my_list.append("The tool '{}' is used in '{}'")
# Define string with rearranged placeholders
my_list.append("The tool '{1}' is used in '{0}'") # That's why it's called 'POSITIONAL FORMATTING'
# Use format to print strings
for my_string in my_list:
print(my_string.format(first_pos, second_pos))
|
968bee9c854610fd5799d875dae04d4227c74cfe | Pasquale-Silv/Improving_Python | /Python Programming language/DataCampPractice/Functions and packages/PackagesInPython/MathPackageInPython.py | 653 | 4.34375 | 4 | """
As a data scientist, some notions of geometry never hurt. Let's refresh some of the basics.
For a fancy clustering algorithm,
you want to find the circumference, C, and area, A, of a circle.
When the radius of the circle is r, you can calculate C and A as:
C=2πr
A=πr**2
To use the constant pi, you'll need the math package.
"""
# Import the math package
import math
# Definition of radius
r = 0.43
# Calculate C
C = 2*r*math.pi
# Calculate A
A = math.pi*r**2
# Build printout
print("Circumference: " + str(C))
print("Area: " + str(A))
print()
print(math.pi)
print("PiGreco dal package math = " + str(math.pi)) |
22d7fa76f904a0ac5061338e9f90bb3b9afd5d41 | Pasquale-Silv/Improving_Python | /Python Programming language/DataCampPractice/Corso_CISCO_netacad/Lists/list4.py | 288 | 3.734375 | 4 | # A four-column/four-row table - a two dimensional array (4x4)
table = [[":(", ":)", ":(", ":)"],
[":)", ":(", ":)", ":)"],
[":(", ":)", ":)", ":("],
[":)", ":)", ":)", ":("]]
print(table)
print(table[0][0]) # outputs: ':('
print(table[0][3]) # outputs: ':)'
|
370b98c1d042d5e7f9d98bcac7c72a2eb080385d | Pasquale-Silv/Improving_Python | /Python Programming language/DataCampPractice/Personal_programs/RandomNum.py | 165 | 3.5625 | 4 | import random
print(random.randint(0, 100))
num_int_rand = random.randint(20, 51)
print(num_int_rand)
for i in range(0, 10):
print(random.randint(-2100,1001)) |
7c92ab969dc4636d99ebe3db1de310dff9dd8727 | Pasquale-Silv/Improving_Python | /Python Programming language/DataCampPractice/Working_with_relational_databases_in_Python/sqliteDB4.py | 729 | 3.625 | 4 | from sqlalchemy import create_engine
import pandas as pd
engine = create_engine('sqlite:///DB4.sqlite')
# Open engine in context manager
# Perform query and save results to DataFrame: df
with engine.connect() as con: # come con file non hai bisogno di chiudere la connessione in questo modo.
rs = con.execute('SELECT LastName, Title FROM Employee;')
df = pd.DataFrame(rs.fetchmany(size=3)) # fetchmany(size=3) considere aolamente le prime 3 righe, fetchall() considera tutto.
df.columns = rs.keys() # Va a settore il nome delle colonne del DF, altrimenti solo indici.
# Print the length of the DataFrame df
print(len(df))
# Print the head of the DataFrame df
print(df.head())
|
100d7f48a899c20b52ee5479eccd7422a87aa667 | Pasquale-Silv/Improving_Python | /Python Programming language/DataCampPractice/Python_Lists/Python_Lists11.py | 707 | 4.125 | 4 | # you can also remove elements from your list. You can do this with the del statement:
# Pay attention here: as soon as you remove an element from a list, the indexes of the elements that come after the deleted element all change!
x = ["a", "b", "c", "d"]
print(x)
del(x[1]) # del statement
print(x)
areas = ["hallway", 11.25, "kitchen", 18.0,
"chill zone", 20.0, "bedroom", 10.75,
"bathroom", 10.50, "poolhouse", 24.5,
"garage", 15.45]
print(areas)
del(areas[-4:-2])
print(areas)
"""
The ; sign is used to place commands on the same line. The following two code chunks are equivalent:
# Same line
command1; command2
# Separate lines
command1
command2
""" |
459188df05fa37b88c1e811b37fae93e096f1ce0 | Pasquale-Silv/Improving_Python | /Python Programming language/SoloLearnPractice/ListsInPython/ProofList.py | 305 | 4.03125 | 4 | number = 3
things = ["string", 0, [1, 2, number], 4.56]
print(things[1])
print(things[2])
print(things[2][2])
print("----------------------")
str = "Hello world!"
print(str[6])
print(str[6-1])
print(str[6-2])
print("--------------------------")
nums = [1, 2, 3]
print(nums + [4, 5, 6])
print(nums * 3) |
1ff840fef8bc267fcf37268800d9bd29dd86f521 | Pasquale-Silv/Improving_Python | /Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part2/Generators_and_GENfunc_yield/GEN2.py | 462 | 4.34375 | 4 | # [ LIST COMPREHENSION ]
# ( GENERATOR )
# Recall that generator expressions basically have the same syntax as list comprehensions,
# except that it uses parentheses () instead of brackets []
# Create generator object: result
result = (num for num in range(31))
# Print the first 5 values
print(next(result))
print(next(result))
print(next(result))
print(next(result))
print(next(result))
# Print the rest of the values
for value in result:
print(value)
|
b3a3caf850d4fffd6f0864bfc293175ab28fd76c | Pasquale-Silv/Improving_Python | /Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part1/Part_I/modulo_builtins.py | 820 | 4.09375 | 4 | import builtins
print(builtins)
print(dir(builtins))
prova = input('Cerca nel modulo builtins: \n')
if prova in dir(builtins):
print('La parola', prova, 'è presente nel modulo builtins.')
else:
print('La parola ' + prova + ' non è stata trovata.')
"""
Here you're going to check out Python's built-in scope, which is really just a built-in module called builtins.
However, to query builtins, you'll need to import builtins 'because the name builtins is not itself built in...
No, I’m serious!' (Learning Python, 5th edition, Mark Lutz). After executing import builtins in the IPython Shell,
execute
dir(builtins)
to print a list of all the names in the module builtins.
Have a look and you'll see a bunch of names that you'll recognize!
Which of the following names is NOT in the module builtins?
""" |
42582cf388cabe7d0ea2e243f171b6608d772443 | Pasquale-Silv/Improving_Python | /Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part1/Part_III/Filter_and_LambdaFunc.py | 395 | 4.0625 | 4 | # Create a list of strings: fellowship
fellowship = ['frodo', 'samwise', 'merry', 'pippin', 'aragorn', 'boromir', 'legolas', 'gimli', 'gandalf']
# Use filter() to apply a lambda function over fellowship: result
result = filter(lambda stringa: len(stringa) > 6, fellowship)
# Convert result to a list: result_list
print(result)
result_list = list(result)
# Print result_list
print(result_list) |
25f9ce7108bc60f7825425c67c7bb1366f184c91 | SGiuri/hamming | /hamming.py | 465 | 3.59375 | 4 | def distance(strand_a, strand_b):
# Check equal Lenght
if len(strand_a) != len(strand_b):
raise ValueError("Equal length not verified")
# set up a counter of differences
hamming_difference = 0
# checking each letter
for j in range(len(strand_a)):
# if there is a difference, increasing the hamming difference by 1
if strand_a[j] != strand_b[j]:
hamming_difference += 1
return hamming_difference
|
ec1a49268a967c2d28c39a06e42f8af02f4d4c26 | zomgroflmao/1st_lesson | /vat.py | 162 | 3.578125 | 4 | def get_vat(price, vat_rate):
vat = price / 100 * vat_rate
price_no_vat = price - vat
print(price_no_vat)
price1 = 100
vat_rate = 18
get_vat(price1, vat_rate1) |
04ce4745d854c9d712ac5089ad94573fe287fae9 | anjiboini/anji_python_games | /anji_tkinter_database.py | 672 | 3.5625 | 4 | from tkinter import *
from PIL import ImageTk,Image
import sqlite3
root = Tk()
root.title('Wellcome to India')
root.iconbitmap('D:/anji_python software/python/anji tkinter projects/resources/thanu1.ico')
root.geometry("400x400")
#Databases
#Create a Databases or connect one
conn = sqlite3.connect('address_book.db')
#Create cursor
c = conn.cursor()
#Create table
c.execute(""" CREATE TABLE addresses (
first_name text,
last_name text,
address text,
city text,
state text,
zipcode integer)""")
conn.commit()
conn.close()
root.mainloop() |
21f6b720fa94adb9330322339200a7c8a7e246f6 | anjiboini/anji_python_games | /anji_tkinter_databaseusing1.py | 1,603 | 4 | 4 | from tkinter import *
from PIL import ImageTk,Image
import sqlite3
root = Tk()
root.title('Wellcome to India')
root.iconbitmap('D:/anji_python software/python/anji tkinter projects/resources/thanu1.ico')
root.geometry("400x400")
#Databases
# Create a Databases or connect one
conn = sqlite3.connect('address_book8.db')
# Create cursor
c = conn.cursor()
#Create table
''''
c.execute(""" CREATE TABLE addresses (
first_name text,
last_name text)""")
'''
def submit():
# Create a Databases or connect one
conn = sqlite3.connect('address_book8.db')
# Create cursor
c = conn.cursor()
#Insert into table
c.execute("INSERT INTO addresses VALUES (:f_name, :l_name )",
{ 'f_name': f_name.get(),
'l_name': l_name.get(),})
conn.commit()
conn.close()
#clear the text boxes
f_name.delete(0, END)
l_name.delete(0, END)
#Create Query function
#create text boxes
f_name = Entry(root,width=30)
f_name.grid(row=0,column=1,padx=20,pady=(10,0))
l_name = Entry(root,width=30)
l_name.grid(row=1,column=1,padx=20)
#create text boxes labels
f_name_label= Label(root, text="First Name").grid(row=0,column=0,padx=20,pady=(10,0))
l_name_name_label= Label(root, text="Last Name").grid(row=1,column=0,padx=20)
#Create Submit Button
submit_btn = Button(root, text="Add Record to Database", command=submit)
submit_btn.grid(row=3, column=0,columnspan=2,padx=10,pady=10,ipadx=100)
conn.commit()
conn.close()
root.mainloop()
|
e478ccc2cff10e77e0a85ce42f68bb822ee61d5e | anjiboini/anji_python_games | /anji_tkinte_01.py | 2,561 | 3.765625 | 4 | from tkinter import *
#..............................................
#root=Tk()
#theLable=Label(root,text="Hi anji how r u")
#theLable.pack()
#root.mainloop()
#............................................
#one=Label(root, text="One", bg="red",fg="white")
#one.pack()
#two=Label(root, text="Two", bg="yellow",fg="black")
#two.pack(fill=X)
#three=Label(root, text="Three", bg="blue",fg="white")
#three.pack(side=LEFT,fill=Y)
#topFrame=Frame(root)
#topFrame.pack()
#bottomFrame=Frame(root)
#bottomFrame.pack(side=BOTTOM)
#.......................................
#button1 = Button(topFrame, text="Thanu sri",fg="red",bg="green",padx=50,pady=50,font=300)
#button2 = Button(topFrame, text="Yesha sri",fg="blue",bg="green",padx=50,pady=50,font=300)
#button3 = Button(topFrame, text="Yesha sri",fg="blue",bg="green",padx=50,pady=50,font=300)
#button4 = Button(topFrame, text="Yesha sri",fg="blue",bg="green",padx=50,pady=50,font=300)
#button5 = Button(bottomFrame, text="Yesha sri",fg="blue",bg="green",padx=50,pady=50,font=300)
#button6 = Button(bottomFrame, text="Yesha sri",fg="blue",bg="green",padx=50,pady=50,font=300)
#button1.pack(side=LEFT)
#button2.pack(side=LEFT)
#button3.pack(side=LEFT)
#button4.pack(side=LEFT)
#button5.pack(side=BOTTOM)
#button6.pack(side=BOTTOM)
#root.mainloop()
#.........................................
#lable1=Label(root, text="Name")
#lable2=Label(root, text="Password")
#entry1=Entry(root)
#entry2=Entry(root)
#lable1.grid(row=0,column=1)
#lable2.grid(row=1,column=1)
#entry1.grid(row=0,column=2)
#entry2.grid(row=1,column=2)
#c = Checkbutton(root, text="Keep me logged in")
#c.grid(columnspan=2)
#root.mainloop()
#.............................................................
#def printName():
# print("Hello thanu sri whate are you doing")
#button1=Button(root, text="Click here", command=printName)
#button1.pack()
#root.mainloop()
#.................................................
class PressButtons:
def __init__(self,master):
frame=Frame(master)
frame.pack()
self.printButton=Button(frame, text="print message", command=self.printMessage)
self.printButton.pack(side=LEFT)
self.quitButton = Button(frame, text="Quit", command=frame.quit)
self.quitButton.pack(side=LEFT)
def printMessage(self):
open("wow it is working")
root= Tk()
b = PressButtons(root)
root.mainloop()
#.........................................................................
|
4f7496a27ea1bc08d7252326cea3ee912857e39a | Angelagoodboy/Python_classifyCustomer | /Main.py | 430 | 3.546875 | 4 | #调用Python文件并且实现输入不同参数对应不同分类组合
import sys
#实现脚本上输入参数
def main():
try:
Type=sys.argv[1]
FileInputpath=sys.argv[2]
FileOutpupath=sys.argv[3]
if Type=='-r':
# 调用客户模块:
except IndexError as e:
print("输入的错误参数")
if __name__ == '__main__':
print('helloworld')
main()
|
0e73fa953efc7182444e9bd7148d489b48f92ef6 | sksuharsh1611/py18thjune2018 | /code21june.py | 1,418 | 3.515625 | 4 | #!/usr/bin/python2
import time,webbrowser,commands
menu='''
press 1: To check current date and time:
press 2: To scan all your Mac Address in your current cOnnected Network:
press 3: To shutdown your machine after 15 minutes:
press 4: To search something on Google:
press 5: To logout your current machine:
press 6: To shutdown all cOnnected system in your current Network:
press 7: To Update status on your Facebook:
press 8: To list Ip Addresses of given Website:
'''
print menu
choice=raw_input("Enter your choice:")
if choice == '1' :
print "current date and time is : ",time.ctime()
elif choice == '2' :
x=commands.getoutput('cat /sys/class/net/*/address')
print x
elif choice == '3' :
print "Your system is being shutting down after 15 minutes"
commands.getoutput("sudo shutdown +1")
elif choice == '4' :
find=raw_input("enter your query : ")
webbrowser.open_new_tab("https://www.google.com/search?q="+find)
elif choice == '5' :
print "logging out from your current machine: "
commands.getoutput("exit")
#elif choice == '6' :
elif choice == '7':
print "update status in facebook"
username=raw_input("enter your username : ")
passwd=raw_input("enter your password : ")
webbrowser.open_new_tab("https://touch.facebook.com/login/")
elif choice == '8' :
web=raw_input("enter your website : ")
ip=commands.getoutput("host "+web)
print ip
else :
print "Invalid OPtion"
|
0f62b89ad95ca5e8bee9b211dc1b5bb6f940234b | melodyquintero/python-challenge | /PyPoll/main.py | 2,291 | 3.9375 | 4 | # Import Modules for Reading raw data
import os
import csv
# Set path for file
csvpath = os.path.join('raw_data','election_data_1.csv')
# Lists to store data
ID = []
County = []
Candidate = []
# Open and read the CSV, excluding header
with open(csvpath, newline="") as csvfile:
next(csvfile)
csvreader = csv.reader(csvfile, delimiter=",")
for row in csvreader:
# Add ID data to the list
ID.append(row[0])
# Add County data to the list
County.append(row[1])
# Add Candidate data to the list
Candidate.append(row[2])
# Count total number of votes
Votes_count = len(ID)
# Import collections to group votes by different candidates
import collections
counter=collections.Counter(Candidate)
# With the results of collections, place candidate names and their votes to lists
candidate_name =list(counter.keys())
candidate_votes = list(counter.values())
# list candidate votes percentage to store data
candidate_percent = []
# calculate and formate votes percentage by candidates
for i in range(len(candidate_name)):
candidate_i_percent='{0:.1%}'.format(float(candidate_votes[i])/Votes_count)
# add candidates percentage to the list
candidate_percent.append(candidate_i_percent)
# locate the index of highest votes and apply on candidate names to find the winner
Winner_index = candidate_votes.index(max(candidate_votes))
Winner = candidate_name[Winner_index]
# Print results on terminal
print("Election Results")
print("-"*30)
print("Total Votes: "+ str(Votes_count))
print("-"*30)
for j in range(len(candidate_name)):
print(str(candidate_name[j])+": "+ str(candidate_percent[j])+ " ("+str(candidate_votes[j])+")")
print("-"*30)
print("Winner: "+str(Winner))
print("-"*30)
# Export Text File
with open("Election_Results.txt", "w+") as f:
f.write("Election Results"+"\n")
f.write("-"*30+"\n")
f.write("Total Votes: "+ str(Votes_count)+"\n")
f.write("-"*30+"\n")
for j in range(len(candidate_name)):
f.write(str(candidate_name[j])+": "+ str(candidate_percent[j])+ " ("+str(candidate_votes[j])+")"+"\n")
f.write("-"*30+"\n")
f.write("Winner: "+str(Winner)+"\n")
f.write("-"*30+"\n") |
cf7dbbfe0ffb7790452be0d9b0734d0f1886ce5b | Vishal19914/VishalClock | /test_clock.py | 473 | 3.625 | 4 | import unittest
from clock import Clock_Angle
class TestClock(unittest.TestCase):
def test_check_angle(self):
ca= Clock_Angle(3,0)
angle= ca.checkValues()
self.assertEqual(angle,90, "Angle is 90")
def test_check_range(self):
ca= Clock_Angle(23213,4324)
result= ca.checkValues()
self.assertEqual(result,"Incorrect hour and minutes value", "incorrect values" )
if __name__ == '__main__':
unittest.main() |
0d77b125701172493da106652ef0aa30551cc60c | tuxnani/open-telugu | /tamil/tscii2utf8.py | 626 | 3.546875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (C) 2013 Muthiah Annamalai
from sys import argv, exit
import tamil
def usage():
return u"tscii2utf8.py <filename-1> <filename-2> ... "
if __name__ == u"__main__":
if not argv[1:]:
print( usage() )
exit(-1)
for fname in argv[1:]:
try:
with open(fname) as fileHandle:
output = tamil.tscii.convert_to_unicode( fileHandle.read() )
print( output )
except Exception as fileOrConvException:
print(u"tscii2utf8 error - file %s could not be processed due to - %s"%(fname,str(fileOrConvException)))
|
7e8298e4733a357b535d473549a4d467b9a7f354 | dilithjay/Double-Blank-NPuzzle-AStar | /Python/a_star.py | 2,988 | 3.515625 | 4 | from enum import Enum
from queue import PriorityQueue
from time import time
from utils import get_blanks, get_heuristic_cost_manhattan, get_heuristic_cost_misplaced, get_2d_array_copy, swap
BLANK_COUNT = 2
DIRECTION_COUNT = 4
dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]
opposite_dirs = ('down', 'up', 'right', 'left')
class HeuristicType(Enum):
MISPLACED = 1
MANHATTAN = 2
# A node in the search tree
class State:
def __init__(self, config, blanks, cost, path):
self.config = config
self.blanks = blanks
self.cost = cost
self.path = path
def __lt__(self, other):
return self.cost <= other.cost
class AStarSearch:
def __init__(self, start, goal, cost_type=HeuristicType.MISPLACED):
self.goal = goal
self.n = len(start)
self.cost_type = cost_type
state = State(start, get_blanks(start), self.get_cost(start), ())
self.open_set = PriorityQueue()
self.open_set.put(state)
self.closed_set = set()
self.iter_count = 0
self.time = 0
def search(self) -> str:
"""
Perform A* search over possibilities of steps.
:return: Path as a string. Format: (1st number to move, move direction (as word)), (2nd number, direction),...
"""
start_time = time()
while not self.open_set.empty():
self.iter_count += 1
state = self.open_set.get()
config = state.config
if str(config) not in self.closed_set:
self.closed_set.add(str(config))
else:
continue
path = state.path
# if cost from heuristic is 0 (goal achieved)
if state.cost == len(path):
self.time = time() - start_time
return ",".join(path)
for i in range(BLANK_COUNT):
blank = state.blanks[i]
for j in range(DIRECTION_COUNT):
r, c = blank[0] + dirs[j][0], blank[1] + dirs[j][1]
if 0 <= r < self.n and 0 <= c < self.n and config[r][c] != '-':
mat = get_2d_array_copy(config)
swap(mat, blank, (r, c))
cost = self.get_cost(mat)
path_new = path + (f"({mat[blank[0]][blank[1]]},{opposite_dirs[j]})",)
self.open_set.put(State(mat, [state.blanks[i - 1]] + [[r, c]], cost + len(path_new), path_new))
return "Failed"
def get_cost(self, config):
"""
Get the cost of the given configuration as per the chosen heuristic.
:param config: Configuration matrix as a 2D list.
:return: Cost of the input configuration
"""
if self.cost_type == HeuristicType.MISPLACED:
return get_heuristic_cost_misplaced(config, self.goal)
# self.cost_type == HeuristicType.MANHATTAN:
return get_heuristic_cost_manhattan(config, self.goal)
|
0b03516098b1e064bad91970b932624408fe53fc | ryanmp/project_euler | /p056.py | 875 | 4.0625 | 4 | '''
A googol (10^100) is a massive number: one followed by one-hundred zeros;
100^100 is almost unimaginably large: one followed by two-hundred zeros.
Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of the form, ab, where a, b < 100, what is the maximum digital sum?
'''
def main():
n = 100
maximum_digit_sum = 0
for a in xrange(n):
for b in xrange(n):
new_sum = digit_sum(a**b)
maximum_digit_sum = max(new_sum, maximum_digit_sum)
return maximum_digit_sum
# in: an integer n
# out: the sum of the digits in n
# since Python supports arbitrarily large Ints, we should be just fine
def digit_sum(n):
return sum([int(i) for i in list(str(n))])
if __name__ == '__main__':
import boilerplate, time, resource
t = time.time()
r = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
boilerplate.all(main(), t, r)
|
6ab7b8b1135b74d6572efd98bb64f86f85e468ce | ryanmp/project_euler | /p076.py | 1,263 | 4.15625 | 4 | ''' counting sums
explanation via example:
n == 5:
4 + 1
3 + 2
3 + 1 + 1
2 + 2 + 1
2 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1
if sum == 5 -> there are 6 different combos
'''
def main():
return 0
# how many different ways can a given number be written as a sum?
# note: combinations, not permutations
def count_sum_reps(n):
''' my gut tells me that this can be formulated as a math problem...
let's first see if we can detect the pattern:
1 -> 1
2 -> 1
3 -> 1+2,
1+1+1: 2
4 -> 1+3,
2+2,2+1+1,
1+1+1+1: 4
5 -> 6
6 -> 5+1,
4+2, 4+1+1,
3+3, 3+2+1, 3+1+1+1,
2+2+2, 2+2+1+1, 2+1+1+1+1,
1+1+1+1+1+1 : 10
7 -> 6+1
5+2 5+1+1
4+3 4+2+1 4+1+1+1
3+3+1 3+2+2 3+2+1+1 3+1+1+1+1
2+2+2+1 2+2+1+1+1 2+1+1+1+1+1
(7x)+1
: 14
8 -> 7+1
6+2 6+1+1
5 = "3"
4 = "4"
3+3+2 3+3+1+1 3+2+2+1 3+2+1+1+1 3+(5x)+1 "5"
2+2+2+2 ... "4"
"1"
: 19
9 ->
yikes, I'm seeing the emergence of a pattern, n-1 rows. growing by +1
descending.. until it reaches the corner,
but i would need to do several more in order to see the pattern on the bottom
rows (after the corner), assuming there is a pattern
'''
return 'not finished yet'
if __name__ == '__main__':
import boilerplate, time
boilerplate.all(time.time(),main())
|
905044cf0b3bbe51124477458e02b069ee72eb0f | ryanmp/project_euler | /p034.py | 1,037 | 3.828125 | 4 | '''
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
'''
import math
f = {}
for i in xrange(0,10):
f[i] = math.factorial(i)
def main():
# hm... still pretty slow... there's gotta be some tricks to speed this one up
n = 2540160 # since 9!*7 = 2540160
all_passing_numbers = []
for i in xrange(3, n):
if is_a_digit_factorial(i):
all_passing_numbers.append(i)
return sum(all_passing_numbers)
'''
def is_a_digit_factorial(n):
arr = [math.factorial(int(i)) for i in str(n)]
return (n == sum(arr))
'''
def is_a_digit_factorial(n):
arr = [int(i) for i in str(n)]
arr.sort(reverse=True)
result = 0
for i in arr:
result += f[i]
if result > n:
return False
return n == result
if __name__ == '__main__':
import boilerplate, time, resource
t = time.time()
r = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
boilerplate.all(main(), t, r)
|
4918127d5c7331402a9aceb8288071c0de80766b | ryanmp/project_euler | /p005.py | 628 | 3.796875 | 4 | '''
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
'''
def main():
divisors = [11, 13, 14, 16, 17, 18, 19, 20]
smallest = 2520
while(True):
passes = True
for i in divisors:
if smallest%i != 0:
passes = False
break
if (passes):
return smallest
else:
smallest += 2520
if __name__ == '__main__':
import boilerplate, time, resource
t = time.time()
r = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
boilerplate.all(main(), t, r)
|
067beb1bcbc592f4a362d68cd4423eee877b094d | ryanmp/project_euler | /p017.py | 1,437 | 3.875 | 4 | '''
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there
are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words,
how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two)
contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and"
when writing out numbers is in compliance with British usage.
'''
d = {1:3, 2:3, 3:5, 4:4, 5:4, 6:3, 7:5, 8:5, 9:4, 10:3, 11:6, 12:6, 13:8, 14:8, 15:7,
16:7, 17:9, 18:8, 19:8, 20:6, 30:6, 40:5, 50:5, 60:6, 70:7, 80:6, 90:6}
def main():
n = 1000
# don't forget 'hundred' & 'and' (...that'll be in the conditional logic)
total_count = 0
for i in xrange(1,n+1):
total_count += get_char_cnt(i)
return total_count
def get_char_cnt(i):
if (i < 1 or i > 1000):
print "number range error: n must be in the range 1:1000"
count = 0
if (i == 1000):
count += 11
if (i>=100 and i<1000):
dig1 = (i/100)
count += d[dig1] + 7 # 7=hundred
i = i%100
if i != 0:
count += 3 # 3=and
if (i<100 and i>=20):
dig1 = (i/10)*10
count += d[dig1]
i = i%10
if (i>0 and i<20):
count += d[i]
return count
if __name__ == '__main__':
import boilerplate, time, resource
t = time.time()
r = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
boilerplate.all(main(), t, r)
|
8b6fbbd63e8a5acb92eb7a2481521cb646abbad6 | ryanmp/project_euler | /p024.py | 990 | 3.796875 | 4 | from itertools import permutations
from math import factorial as f
'''
Q: What is the millionth lexicographic permutation
of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
'''
def main():
p = permutations([0,1,2,3,4,5,6,7,8,9])
# lists them in lexicographic order by default
l = list(p)
ans = l[1000000-1] #Why the '-1'? l[0] is the first permutation
return join_ints(ans)
# input: array of ints
# e.g.: [1,2,3,4]
# output: a single int
# e.g.: 1234
def join_ints(l):
l = [str(i) for i in l] # to array of chars
as_str = ''.join(l)
return int(as_str)
if __name__ == '__main__':
import boilerplate, time, resource
t = time.time()
r = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
boilerplate.all(main(), t, r)
# ha! So originally I started with the math
# approach, thinking that the factorials would
# slow us down - but then I went back and tested
# the naive approach and it still takes less than
# 5 seconds... so that's what I have down here,
# for simplicity sake |
73f0378d6358f6fe1b7ae727facbd236f0134baa | ryanmp/project_euler | /p036.py | 611 | 3.6875 | 4 | '''
The decimal number, 585 = 1001001001 (binary), is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2
'''
def is_palindrome(n):
return str(n) == str(n)[::-1]
def main():
sum = 0
for i in xrange(1,int(1e6),2): # via logic, no even solutions - 01...10 (can't start with a zero)
if is_palindrome(i):
if (is_palindrome(bin(i)[2:])):
sum += i
return sum
if __name__ == '__main__':
import boilerplate, time, resource
t = time.time()
r = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
boilerplate.all(main(), t, r)
|
1ddf72a48f1db42476f00c50e39af6f523899ff6 | ankitjnyadav/LeetCode | /Strings/Reverse a String.py | 258 | 3.890625 | 4 | def reverseString(s) -> None:
"""
Do not return anything, modify s in-place instead.
"""
#Approach 1
s[:] = s[::-1]
#Approach 2
i = 0
for c in s[::-1]:
s[i] = c
i = i + 1
reverseString(["h","e","l","l","o"]) |
58667121c08c196a1c8141bcdbfce21154849de2 | ankitjnyadav/LeetCode | /30 Day Leet Coding Challenge/Day1 - First Bad Version/Day1.py | 751 | 3.53125 | 4 | '''
Problem Statement - https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/534/week-1-may-1st-may-7th/3316/
'''
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):
class Solution:
def isBadVersion(n):
if n >= 4:
return True
else:
return False
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1: return 1;
begin = 1
end = n
while begin < end:
mid = begin + (end - begin) / 2
if isBadVersion(mid):
end = mid
else:
begin = mid + 1
return int(begin) |
e9916dcf5e90daa9e263831aa893b333bf0b914d | andreea-munteanu/AI-2020 | /Lab2-3/Lab2.py | 9,042 | 3.578125 | 4 | import random
import sys
from queue import Queue
n = 12
m = 15
# n = 4
# m = 4
print("n = ", n, "m = ", m)
SIZE = (n, m) # n rows, m columns
if sys.getrecursionlimit() < SIZE[0] * SIZE[1] :
sys.setrecursionlimit(SIZE[0] * SIZE[1])
# if max recursion limit is lower than needed, adjust it
sys.setrecursionlimit(30000)
my_list = [0] * 55 + [1] * 45 # weights
# initializing labyrinth with 0s and 1s at weighted random
lab = list(list(random.choice(my_list) for i in range(SIZE[0])) for j in range(SIZE[1]))
# lab = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
# parameters: start, destination
def print_labyrinth(xs, ys, xd, yd) :
print(" ", end='')
for i in range(n) :
if i < n - 1 :
print(i, end=' ')
else :
print(i)
print(" ", end='')
for i in range(2 * n) :
print("_", end='')
print('')
for j in range(m) :
if j < 10 :
print(j, " |", end='')
else :
print(j, "|", end='')
# print("| ", end='')
for i in range(n) :
# start position
if i == xs and j == ys :
print('S', end=' ')
# destination
elif i == xd and j == yd :
print('D', end=' ')
# free cell
elif lab[j][i] == 0 :
print(' ', end=' ')
# obstacle
elif lab[j][i] == 1:
print('∎', end=' ')
else: # lab[i][j] == 2
print("+", end=' ')
print('|', j, end='\n')
"""_________________________________________________________________________________________________________
1. STATE
(xc , yc , xs , ys , xd , yd)
______________ _________ ___________
current state | start |destination|
# (xc, yc) - current position
# (xs, ys) - start position
# (xd, yd) - destination
_________________________________________________________________________________________________________
2. INITIALIZATION, INITIAL/FINAL STATE, CHECK_FINAL()
2.2. initial state: current position is start(xs, ys)
_________________________________________________________________________________________________________
"""
# 2.1.initialization + returning state
def initialState(xc, yc, xs, ys, xd, yd) :
xc = xs
yc = ys
return xc, yc, xs, ys, xd, yd
# 2.3. bool function checking whether a state is final
def finalState(xc, yc, xd, yd) :
return xc == xd and yc == yd
"""_________________________________________________________________________________________________________
3. TRANSITION FUNCTION
3.1. validation function (bool)
3.2. transition function returning current state
_________________________________________________________________________________________________________
"""
visited = []
# checks if (xc, yc) is within bounds
def inside(x, y) :
return 0 <= x < n and 0 <= y < m
# checks if (xc, yc) has been visited before: visited = False, not visited = true
def not_visited(x, y) :
for i in range(0, len(visited), 2) :
if visited[i] == x and visited[i + 1] == y :
return False
return True
def is_obstacle(x, y) :
if 0 <= x < n and 0 <= y < m:
return lab[x][y] == 1 or lab[x][y] == 2
else:
return True
# validate transition
def valid_transition(x, y) :
return inside(x, y) and not_visited(x, y) and is_obstacle(x, y) is False
def valid_transition_for_bkt(x, y):
if inside(x, y):
return is_obstacle(x, y) is False
return False
# TRANSITION FUNCTION (returns new state)
def transition(x_new, y_new, xs, ys, xd, yd) :
xc = x_new
yc = y_new
# current position (xc, yc) becomes (x_new, y_new)
return xc, yc, xs, ys, xd, yd
N, S, E, W = 1, 2, 4, 8
GO_DIR = {N : (0, -1),
S : (0, 1),
E : (1, 0),
W : (-1, 0)}
# dictionary with directions translated to digging moves
directions = [N, E, S, W]
"""_________________________________________________________________________________________________________
4. BACKTRACKING STRATEGY
_________________________________________________________________________________________________________
"""
BKT_stack = []
def print_BKT_path(xs, ys, xd, yd, stack) :
# stack contains indices (i,j) of the path --> requires step = 2
for i in range(0, len(stack), 2) :
# printing stack for check
print("(", stack[i], ", ", stack[i + 1], ")", end='; ')
lab[stack[i]][stack[i + 1]] = 2
# printing resulting path
print("\nBKT path: ")
print_labyrinth(xs, ys, xd, yd)
# changing matrix to original
for i in range(0, len(stack), 2) :
lab[stack[i]][stack[i + 1]] = 0
def BKT(xc, yc, xs, ys, xd, yd) :
# add current position to stack (for future printing)
BKT_stack.append(xc)
BKT_stack.append(yc)
# # mark cell as visited
lab[xc][yc] = 2 # path
# check if current state is final
if finalState(xc, yc, xd, yd) :
print('Found solution: ')
print_BKT_path(xs, ys, xd, yd, BKT_stack)
return True
# check the neighbouring cells
else :
for direction in directions : # N, E, W, S
# if transition has been made successfully, move to new position
sum_x = [GO_DIR[direction][1], xc]
sum_y = [GO_DIR[direction][0], yc]
# neighbour coordinates:
xc_new = sum(sum_x)
yc_new = sum(sum_y)
# if transition can be done, perform
if valid_transition_for_bkt(xc_new, yc_new) :
new_x, new_y, xs, ys, xd, yd = transition(xc_new, yc_new, xs, ys, xd, yd)
print("X: " , new_x , " ,Y: " , new_y)
if BKT(new_x, new_y, xs, ys, xd, yd):
return True
# complementary operations
lab[xc][yc] = 0
BKT_stack.pop()
BKT_stack.pop()
"""_________________________________________________________________________________________________________
5. BFS STRATEGY
_________________________________________________________________________________________________________
"""
class Point(object) :
def __init__(self, x, y) :
self.x = x
self.y = y
def BFS(xc, yc, xs, ys, xd, yd) :
q = Queue(maxsize=10000)
current_position = Point(xc, yc)
BFS_visited = set()
BFS_visited.add(current_position)
q.put(current_position)
while q :
u = q.get()
# calculate neighbours of u, check if they are visited
for dir in directions :
# directions N, S, E, W
sum_x = [GO_DIR[dir][1], u.x]
sum_y = [GO_DIR[dir][0], u.y]
# neighbour coordinates:
x_neigh = sum(sum_x)
y_neigh = sum(sum_y)
neighbour = Point(x_neigh, y_neigh)
list_queue = list(q.queue)
if neighbour not in list_queue :
BFS_visited.add(neighbour)
q.put(neighbour)
return BFS_visited
def print_BFS_path(xs, ys, xd, yd, BFS_visited) :
# BFS_visited() is a set containing the visited cells (in order)
initial_set = set()
for i in range(len(BFS_visited)) :
v = BFS_visited.pop()
initial_set.add(v)
lab[v.y][v.x] = 2 # path
# printing resulting path
print("\nBFS path: ")
print_labyrinth(xs, ys, xd, yd)
# changing matrix to original
for i in range(len(initial_set)) :
v = initial_set.pop()
lab[v.y][v.x] = 0
"""_________________________________________________________________________________________________________
5. HILLCLIMBING STRATEGY
_________________________________________________________________________________________________________
"""
def HillClimbing(xc, yc, xs, ys, xd, yd) :
print('nothing here :) ')
def main() :
print("\nChoose start(xs, ys) and destination (xd, yd): ", end='')
# xs, ys, xd, yd = input().split()
xs = input()
xs = int(xs)
ys = input()
ys = int(ys)
xd = input()
xd = int(xd)
yd = input()
yd = int(yd)
print("\nYour labyrinth is: ")
print_labyrinth(xs, ys, xd, yd)
# BKT
if not BKT(xs, ys, xs, ys, xd, yd):
print("Solution does not exist")
# BFS
# BFS(xs, ys, xs, ys, xd, yd)
# BFS_set = BFS(xs, ys, xs, ys, xd, yd)
# print_BFS_path(xs, ys, xd, yd, BFS_set)
if __name__ == "__main__" :
main()
|
8d6dd0da1e52152ebbec09722fae2d166dbcdd92 | urzyasar/Python | /OOPs/Encapsulation.py | 797 | 3.875 | 4 | #Encapsulation
class Bike:
def __init__(self,n):
self.name=n
self.__price=50,000 #private variable
def setprice(self,p):
self.__price=p
print(self.__price)
self.__display()
def __display(self):
print("Bike:{} and price:{}".format(self.name,self.__price))
def getdisplay(self):
self.__display()
obj=Bike("yamaha")
#print(obj.price) #cannot access from outside
#print(obj.__price)
#print(obj.name)
#trying to set price
obj.name="honda"
print(obj.name)
#obj.__price=100
obj.setprice(10000)
#print(obj.__price) #Again it cannot access from outside
#obj.__display() #cannot access this method from outside
obj.getdisplay()
|
240066b054c327e6a05ab214ce54466ba9b39d6f | gonzrubio/HackerRank- | /InterviewPracticeKit/Dictionaries_and_Hashmaps/Sherlock_and_Anagrams.py | 992 | 4.15625 | 4 | """Given a string s, find the number of pairs of substrings of s that are anagrams of each other.
1<=q<=10 - Number of queries to analyze.
2<=|s|<=100 - Length of string.
s in ascii[a-z]
"""
def sherlockAndAnagrams(s):
"""Return the number (int) of anagramatic pairs.
s (list) - input string
"""
n = len(s)
anagrams = dict()
for start in range(n):
for end in range(start,n):
substring = ''.join(sorted(s[start:end+1]))
anagrams[substring] = anagrams.get(substring,0) + 1
count = 0
for substring in anagrams:
freq = anagrams[substring]
count += freq*(freq-1) // 2
return count
def main():
#tests = ['abba','abcd','ifailuhkqq','kkkk']
#for test in tests: # 1<=q<=10
for _ in range(int(input())): # 1<=q<=10
print(sherlockAndAnagrams(input())) # 2<=|s|<=100
if __name__ == '__main__':
main()
|
77dcb824eb6c6197667cb94284a26a69eb445f11 | kirtivr/leetcode | /Leetcode/384.py | 1,036 | 3.703125 | 4 | from random import *
class Solution:
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.N = len(nums)
self.orig = list(nums)
self.nums = nums
def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
return self.orig
def shuffle(self):
"""
Returns a random shuffling of the array.
:rtype: List[int]
"""
used_nums = {}
for i in range(self.N):
idx = randint(0,self.N-1)
while used_nums.get(self.orig[idx]) != None:
idx = randint(0,self.N-1)
used_nums[self.orig[idx]] = True
self.nums[i],self.nums[idx] = self.nums[idx],self.nums[i]
return self.nums
# Your Solution object will be instantiated and called as such:
nums = [1,2,3,4,5]
obj = Solution(nums)
param_1 = obj.reset()
param_2 = obj.shuffle()
print(param_2)
|
66e4433f8027b693e555e2d80e888e69bb352834 | kirtivr/leetcode | /48.py | 972 | 3.828125 | 4 | class Solution:
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
N = len(matrix)
for i in range(N):
for j in range(N//2):
matrix[i][N-j-1],matrix[i][j] = matrix[i][j],matrix[i][N-j-1]
#print(matrix)
for i in range(N):
for j in range(N-i-1):
matrix[i][j], matrix[N-j-1][N-i-1]= matrix[N-j-1][N-i-1],matrix[i][j]
return matrix
if __name__ == '__main__':
matrix = [
[ 5, 1, 9,11,3],
[ 2, 4, 8,10,4],
[13, 3, 6, 7,8],
[15,14,12,16,14],
[20,21,22,23,24]
]
matrix = [
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
]
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
print(Solution().rotate(matrix))
|
31f66d99d35913915be26b0453125089675a58ca | kirtivr/leetcode | /Leetcode/3.py~ | 1,070 | 3.546875 | 4 | from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
left = 0
right = len(nums) - 1
def binary_search(start: int, end: int, target: int) -> int:
if start > end:
return -1
mid = start + (end - start)//2
if nums[mid] == target:
print(f'mid eq = %d', mid)
return mid
elif nums[mid] < target:
print(f'mid lt = %d end = %d', mid, end)
return binary_search(mid+1, end, target)
else:
print(f'mid gt = %d', mid)
return binary_search(start, mid-1, target)
if nums[-1] == target:
return len(nums)
while left < len(nums) - 1:
right = binary_search(left + 1, len(nums) - 1, target - nums[left])
if right != -1:
return [left + 1, right + 1]
left += 1
if __name__ == '__main__':
N = [-4,-1,0,3,10]
N = [-1]
N = [5,25,75]
target = 100
#N = [-7,-3,2,3,11]
#N = [-5,-3,-2,-1]
x = Solution()
print(x.twoSum(N, target))
|
da16b28f0fdb072a6eacba8883f72c16506ee9b0 | kirtivr/leetcode | /Leetcode/151.py | 1,165 | 3.65625 | 4 | class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
s = s.strip()
N = len(s)
ls = []
j = 0
for i in range(N):
if i > 0 and s[i] == ' ' and s[i-1] == ' ':
continue
else:
ls.append(s[i])
j += 1
s = ls
N = len(s)
def reverse(st,end):
mid = st + (int(end - st + 0.5)//2)
for i in range(mid - st):
s[st+i],s[end-i-1] = s[end-i-1],s[st+i]
reverse(0,N)
s.append(' ')
N += 1
prev = None
for i in range(N):
if s[i] == ' ':
if prev == None:
reverse(0,i)
else:
#print('reversing indices '+str(prev+1) +' to '+str(i))
reverse(prev+1,i)
prev = i
#print(s)
return "".join(s[:-1])
if __name__ == '__main__':
s = "the sky is blue"
s = "hi!"
#s = " "
#s = " a b "
print(Solution().reverseWords(s))
|
99e743c3548ab28186bb6f39b0c2f8ac666fe722 | kirtivr/leetcode | /121.py | 542 | 3.625 | 4 | class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
minNow = 1 << 30
maxProfit = 0
for i in range(len(prices)):
price = prices[i]
if price - minNow > maxProfit:
maxProfit = price - minNow
if price < minNow:
minNow = price
return maxProfit
if __name__ == '__main__':
# l = [7, 1, 5, 3, 6, 4]
l = [7,6,4,3,1]
print(Solution().maxProfit(l))
|
c630d50c2ba134e47f202ef7021270cd50198ea5 | kirtivr/leetcode | /Leetcode/33.py | 1,672 | 3.8125 | 4 | class Solution:
def findPivot(self, start, end, arr):
if start > end:
return 0
mid = start + (end - start)//2
#print(mid)
if mid != 0 and arr[mid-1] >= arr[mid]:
return mid
elif arr[mid] > arr[end]:
return self.findPivot(mid + 1, end, arr)
else:
return self.findPivot(start, mid - 1, arr)
def binSearch(self, start, end, arr, target):
if start > end:
return None
mid = start + (end - start)//2
# print(mid)
if arr[mid] == target:
print('!')
return mid
elif arr[mid] < target:
return self.binSearch(mid + 1, end, arr, target)
else:
return self.binSearch(start, mid - 1, arr, target)
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
N = len(nums)
idx = self.findPivot(0,N-1,nums)
# print(idx)
if N > 1:
if N == 0 or idx == 0 or nums[0] > target:
r = self.binSearch(idx,N-1,nums,target)
return r if r != None else -1
elif nums[0] == target:
return 0
else:
r = self.binSearch(0,idx-1,nums,target)
return r if r != None else -1
elif N == 1:
return 0 if nums[0] == target else -1
return -1
if __name__ == '__main__':
# nums = [4,5,6,7,0,1,2,3]
# target = 2
nums = [3,1]
target = 3
print(Solution().search(nums,target))
|
ccc20ea56a993806ec35c35eea33564c6bb83d1d | kirtivr/leetcode | /Leetcode/skip_lists_code_for_2407.py | 6,090 | 3.625 | 4 | from typing import List, Optional, Tuple, Dict
import heapq
import pdb
import ast
import sys
from dataclasses import dataclass, field
from functools import cmp_to_key
import time
class ListNode:
def __init__(self, val, idx):
self.idx = idx
self.val = val
self.next = None
self.prev = None
def __repr__(self) -> str:
return 'idx = ' + str(self.idx) + ' val = ' + str(self.val)
def AddAfter(node: ListNode, priority: int, idx: int):
if node == None:
return
new_node = ListNode(priority, idx)
next = node.next
new_node.prev = node
new_node.next = next
if next:
next.prev = new_node
node.next = new_node
def PrintList(head: Optional[ListNode]):
while head is not None:
print(f'idx = {head.idx} val = {head.val} next idx = {None if head.next == None else head.next.idx} prev idx = {None if head.prev == None else head.prev.idx}', end = "\n")
head = head.next
# Transition from greater than to less than.
def FindClosestSkipListNodeBefore(sl, priority):
#print('---------------------------')
if sl[0].val < priority:
return None
def searchBinary(sl, left, right):
nonlocal priority
if left > right:
return None
mid = left + (right - left)//2
# We found the right element when:
# there is only one element in sl and this is the one.
# or, mid.val <= priority < (mid + 1).val
node = sl[mid]
#print(f'cheking idx = {node.idx} val = {node.val} looking for val = {priority} left = {left} right = {right}')
#if node == None:
# print(f'Line 48 Invariant violated')
# for i in range(len(sl)):
# print(f'i = {i} sl[i] = {sl[i]}')
if (node.val > priority and mid + 1 >= right) or (node.val == priority):
return mid
if node.val >= priority and (mid + 1 <= right and sl[mid + 1].val <= priority):
return mid
elif node.val > priority:
return searchBinary(sl, mid + 1, right)
else:
return searchBinary(sl, left, mid - 1)
return searchBinary(sl, 0, len(sl) - 1)
def UpdateHead(ll, node):
old_head = ll
old_head.prev = node
node.next = old_head
return node
# Transition from greater than to less than.
def FindClosestLinkedListNodeBeforeStartingFrom(ll, priority):
prev = ll
while ll.next != None:
if ll.next.val <= priority:
return ll
prev = ll
ll = ll.next
return prev
def UpdateSkipListAfterIdx(sl, sl_idx):
# 0-----------------10------------------20
# 0-------new-------9-------------------19
# Something was added after sl_idx and before sl_idx + 1.
# Update all consequent pointers to point to the previous element.
print(f'old list = {sl} i = {sl_idx}')
for i in range(sl_idx + 1, len(sl)):
sl[i] = sl[i].prev
#print(f'new list = {sl}')
def MoveSkipListOneIndexForward(sl):
sl.append(None)
prev = sl[0]
for i in range(1, len(sl)):
temp = sl[i]
sl[i] = prev
prev = temp
class Solution:
def lengthOfLIS(self, nums: List[int], k: int) -> int:
lis = [1 for i in range(len(nums))]
sl = []
ll = None
#print(nums)
for i in range(0, len(nums)):
#print(f'lis = {lis}')
curr = ll
#PrintList(ll)
for j in range(0, i):
index = curr.idx
diff = nums[i] - nums[index]
#print(f'i = {i} j = {j} nums[i] = {nums[i]} lis[j] = {curr.val} k = {k} diff = {diff}')
if diff > 0 and diff <= k:
lis[i] = max(lis[i], lis[index] + 1)
break
curr = curr.next
# Insert to linked list after a binary search.
if len(sl) == 0 or ll == None:
# Seed the skip list with one element to begin with.
node = ListNode(lis[i], i)
ll = node
sl.append(node)
else:
sl_idx = FindClosestSkipListNodeBefore(sl, lis[i])
#print(f'sl_idx = {sl_idx}')
if sl_idx == None:
#if ll.val < lis[i]:
# print(f"Invariant violated ll.val = {ll.val} lis[{i}] = {lis[i]} skip list = {sl}")
# The current element is the smallest element.
MoveSkipListOneIndexForward(sl)
node = ListNode(lis[i], i)
sl[0] = node
ll = UpdateHead(ll, node)
#print(f'After adding to head new sl = {sl}')
else:
sl_node = sl[sl_idx]
#print(f'sl_idx = {sl_idx} sl_node = ( {sl_node} ) sl ={sl}')
ll_node = FindClosestLinkedListNodeBeforeStartingFrom(sl_node, lis[i])
AddAfter(ll_node, lis[i], i)
#PrintList(ll)
UpdateSkipListAfterIdx(sl, sl_idx)
if i != 0 and i % 512 == 0:
# Add a new skip list element, which will be the tail of the linked list.
if len(sl) > 0:
sl_node = sl[-1]
curr = sl_node
#print(f'going to append to skip list {sl}')
while curr != None and curr.next != None:
curr = curr.next
sl.append(curr)
#print(f'appended new skip list is {sl}')
#print('\n')
#print(lis)
max_lis = max(x for x in lis)
return max_lis
if __name__ == '__main__':
x = Solution()
start = time.time()
with open('2407_tc.text', 'r') as f:
n = ast.literal_eval(f.readline())
k = ast.literal_eval(f.readline())
#print(n)
#print(edges)
print(x.lengthOfLIS(n, k))
end = time.time()
elapsed = end - start
print(f'time elapsed: {elapsed}') |
c66a57a11aa2c998cb24ba707020f1a9f14eeefa | kirtivr/leetcode | /Leetcode/binary_indexed_tree_example.py | 1,663 | 4.03125 | 4 | # Python3 program to count inversions using
# Binary Indexed Tree
# Returns sum of arr[0..index]. This function
# assumes that the array is preprocessed and
# partial sums of array elements are stored
# in BITree[].
def getSum( BITree, index):
sum = 0 # Initialize result
# Traverse ancestors of BITree[index]
while (index > 0):
# Add current element of BITree to sum
sum += BITree[index]
# Move index to parent node in getSum View
index -= index & (-index)
return sum
# Updates a node in Binary Index Tree (BITree)
# at given index in BITree. The given value
# 'val' is added to BITree[i] and all of its
# ancestors in tree.
def updateBIT(BITree, n, index, val):
# Traverse all ancestors and add 'val'
while (index <= n):
# Add 'val' to current node of BI Tree
BITree[index] += val
# Update index to that of parent
# in update View
index += index & (-index)
# Returns count of inversions of size three
def getInvCount(arr, n):
invcount = 0 # Initialize result
# Find maximum element in arrays
maxElement = max(arr)
# Create a BIT with size equal to
# maxElement+1 (Extra one is used
# so that elements can be directly
# be used as index)
BIT = [0] * (maxElement + 1)
for i in range(n - 1, -1, -1):
invcount += getSum(BIT, arr[i] - 1)
updateBIT(BIT, maxElement, arr[i], 1)
return invcount
# Driver code
if __name__ =="__main__":
arr = [8, 4, 2, 1]
n = 4
print("Inversion Count : ",
getInvCount(arr, n)) |
c2e40105692a0a132ae3f2304e99d207d9cceae1 | kirtivr/leetcode | /Leetcode/62.py | 4,326 | 3.578125 | 4 | from typing import List, Optional, Tuple, Dict
import pdb
from functools import cmp_to_key
import time
def make_comparator(less_than):
def compare(x, y):
if less_than(x, y):
return -1
elif less_than(y, x):
return 1
else:
return 0
return compare
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
if m == 0 or n == 0:
return 0
paths = [[0 for column in range(n)] for row in range(m)]
prefill_column = n-1
for row in range(m):
paths[row][prefill_column] = 1
prefill_row = m-1
for col in range(n):
paths[prefill_row][col] = 1
for row in range(m-2, -1, -1):
for col in range(n-2, -1, -1):
paths[row][col] = paths[row + 1][col] + paths[row][col + 1]
return paths[0][0]
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m = len(obstacleGrid)
n = len(obstacleGrid[0]) if len(obstacleGrid) > 0 else 0
if m == 0 or n == 0 or obstacleGrid[-1][-1] == 1 or obstacleGrid[0][0] == 1:
return 0
paths = [[0 for column in range(n)] for row in range(m)]
prefill_col = n-1
for row in range(m):
if obstacleGrid[row][prefill_col] == 1:
paths[row][prefill_col] = -1
# Left is an obstacle, may be no way to get to cell
elif prefill_col >= 1 and obstacleGrid[row][prefill_col - 1] == 1 and (row == 0 or paths[row - 1][prefill_col] == -1):
# First row or row above is unreachable
print(f'setting 0 {row} {prefill_col}')
paths[row][prefill_col] = -1
else:
paths[row][prefill_col] = 1
bottom_block = None
for row in range(m):
if paths[row][prefill_col] == -1:
bottom_block = row
if bottom_block:
for row in range(bottom_block, -1, -1):
paths[row][prefill_col] = -1
prefill_row = m-1
#print(paths)
for col in range(n):
if obstacleGrid[prefill_row][col] == 1:
paths[prefill_row][col] = -1
#print(f'checking {prefill_row} {col}')
# Top is an obstacle - no way to get to the cell
elif (prefill_row >= 1 and obstacleGrid[prefill_row - 1][col] == 1) and (
col == 0 or paths[prefill_row][col - 1] == -1):
#print(f'setting 0 {prefill_row} {col}')
paths[prefill_row][col] = -1
# Can't go right, so can't go anywhere.
elif (col < n - 1 and obstacleGrid[prefill_row][col + 1] == 1):
paths[prefill_row][col] = -1
#print(f'{prefill_row} {col}')
else:
paths[prefill_row][col] = 1
right_block = None
for col in range(n):
if paths[prefill_row][col] == -1:
right_block = col
if right_block:
for col in range(right_block, -1, -1):
paths[prefill_row][col] = -1
#print(paths)
for row in range(m):
for col in range(n):
if obstacleGrid[row][col] == 1:
paths[row][col] = -1
for path in paths:
print(path)
print('---------------')
for row in range(m-2, -1, -1):
for col in range(n-2, -1, -1):
if paths[row][col] == -1:
continue
paths[row][col] = 0 if paths[row + 1][col] == -1 else paths[row + 1][col]
paths[row][col] += 0 if paths[row][col + 1] == -1 else paths[row][col + 1]
for path in paths:
print(path)
return paths[0][0] if paths[0][0] > 0 else 0
if __name__ == '__main__':
x = Solution()
start = time.time()
m = 3
n = 7
m = 3
n = 3
#print(x.uniquePaths(m, n))
obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
# obstacleGrid = [[0,0],[1,1],[0,0]]
#obstacleGrid = [[0,0,0,0,0],
# [0,0,0,0,1],
# [0,0,0,1,0],
# [0,0,1,0,0]]
print(x.uniquePathsWithObstacles(obstacleGrid))
end = time.time()
elapsed = end - start
print(f'time elapsed: {elapsed}') |
7d6ef70b32516d620199e1002228326e308d7893 | kirtivr/leetcode | /Leetcode/python_linked_list_template.py | 1,566 | 3.6875 | 4 | from typing import List, Optional, Tuple, Dict
from heapq import heappop, heappush, heapify
import pdb
import ast
import sys
from functools import cmp_to_key
import time
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __repr__(self):
return str(self.val)
def PrintList(head: Optional[ListNode]):
while head is not None:
print(head.val, end = " ")
head = head.next
print()
def MakeNodes(input: List[int]):
head = None
current = None
for i in range(len(input)):
new_node = ListNode(input[i], None)
if head == None:
head = new_node
current = new_node
continue
current.next = new_node
current = new_node
return head
def AddAfter(node: Optional[ListNode], to_add: int):
if node == None:
return
next = node.next
new_node = ListNode(to_add, next)
node.next = new_node
def Length(head: Optional[ListNode]):
out = 0
while head is not None:
out += 1
head = head.next
return out
def ElementAt(head: Optional[ListNode], idx: int):
out = 0
while head is not None:
out += 1
if idx == out:
return head
head = head.next
return None
'''if __name__ == '__main__':
x = Solution()
start = time.time()
nodes = MakeNodes([1, 2, 3, 4, 5])
PrintList(nodes)
end = time.time()
elapsed = end - start
print(f'time elapsed: {elapsed}')'''
|
a480c4a2c398cf11d06d5d67301e2ceeff4a7a1e | kirtivr/leetcode | /538.py | 754 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
'''
7
5 9
3 6 8 10
'''
class Solution(object):
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
def greaterTree(node, currentSum):
if node == None:
return 0
rSum = greaterTree(node.right, currentSum)
lSum = greaterTree(node.left, rSum + currentSum + node.val)
node.val = currentSum + node.val + rSum
return node.val+lSum+rSum
return root
|
a9e85bc4f8f394810469202a03beda752a0c8b4a | kirtivr/leetcode | /Leetcode/19.py | 1,008 | 3.703125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
slowPtr = None
fastPtr = head
temp = None
for i in range(n-1):
fastPtr = fastPtr.next
while fastPtr != None and fastPtr.next != None:
fastPtr = fastPtr.next
if slowPtr == None:
slowPtr = head
temp = slowPtr
else:
slowPtr = slowPtr.next
if slowPtr != None:
print(slowPtr.val)
if slowPtr != None:
if slowPtr.next != None:
slowPtr.next = slowPtr.next.next
elif head != None:
slowPtr = head.next
temp = slowPtr
return temp
|
9fe6f08df783fa4744f9dc2efe179019007d9966 | kirtivr/leetcode | /First attempts at/19.py | 1,205 | 3.5625 | 4 | #!/usr/bin/env python
import time
import pdb
import sys
import copy
from typing import List, TypedDict
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseLinkedList(self, head: Optional[ListNode]) -> bool:
if head.next == None:
return head
first = None
second = head
while second != None:
temp = second.next
second.next = first
first = second
second = temp
return first
def isPalindrome(self, head: Optional[ListNode]) -> bool:
temp = []
ptr = head
while ptr != None:
temp.append(ptr.val)
ptr = ptr.next
head = self.reverseLinkedList(head)
ptr = head
i = 0
while ptr != None:
if ptr.val != temp[i]:
return False
ptr = ptr.next
i += 1
return True
if __name__ == '__main__':
x = Solution()
print(x.minPathSum(grid))
end = time.time()
elapsed = end - start
print (f'time elapsed = {elapsed}')
|
e9b85cf35392d9b35970ccab0dab86c258aa1c37 | kirtivr/leetcode | /First attempts at/146.py | 5,777 | 3.78125 | 4 | #!/usr/bin/env python
import time
import pdb
import sys
import copy
from typing import List, TypedDict
class Element(object):
def __init__(self, key: int, val: int, prev, next):
self.key = key
self.value = val
self.prev = prev
self.next = next
def __repr__(self):
return f'{self.key}'
class LRUCache:
def __init__(self, capacity: int):
self.cache = {}
self.capacity = capacity
self.head = None
self.tail = None
def print_cache(self):
curr = self.head
while curr != None:
print(f'{curr}', end = " ")
curr = curr.next
if curr is not None:
print('->', end = " ")
print()
def print_cache_reverse(self):
print('reverse print')
curr = self.tail
while curr != None:
print(f'{curr}', end = " ")
curr = curr.prev
if curr is not None:
print('->', end = " ")
print()
def get(self, key: int) -> int:
print()
self.print_cache()
self.print_cache_reverse()
print(f'get key = {key} head = {self.head} tail = {self.tail} cache = {self.cache}')
if key in self.cache:
el = self.cache[key]
if self.head is not None and self.head.key != key:
# el will move. So set the pointers of el's previous and next elements accordingly.
preceding = el.prev
if el.prev:
el.prev.next = el.next
if el.next:
el.next.prev = el.prev
# Move element to front of the list
old_head = self.head
el.prev = None
el.next = old_head
old_head.prev = el
self.head = el
#print(f'done getting key = {key} head = {self.head} tail = {self.tail} cache = {self.cache}')
# Element is now head. If el was tail, el.prev is tail now
if self.tail is not None and self.tail.key == el.key and preceding is not None:
self.tail = preceding
self.tail.next = None
return el.value
return -1
def put(self, key: int, value: int) -> None:
print()
self.print_cache()
self.print_cache_reverse()
print(f'put key = {key} head = {self.head} tail = {self.tail} cache = {self.cache}')
el = None
new_tail = None
if key not in self.cache and len(self.cache) == self.capacity and self.tail != None:
#Evict LRU element.
print(f'Evicting {self.tail.key}')
del self.cache[self.tail.key]
new_tail = self.tail.prev
if key in self.cache:
el = self.cache[key]
el.value = value
else:
el = Element(key, value, None, None)
if self.head is not None and self.head.key != key:
print(f'updating head from {self.head} to {el}')
if key in self.cache:
# el will move. So set the pointers of el's previous and next elements accordingly.
preceding = el.prev
if el.prev:
el.prev.next = el.next
if el.next:
el.next.prev = el.prev
# Element is now head. If el was tail, el.prev is tail now
if self.tail is not None and self.tail.key == el.key and preceding is not None:
new_tail = preceding
el.next = self.head
self.head.prev = el
self.head = el
self.head.prev = None
self.cache[key] = el
if len(self.cache) == 1:
self.tail = el
elif len(self.cache) == 2:
self.tail = el.next
elif new_tail:
#Remove evicted element from cache.
self.tail = new_tail
self.tail.next = None
if __name__ == '__main__':
lRUCache = LRUCache(2);
#lRUCache.put(1, 1); # cache is {1=1}
#lRUCache.put(2, 2); # cache is {1=1, 2=2}
#print(lRUCache.get(1)); # return 1
#lRUCache.put(3, 3); # LRU key was 2, evicts key 2, cache is {1=1, 3=3}
#print(lRUCache.get(2)); # returns -1 (not found)
#lRUCache.put(4, 4); # LRU key was 1, evicts key 1, cache is {4=4, 3=3}
#print(lRUCache.get(1)); # return -1 (not found)
#print(lRUCache.get(3)); # return 3
#print(lRUCache.get(4)); # return 4
print(lRUCache.get(2))
lRUCache.put(2, 1); # cache is {1=1}
#print(lRUCache.get(1))
lRUCache.put(1, 1); # cache is {1=1, 2=2}
lRUCache.put(2, 3); # cache is {1=1, 2=2}
lRUCache.put(4, 1); # cache is {1=1, 2=2}
#print(lRUCache.get(1))
#print(lRUCache.get(2))
#print(lRUCache.get(1)); # return 1
#lRUCache.put(3, 3); # LRU key was 2, evicts key 2, cache is {1=1, 3=3}
#print(lRUCache.get(2)); # returns -1 (not found)
#lRUCache.put(4, 4); # LRU key was 1, evicts key 1, cache is {4=4, 3=3}
#print(lRUCache.get(1)); # return -1 (not found)
#print(lRUCache.get(3)); # return 3
#print(lRUCache.get(4)); # return 4
# x = Solution()
# start = time.time()
# print(x.minPathSum(grid))
# end = time.time()
# elapsed = end - start
# print (f'time elapsed = {elapsed}')
# Adversarial input:
# ["LRUCache","get","put","get","put","put","get","get"]
# [[2],[2],[2,6],[1],[1,5],[1,2],[1],[2]]
|
c8c217a9b1cbcc7f7058ac1c5d31c1774edf550c | kirtivr/leetcode | /170.py | 1,999 | 3.859375 | 4 | class TwoSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.hashmap = []
self.numbers = set()
def add(self, number):
"""
Add the number to an internal data structure..
:type number: int
:rtype: void
"""
index = hash(abs(number))%200000001
self.numbers.add(number)
if len(self.hashmap) > index:
self.hashmap[index].append(number)
else:
diff = index - len(self.hashmap) + 1
while diff > 0:
self.hashmap.append([])
diff -= 1
self.hashmap[index].append(number)
def find(self, value):
"""
Find if there exists any pair of numbers which sum is equal to the value.
:type value: int
:rtype: bool
"""
if value == 1467164459:
print(self.hashmap)
# print(value)
def evaluate(curr,diff,index,diff_index):
if (curr == diff):
egg = 0
if len(self.hashmap[index]) >= 2:
for y in self.hashmap[index]:
if y == diff:
egg += 1
if egg >= 2:
return True
elif diff_index < len(self.hashmap) and len(self.hashmap[diff_index]) >= 1:
for y in self.hashmap[diff_index]:
if y == diff:
return True
return False
for i in self.numbers:
index = hash(abs(i))%200000001
for curr in self.hashmap[index]:
diff = value-curr
diff_index = hash(abs(diff))
if evaluate(curr,diff,index,diff_index):
return True
return False
|
79cd77f09d5b0c796dd4744cd60756c735bf5105 | kirtivr/leetcode | /70.py | 429 | 3.640625 | 4 | class Solution(object):
def tryClimb(self, n, steps):
if n in steps:
return steps[n]
return steps[n-1]+steps[n-2]
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
steps = {}
steps[0] = 0
steps[1] = 1
steps[2] = 2
for i in range(2,n+1):
steps[i] = self.tryClimb(i,steps)
return steps[n]
|
1a7b2f86630f2409b8100d4bc6dc040b657c3d03 | kirtivr/leetcode | /56.py | 1,173 | 3.640625 | 4 | class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
def __str__(self):
return(str(self.start) + ' ' + str(self.end))
class Solution(object):
def mergeInt(self, intv1, intv2):
return Interval(intv1.start,max(intv1.end, intv2.end))
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: int
"""
# Sort the intervals by starting time
sortIntervals = sorted(intervals, key=lambda interval : interval.start)
mergedInts = []
numInt = len(sortIntervals)
i = 0
while i < numInt:
cInt = sortIntervals[i]
for j in range(i+1,numInt):
nInt = sortIntervals[j]
if cInt.end >= nInt.start or cInt.end >= nInt.end:
cInt = self.mergeInt(cInt,nInt)
i = j
mergedInts.append(cInt)
i = i + 1
return mergedInts
il = [[1,3],[2,6],[8,10],[15,18]]
intv = [ Interval(item[0],item[1]) for item in il ]
Solution().merge(intv)
|
b854946978b0c35cb74f63eae02ea1a2aeed0967 | zwilhelmsen/regex-tool | /regex-tool.py | 4,451 | 3.75 | 4 | #######################################################
# Regular expressions tool
#######################################################
"""
Regular expressions tool
created: zac wilhelmsen
08/31/17
Finds the regular expression used to identify patterns/strings
"""
def regex_tool(string):
split = string.split(" ")
regex = []
double_space = 0
esc_char = [r"\\", r"\'", r"\"", r"[", r"]", r"^", r"$", r".", r"|", r"?", r"*", r"+", r"(", r")", r"{", r"}"]
for i in range(0, len(split), 1):
# print(i,len(split))
# print("i is:", i)
# print(split[i])
for k in range(0, len(split[i]), 1):
# print(split[i][k])
if split[i].isdigit() and len(split[i]) > 1:
regex.append(r"\d+")
break
elif split[i].isalpha() and len(split[i]) > 1:
if r'\w' in regex[-2:] or r'\w+' in regex[-2:]:
# print("should we add +?")
# print(regex)
if r"\w" in regex[-2:] and r"\s" in regex[-2:]:
# print("adding +")
# print(regex)
count = -2
for element in regex[-2:]:
if element == r"\w":
regex[count] = r"\w+"
double_space = 1
count += 1
break
elif r"\w+" in regex[-2:]:
# print("escape")
double_space = 1
break
# else: # Uncomment for testing
# print("IDK why i'm here.")
else:
regex.append(r"\w")
break
# print(split[i][k])
if split[i][k].isdigit():
if prev_regex(regex) == r"\d" or prev_regex(regex) == r"\d+":
# print("second digit")
regex[len(regex)-1] = r"\d+"
else:
# print("First digit")
regex.append(r"\d")
elif split[i][k].isalpha():
if prev_regex(regex) == r"\p{L}" or prev_regex(regex) == r"\w":
# print("second letter")
regex[len(regex)-1] = r"\w"
else:
# print("first letter")
regex.append(r"\p{L}")
else:
# print("its a special!")
# print(split[i][k])
if not prev_regex(regex) == split[i][k]:
# print("it is not already present!")
# print(split[i][k])
if not split[i][k] in esc_char:
# print(split[i][k])
# print("This is a regular special character. %s is not in list" % split[i][k])
regex.append(split[i][k])
else:
# print("regex escape character")
regex.append(r"\%s" % split[i][k])
double_space = 0
if i+1 == len(split):
break
count = -2
if double_space == 1:
for element in regex[-2:]:
# print(regex, count)
if element == r"\s":
# print("adding +")
regex[count] = r"\s+"
count += 1
double_space = 0
else:
regex.append(r"\s")
# print(regex)
stringOfRegex = ""
for each in regex:
stringOfRegex += each
print("Your regex is: %s" % stringOfRegex)
def has_number(string):
# print("Has number!")
return any(str.isdigit(c) for c in string)
def has_spec(string):
# print("Has Special!")
return any(char.isalnum() for char in string)
def prev_regex(list):
if len(list) >= 1:
# print(list[len(list)-1])
return list[len(list)-1]
# def rem_space(list):
# return r"\s" in list[-2:]
def main():
# print(has_spec("$abc"))
# list = ['1', 2]
# print(len(list))
# print("[" == r"[")
while True:
regex_tool(input("> Input the string you want to identify with regular expressions\n"))
ans = input("Do you want to play again? y/n\n").lower()
if ans == "n":
break
if __name__ == "__main__":
main()
|
a0742f744b2d66be9131ab31988fba386e9178ec | likeke201/qt_code | /DemoUIonly-PythonQt/chap14matplotlib/Demo14_1Basics/Demo14_1Script.py | 1,019 | 3.671875 | 4 | ## 程序文件: Demo14_1Script.py
## 使用matplotlib.pyplot 指令式绘图
import numpy as np
import matplotlib.pyplot as plt
plt.suptitle("Plot by pyplot API script") #总的标题
t = np.linspace(0, 10, 40) #[0,10]之间平均分布的40个数
y1=np.sin(t)
y2=np.cos(2*t)
plt.subplot(1,2,1) #1行2列,第1个子图
plt.plot(t,y1,'r-o',label="sin", linewidth=1, markersize=5)
plt.plot(t,y2,'b:',label="cos",linewidth=2)
plt.xlabel('time(sec)') # X轴标题
plt.ylabel('value') # Y轴标题
plt.title("plot of functions") ##子图标题
plt.xlim([0,10]) # X轴坐标范围
plt.ylim([-2,2]) # Y轴坐标范围
plt.legend() # 生成图例
plt.subplot(1,2,2) #1行2列,第2个子图
week=["Mon","Tue","Wed","Thur","Fri","Sat","Sun"]
sales=np.random.randint(20,70,7) #生成7个[20,70)之间的整数
plt.bar(week,sales) #柱状图
plt.ylabel('sales') # Y轴标题
plt.title("Bar Chart") #子图标题
plt.show()
|
905ea1bc35f9777f9afc3d693b90aa5cde8c6c2e | patrickhaoy/RL-Tic-Tac-Toe | /src/state.py | 6,654 | 3.921875 | 4 | import numpy as np
board_rows = 3
board_cols = 3
"""
Tic Tac Toe board which updates states of either player as they take an action, judges end of game,
and rewards players accordingly.
"""
class State:
def __init__(self, p1, p2):
self.board = np.zeros((board_rows, board_cols))
self.p1 = p1
self.p2 = p2
self.is_end = False # indicates if game ended
self.board_hash = None
self.player_symbol = 1 # p1 plays first (p1: 1, p2: -1)
"""
Converts current board state to String so it can be stored as the value in the dictionary
"""
def get_hash(self):
self.board_hash = str(self.board.reshape(board_cols * board_rows))
return self.board_hash
"""
Returns available positions (cells with 0) as an array of pairs representing (x, y) coordinates
"""
def available_pos(self):
pos = []
for i in range(board_rows):
for j in range(board_cols):
if self.board[i, j] == 0:
pos.append((i, j))
return pos
"""
Updates state of board with player's move and switches players for the next turn
"""
def update_state(self, pos):
self.board[pos] = self.player_symbol
# switch players for next turn
if self.player_symbol == 1:
self.player_symbol = -1
else:
self.player_symbol = 1
"""
If p1 wins, 1 is returned. If p2 wins, -1 is returned. If it is a tie, 0 is returned.
In either of these three cases, the game ends. If the game continues, None is returned.
"""
def winner(self):
# checks rows for winner
for i in range(board_rows):
if sum(self.board[i, :]) == 3:
self.is_end = True
return 1
if sum(self.board[i, :]) == -3:
self.is_end = True
return -1
# checks columns for winner
for i in range(board_rows):
if sum(self.board[:, i]) == 3:
self.is_end = True
return 1
if sum(self.board[:, i]) == -3:
self.is_end = True
return -1
# checks diagonals for winner
diag_sum1 = sum([self.board[i, i] for i in range(board_cols)])
diag_sum2 = sum([self.board[i, board_cols - i - 1] for i in range(board_cols)])
if abs(diag_sum1) == 3 or abs(diag_sum2) == 3:
self.is_end = True
if diag_sum1 == 3 or diag_sum2 == 3:
return 1
else:
return -1
# checks for tie
if len(self.available_pos()) == 0:
self.is_end = True
return 0
# else, game has not ended yet
self.is_end = False
return None
"""
The winner gets a reward of 1, and the loser gets a reward of 0.
As ties are also "undesirable", we set its reward from 0.5 to 0.1 (this is up for experimentation).
"""
def give_reward(self):
winner = self.winner()
if winner == 1:
self.p1.feed_reward(1)
self.p2.feed_reward(0)
elif winner == -1:
self.p1.feed_reward(0)
self.p2.feed_reward(1)
else:
self.p1.feed_reward(0.1)
self.p2.feed_reward(0.1)
"""
Training the bots against each other and saving the policies for the player going first as "policy_p1"
and the player going second as "policy_p2".
"""
def play(self, rounds=100):
for i in range(rounds):
if i % 1000 == 0:
print("Round {}".format(i))
while not self.is_end:
# Simulating p1's turn
pos = self.available_pos()
p1_action = self.p1.choose_action(pos, self.board, self.player_symbol)
self.update_state(p1_action)
board_hash = self.get_hash()
self.p1.add_state(board_hash)
if self.winner() is not None:
self.total_reset()
break
else:
pos = self.available_pos()
p2_action = self.p2.choose_action(pos, self.board, self.player_symbol)
self.update_state(p2_action)
board_hash = self.get_hash()
self.p2.add_state(board_hash)
if self.winner() is not None:
self.total_reset()
break
self.p1.save_policy()
self.p2.save_policy()
"""
Simulating play against a human.
"""
def play2(self):
while not self.is_end:
# Simulating p1's turn
pos = self.available_pos()
p1_action = self.p1.choose_action(pos, self.board, self.player_symbol)
self.update_state(p1_action)
self.show_board()
winner = self.winner()
if winner is not None:
if winner == 1:
print(self.p1.name, "wins!")
else:
print("tie!")
self.state_reset()
break
else:
# Simulating p2's turn
pos = self.available_pos()
p2_action = self.p2.choose_action(pos)
self.update_state(p2_action)
self.show_board()
winner = self.winner()
if winner is not None:
if winner == -1:
print(self.p2.name, "wins!")
else:
print("tie!")
self.state_reset()
break
"""
Resets state of board and is_end for next round
"""
def state_reset(self):
self.board = np.zeros((board_rows, board_cols))
self.board_hash = None
self.is_end = False
self.player_symbol = 1
"""
Reset players and board for next round
"""
def total_reset(self):
self.give_reward()
self.p1.reset()
self.p2.reset()
self.state_reset()
"""
Prints out board for human user
"""
def show_board(self):
for i in range(0, board_rows):
print("-------------")
out = "|"
for j in range(0, board_cols):
if self.board[i, j] == 1:
token = 'x'
elif self.board[i, j] == -1:
token = 'o'
else:
token = ' '
out += token + ' | '
print(out)
print('-------------')
|
0c1b5328bcf938b70a3a96ef1b4ac433ea771e4c | jiangeyre/Graphs | /Day_2_Lecture/graph_with_search.py | 2,516 | 3.921875 | 4 | class Queue:
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
if self.size() > 0:
return self.queue.pop(0)
else:
return None
def size(self):
return len(self.queue)
class Graph:
def __init__(self):
self.vertices = {}
def add_vertex(self, vertex_id):
self.vertices[vertex_id] = set() # set of edges
def add_edge(self, v1, v2):
"""Add edge from v1 to v2."""
# If they're both in the graph
if v1 in self.vertices and v2 in self.vertices:
self.vertices[v1].add(v2)
else:
raise IndexError("Vertex does not exist in graph")
def get_neighbors(self, vertex_id):
return self.vertices[vertex_id]
def bft(self, starting_vertex_id):
"""Breadth-first Traversal."""
q = Queue()
q.enqueue(starting_vertex_id)
# Keep track of visited nodes
visited = set()
# Repeat until queue is empty
while q.size() > 0:
# Dequeue first vert
v = q.dequeue()
# If it's not visited:
if v not in visited:
print(v)
# Mark visited
visited.add(v)
for next_vert in self.get_neighbors(v):
q.enqueue(next_vert)
def dft_recursive(self, start_vert, visited=None):
print(start_vert)
if visited is None:
visited = set()
visited.add(start_vert)
for child_vert in self.vertices[start_vert]:
if child_vert not in visited:
self.dft_recursive(child_vert, visited)
def dfs_recursive(self, start_vert, target_value, visited=None, path=None):
print(start_vert)
if visited is None:
visited = set()
if path is None:
path = []
visited.add(start_vert)
# Make a copy of the list, adding the new vert on
path = path + [start_vert]
# Base case
if start_vert == target_value:
return path
for child_vert in self.vertices[start_vert]:
if child_vert not in visited:
new_path = self.dfs_recursive(child_vert, target_value, visited, path)
if new_path:
return new_path
return None
g = Graph()
g.add_vertex(99)
g.add_vertex(3)
g.add_vertex(3490)
g.add_vertex(34902)
g.add_edge(99, 3490) # Connect node 99 to node 3490
g.add_edge(99, 3) # Connect node 99 to node 3
g.add_edge(3, 99) # Connect node 3 to node 99
g.add_edge(3490, 34902)
#print(g.get_neighbors(99))
#print(g.get_neighbors(3))
g.bft(99)
g.bft(3490)
g.dft_recursive(99)
print(g.dfs_recursive(99, 34902)) |
d38f462e41e1f2fd0e9f07623bca3fc6a5619272 | mikaelgba/PythonDSA | /cap5/Metodos.py | 1,411 | 4.25 | 4 | class Circulo():
# pi é um varialvel global da classe
pi = 3.14
# com raio = 'x valor' toda vez que criar um objeto Circulo ele automaticamnete já concidera que o raio será 'x valor'
#mas se colocar um outro valor ele vai sobreescrever o 'x valor'
def __init__( self, raio = 3 ):
self.raio = raio
def area( self ):
return ((self.raio * self.raio) * Circulo.pi)
def getRaio( self ):
return self.raio
def setRaio( self, novo_circulo ):
self.raio = novo_circulo
circulo = Circulo(4)
print(circulo.getRaio(),"\n")
print(circulo.area(),"\n")
circulo.setRaio(7)
print(circulo.area(),"\n")
#Classe quadrado
class Quadrado():
def __init__( self, altura, largura ):
self.altura = altura
self.largura = largura
def area( self ):
return ( self.altura * self.largura )
def getAltura( self ):
return self.altura
def setAltura( self, nova_altura ):
self.altura = nova_altura
def getLargura( self ):
return self.largura
def setLargura( self, nova_largura ):
self.largura = nova_largura
quad = Quadrado(2,2)
print("Altura:",quad.getAltura(),"Largura:", quad.getLargura(),"\n")
print(quad.area(),"\n")
quad.setAltura(4)
print(quad.getAltura(),"\n")
quad.setLargura(4)
print(quad.getLargura(),"\n")
print(quad.area(),"\n")
|
c735af789942fa33262fc7f6b6e6970351d3cb1d | mikaelgba/PythonDSA | /cap4/Funcao_Filter.py | 687 | 3.828125 | 4 | #Criando uma função para verificar se um numero é impar
def ver_impar(numero):
if ((numero % 2) != 0):
return True
else:
return False
print(ver_impar(10), "\n")
#Criando uma lista adicionando nela valores randomicos
import random
# a se torna em uma lista com 10 varoles random
a = random.sample(range(100),10)
print(a)
print("\n")
# In[ ]:
print(filter(ver_impar,a))
print("\n")
# In[ ]:
#imprimindo o retorno da função com os valores apenas imapres
print(list(filter(ver_impar,a)))
print("\n")
# In[ ]:
#Ultilixando o filter com lambda
print(list(filter(lambda x: (x % 2) == 0, a)))
print("\n")
print(list(filter(lambda x: x >= 50, a)))
|
26690c4000dbfd7bc49817c00aee7d1a406f4475 | mikaelgba/PythonDSA | /cap2/Dicionarios.py | 1,339 | 3.875 | 4 | dicio1 = {"Mu":1,"Aiolia":5,"Aiolos":9,"Aldebaran":2,"Shaka":6,"Shura":10,"Saga":3,"Dorko":7,"Kamus":11,"Mascará da Morte":4,"Miro":8,"Afodite":12}
print(dicio1)
print(dicio1["Mu"])
#Limpar os elementos do Dicionario
dicio1.clear()
print(dicio1)
dicio2 ={"Seiya":13,"Shiryu":15,"Ikki":15,"Yoga":14,"Shun":13}
dicio2["Seiya"] = 14
print(dicio2)
#Retorna se há uma chave no dicionario
print("Seiya" in dicio2)
#Retorna se há uma elemento no dicionario
print(13 in dicio2.values())
#Retorna o tamanho
print(len(dicio2))
#Retorna as chaves dos elementos
print(dicio2.keys())
#Retorna os elementos do dicionario
print(dicio2.values())
#Retorna os elementos do dicionario
print(dicio2.items())
#Mescla 2 dicionarios
dicio3 = {"Saori":14, "Karno":23}
dicio2.update(dicio3)
print(dicio3)
dicio4 = {1:"eu", 2:"você",3:"e o zubumafu"}
print(dicio4[1].upper())
dicio4 = {1:"eu", 2:"você",3:"e o zubumafu"}
print(dicio4[1].lower())
#Adicionando um elemento
dicio4[4] = " para sempre"
print(dicio4)
#Removendo um elemento
del dicio4[4]
print(dicio4)
#Dicioario com subListas
dicio5 = {"a":[23,58,19],"b":[35,75,95],"c":[41,53,24]}
dicio5["a"][0] -= 2
print(dicio5)
#Dicioario com mais de uma chave para cada elemento
dicio6 = {"id1":{"user1":"a"},"id2":{"user2":"b"}}
dicio6["id1"]["user1"] = "A"
dicio6["id2"]["user2"] = "B"
print(dicio6)
|
ea8211501e5fcb7ae3a319cf7c9f2e6878ad759b | mikaelgba/PythonDSA | /cap2/Variaveis.py | 362 | 3.734375 | 4 |
a = 1.7
b = 2
print(a , b)
print(pow(a,b))
print()
a = 1.7777
b = 2
print(round(a,b))
print()
b = 2
print(float(b))
print()
a = 1.7
print(int(a))
print()
var_test = 1
print(var_test)
print(type(var_test))
print()
pessoa1, pessoa2, pessoa3 = "eu", "você", "E o Zubumafu"
print(pessoa1)
print(pessoa2)
print(pessoa3)
print()
print(pessoa1 == pessoa2)
|
ea62f060d4d0d4e1b9250e8edd041cc939b109da | mikaelgba/PythonDSA | /cap4/Datetime.py | 1,007 | 3.90625 | 4 | #Importando o pacote DataTime, aplicações de data e hora
import datetime
# datetime.datetime.now() retorna a data e o horario atual
hora_agora = datetime.datetime.now()
print(hora_agora)
print("\n")
# datetime.time() cria um horario
hora_agora2 = datetime.time(5,7,8,1562)
print("Hora(s): ", hora_agora2.hour)
print("Minuto(s): ", hora_agora2.minute)
print("Segundo(s): ", hora_agora2.second)
print("Mini segundo(s): ", hora_agora2.microsecond)
print("\n")
print(datetime.time.min)
print("\n")
# datetime.date.today() retorna a data atual
hoje = datetime.date.today()
print(hoje)
print("Hora(s): ", hoje.ctime())
print("Minuto(s): ", hoje.year)
print("Segundo(s): ", hoje.month)
print("Mini segundo(s): ", hoje.day)
print("\n")
#Criando uma data com o datetime.date()
data1 = datetime.date(2019,12,31)
print("Dia: ", data1)
print("\n")
#Alterando a data com replace(year='x'), replace(month='x'), replace(day='x')
data2 = data1.replace(year=2020)
print(data2)
print(data2 - data1)
# In[ ]:
|
e1a234adfa92c9621b97e9ea3b9b07b112ff8a23 | itsanti/gbu-ch-py-algo | /hw6/hw6_task3.py | 1,979 | 3.609375 | 4 | """HW6 - Task 3
Подсчитать, сколько было выделено памяти под переменные в ранее разработанных программах в рамках первых трех уроков.
Проанализировать результат и определить программы с наиболее эффективным использованием памяти.
"""
import sys
from math import sqrt
from memory_profiler import profile
print(sys.version, sys.platform)
def meminfo(obj):
print(f'ref count: {sys.getrefcount(obj)}')
print(f'sizeof: {sys.getsizeof(obj)}')
@profile()
def sieve(n):
def _sieve(n):
sieve = [i for i in range(n)]
sieve[1] = 0
for i in range(2, n):
j = i * 2
while j < n:
sieve[j] = 0
j += i
return [i for i in sieve if i != 0]
i = 100
result = _sieve(i)
while len(result) < n:
i += 50
result = _sieve(i)
meminfo(result)
return result[n - 1]
@profile()
def prime(n):
def is_prime(n):
i = 2
while i <= sqrt(n):
if n % i == 0:
return False
i += 1
return True
result = []
first = 2
size = 50
while len(result) < n:
for k in range(first, size):
if is_prime(k):
result.append(k)
first = size
size *= 2
meminfo(result)
return result[n - 1]
n = 500
print(f"sieve: {sieve(n)}")
print(f"prime: {prime(n)}")
"""
3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)] win32
Количество ссылок на объект result:
sieve: 6
prime: 6
Размер объекта result в байтах:
sieve: 4272
prime: 7056
Выделено памяти на выполнение скрипта:
sieve: 37.6 MiB
prime: 37.9 MiB
Вариант sieve - оптимальный по памяти.
"""
|
c58df5c0848e33e443e455f26433efd010276218 | itsanti/gbu-ch-py-algo | /hw8/hw8_task1.py | 589 | 3.6875 | 4 | """HW8 - Task 1
На улице встретились N друзей. Каждый пожал руку всем остальным друзьям (по одному разу).
Сколько рукопожатий было? Примечание. Решите задачу при помощи построения графа.
"""
n = int(input('Сколько встретилось друзей: '))
graph = [[int(i > j) for i in range(n)] for j in range(n)]
count = 0
for r in range(len(graph)):
count += sum(graph[r])
print(f'Количество рукопожатий {count}')
|
dc4153dddd83d25e90daaa526124291729b85405 | itsanti/gbu-ch-py-algo | /hw3/hw3_task5.py | 1,288 | 3.9375 | 4 | """HW3 - Task 5
В массиве найти максимальный отрицательный элемент. Вывести на экран его значение и позицию в массиве.
Примечание к задаче: пожалуйста не путайте «минимальный» и «максимальный отрицательный».
Это два абсолютно разных значения.
"""
import random
in_arr = [random.randint(-3, 3) for _ in range(5)]
print(in_arr)
max_negative = (-1, 0)
for i, el in enumerate(in_arr):
if 0 < -el and -el > max_negative[1]:
max_negative = (i, el)
if max_negative[0] > -1:
print(f'максимальный отрицательный элемент: {max_negative[1]}\nнаходится на позиции: {max_negative[0]}')
else:
print('все элементы в массиве положительные')
'''OUTPUT
[2, -2, 1, -1, 2]
максимальный отрицательный элемент: -1
находится на позиции: 3
[3, 1, -3, -2, -1]
максимальный отрицательный элемент: -1
находится на позиции: 4
[3, 3, 2, 2, 3]
все элементы в массиве положительные
'''
|
f6c3bc55ec38fefd1cf9b8dd646f6bf5135716d4 | itsanti/gbu-ch-py-algo | /hw2/hw2_task5.py | 489 | 3.6875 | 4 | """HW2 - Task 5
Вывести на экран коды и символы таблицы ASCII, начиная с символа под номером 32 и заканчивая 127-м включительно.
Вывод выполнить в табличной форме: по десять пар «код-символ» в каждой строке.
"""
i = 1
for code in range(32, 128):
end = '\n' if i % 10 == 0 else '\t'
print(f'{code:3}-{chr(code)}', end=end)
i += 1
|
51ac5cfbf207126f3cf7ea7066c7c942d91dc074 | mahanta-tapas/WebScrapers | /verbose.py | 467 | 3.765625 | 4 | import sys
question = "Are you Sure ??"
default = "no"
valid = {"yes": True , "y": True, "ye" : True}
invalid = {"no" :False,"n":False}
prompt = " [y/N] "
while True:
choice = raw_input(question + prompt )
if choice in valid:
break
elif choice in invalid:
sys.stdout.write("exiting from program \n")
exit()
else:
sys.stdout.write("Please respond with 'yes' or 'no' " +
"(or 'y' or 'n').\n")
print "Going Ahead\n"
|
c2d821b83ecc693ba04247ba12a8d7ffcf0919cc | MatthewH1988/Python-Techdegree-Project-1 | /guessing_game.py | 1,238 | 4.0625 | 4 |
import random
def start_game():
print("Welcome to the Number Guessing Game!")
import random
guess_count = 1
while True:
try:
random_number = random.randrange(0, 11)
player_guess = int(input("Please guess a number between 0 and 10: "))
if player_guess < 0 or player_guess > 10:
raise ValueError
except ValueError:
print("That is not a valid response! Please try again!")
continue
else:
while player_guess != random_number:
if (player_guess > random_number):
print("It's lower")
guess_count += 1
player_guess = int(input("Please guess again!: "))
elif (player_guess < random_number):
print("It's higher")
guess_count += 1
player_guess = int(input("Please guess again!: "))
else:
attempt_count += 1
break
print("That's correct!")
break
print("That's the end of the game! It took you {} attempts to guess correctly!".format(guess_count))
start_game() |
aaa0660306c6486820cde0f6e75f315cfec3ca3b | NickSKim/csci321 | /PygameDemos/0700rpg/tiles.py | 4,897 | 3.625 | 4 | import os, pygame
from pygame.locals import *
from utilities import loadImage
class InvisibleBlock(pygame.sprite.Sprite):
def __init__(self, rect):
pygame.sprite.Sprite.__init__(self)
self.rect = rect
def draw(surface):
pass
class Tile(pygame.sprite.Sprite):
def __init__(self, image, position, wall):
pygame.sprite.Sprite.__init__(self)
self.image = image
self.rect = image.get_rect()
self.rect.topleft = position
self.wall = wall
class EmptyTile(pygame.sprite.Sprite):
"""Used to fill empty space, so that each cell of the board
can hold some data. For example, "Are you a wall?"""
def __init__(self, wall = False):
pygame.sprite.Sprite.__init__(self)
self.wall = wall
class _TileManager():
def __init__(self,tilefile='basictiles.png',
room='roomtiling.data',
tilemap='tilemap.data',
datafolder=os.path.join('data','text'),
imagefolder=os.path.join('data','images')
):
self.tilefile = tilefile
self.room = room
self.tilemap = tilemap
self.datafolder = datafolder
self.imagefolder = imagefolder
self.invisibleBlocks = []
self.initialized = False
def initialize(self, scale = 3):
if self.initialized:
return self
self.initialized = True
# load all the tiles
self.tilefile = loadImage( self.tilefile, self.imagefolder, colorkey=None)
mapfile = open(os.path.join(self.datafolder, self.tilemap), 'r')
maplines = mapfile.read().splitlines()
self.dict = {}
for x in maplines:
mapping = [s.strip() for s in x.split(',')]
key = mapping[6]
self.dict[key] = {}
w,h = int(mapping[2]), int(mapping[3])
row, col = int(mapping[4]), int(mapping[5])
self.dict[key]['name'] = mapping[0]
self.dict[key]['file'] = mapping[1]
self.dict[key]['width'] = w
self.dict[key]['height'] = h
self.dict[key]['row'] = row
self.dict[key]['col'] = col
self.dict[key]['roomkey'] = mapping[6]
self.dict[key]['wall'] = mapping[7] == 'wall'
# find image for this tile
#w, h = self.dict[key]['width'], self.dict[key]['height']
#row, col = self.dict[key]['row'], self.dict[key]['col']
image = pygame.Surface((w,h))
image.blit(self.tilefile, (0,0),
((col*w, row*h), (w,h)))
image = pygame.transform.scale(image, (scale*w, scale*h))
letter = self.dict[key]['roomkey']
if letter in '12346':
w,h = image.get_size()
image.set_colorkey(image.get_at((w/2,h/2)))
elif letter in '578':
image.set_colorkey(image.get_at((0,0)))
self.dict[key]['image'] = image
# tile the room
roomfile = open(os.path.join(self.datafolder, self.room),'r')
roomrows = roomfile.read().splitlines()
self.tiles = pygame.sprite.RenderPlain()
self.tileArray = [[None for x in range(len(roomrows[0]))]
for y in range(len(roomrows))]
for roomrow, keys in enumerate(roomrows):
for roomcol, letter in enumerate(keys):
if letter == '.':
newTile = EmptyTile()
else:
data = self.dict[letter]
newTile = Tile(data['image'],
(roomcol*scale*w, roomrow*scale*h),
data['wall'])
if data['wall']:
newBlock = InvisibleBlock(
pygame.Rect(roomcol*scale*w, roomrow*scale*h,
scale*w, scale*h))
self.invisibleBlocks.append(newBlock)
self.tiles.add(newTile)
self.tileArray[roomrow][roomcol] = newTile
return self
_tilemanager = _TileManager()
def TileManager():
return _tilemanager
#### Some tests:
if __name__ == "__main__":
scale = 3
try:
pygame.init()
screen = pygame.display.set_mode((scale*400, scale*240))
# now we can initialize the tile manager:
tm = TileManager().initialize()
done = False
while not(done):
screen.fill((128,0,0))
tm.tiles.draw(screen)
pygame.display.flip()
for event in pygame.event.get():
if event.type == QUIT:
done = True
elif event.type == KEYDOWN and event.key == K_ESCAPE:
done = True
finally:
pygame.quit()
|
c6248c29ef8daad133c18babcffa42664d602a72 | RiverTate/Chern | /hofstadter.py | 2,417 | 3.609375 | 4 | # This program calculate the eigen energies of a qantum Hall
# system (square lattice), and plot the energy as a function
# of flux (applied magnetic filed). The plot of nergy vs. flux
# would generate hofstadter butterfly
# Author: Amin Ahmadi
# Date: Jan 16, 2018
############################################################
# importing numpy and linear algebra modules
import numpy as np
import numpy.linalg as lg
# Function that calculate Hamiltonian H(k)
def H_k(k_vec, p, q):
""" This function calulate the Hamiltonian of a
2D electron gas in presence of an applied magnetic
field. The magnetic field is introduced using
Landau's guage.
in: kx, ky,
p and q are the ratio of p/q = phi/phi0
out: H_k, k-representation of H
"""
Hk = np.zeros((q,q), dtype=complex)
t = 1. # hopping amplitude
phi_ratio = (1.*p)/q # flux per plaquette
kx = k_vec[0]
ky = k_vec[1]
# diagonal elements
for i in range(q):
Hk[i,i] = -t*np.cos( ky - 2.*(i+1)*np.pi*phi_ratio )
# off-diagonal elements
for i in range(q-1):
Hk[i,i+1] = -t
# Magnetic Bloch element
Hk[0,q-1] = -t*np.exp(-q*1.j*kx)
# Make it hermitian
Hk = Hk + Hk.conj().T
return Hk
############################################################
################### Main Program #########################
############################################################
q = 501 # phi/phi0 = p/q
k_vec = np.array([3.0,0], float)
E_arr = np.zeros((q,q), float)
for p in range(q):
E_k= lg.eigvalsh(H_k(k_vec, p, q))
# save data for plotting
E_arr[:, p] = E_k[:]
# save date in file
np.save('./Result/hofs_501_00', E_arr)
############################################################
#################### plotting #########################
############################################################
import matplotlib.pyplot as pl
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
pl.rc("font", family='serif')
pl.rc('text', usetex=True)
fig = pl.figure(figsize=(8,6))
ax = fig.add_subplot(1,1,1)
pq = np.linspace(0,1,q)
for p in range(q):
ax.plot(pq, E_arr[p,:],',k')
ax.set_xlabel(r'$\frac{\phi}{\phi_0}$', fontsize=16)
ax.set_ylabel(r'$E$', fontsize=16)
pl.show()
fig.savefig('./Result/butterfly_501.pdf', bbox_inches='tight')
|
ea9d13753a22f346cd86b677fa49ad6ad54846f6 | AlexFabra/Sudoku | /Sudoku.py | 8,138 | 4 | 4 | import math
class Sudoku:
# guardem els números necessaris per que una fila, columna o quadrant estiguin complets:
nombresNecessaris = [1, 2, 3, 4, 5, 6, 7, 8, 9]
#creem el constructor de Sudoku. Li passarem com a paràmetre un array d'arrays:
def __init__(self,arrays):
self.arrays=arrays
#el métode actualitza actualitza arrays, posant el número introduït a les coordenades:
def actualitza(self,nouNumero,cX,cY):
self.arrays[cX][cY]=nouNumero
#Donats els paràmetres cX i nouNumero, el mètode comprovar fila serveix
# per analitzar si l'últim número introduït és repeteix.
#cX és la coordenadaX, és a dir, la fila que volem obtenir.
#nouNumero és el número introduït per l'usuari.
def comprovarFila(self,fila,nouNumero):
numerosFila = []
for nColumna in range(len(self.arrays)):
numerosFila.append(arrays[fila][nColumna])
#si al vector hi ha més d'un valor igual al nouNumero, retorna false
#false representa un error en el Sudoku:
if numerosFila.count(nouNumero)>1:
print("Aquest número ja hi és a la fila.")
return False
else:
return True
#funció que donat el número a comprovar i la fila on comprovar la seva repetició, retorna true si no s'ha repetit.
#columna és la columna que volem obtenir.
#nouNumero és el número que volem veure si es repeteix.
def comprovarColumna(self,columna,nouNumero):
numerosColumna = []
for nFila in range(len(self.arrays)):
numerosColumna.append(arrays[nFila][columna])
#si al vector hi ha més d'un valor igual al nouNumero, retorna false
#false representa un error en el Sudoku:
if numerosColumna.count(nouNumero)>1:
print("Aquest número ja hi és a la columna.")
return False
else:
return True
#funció que donat un número a comprovar i la posició horitzontal i vertical on s'ubica, identifica el cuadrant
#i retorna false si ja hi ha un número igual en aquest:
def comprovarQuadrant(self,columna,fila,nouNumero):
#vector on guardarem els nombres del quadrant:
numQuadrant = []
# Com que volem trobar el primer número del quadrant per iterar fins a l'últim, treiem el floor de la divisió
# de les coordenades entre 3 (això ens donarà un numero del 0 al 2) i ho multipliquem per 3, que en donarà el
# numero inicial d'un quadrant:
fila = (math.floor(fila / 3)*3)
columna = (math.floor(columna / 3)*3)
# Amb el iterador posem els numeros del quadrant a la llista:
for num in range(fila, fila + 3):
#extend afegeix al final de la llista 'numQuadrant' el valor de la coordenada de 'arrays':
#guardem els valors de tres en tres:
numQuadrant.extend(arrays[num][columna:columna + 3])
#si al vector hi ha més d'un valor igual al nouNumero, retorna false
#false representa un error en el Sudoku:
if numQuadrant.count(nouNumero)>1:
print("Aquest número ja hi és al quadrant.")
return False
else:
return True
#finalFila comprova que la fila estigui complerta i retorna true només en aquest cas:
def finalFila(self,fila):
numerosFila = []
for nColumna in range(len(self.arrays)):
numerosFila.append(arrays[fila][nColumna])
#mirem si els valors de la llista nombresNecessaris hi son a numerosFila:
comprovacio = all(item in numerosFila for item in self.nombresNecessaris)
return comprovacio
#finalColumna comprova que la columna estigui complerta i retorna true només en aquest cas:
def finalColumna(self,columna):
numerosColumna = []
for nFila in range(len(self.arrays)):
numerosColumna.append(arrays[nFila][columna])
#mirem si els valors de la llista nombresNecessaris hi son a numerosColumna:
comprovacio = all(item in numerosColumna for item in self.nombresNecessaris)
return comprovacio
#finalQuadrant comprova que el quadrant estigui complert i retorna true només en aquest cas:
def finalQuadrant(self,fila,columna):
#aquest codi és reutilitzat de la funció comprovarQuadrant i està comentat allà:
numerosQuadrant = []
fila = (math.floor(fila / 3)*3)
columna = (math.floor(columna / 3)*3)
for num in range(fila, fila + 3):
numerosQuadrant.extend(arrays[num][columna:columna + 3])
#mirem si els valors de la llista nombresNecessaris hi son a numerosQuadrant:
comprovacio = all(item in numerosQuadrant for item in self.nombresNecessaris)
return comprovacio
def sudokuComplert(self):
completat = True
comptador=0
comptador1=0
while completat and comptador<9:
completat=self.finalFila(comptador)
if completat:
completat=self.finalColumna(comptador)
comptador+=1
while completat and comptador1<9:
completat=self.finalQuadrant(comptador,comptador1)
comptador1+=1
return completat
# creem el métode toString que retorna l'estat de l'objecte:
def __str__(self):
mostraString=""
contador=0
contador1=0
mostraString += "\n-------------------------------\n"
#fem un for anidat per recòrrer el vector de vectors:
for y in arrays:
for x in y:
if(contador%3==0):
mostraString+="|"
#guardem a mostraString el valor:
mostraString+=" "+ str(x)+ " "
contador += 1
mostraString += "|"
contador1+=1
#si el modul del contador1 entre 3 equival a 0:
if (contador1 % 3 == 0):
#fem un salt de línea quan sortim del for intern:
mostraString+="\n-------------------------------\n"
else:
mostraString += "\n"
#tornem a posar el contador a 1:
contador=0
#retornem el string que és el sudoku:
return(mostraString)
#declarem l'array que tractarem com a sudoku:
arrays = \
[[3, 1, 5, 6, 2, 9, 8, 4, 7],
[7, 0, 6, 1, 0, 8, 0, 0, 0],
[8, 3, 1, 4, 7, 9, 2, 6, 5],
[5, 0, 3, 0, 0, 5, 0, 7, 0],
[6, 8, 7, 0, 0, 0, 0, 0, 0],
[2, 0, 0, 7, 0, 0, 6, 0, 0],
[4, 7, 9, 5, 8, 0, 0, 2, 0],
[1, 0, 0, 4, 3, 0, 5, 0, 9],
[9, 0, 8, 9, 0, 0, 0, 0, 6]]
#fem un objecte passant-li 'arrays' com a paràmetre:
s1 = Sudoku(arrays)
#declarem el boolean sudokuComplert en valor false:
sudokuComplert=False
while sudokuComplert==False:
#mostrem el sudoku (#imprimim el vector de vectors amb format gràcies al __str__):
print(s1)
#declarem l'String coordenada:
coordenada = "0,0"
#demanem les coordenades a modificar:
coordenada=input("introdueïx coordenada ([fila],[columna]): ")
#demanem un valor per posar en les coordenades:
nouValor=int(input("introdueïx nou valor: "))
#dividim l'String 'coordenada' per la coma per treballar amb els valors
coo=coordenada.split(',')
#fem un cast a integer i guardem els valors:
x=int(coo[0])
y=int(coo[1])
#restem els valors perque 1 sigui la primera fila o columna, i no la segona:
x=x-1
y=y-1
#executem la funció 'actualitza()'
s1.actualitza(nouValor,x,y)
#si cap d'aquest mètodes retorna false, és que es repeteix el valor en fila, columna o quadrant:
filaValorRepetit=s1.comprovarFila(x,nouValor)
columnaValorRepetit=s1.comprovarColumna(y,nouValor)
quadrantValorRepetit=s1.comprovarQuadrant(x,y,nouValor)
#si cap d'aquests mètodes retorna false, és que no estan complerts la fila, la columna o el quadrant:
filaComplerta=s1.finalFila(x)
columnaComplerta=s1.finalColumna(y)
quadrantComplert=s1.finalQuadrant(x,y)
#si la funció sudokuComplert() ens retorna false, és que el sudoku no està complert:
sudokuComplert=s1.sudokuComplert()
|
1825ecd0df5fdfa00eb0e0c5322caef87081e4c5 | yijirong/movie-dataset-analysis | /model.py | 427 | 3.609375 | 4 | class StudentModel:
def __init__(self, name="", sex="", score=0.0, age=0, sid=0):
self.name = name
self.sex = sex
self.score = score
self.age = age
self.sid = sid
def __str__(self):
return f"{self.name} your account is {self.sid},age is {self.age},movie name is {self.sex},movie score is {self.score}"
def __eq__(self, other):
return self.sid == other.sid |
86afe70c6c5a94161b4a211ca835ffb0e402765a | willbrom/py_prog | /guess_a_number.py | 514 | 4.09375 | 4 | #!/bin/python3
#This is a guess the number game
from random import randint
rand_num = randint(1,20)
print('I am thinking of a number between 1 and 20')
for guess_taken in range(0, 7):
print('Take a guess')
guess = int(input())
if guess < rand_num:
print('Your guess is too low')
elif guess > rand_num:
print('Your guess is too high')
else:
break
if guess == rand_num:
print('Good job! you guessed my number in ' + str(guess_taken + 1) + ' guesses!')
else:
print('Better luck next time, scrub!')
|
df8537c34ccabcdf0404e8b0416d6711c59410ca | felipebregalda/gogitcl | /notas.py | 278 | 3.53125 | 4 | #-*- coding utf-8 -*-
from funcoes import notaFinal
print 'Calculo de notas do Aluno\n'
nome = raw_input ('Nome: ')
nota1 = float( raw_input('Nota 1: '))
nota2 = float( raw_input('Nota 2: '))
notaFinal = notaFinal(nota1, nota2)
print 'Nota final do aluno',nome,'eh',notaFinal |
5a9c5719e053d265dd173e766008bc33118b6dae | peterzhou84/datastructure | /samples/python/array.py | 1,542 | 4.4375 | 4 | #coding=utf-8
#!/usr/bin/python3
'''
展示在Python中,如何操作数组
'''
#################################################
### 一维数组 http://www.runoob.com/python3/python3-list.html
squares = [1, 4, 9, 16, 25, 36]
print("打印原数组:")
print(squares)
'''
Python的编号可以为正负
+---+---+---+---+---+---+
| 1 | 4 | 9 | 16| 25| 36|
+---+---+---+---+---+---+
0 1 2 3 4 5 从第一个开始编号为0
-6 -5 -4 -3 -2 -1 从最后一个开始,编号为-1
'''
## 找到特定下标的元素
print("打印下标为4的元素:")
print(squares[4]) # 从第一个开始数,指向25
print("打印下标为-2的元素:")
print(squares[-2]) # 从最后一个开始数,指向25
## 找到特定下标范围的元素
print("打印下标为2(包含)到4(不包含)之间的所有元素:")
print(squares[2:4])
print("打印下标从4开始(包含)到数组最后的所有元素:")
print(squares[4:])
print("打印第一个元素到第-2(不含)的元素:")
print(squares[:-2])
## 设置数组元素的值
print("下标为2的元素乘以10:")
squares[2] *= 10
print(squares)
## 删除数组里面的元素
print("删除下标为4的元素")
del squares[4]
print(squares)
#################################################
### 元组 Python 的元组与列表类似,不同之处在于元组的元素不能修改。
# 元组使用小括号,列表使用方括号。
tup1 = ('Google', 'Runoob', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d"; |
2630ddaf65b81180029e68506dce3a45e8c82c08 | jamesmold/learning | /aoc2.py | 528 | 3.53125 | 4 | from collections import Counter
fhand = open("aoc2.txt")
lines = [x.strip() for x in fhand] #removes the new lines from the input file aoc2.txt
def part1():
has2 = 0
has3 = 0
for line in lines:
c = Counter(line).values() #Counter counts like elements in a string (returns as dict key value pair, adding the .values just returns the value not the key)
if 2 in c:
has2 = has2 + 1
if 3 in c:
has3 = has3 + 1
else: continue
return has2 * has3
print(part1()) |
5e0f8b72f7946109f1bb70e8cca938c7a5d0da0e | DarioBernardo/hackerrank_exercises | /dinner_party.py | 1,521 | 3.78125 | 4 | # Find all possible combination of friends using recursion
# the total number of combination is given by binomial coefficient formula
# n choose k where n is the number of guest and k is the table size
# binomial coefficient = n!/(k!*(n-k)!)
from itertools import combinations
friends = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'L', 'M', 'N']
# friends = ['A', 'B', 'C', 'D']
table_size = 5
# print([tuple(elem) for elem in friends])
solution = [x for x in combinations(friends, table_size)]
print(solution)
def get_table_guest(friends_list, table_size, group=[], groups=[]):
if len(group) is table_size:
groups.append(tuple(group))
return
if len(group) + len(friends_list) == table_size:
group.extend(friends_list)
groups.append(tuple(group))
return
curr_friend = friends_list.pop(0)
group_without = group.copy()
group.append(curr_friend)
# take branch
get_table_guest(friends_list.copy(), table_size, group, groups)
# leave branch
get_table_guest(friends_list.copy(), table_size, group_without, groups)
return groups
prop_solution = get_table_guest(friends, table_size)
print(prop_solution)
for elem in solution:
if elem in prop_solution:
prop_solution.remove(elem)
else:
raise Exception(f"Element {elem} not present")
if len(prop_solution) > 0:
raise Exception(f"There are some extra elements in the proposed solution: {prop_solution}")
if len(prop_solution) == 0:
print("ALL GOOD!")
|
7a39583a260a600b2228795bcaa18dd97cb9acde | DarioBernardo/hackerrank_exercises | /recursion/word_break.py | 1,959 | 4.0625 | 4 | """
EASY
https://leetcode.com/explore/interview/card/facebook/55/dynamic-programming-3/3036/
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "leetcode", wordDict = ["leet","code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false
"""
from functools import lru_cache
from typing import List, FrozenSet
def wordBreak(s: str, wordDict: List[str]) -> bool:
@lru_cache()
def wordBreakMemo(s: str, wordDict: FrozenSet[str]) -> bool:
if len(wordDict) == 0:
return False
if len(s) == 0:
return True
pointer = 1
is_valid = False
while pointer < len(s) + 1:
sub = s[0:pointer]
if sub in wordDict:
is_valid = wordBreakMemo(s[pointer:], wordDict)
if is_valid:
return True
pointer += 1
return is_valid
return wordBreakMemo(s, frozenset(wordDict))
din = [
("leetcode", ["leet", "code"]),
("applepenapple", ["apple", "pen"]),
("catsandog", ["cats", "dog", "sand", "and", "cat"]),
("ccbb", ["bc", "cb"]),
("a", ["b"])
]
dout = [
True,
True,
False,
False
]
for data_in, expected_result in zip(din, dout):
actual_result = wordBreak(data_in[0], data_in[1])
print(f"Expected: {expected_result} Actual: {actual_result}")
assert expected_result == actual_result
|
0a992d783e6c4208da21a3efbdccfd612437d30b | DarioBernardo/hackerrank_exercises | /stacks_and_queues/minimum_lenght_substring.py | 4,025 | 4.125 | 4 | """
Minimum Length Substrings
You are given two strings s and t. You can select any substring of string s and rearrange the characters of the selected substring. Determine the minimum length of the substring of s such that string t is a substring of the selected substring.
Signature
int minLengthSubstring(String s, String t)
Input
s and t are non-empty strings that contain less than 1,000,000 characters each
Output
Return the minimum length of the substring of s. If it is not possible, return -1
Example
s = "dcbefebce"
t = "fd"'
output = 5
Explanation:
Substring "dcbef" can be rearranged to "cfdeb", "cefdb", and so on. String t is a substring of "cfdeb". Thus, the minimum length required is 5.
"""
def compare_dicts(a, b) -> bool:
for k in b.keys():
if k not in a:
return False
else:
if b[k] > a[k]:
return False
return True
def min_length_substring(s, t):
# Write your code here
if len(s) == 0 or len(t) == 0:
return 0
control = s
test = t
if len(s) < len(t):
test = s
control = t
if len(test) == 1:
return 1 if test in control else 0
results = []
stack_index = []
stack = []
string_hash = {}
test_hash = {}
for c in test:
char_counter = test_hash.get(c, 0)
char_counter += 1
test_hash[c] = char_counter
for pos, c in enumerate(control):
if c in test_hash.keys():
stack.append(c)
stack_index.append(pos)
char_counter = string_hash.get(c, 0)
char_counter += 1
string_hash[c] = char_counter
if compare_dicts(string_hash, test_hash):
results.append(stack_index[-1] - stack_index[0] + 1)
removed_elem = stack.pop(0)
_ = stack_index.pop(0)
string_hash[removed_elem] -= 1
while string_hash[stack[0]] > 1:
removed_elem = stack.pop(0)
_ = stack_index.pop(0)
string_hash[removed_elem] -= 1
if string_hash[removed_elem] <= 0:
del string_hash[removed_elem]
if compare_dicts(string_hash, test_hash):
results.append(stack_index[-1] - stack_index[0] + 1)
return -1 if len(results) == 0 else min(results)
# These are the tests we use to determine if the solution is correct.
# You can add your own at the bottom, but they are otherwise not editable!
def printInteger(n):
print('[', n, ']', sep='', end='')
test_case_number = 1
def check(expected, output):
global test_case_number
result = False
if expected == output:
result = True
rightTick = '\u2713'
wrongTick = '\u2717'
if result:
print(rightTick, 'Test #', test_case_number, sep='')
else:
print(wrongTick, 'Test #', test_case_number, ': Expected ', sep='', end='')
printInteger(expected)
print(' Your output: ', end='')
printInteger(output)
print()
test_case_number += 1
if __name__ == "__main__":
s1 = "dcbefebce"
t1 = "fd"
expected_1 = 5
output_1 = min_length_substring(s1, t1)
check(expected_1, output_1)
s2 = "bfbeadbcbcbfeaaeefcddcccbbbfaaafdbebedddf"
t2 = "cbccfafebccdccebdd"
expected_2 = -1
output_2 = min_length_substring(s2, t2)
check(expected_2, output_2)
# Add your own test cases here
s3 = "abcdefghilmno"
t3 = "gme"
expected_3 = 7
output_3 = min_length_substring(s3, t3)
check(expected_3, output_3)
s2 = "ambhicdefgmnbo"
t2 = "gme"
expected_2 = 4
output_2 = min_length_substring(s2, t2)
check(expected_2, output_2)
s2 = "ambhicdefgmnboglkslkbtemg"
t2 = "gme"
expected_2 = 3
output_2 = min_length_substring(s2, t2)
check(expected_2, output_2)
s6 = "ambhicdefgmnboglkslkbtmegdff"
t6 = "gme"
expected_6 = 3
output_6 = min_length_substring(s6, t6)
check(expected_6, output_6)
|
2a4554a80c37176663dba8d9e8159fc3676c0e74 | DarioBernardo/hackerrank_exercises | /graphs/alien_dictionary.py | 2,872 | 4.03125 | 4 | """
ALIEN DICTIONARY (HARD)
https://leetcode.com/explore/interview/card/facebook/52/trees-and-graphs/3025/
Example of topological sort exercise.
There is a new alien language that uses the English alphabet. However, the order among letters are unknown to you.
You are given a list of strings words from the dictionary, where words are sorted lexicographically by the rules of this new language.
Derive the order of letters in this language, and return it. If the given input is invalid, return "". If there are multiple valid solutions, return any of them.
Example 1:
Input: words = ["wrt","wrf","er","ett","rftt"]
Output: "wertf"
Example 2:
Input: words = ["z","x"]
Output: "zx"
Example 3:
Input: words = ["z","x","z"]
Output: ""
Explanation: The order is invalid, so return "".
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i] consists of only lowercase English letters.
"""
from typing import List, Tuple
def get_association(a: str, b: str):
for ca, cb in zip(a, b):
if ca != cb:
return ca, cb
if len(a) > len(b):
return -1
return ""
def alien_order(words: List[str]) -> str:
if len(words) == 0:
return ""
if len(words) == 1:
return words[0]
if len(words[0][0]) == 0:
return ""
associations_map = dict()
indegree_count = dict()
for i in range(0, len(words)):
if i < len(words) - 1:
association = get_association(words[i], words[i + 1])
if association == -1:
return ""
if association != "":
children = associations_map.get(association[0], [])
children.append(association[1])
associations_map[association[0]] = children
counter = indegree_count.get(association[1], 0)
indegree_count[association[1]] = counter + 1
for c in set(words[i]):
counter = indegree_count.get(c, 0)
indegree_count[c] = counter
queue = []
seen = set()
for letter, counter in indegree_count.items():
if counter == 0:
queue.append(letter)
sol = ""
while len(queue) != 0:
node = queue.pop(0)
seen.add(node)
sol += node
children = associations_map.get(node, [])
for child in children:
indegree_count[child] -= 1
if indegree_count[child] == 0 and child not in seen:
queue.append(child)
if len(indegree_count) - len(seen) > 0:
return ""
return sol
words_in = [
["wrt", "wrf", "er", "ett", "rftt"],
["z", "x"],
["z", "x", "z"],
["z", "z"],
["zy", "zx"]
]
sols = [
"wertf",
"zx",
"",
"z",
"yzx"
]
for i, expected in zip(words_in, sols):
actual = alien_order(i)
print(actual)
assert actual == expected
|
486b6adf4f4fc17b23f16aafca1a3fdafe92465d | DarioBernardo/hackerrank_exercises | /new_year_chaos.py | 1,301 | 3.65625 | 4 | """
NEW YEAR CHAOS
https://www.hackerrank.com/challenges/new-year-chaos
"""
def shift(arr, src_index, dest_index):
if src_index == dest_index or abs(src_index - dest_index) > 2:
return
if src_index - dest_index == 1:
swap(arr, dest_index, src_index)
else:
swap(arr, dest_index, src_index)
swap(arr, dest_index, src_index+1)
def swap(arr, dest_index, src_index):
temp = arr[src_index]
arr[src_index] = arr[dest_index]
arr[dest_index] = temp
def minimumBribes(q):
tot_bribes = 0
state = list(range(1, len(q)+1))
for index, elem in enumerate(q):
bribe = 0
while elem != state[index+bribe] and bribe < 3:
bribe += 1
if bribe >= 3:
print("Too chaotic")
return
if bribe > 0:
shift(state, index, index+bribe)
tot_bribes += bribe
print(f"Bribes: {tot_bribes}")
return tot_bribes
q = [2, 1, 5, 3, 4]
bribes = minimumBribes(q)
assert bribes == 3
q = [1, 2, 5, 3, 7, 8, 6, 4]
"""
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 5, 4, 6, 7, 8]
[1, 2, 5, 3, 4, 6, 7, 8]
[1, 2, 5, 3, 4, 7, 6, 8]
[1, 2, 5, 3, 7, 4, 6, 8]
[1, 2, 5, 3, 7, 4, 8, 6]
[1, 2, 5, 3, 7, 8, 4, 6]
[1, 2, 5, 3, 7, 8, 6, 4]
"""
bribes = minimumBribes(q)
assert bribes == 7
|
3720bb40db37bf3006c90c72bce9419a953aded6 | DarioBernardo/hackerrank_exercises | /arrays/merge_intervals.py | 1,271 | 4.0625 | 4 | """
MEDIUM
https://leetcode.com/problems/merge-intervals/
Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals,
and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example 1:
Input: intervals = [[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: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
"""
from typing import List
def merge(intervals: List[List[int]]) -> List[List[int]]:
if len(intervals) <= 1:
return intervals
intervals = sorted(intervals, key=lambda tup: tup[0])
start_interval = intervals[0][0]
end_interval = intervals[0][1]
sol = []
for i in range(1, len(intervals)):
if end_interval >= intervals[i][0]:
start_interval = min(intervals[i][0], start_interval)
end_interval = max(intervals[i][1], end_interval)
else:
sol.append([start_interval, end_interval])
start_interval = intervals[i][0]
end_interval = intervals[i][1]
sol.append([start_interval, end_interval])
return sol
|
b347b04bc5734a10812e42e9060e8d6323038692 | DarioBernardo/hackerrank_exercises | /search/insert_in_sorted_list.py | 1,090 | 3.84375 | 4 | """
Insert a new elem in a sorted list in O(log N)
"""
import random
from typing import List
def insert_elem(in_list: List, val: int):
if len(in_list) == 0:
in_list.append(elem)
return
start = 0
end = len(in_list)
while start < end:
middle = start + int((end - start) / 2)
if in_list[middle] > val:
end = middle
else:
start = middle + 1
in_list.insert(start, val)
INPUT_LIST_SIZE = 20
NUMBER_OF_TESTS = 10
for _ in range(0, NUMBER_OF_TESTS):
input_list = sorted(list([random.randint(-int(INPUT_LIST_SIZE/2), int(INPUT_LIST_SIZE/2)) for _ in range(0, INPUT_LIST_SIZE)]))
elem = random.randint(-int(INPUT_LIST_SIZE/2), int(INPUT_LIST_SIZE/2))
solution = input_list.copy()
solution.append(elem)
solution = sorted(solution)
insert_elem(input_list, elem)
print(input_list)
print(solution)
assert solution == input_list
input_list = [0, 0, 0, 0, 0]
insert_elem(input_list, 1)
print(input_list)
print([0, 0, 0, 0, 0, 1])
assert [0, 0, 0, 0, 0, 1] == input_list
|
bfecec5ea05dd2fd58ee9e5d88cf083126a5bd06 | DarioBernardo/hackerrank_exercises | /linked_lists/reorder_list.py | 2,478 | 4.0625 | 4 | """
https://leetcode.com/explore/interview/card/facebook/6/linked-list/3021/ (HARD)
You are given the head of a singly linked-list. The list can be represented as:
L0 → L1 → … → Ln - 1 → Ln
Reorder the list to be on the following form:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4]
Output: [1,4,2,3]
Example 2:
Input: head = [1,2,3,4,5]
Output: [1,5,2,4,3]
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reorderList(head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head:
return
if not head.next:
return
# STEP 1: find middle point
# STEP 2: reverse second part
# STEP 3: stitch them togheter
# STEP 1:
slow_pointer = head
fast_pointer = head
while fast_pointer.next and fast_pointer.next.next:
fast_pointer = fast_pointer.next.next
slow_pointer = slow_pointer.next
# STEP 2:
prev = None
current = slow_pointer.next # in current I will find the beginning of the reversed list
slow_pointer.next = None
next_elem = current.next
while next_elem:
current.next = prev
temp = next_elem.next
prev = current
current = next_elem
next_elem = temp
current.next = prev
# STEP 3:
pointer = head
while current:
temp_reverse = current.next
temp_forwad = pointer.next
pointer.next = current
current.next = temp_forwad
current = temp_reverse
pointer = temp_forwad
din = [
[1, 2, 3, 4],
[1, 2, 3, 4, 5]
]
dout = [
[1, 4, 2, 3],
[1, 5, 2, 4, 3]
]
for data_in, expected in zip(din, dout):
head = None
pointer = None
for val in data_in:
node = ListNode(val)
if pointer:
pointer.next = node
pointer = node
if not head:
head = node
reorderList(head)
pointer = head
counter = 0
while pointer:
print(pointer.val)
assert pointer.val == expected[counter], "value {} do not match expected {}".format(pointer.val, expected[counter])
counter += 1
pointer = pointer.next
assert counter == len(expected), "Different number of element returned!"
|
0ef227f6d8f07559a75faa3767d0da5d8fbcbb88 | DarioBernardo/hackerrank_exercises | /tree_and_graphs/tree_level_avg_bfs_and_dfsv2.py | 2,446 | 4 | 4 | """
Given a binary tree, get the average value at each level of the tree.
Explained here:
https://vimeo.com/357608978
pass fbprep
"""
from typing import List
class Node:
def __init__(self, val):
self.value = val
self.right = None
self.left = None
def get_bfs(nodes: List[Node], result: list):
if len(nodes) == 0:
return
current_level_values = []
next_level_children = []
for n in nodes:
current_level_values.append(n.value)
if n.left:
next_level_children.append(n.left)
if n.right:
next_level_children.append(n.right)
result.append(sum(current_level_values)/len(current_level_values))
get_bfs(next_level_children, result)
def get_dfs(n: Node, level_map: dict, current_level: int = 0):
this_level_map = level_map.get(current_level, [])
this_level_map.append(n.value)
level_map[current_level] = this_level_map
if n.left:
get_dfs(n.left, level_map, current_level+1)
if n.right:
get_dfs(n.right, level_map, current_level+1)
def get_level_average(head: Node) -> list:
if head is None:
return []
level_map = {}
get_dfs(head, level_map)
result = []
levels = sorted(level_map.keys())
for level in levels:
level_values = level_map[level]
result.append(sum(level_values)/len(level_values))
return result
def get_level_average_2(head: Node) -> list:
if head is None:
return []
result = []
get_bfs([head], result)
return result
th = Node(4)
th.left = Node(7)
th.right = Node(9)
th.right.right = Node(6)
th.left.left = Node(10)
th.left.right = Node(2)
th.left.right.right = Node(6)
th.left.right.right.left = Node(2)
expected = [4, 8, 6, 6, 2]
actual = get_level_average(th)
actual_bfs = get_level_average_2(th)
print("ACTUAL: \t{}".format(actual))
print("EXPECTED:\t{}".format(expected))
assert actual == expected
assert actual_bfs == expected
root_2 = Node(10)
root_2.left = Node(8)
root_2.right = Node(15)
root_2.left.left = Node(3)
root_2.left.left.right = Node(5)
root_2.left.left.right.right = Node(6)
root_2.right.left = Node(14)
root_2.right.right = Node(16)
expected = [10.0, 11.5, 11, 5, 6]
actual = get_level_average(root_2)
actual_bfs = get_level_average_2(root_2)
print("ACTUAL: \t{}".format(actual))
print("EXPECTED:\t{}".format(expected))
assert actual == expected
assert actual_bfs == expected
|
d4f7b9d7c21da7b017e930daf5fbf1fb729dfe7f | DarioBernardo/hackerrank_exercises | /graphs/journey_to_the_moon.py | 2,213 | 3.703125 | 4 | """
medium
https://www.hackerrank.com/challenges/journey-to-the-moon/problem
"""
class GraphMap:
def __init__(self):
self.graph_map = dict()
def add_link(self, a, b):
links = self.children_of(a)
links.append(b)
self.graph_map[a] = links
def add_bidirectional_link(self, a, b):
self.add_link(a, b)
self.add_link(b, a)
def children_of(self, a):
return self.graph_map.get(a, [])
def size_of_parent_graph(astronaut, gm, visited_astronauts):
queue = [astronaut]
graph_size = 0
while len(queue) != 0:
a = queue.pop(0)
if a not in visited_astronauts:
visited_astronauts.add(a)
graph_size += 1
children = gm.children_of(a)
queue.extend(children)
return graph_size
# Complete the journeyToMoon function below.
def journeyToMoon(n, astronaut):
if n <= 1:
return 0
graph_map = GraphMap()
for pair in astronaut:
graph_map.add_bidirectional_link(pair[0], pair[1])
# find unique separate graphs
country_sizes = []
visited_astronauts = set()
for a in range(0, n):
if a not in visited_astronauts:
country_size = size_of_parent_graph(a, graph_map, visited_astronauts)
country_sizes.append(country_size)
total = 0
my_result = 0
for size in country_sizes:
my_result += total * size
total += size
return my_result
data_in = [
(5, [(0, 1), (2, 3), (0, 4)]),
(4, [(0, 2)]),
(10, [(0, 2), (1, 8), (1, 4), (2, 8), (2, 6), (3, 5), (6, 9)])
]
expected_outputs = [6, 5, 23]
test_case_number = 1
for (tot_number_of_astronauts, astronauts_pairs), expected in zip(data_in, expected_outputs):
actual = journeyToMoon(tot_number_of_astronauts, astronauts_pairs)
result = actual == expected
rightTick = '\u2713'
wrongTick = '\u2717'
if result:
print(rightTick, 'Test #', test_case_number, sep='')
else:
print(wrongTick, 'Test #', test_case_number, ': Expected ', sep='', end='')
print(expected, end='')
print(' Your output: ', end='')
print(actual)
print()
test_case_number += 1
|
79fe834ad9528d7d1d6bdfcb8c8e37dfe8e90fc9 | DarioBernardo/hackerrank_exercises | /graphs/number_of_islands.py | 2,474 | 3.953125 | 4 | """
Given an m x n 2d grid map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
Example 2:
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
"""
from typing import List
def hash(i, j) -> str:
return "{}-{}".format(i, j)
def get_children(x: int, y: int, x_max: int, y_max: int) -> list:
children = []
if x > 0:
children.append((x - 1, y))
if x < x_max:
children.append((x + 1, y))
if y > 0:
children.append((x, y - 1))
if y < y_max:
children.append((x, y + 1))
return children
def bfs(queue, visited_nodes, grid):
x = len(grid)-1
y = len(grid[0])-1
while len(queue) > 0:
elem = queue.pop(0)
if hash(elem[0], elem[1]) not in visited_nodes:
visited_nodes.add(hash(elem[0], elem[1]))
children = get_children(elem[0], elem[1], x, y)
for child in children:
if grid[child[0]][child[1]] == "1":
queue.append(child)
def num_islands(grid: List[List[str]]) -> int:
if len(grid) == 0:
return 0
if len(grid[0]) == 0:
return 0
if len(grid) == 1 and len(grid[0]) == 1:
return 1 if grid[0][0] == "1" else "0"
x = len(grid)
y = len(grid[0])
visited_nodes = set()
island_counter = 0
for xi in range(0, x):
for yi in range(0, y):
starting_point = grid[xi][yi]
if hash(xi, yi) not in visited_nodes and starting_point == "1":
island_counter += 1
queue = [(xi, yi)]
bfs(queue, visited_nodes, grid)
return island_counter
din = [
[["1", "1", "1", "1", "0"],
["1", "1", "0", "1", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "0", "0", "0"]],
[["1", "1", "0", "0", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "1", "0", "0"],
["0", "0", "0", "1", "1"]]
]
expected_results = [
1,
3
]
for i, expected in zip(din, expected_results):
actual = num_islands(i)
print(actual)
print(expected)
assert actual == expected
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.