blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
55b00d4ec187dfd88f71584ce85af1b217af704c | frankieliu/problems | /leetcode/python/ListNode/ListNode.py | 714 | 3.71875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x=None):
self.val = x
self.next = None
self.label = x
self.random = None
def __repr__(self):
out = []
out.append(str(self.val))
head = self.next
while head:
out.append(str(head.val))
head = head.next
return "->".join(out)
def make(h):
ll = []
for el in h:
ll.append(ListNode(el))
for i in range(0, len(ll)-1):
ll[i].next = ll[i+1]
if len(ll) == 0:
return None
return ll[0]
if __name__ == "__main__":
ll = ListNode.make([1, 2, 3, 4, 5])
print(ll)
|
d5f8d17e402d580bd4e305071def1cb02cb91fad | a1exlism/HackingSecretCiphersWithPy | /Transposition/BruteForce/detectEnglish.py | 1,367 | 3.5 | 4 | import sys
def load_dictionary():
# load English dictionary alpha means all letters
w_obj = open('words_alpha.txt')
dict_eng = {}
for word in w_obj.read().split('\n'):
dict_eng[word] = None
w_obj.close()
return dict_eng
def transform_letter(msg):
UPPER_LATTER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
LETTER_SPACE = UPPER_LATTER + UPPER_LATTER.lower() + ' \t\n'
new_msg = ''
for c in msg:
if c in LETTER_SPACE:
new_msg += c
return new_msg
# @type msg: string
def is_english(msg, std_word_precentage=20, std_letter_percentage=85):
possible_words_list = msg.split()
possible_counter = len(possible_words_list)
# No msg
if not possible_counter:
return 0
# with all letters
ENGLISH_WORDS = load_dictionary()
# count english words
word_counter = 0
for word in possible_words_list:
if word in ENGLISH_WORDS:
word_counter += 1
# remove non letter
msg_letter = transform_letter(msg)
# precent for Python2.x
msg_word_precentage = word_counter / possible_counter * 100
msg_letter_precentage = float(len(msg_letter)) / len(msg) * 100
# print(msg_word_precentage)
# print(msg_letter_precentage)
return msg_word_precentage >= std_word_precentage \
and msg_letter_precentage >= std_letter_percentage
|
c803ba5e9859c23727d3237a03a9716d838c53f5 | PerseuSam/FATEC-MECATRONICA-0791811039-SAMUEL | /LTPC2-2020-2/Prova/exerci3.py | 938 | 4.09375 | 4 | temperaturas = []
continuar = True
while continuar == True:
temperatura = int(input("Temperatura que deseja informar: "))
temperaturas.append(temperatura)
if input("Deseja continuar (s/n)? ") == 's':
continuar = True
else:
continuar = False
valor_limiar = int(input("Digite um valor limiar(média): "))
acima_da_media = []
for temperatura in temperaturas:
if temperatura > valor_limiar:
acima_da_media.append(temperatura)
percentual = (len(acima_da_media)*100)/len(temperaturas)
if percentual >= 20 and percentual <45:
print("Dentro do esperado")
elif percentual >=45 and percentual <70:
print("Acima do esperado")
elif percentual >=70 and percentual <100:
print("Muitos valores acima do limiar")
else:
print("Sem problemas aqui")
print("Temperaturas: ", sorted(temperaturas))
print("Valor Limiar: ", valor_limiar)
print("Acima da média: ", sorted(acima_da_media))
print("Percentual: ", percentual)
|
a6bed297fe9e4494999191684baa3e96eec4ac46 | farhasalim/hacktoberfest2021-1 | /Python/Fractal Tree/Fractal_Tree.py | 558 | 3.59375 | 4 | import turtle
import math
import random
t = turtle.Turtle()
t.screen.bgcolor("black")
t.pensize(2)
t.color("brown")
t.penup()
t.left(90)
t.backward(250)
t.pendown()
t.speed(0)
def start(x):
if x < 10:
return
else:
t.forward(x)
t.right(30)
t.color("red")
t.circle(2)
start(x-10)
t.color("yellow")
t.left(60)
t.color("green")
start(x-10)
t.color("white")
t.right(30)
t.backward(x)
start(100)
turtle.done()
|
29b694500f92a03f4bbff521c65cb69ec0fd7051 | pedrovs16/PythonEx | /ex115Library/home.py | 2,208 | 3.703125 | 4 | def inicio():
print('\033[33m=' * 60)
print('MENU PRINCIPAL'.center(50))
print('=' * 60)
print('\033[34m1\033[m - \033[35mCadastrar nova pessoa\033[m')
print('\033[34m2\033[m - \033[35mVer pessoas cadastradas\033[m')
print('\033[34m3\033[m - \033[35mSair do Sistema\033[m')
print('\033[33m=\033[m' * 60)
def escolha():
while True:
try:
escolha = int(input('Sua escolha: '))
while escolha > 3 or escolha < 1:
print('\033[31mValor digitado não condiz com a tabela\033[m')
escolha = int(input('Sua escolha: '))
if escolha > 3 and escolha < 1:
break
except:
print('\033[31mValor digitado não condiz com a tabela\033[m')
else:
break
return escolha
def arquivoExiste(nome):
try:
arquivo = open(nome, 'rt')
arquivo.close()
except (FileNotFoundError):
return False
else:
return True
def criarArquivo(nome):
try:
arquivo = open(nome, 'wt+')
arquivo.close()
except:
print('Houve algum erro')
def opcao1(arquivo) :
print('\033[33m-' * 60)
print('CADASTRAR PESSOA'.center(50))
print('\033[33m-\033[m' * 60)
nome = input('Digite o nome: ')
idade = int(input('Digite a idade: '))
try:
arquivo = open(arquivo, 'at')
except:
print('Arquivo não conseguiu ser aberto')
else:
try:
arquivo.write(f'{nome};{idade}\n')
except:
print('Não consegui computar')
else:
print('Pessoa cadastrada com sucesso!')
arquivo.close()
def opcao2(nome):
print('\033[33m-' * 60)
print('LISTA DE PESSOAS'.center(50))
print('\033[33m-\033[m' * 60)
try:
arquivo = open(nome, 'rt')
except:
print('Arquivo não conseguiu ser aberto')
else:
print('...')
print(f'Nome Idade')
print('-' * 60)
for linha in arquivo:
dado = linha.split(';')
dado[1] = dado[1].replace('\n', '')
print(f'{dado[0]:<30}{dado[1]:>3} anos')
arquivo.close() |
e82cc502cba9ed5151594e5a9b9248e97fa9f53d | arvakagdi/UdacityNanodegree | /LinkedLists/LinkedListModified.py | 5,858 | 3.921875 | 4 | '''
Linked lists with multiple functionality
'''
class Node:
def __init__(self,value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self,value):
if self.head is None:
self.head = Node(value)
return
node = self.head
while node.next:
node = node.next
node.next = Node(value)
return
def to_list(self):
start = self.head
MyList = []
while start:
MyList.append(start.value)
start = start.next
return MyList
def prepend(self, value):
""" Prepend a value to the beginning of the list. """
newnode = None
if self.head is None:
self.head = Node(value)
else:
newnode = self.head
self.head = Node(value)
self.head.next = newnode
pass
def search(self, value):
""" Search the linked list for a node with the requested value and return the node. """
if self.head is None:
return None
newlist = self.head
while newlist:
if newlist.value == value:
return newlist
else:
newlist = newlist.next
pass
def remove(self, value):
""" Remove first occurrence of value. """
if self.head is None:
return None
if self.head.value == value:
self.head = self.head.next
else:
newlist = self.head
while newlist:
if newlist.next.value == value:
newlist.next = newlist.next.next
return
else:
newlist = newlist.next
pass
def pop(self):
""" Return the first node's value and remove it from the list. """
if self.head is None:
return None
value = 0
value = self.head.value
self.head = self.head.next
return value
pass
def insert(self, value, pos):
""" Insert value at pos position in the list. If pos is larger than the
length of the list, append to the end of the list. """
if pos == 0:
self.prepend(value)
return
length = self.size()
newlist = self.head
if pos > length:
while newlist.next is not None:
newlist = newlist.next
newlist.next = Node(value)
else:
newlist = self.head
i = 1
addNode = Node(value)
while newlist:
if i == pos:
addNode.next = newlist.next
newlist.next = addNode
return
else:
i += 1
newlist = newlist.next
pass
def size(self):
""" Return the size or length of the linked list. """
newlist = self.head
size = 0
while newlist:
size += 1
newlist = newlist.next
return size
def __iter__(self):
node = self.head
while node:
yield node.value
node = node.next
def __repr__(self):
return str([v for v in self])
def reverse(linked_list):
ReverseList = LinkedList()
ReverseList.head = None
for value in linked_list:
newnode = Node(value)
newnode.next = ReverseList.head
ReverseList.head = newnode
return ReverseList
pass
## Test your implementation here
# Test prepend
linked_list = LinkedList()
linked_list.prepend(1)
assert linked_list.to_list() == [1], f"list contents: {linked_list.to_list()}"
linked_list.append(3)
linked_list.prepend(2)
assert linked_list.to_list() == [2, 1, 3], f"list contents: {linked_list.to_list()}"
# Test append
linked_list = LinkedList()
linked_list.append(1)
assert linked_list.to_list() == [1], f"list contents: {linked_list.to_list()}"
linked_list.append(3)
assert linked_list.to_list() == [1, 3], f"list contents: {linked_list.to_list()}"
#
# Test search
linked_list.prepend(2)
linked_list.prepend(1)
linked_list.append(4)
linked_list.append(3)
assert linked_list.search(1).value == 1, f"list contents: {linked_list.to_list()}"
assert linked_list.search(4).value == 4, f"list contents: {linked_list.to_list()}"
#
# Test remove
linked_list.remove(1)
assert linked_list.to_list() == [2, 1, 3, 4, 3], f"list contents: {linked_list.to_list()}"
linked_list.remove(3)
assert linked_list.to_list() == [2, 1, 4, 3], f"list contents: {linked_list.to_list()}"
linked_list.remove(3)
assert linked_list.to_list() == [2, 1, 4], f"list contents: {linked_list.to_list()}"
# #
# Test pop
value = linked_list.pop()
assert value == 2, f"list contents: {linked_list.to_list()}"
assert linked_list.head.value == 1, f"list contents: {linked_list.to_list()}"
#
# Test insert
linked_list.insert(5, 0)
assert linked_list.to_list() == [5, 1, 4], f"list contents: {linked_list.to_list()}"
linked_list.insert(2, 1)
assert linked_list.to_list() == [5, 2, 1, 4], f"list contents: {linked_list.to_list()}"
linked_list.insert(3, 6)
assert linked_list.to_list() == [5, 2, 1, 4, 3], f"list contents: {linked_list.to_list()}"
# # Test size
assert linked_list.size() == 5, f"list contents: {linked_list.to_list()}"
llist = LinkedList()
for value in [4,2,5,1,-3,0]:
llist.append(value)
flipped = reverse(llist)
is_correct = list(flipped) == list([0,-3,1,5,2,4]) and list(llist) == list(reverse(flipped))
print("Pass" if is_correct else "Fail") |
46e48a40dae7276ff2a04870329f2e464887f17a | igorlongoria/python-fundamentals | /03_more_datatypes/2_lists/03_09_flatten.py | 335 | 3.828125 | 4 | '''
Write a script that "flattens" a list. For example:
starting_list = [[1, 2, 3, 4], [5, 6], [7, 8, 9]]
flattened_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
'''
starting_list = [[1, 2, 3, 4], [5, 6], [7, 8, 9]]
flatten_list = []
for sublist in starting_list:
for item in sublist:
flatten_list.append(item)
print(flatten_list)
|
d2cd8e8db4cb5848cfcd74b43bb3ec68d15410fc | escm1990/PhythonProjects | /Tareas/T5_Ejercicio1.py | 355 | 3.859375 | 4 | #Ejercicios de concatenación
print("-----EJERCICIO 1-------")
cadena = "Bienvenidos al curso de Python"
cambio = "b" + cadena[1:]
print(cambio)
#############################
print("\n\n-----EJERCICIO 2-------")
cadena2 = "esto es un texto"
numero = 777
cambio2 = "Hola. E" + cadena2[1:] + " y le contateno el número "+str(numero)
print(cambio2)
|
991416e1a143f742350427150c6c293c87e6ead1 | Xolani96/search_base | /05_nqueens_exercise.py | 12,969 | 3.890625 | 4 | """The n queens puzzle: put down n queens on an n by n chessboard so no two
queens attack each other.
The state will be the whole chessboard in these exercises to make implementation
easier.
Implement the BT1 search first, then the two additional state spaces.
"""
from enum import Flag
import copy
from functools import partial
from typing import Any, Generator, List, Mapping, Optional, Tuple, Type, Union
from abc import ABC, abstractmethod
import framework.PySimpleGUI as sg
from framework.board import Board
from framework.gui import BoardGUI
QUEEN_IMAGE_PATH = "tiles/queen_scaled.png"
BLANK_IMAGE_PATH = "tiles/chess_blank_scaled.png"
IMAGE_SIZE = (64, 64)
sg.ChangeLookAndFeel("SystemDefault")
QueensFields = Flag("QueensFields", "W B Q U")
class ChessBoard(Board):
"""The representation of the chessboard. In our search problem, the state is the
chessboard."""
def _default_state_for_coordinates(self, i: int, j: int) -> QueensFields:
# white or black
return QueensFields.W if (i + j) % 2 == 0 else QueensFields.B
def is_under_attack(self, row_ind: int, col_ind: int) -> bool:
"""Checks whether a field is under attack."""
for i, row in enumerate(self.board):
for j, field in enumerate(row):
if not (row_ind == i and col_ind == j):
if field & QueensFields.Q:
if (
row_ind == i
or col_ind == j
or abs(row_ind - i) == abs(col_ind - j)
):
return True
return False
def update_attack(self) -> None:
"""Updates the whole board with all the attacked squares of the queens on the board."""
for row_ind, row in enumerate(self.board):
for col_ind, field in enumerate(row):
if self.is_under_attack(row_ind, col_ind):
self.board[row_ind][col_ind] = field | QueensFields.U
else:
self.board[row_ind][col_ind] = field & ~QueensFields.U
def nqueens(self) -> int:
"""Returns the number of queens on the board."""
return sum(1 for row in self.board for field in row if field & QueensFields.Q)
class QueensProblem(ABC):
"""The abstract n-queens problem. All of the search problems are subclassed from
this class."""
def __init__(self, n: int):
self.n = n
self.board = ChessBoard(n, n)
def start_state(self) -> Board:
"""Returns the start state."""
return self.board
def is_goal_state(self, state: Board) -> bool:
"""Returns true if state is a goal state, false otherwise."""
board = state
nqueens = 0
for i, row in enumerate(board):
for j, field in enumerate(row):
if field & QueensFields.Q:
if board.is_under_attack(i, j):
return False
else:
nqueens += 1
return nqueens == self.n
@abstractmethod
def next_states(self, state: Board) -> Generator[Board, None, None]:
"""Returns the possible next states for state.
This will be different in the different search problems."""
pass
def _to_drawable(self, state: Board) -> Board:
"""As the state is a board, we can just return it as it's already drawable."""
return state
class QueensProblemNoAttack(QueensProblem):
"""This search problem doesn't check attacks and puts Queens arbitrarily on the board."""
def next_states(self, state: Board) -> Generator[Board, None, None]:
board = state
if board.nqueens() >= self.n:
return None
for i, row in enumerate(board):
for j, field in enumerate(row):
if not (field & QueensFields.Q): #if there is not a queen in that Field then we put down a Queen.
next_board = copy.deepcopy(board)
next_board[i, j] = next_board[i, j] | QueensFields.Q
next_board.update_attack()
yield next_board
# YOUR CODE HERE
# The state for the row-by-row search problem will be a board and the current
# row
RowByRowState = Tuple[Board, int]
# SEARCH
# implement the BT1 algorithm
#
# Make it possible to show the steps taken by the algorithm, not just the
# solution. At first you can start by only finding the solution, then extend the
# algorithm with so it also returns the steps. You don't have to store the arcs,
# it's enough to store the states
# the state in backtrack can be either a Board or a combination of a Board and
# the current row
State = Union[Board, RowByRowState]
def backtrack(
problem: QueensProblem, step_by_step: bool = False
) -> Optional[Generator[State, None, None]]:
"""The BT1 algorithm implemented recursively with an inner funcion."""
state = problem.start_state()
path = []
def backtrack_recursive(state: State) -> Optional[List[State]]:
"""The inner function that implements BT1."""
# WRITE CODE HERE
path.append(state)
if problem.is_goal_state(state): #if the current state is the goal state, then return an empty list.
return []
for next_state in problem.next_states(state): #(Go over)/(Loop through) all the neighbours(next_states) of the current(State) state
solution = backtrack_recursive(next_state)
if solution is not None: #if we found a solution, we return the concatenation of the solution with the state that yielded the solution.
return [next_state] + solution
return None
result = backtrack_recursive(state)
# WRITE CODE HERE
if result:
return (r for r in path) if step_by_step else (r for r in result) #we return the Path if we need to go step by step, else we return just the results. We return Generator values
else:
return None #return None if there is no solution.
# SEARCH PROBLEMS (STATE SPACES)
# implement the "next_states" methods
class QueensProblemAttack(QueensProblem):
"""This search problem checks attacks, but puts Queens arbitrarily on the board."""
def next_states(self, state: Board) -> Generator[Board, None, None]:
board = state
if board.nqueens() >= self.n:
return None
for i, row in enumerate(board):
for j, field in enumerate(row):
if not (field & QueensFields.U) and not (field & QueensFields.Q): #if the field does not have a queen and it is not under attack by another queen htne we can place a queen there
next_board = copy.deepcopy(board)
next_board[i, j] = next_board[i, j] | QueensFields.Q
next_board.update_attack()
yield next_board
class QueensProblemRowByRow(QueensProblem):
"""This search problem checks attacks and puts queens on the board row by row.
The state is the board and the next row to put a queen in."""
def start_state(self) -> RowByRowState:
return self.board, 0
def next_states(self, state: RowByRowState) -> Generator[RowByRowState, None, None]:
(
board,
row_ind,
) = state # the state consists of a board and the row index of the next row in which there is no queen
for j,field in enumerate(board[row_ind]):
if not (field & QueensFields.U):
next_board = copy.deepcopy(board)
next_board[row_ind,j] = next_board[row_ind,j] | QueensFields.Q
next_board.update_attack()
yield next_board, row_ind + 1
def is_goal_state(self, state: RowByRowState) -> bool:
board, row_ind = state
return row_ind == board.m
def _to_drawable(self, state: RowByRowState) -> Board:
board, row_ind = state
return board
# END OF YOUR CODE
queens_draw_dict = {
QueensFields.W: ("", ("black", "white"), BLANK_IMAGE_PATH),
QueensFields.B: ("", ("black", "lightgrey"), BLANK_IMAGE_PATH),
QueensFields.U | QueensFields.W: ("", ("black", "red"), BLANK_IMAGE_PATH),
QueensFields.U | QueensFields.B: ("", ("black", "#700000"), BLANK_IMAGE_PATH),
QueensFields.W | QueensFields.Q: ("", ("black", "white"), QUEEN_IMAGE_PATH),
QueensFields.B | QueensFields.Q: ("", ("black", "lightgrey"), QUEEN_IMAGE_PATH),
QueensFields.U
| QueensFields.W
| QueensFields.Q: ("", ("black", "white"), QUEEN_IMAGE_PATH),
QueensFields.U
| QueensFields.B
| QueensFields.Q: ("", ("black", "lightgrey"), QUEEN_IMAGE_PATH),
}
algorithms = {
"Backtrack - step by step": partial(backtrack, step_by_step=True),
"Backtrack - just the solution": backtrack,
}
state_spaces: Mapping[str, Type[QueensProblem]] = {
"Don't check attacks": QueensProblemNoAttack,
"Check attacks": QueensProblemAttack,
"Row by row": QueensProblemRowByRow,
}
board_sizes = {"4x4": 4, "6x6": 6, "8x8": 8, "10x10": 10}
def create_window(board_gui):
layout = [
[sg.Column(board_gui.board_layout)],
[
sg.Frame(
"Algorithm settings",
[
[
sg.T("Algorithm: ", size=(12, 1)),
sg.Combo(
[
"Backtrack - just the solution",
"Backtrack - step by step",
],
key="algorithm",
readonly=True,
),
],
[
sg.T("State space: ", size=(12, 1)),
sg.Combo(
["Don't check attacks", "Check attacks", "Row by row"],
key="state_space",
readonly=True,
),
],
[sg.Button("Change", key="change_algorithm")],
],
),
sg.Frame(
"Problem settings",
[
[
sg.T("Board size: ", size=(12, 1)),
sg.Combo(
["4x4", "6x6", "8x8", "10x10"],
key="board_size",
readonly=True,
),
],
[sg.Button("Change", key="change_problem")],
],
),
],
[sg.T("Steps: "), sg.T("0", key="steps", size=(7, 1), justification="right")],
[sg.Button("Restart"), sg.Button("Step"), sg.Button("Go!"), sg.Button("Exit")],
]
window = sg.Window(
"N queens problem",
layout,
default_button_element_size=(10, 1),
auto_size_buttons=False,
)
return window
starting = True
go = False
steps = 0
board_size = 4
board_gui = BoardGUI(ChessBoard(board_size, board_size), queens_draw_dict)
window = create_window(board_gui)
while True: # Event Loop
event, values = window.Read(0)
window.Element("Go!").Update(text="Stop!" if go else "Go!")
if event is None or event == "Exit":
break
if event == "change_algorithm" or starting:
queens_problem = state_spaces[values["state_space"]](board_size)
algorithm: Any = algorithms[values["algorithm"]]
board_gui.board = queens_problem.board
path = algorithm(queens_problem)
steps = 0
starting = False
stepping = True
if event == "change_problem":
board_size = board_sizes[values["board_size"]]
queens_problem = state_spaces[values["state_space"]](board_size)
board_gui.board = queens_problem.board
board_gui.create()
path = algorithm(queens_problem)
steps = 0
window.Close()
window = create_window(board_gui)
window.Finalize()
window.Element("algorithm").Update(values["algorithm"])
window.Element("state_space").Update(values["state_space"])
window.Element("board_size").Update(values["board_size"])
stepping = True
continue
if event == "Restart":
queens_problem = state_spaces[values["state_space"]](board_size)
board_gui.board = queens_problem.board
path = algorithm(queens_problem)
steps = 0
stepping = True
if (event == "Step" or go or stepping) and path:
try:
state = next(path)
steps += 1
window.Element("steps").Update(f"{steps}")
except StopIteration:
pass
board = queens_problem._to_drawable(state)
board_gui.board = board
board_gui.update()
stepping = False
if event == "Go!":
go = not go
window.Close()
|
66301bd070f5daa788007dfc888275116155cc48 | whitefly/leetcode_python | /链表/92_reverse_linked_list_ii.py | 1,271 | 3.75 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
思入: 和反转链表差不多, 在反转链表的基础上要进行收尾连接.
先到需要反转的首节点上,反转完成后,进行首位拼接. l为反转节点第一个的上一个. 由于
"""
first = ListNode(0)
first.next = head
head = first
for i in range(0, m - 1):
head = head.next
l = head
node1 = head = l.next
count = 0
end = n - m
if not end:
return first.next
last = None
# 开始反转
while count <= end:
temp = head
head = head.next
temp.next = last
last = temp
count += 1
# 拼接首位(反转最后一个节点)和head(反转最后节点的下一个)
node1.next = head
l.next = last
return first.next
if __name__ == '__main__':
s = Solution()
demo = ListNode(5)
m = 1
n = 1
result = s.reverseBetween(demo, m, n)
print(1)
|
753b86f21a1a32dc6cd70ef192082543ef71f83b | jriall/leetcode | /easy/monotonic_array.py | 801 | 4.3125 | 4 | # Monotonic Array
# An array is monotonic if it is either monotone increasing or monotone
# decreasing.
# An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j].
# An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].
# Return true if and only if the given array nums is monotonic.
# Example 1:
# Input: nums = [1,2,2,3]
# Output: true
class Solution:
def isMonotonic(self, nums: List[int]) -> bool:
if len(nums) <= 2:
return True
is_increasing = None
for i in range(1, len(nums)):
if nums[i] > nums[i-1]:
if is_increasing == False:
return False
is_increasing = True
elif nums[i] < nums[i-1]:
if is_increasing == True:
return False
is_increasing = False
return True |
750b2af56d173f32973df187e39d02de498a5005 | yungjoong/leetcode | /20.valid-parentheses.py | 1,554 | 3.890625 | 4 | #
# @lc app=leetcode id=20 lang=python3
#
# [20] Valid Parentheses
#
# https://leetcode.com/problems/valid-parentheses/description/
#
# algorithms
# Easy (38.24%)
# Likes: 4571
# Dislikes: 207
# Total Accepted: 936.3K
# Total Submissions: 2.4M
# Testcase Example: '"()"'
#
# Given a string containing just the characters '(', ')', '{', '}', '[' and
# ']', determine if the input string is valid.
#
# An input string is valid if:
#
#
# Open brackets must be closed by the same type of brackets.
# Open brackets must be closed in the correct order.
#
#
# Note that an empty string is also considered valid.
#
# Example 1:
#
#
# Input: "()"
# Output: true
#
#
# Example 2:
#
#
# Input: "()[]{}"
# Output: true
#
#
# Example 3:
#
#
# Input: "(]"
# Output: false
#
#
# Example 4:
#
#
# Input: "([)]"
# Output: false
#
#
# Example 5:
#
#
# Input: "{[]}"
# Output: true
#
#
#
# @lc code=start
class Solution:
def isValid(self, s: str) -> bool:
l = []
for ch in s :
if ch == '(' or ch == '{' or ch == '[' :
l.append(ch)
else :
if len(l) == 0 :
return False
elif ch == ')' :
if l.pop() != '(' :
return False
elif ch == '}' :
if l.pop() != '{' :
return False
elif ch == ']' :
if l.pop() != '[' :
return False
return len(l) == 0
# @lc code=end
|
247cedce1dd2fe23bb90357048bf5856adc2c07d | jayantraj66041/python-calculator | /python-calculator/calculator design.py | 4,227 | 3.8125 | 4 | import tkinter
from tkinter import *
root = tkinter.Tk()
root.title("Jayant's Calculator")
root.minsize(440, 505)
root.maxsize(440, 505)
top = Frame(root, width=400, height=150, bg="black")
top.pack(fil=X)
num = IntVar()
sum = ""
def clear():
global sum
#num.set(0)
form.delete(0,END)
sum = ""
def total(data):
global sum
sum += str(data)
num.set(sum)
def final():
global sum
data = eval(sum)
num.set(data)
sum = ""
form = Entry(top, width=20, font="arial 27 bold", fg="white", bd=10, bg="black", textvariable=num)
form.pack()
bottom = Frame(root, width=400, height=450, bg="black")
bottom.pack(fill=X)
btn1 = Button(bottom, text="CE", width=4, bd=15, relief="raised", bg="black", fg="white", font="arial 20", command=clear)
btn2 = Button(bottom, text="C", width=4, bd=15, relief="raised", bg="black", fg="white", font="arial 20")
btn3 = Button(bottom, text="X", width=4, bd=15, relief="raised", bg="black", fg="white", font="arial 20")
btn4 = Button(bottom, text="/", width=4, command=lambda:total("/"), bd=15, relief="raised", bg="black", fg="white", font="arial 20")
btn5 = Button(bottom, text="7", width=4, command=lambda:total("7"), bd=15, relief="raised", bg="#4b4b4b", fg="white", font="arial 20")
btn6 = Button(bottom, text="8", width=4, command=lambda:total("8"), bd=15, relief="raised", bg="#4b4b4b", fg="white", font="arial 20")
btn7 = Button(bottom, text="9", width=4, command=lambda:total("9"), bd=15, relief="raised", bg="#4b4b4b", fg="white", font="arial 20")
btn8 = Button(bottom, text="*", width=4, command=lambda:total("*"), bd=15, relief="raised", bg="black", fg="white", font="arial 20")
btn9 = Button(bottom, text="4", width=4, command=lambda:total("4"), bd=15, relief="raised", bg="#4b4b4b", fg="white", font="arial 20")
btn10 = Button(bottom, text="5", width=4, command=lambda:total("5"), bd=15, relief="raised", bg="#4b4b4b", fg="white", font="arial 20")
btn11 = Button(bottom, text="6", width=4, command=lambda:total("6"), bd=15, relief="raised", bg="#4b4b4b", fg="white", font="arial 20")
btn12 = Button(bottom, text="-", width=4, command=lambda:total("-"), bd=15, relief="raised", bg="black", fg="white", font="arial 20")
btn13 = Button(bottom, text="1", width=4, command=lambda:total("1"), bd=15, relief="raised", bg="#4b4b4b", fg="white", font="arial 20")
btn14 = Button(bottom, text="2", width=4, command=lambda:total("2"), bd=15, relief="raised", bg="#4b4b4b", fg="white", font="arial 20")
btn15 = Button(bottom, text="3", width=4, command=lambda:total("3"), bd=15, relief="raised", bg="#4b4b4b", fg="white", font="arial 20")
btn16 = Button(bottom, text="+", width=4, command=lambda:total("+"), bd=15, relief="raised", bg="black", fg="white", font="arial 20")
btn17 = Button(bottom, text="+-", width=4, command=lambda:total("+-"), bd=15, relief="raised", bg="black", fg="white", font="arial 20")
btn18 = Button(bottom, text="0", width=4, command=lambda:total("0"), bd=15, relief="raised", bg="#4b4b4b", fg="white", font="arial 20")
btn19 = Button(bottom, text=".", width=4, command=lambda:total("."), bd=15, relief="raised", bg="black", fg="white", font="arial 20")
btn20 = Button(bottom, text="=", width=4, bd=15, command=final, relief="raised", bg="black", fg="white", font="arial 20")
btn1.grid(row=0, column=0, padx=5, pady=3)
btn2.grid(row=0, column=1, padx=5, pady=3)
btn3.grid(row=0, column=2, padx=5, pady=3)
btn4.grid(row=0, column=3, padx=5, pady=3)
btn5.grid(row=1, column=0, padx=5, pady=3)
btn6.grid(row=1, column=1, padx=5, pady=3)
btn7.grid(row=1, column=2, padx=5, pady=3)
btn8.grid(row=1, column=3, padx=5, pady=3)
btn9.grid(row=2, column=0, padx=5, pady=3)
btn10.grid(row=2, column=1, padx=5, pady=3)
btn11.grid(row=2, column=2, padx=5, pady=3)
btn12.grid(row=2, column=3, padx=5, pady=3)
btn13.grid(row=3, column=0, padx=5, pady=3)
btn14.grid(row=3, column=1, padx=5, pady=3)
btn15.grid(row=3, column=2, padx=5, pady=3)
btn16.grid(row=3, column=3, padx=5, pady=3)
btn17.grid(row=4, column=0, padx=5, pady=3)
btn18.grid(row=4, column=1, padx=5, pady=3)
btn19.grid(row=4, column=2, padx=5, pady=3)
btn20.grid(row=4, column=3, padx=5, pady=3)
root.mainloop() |
da376b2371aaf992f321d37f8e83881d3b384a3a | csiggydev/crashcourse | /3-1_names.py | 193 | 3.578125 | 4 | #! /usr/bin/env python
# 3-1 Names
names = ['Mike', 'Jason', 'Matt']
print(names)
# Print Mike only
print(names[0])
# Print Jason only
print(names[1])
# Print Matt only
print(names[2]) |
763e10cbeb85e0a00e6d8bbea2c4a139845202d9 | shadowflush/my_LeetCode | /findMedianSortedArrays.py | 1,439 | 3.953125 | 4 | def median(nums1, nums2):
len1, len2 = len(nums1), len(nums2)
if len1 > len2:#make sure len(nums1)<=len(nums2)
nums1,nums2,len1,len2 = nums2,nums1,len2,len1
if len1 == 0:# if one list is empty
if len2%2:
return nums2[len2//2]
else:
return (nums2[len2//2]+nums2[len2//2-1])/2
i_former, i_later, half_len = 0, len1, (len1 + len2 + 1) // 2
while i_former <= i_later:
i = (i_former + i_later) // 2
j = half_len - i
if i < len1 and nums2[j-1] > nums1[i]:#L2>R1,i < we want
i_former = i + 1
elif i >0 and nums1[i-1] > nums2[j]:#L1>R2, i > we want
i_later = i - 1
else:# i is we want
if i == 0: max_of_left = nums2[j-1]
elif j == 0: max_of_left = nums1[i-1]
else:max_of_left = max(nums1[i-1], nums2[j-1])
if (len1+len2)%2:# if len1+len2 is odd max_of_left is we want. in order to cut down runtime ,place this statement at here not the end
return max_of_left
if i == len1: min_of_right = nums2[j]
elif j == len2: min_of_right = nums1[i]
else:min_of_right = min(nums1[i],nums[j])
return (max_of_left + min_of_right) / 2.0
a = [7]
c = [6,7,8,9]
d=median(a,c)
print(d)
#the answer based on MissMary : https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2481/Share-my-O(log(min(mn))-solution-with-explanation |
eb101b948b5209b0e6af3757cf74d8bf92b3b18f | danilosp1/Exercicios-curso-em-video-python | /ex044.py | 476 | 4.03125 | 4 | val = float(input('Qual o valor do produto? '))
print('Digite a forma de pagamento:')
print('[1] À vista no dinheiro')
print('[2] À vista no cartão')
print('[3] Até 2x no cartão')
print('[4] 3x ou mais no cartão')
tip = int(input('Qual sua opção de pagamento? '))
if(tip == 1):
pagamento = val*0.9
elif(tip == 2):
pagamento = val*0.95
elif(tip == 3):
pagamento = val
else:
pagamento = val*1.2
print('Voce pagará no total R${:.2f}'.format(pagamento)) |
579137ee63152401b0cae5e3f564c378ad4f5d29 | EyesMcKinney/Python-Projects-CS1 | /lab08/train_run.py | 2,199 | 4.09375 | 4 | """
file: train_run.py
by: Isaac McKinney
runs a simulated train yard based off a serious of user inputted commands
"""
from command_list import *
def process_commands(command, train):
"""
process the inputted command
pre-condition: command has been passed in as an input and a train has been created
post-condition: command has been read and processed, train is adjusted accordingly
:param command: the action the user wishes to have processed
:param train: the linked list which represents the train
:return: N/A
"""
action = command.split()[0]
if action == "set_speed":
try:
speed = command.split()[1]
set_speed(speed, train)
except ValueError:
print("Illegal Command Use or Form")
elif action == "help":
help()
elif action == "add_car":
try:
content, place, distance = command.split()[1:]
add_car(content, place, distance, train)
except ValueError:
print("Illegal Command Use or Form")
elif action == "quit":
return quit()
elif action == "train_size":
print("Number of cars attached to the train is " + str(train_size(train)))
elif action == "show_train":
print(show_train(train))
elif action == "start":
if train.speed <= 0:
print("Illegal Command Use or Form")
else:
start(train)
else:
print("Illegal Command Name: Command doesn't exist in database")
command = str(input("Enter a command: "))
process_commands(command, train)
def main():
"""
initials the train(linked list), prints a welcome message, and compiles the program
pre-condition: train is made and command is an empty string
post-condition: train is manipulated appropriately and it is used in the sim.
string is filled
:return: N/A
"""
train = Entire_Train(None, 0, 0)
print("welcome to the train yard!")
command = str(input("Enter a command: "))
process_commands(command, train)
if __name__ == '__main__':
main()
|
b94a4c99cfd1c0dea043afd9452ade2ef29552d6 | falcon97/wallbreakers | /Week 2/Hashmaps and Sets/word_pattern.py | 367 | 3.703125 | 4 | class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
s = str.split()
return len(set(zip(pattern, s))) == len(set(pattern)) == len(set(s)) and len(pattern) == len(s)
if __name__ == "__main__":
solution = Solution()
pattern = "abba"
str = "dog cat cat dog"
out = solution.wordPattern(pattern, str)
print(out)
|
21b4af045fa440a952e5b7f62e6a1b49f8cb40d4 | beidou9313/deeptest | /第二期/北京-辉色秋天/day-2/day2-convert.py | 197 | 3.71875 | 4 | # -*- coding:utf-8 -*-
if __name__ == "__main__":
x = 1.68
y = 10
print("整数为%d"%int(x))
print("浮点数为%f"%float(y))
print("复数为", end='')
print(complex(x))
|
e65dfe0b108b098789b0dd1f95ab923c7de06970 | Acc-one/vsu_programming | /3.2 .py | 236 | 4.09375 | 4 | a = int(input('Введите номер месяца: '))
if 0 < a < 3 or a == 12:
print('Зима')
elif 2 < a < 6:
print('Весна')
elif 5 < a < 9:
print('Лето')
elif 8 < a < 12:
print('Осень')
|
972214935177b10614e04d0c5928da6eded6bc28 | lvrcek/advent-of-code-2020 | /day19/1.py | 1,749 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Advent of Code 2020
Day 19, Part 1
"""
from time import time
memo = {}
def parse(f):
d = {}
for line in f:
line = line.strip()
if len(line) == 0:
return d
rule_num, rest = line.split(':')
rule_num = int(rule_num)
rest = rest.strip()
if '"' in rest:
c = rest[1]
d[rule_num] = c
elif '|' in rest:
rule1, rule2 = rest.split('|')
r1 = tuple(map(int, rule1.strip().split()))
r2 = tuple(map(int, rule2.strip().split()))
d[rule_num] = [r1, r2]
else:
rules = [tuple(map(int, rest.strip().split()))]
d[rule_num] = rules
return d
def get_all_strings(rules_dict, rule):
if rule in memo:
return memo[rule]
if isinstance(rules_dict[rule], str):
memo[rule] = list(rules_dict[rule])
return memo[rule]
groups = rules_dict[rule]
new_strings = []
for group in groups:
append_prefix = ['']
for next_rule in group:
strings = get_all_strings(rules_dict, next_rule)
new = [a + s for a in append_prefix for s in strings]
append_prefix = new.copy()
new_strings.extend(append_prefix)
memo[rule] = new_strings
return new_strings
def main():
with open('in.txt') as f:
rules = parse(f)
start = time()
get_all_strings(rules, 0)
variations = set(memo[0])
counter = 0
for line in f:
line = line.strip()
counter += line in variations
print(counter)
end = time()
print(f'{end - start} s')
if __name__ == '__main__':
main()
|
0f74f85526b5d961c800d4334ace72176b7a1853 | anoopkcn/meeseeks | /meeseeks/format.py | 1,910 | 4.59375 | 5 | def to_string(list, sep=' '):
'''returns a list without brakets[]
For using python list's in other programs
Arguments:
a {list} -- one dimensional list
Example:
>>> a = [1,2,3,4,5]
>>> print(strip(a))
>>> 1 2 4 5
'''
return f'{sep}'.join(map(str, list))
def with_commas(N):
'''returns a number separated with commas
Number is returend in a readable format...
... with commas separating the digits
Arguments:
N {number} -- a whole number
Example:
>>> a = 12345
>>> print(commas(a))
>>> 12,345
'''
return '{:,}'.format(N)
def is_number(s):
'''
Check if a string can be cast to a float or numeric (integer).
Takes a string.
Returns True or False
'''
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
def to_number(s):
'''
Cast a string to a float or integer.
Tries casting to float first and if that works then it tries casting the
string to an integer.
Returns a float, int, or if fails, False. (Where using, it shouldn't ever
trigger returning `False` because checked all could be converted first.)
'''
try:
number = float(s)
try:
number = int(s)
return number
except ValueError:
pass
return number
except ValueError:
pass
try:
import unicodedata
num = unicodedata.numeric(s)
return num
except (TypeError, ValueError):
pass
return False
if __name__ == '__main__':
# tests
print(to_string([1, 2, 3, 4, 5]))
print(with_commas(20000))
print(is_number('3e-4'))
print(is_number('30,000'))
print(to_number('3.12e2'))
|
2a00e1e90af48761b0f676057bb355ad46533f42 | ArshSood/Codechef_Assignment | /PEC2021C/lineartime.py | 237 | 3.65625 | 4 | n = int(input())
set={""}
for i in range(0, n):
x = int(input())
set.add(x)
set.remove("")
q = int(input())
print("1")
for i in range(0, q):
x = int(input())
if x in set:
print('yes')
else:
print('no') |
9657dd8cbef2614a646d155955744ffe90e34fcd | billakantisandeep/pythonproj | /Files/file2.py | 576 | 4.09375 | 4 | #This program demonstrates the closing of the file without using the f.close()
#Using the context managers -- Which will help inclosing
#Within the context manager
with open('C:\\Users\\sbillakanti\\pythonlearning\\Files\\test.txt', 'r') as f:
f_contents = f.read()
print(f_contents)
print(f.name) #To open the file name
# print(f.read()) #It gives error since we need to work within the with(Block)
#Reading from the file
#You can use the print(f.read()) method to read the contents but it would be better to take in a variable so that you can work on that. |
4793cc0ff2a53bc044ca6cac1a3ab6c8629ba75e | zhaobe/splinter-dev | /quick-tut.py | 631 | 3.734375 | 4 | # creating the browser instance
from splinter import Browser
browser = Browser('chrome')
# going to google.com
browser.visit('http://google.com')
# input search for splinter - python acceptance ...
browser.fill('q', 'splinter - python acceptance testing for web applications')
# find the search button and click it
browser.find_by_name('btnG').click()
# check if the Splinter official website is in search
if browser.is_text_present('splinter.readthedocs.io'):
print "Yes, the official website was found!"
else:
print "No, it wasn't found... We need to improve our SEO techniques"
# close the browser
browser.quit()
|
041271b7c348bf52176a78b4b64ba7f2e2d8c2d2 | liuyuzhou/ai_pre_sourcecode | /chapter4/dict_list_df_3.py | 257 | 3.703125 | 4 | import pandas as pd
data = [{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}]
df_1 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b'])
print(df_1)
df_2 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b1'])
print(df_2)
|
a4cdf65a3cd5f1eff76e47e29e498b911e000d58 | itsuna/Python-matplotlib-Usage | /angle_distribution_plot.py | 5,193 | 3.671875 | 4 | # モジュールをインポートする
# 数値計算を効率的に行う"numpy"というモジュールを"np"という名前でインポート
import numpy as np
# データ解析をサポートする"pandas"というモジュールを"pd"という名前でインポート
import pandas as pd
# グラフ作成に必要な"matplotlib"の中の"pyplot"を"plt"という名前でインポート
import matplotlib.pyplot as plt
# グラフにしたいデータの入っているExcelファイル("angle_distribution_ex.xlsx)の場所と名前を入れる
excel_path = ".\\"
excel_file_name = "angle_distribution_ex.xlsx"
# そのExcelファイルをexcel_dataという名前で読み込む
excel_data = pd.ExcelFile(excel_path + excel_file_name)
# 一番始めのSheetの中身をdataframe型にする
df = excel_data.parse(excel_data.sheet_names[0])
# 項目"Sample"の中で"A"が入っている列だけ取り出し保存
df_A = df[df["Sample"]=="A"]
# 項目"Sample"の中で"B"が入っている列だけ取り出し保存
df_B = df[df["Sample"]=="B"]
# 角度の度数分布表を作成する関数
def create_angular_frequency_distribution_table(df, div_num, MAX_DEGREE=180):
# 1つのエリアの幅を計算する。(ex. MAX_DEGREE=180°かつdiv_num=9の場合, 1つのエリアの幅は20°)
each_angle_size = MAX_DEGREE / div_num
# 各エリアの角度を入れる。(+1により最後の角度も入る)
angle_list = [i * each_angle_size for i in range(div_num + 1)]
# 度数分布表を辞書型で初期化する
angular_distribution = {angle: 0 for angle in angle_list[:-1]}
# dataframeを一行ずつ読み込む
for index, row in df.iterrows():
# ある行の角度が度数分布表のどこに入るかを探す
for i in range(len(angle_list)-1):
# もしある行の角度が, angle_list[i]以上angle_list[i+1]未満ならその度数分布表を+1してループを抜ける
if ((row["Angle"] >= angle_list[i]) and (row["Angle"] < angle_list[i+1])):
angular_distribution[angle_list[i]] += 1
break
print(angular_distribution)
return [angular_distribution, angle_list]
def plot_angular_distribution(ax, angle_dist, angle_list, r_max, r_tick_width, MAX_DEGREE=180):
import math
# 偏角Θの範囲を決める
ax.set_xlim([0, np.pi*MAX_DEGREE/180])
# 30°刻みにtickを入れる
ax.set_xticks([i * np.pi / 6 for i in range(int(math.floor(MAX_DEGREE/30)+1))])
# 動径rの範囲を引数r_maxから設定する
ax.set_ylim([0, r_max])
# r_tick_width刻みにtickを入れる
ax.set_yticks([r_tick_width * i for i in range(int(math.ceil(r_max/r_tick_width)))])
for i in range(len(angle_list)-1):
# 扇形の閉曲線を作る
theta = np.array(
[angle_list[i]*np.pi/180, angle_list[i]*np.pi/180] +
[theta*np.pi/180 for theta in np.linspace(angle_list[i], angle_list[i+1], num=int(angle_list[i+1]-angle_list[i]))] +
[angle_list[i+1]*np.pi/180, angle_list[i+1]*np.pi/180]
)
r = np.array(
[0, angle_dist[angle_list[i]]] +
[angle_dist[angle_list[i]] for theta in np.linspace(angle_list[i], angle_list[i+1], num=int(angle_list[i+1]-angle_list[i]))] +
[angle_dist[angle_list[i]], 0]
)
# 作った扇形をプロット
ax.plot(theta, r, color="#333333", linewidth=1)
# 扇の内側を塗りつぶす
ax.fill(theta, r, "#aaaaaa")
return ax
# ここからグラフを作成
# 1行2列のグラフの土台を作成
fig, axes = plt.subplots(1, 2, subplot_kw=dict(projection="polar"))
# グラフのサイズ指定
fig.set_size_inches(12, 5)
# df_Aからangular_distributionとangle_listを計算する
angle_dist_A, angle_list_A = create_angular_frequency_distribution_table(df_A, 9)
# 1行1列目のグラフにプロット
axes[0] = plot_angular_distribution(axes[0], angle_dist_A, angle_list_A, 22, 10)
# df_Bからangular_distributionとangle_listを計算する
angle_dist_B, angle_list_B = create_angular_frequency_distribution_table(df_B, 9)
# 1行2列目のグラフにプロット
axes[1] = plot_angular_distribution(axes[1], angle_dist_B, angle_list_B, 22, 10)
for ax, name in zip(axes, ["Sample A", "Sample B"]):
# タイトルをフォントサイズ14で"Sample B"とし、位置調整
ax.set_title(name, y=0.85, fontsize=14)
# xlabelをフォントサイズ14で"Frequency"に
ax.set_xlabel("Frequency", fontsize=14)
# xlabelの位置調整
ax.xaxis.set_label_coords(0.5, 0.15)
fig.tight_layout()
# saveするかどうかのboolean
save = False
# 保存先のpathとファイル名を指定
save_path = ".//"
save_file_name = "20181024 angle_distribution_plot_ex"
# saveするなら以下で保存 (ex. png and svg)
if save==True:
plt.savefig(save_path + save_file_name + ".png")
plt.savefig(save_path + save_file_name + ".svg")
# グラフを見る
plt.show()
# グラフの情報を捨てる
plt.close()
|
e2189990028d9fefc53eb4f656cba7af62e16f11 | taoranzhishang/Python_codes_for_learning | /study_code/Day_03/5多个数据输入和交互赋值数据交换.py | 210 | 3.953125 | 4 | num1, num2, num3 = input("请输入:") # 依次输入三个数,用逗号隔开
print(num1, num2, num3)
# 不引入中间变量实现交换
a, b, c = 1, 2, 3
print(a, b, c)
a, b, c = c, b, a
print(a, b, c)
|
f494735911e12b17f7b38e16312ec3989cad10f9 | fafaovo/python | /p127-tuple.py | 444 | 4.1875 | 4 | # 元组:可以存储多个数据,但是不能修改
tuple1 = (10, 20, 30)
print(tuple1)
tuple2 = (19,)
# 使用元组存储单个要在后面添加一个逗号
# 下标 index count len [通用方法]
# 元组中有列表,这个列表是可以修改的,一个列表里面有个元组,里面的元组不可修改
tl1 = list(tuple1)
tl1[0] = 30
tuple1 = tuple(tl1)
print(tuple1)
# 如果需求修改元组可以把他转换成列表进行修改
|
0355a47aba19239733d448d96063595597b18023 | anupivan/anup | /dicegame2.py | 155 | 3.875 | 4 | #dicegame
import random
while True:
i=input("enter r to roll or q to quit")
if(i=='r'):
print(random.randint(1,6))
else:
print("bye!")
exit()
|
5bfe083845d9622557f31675d25782fb7d6cc544 | knuu/competitive-programming | /hackerrank/unkoder/unkoder06_tera.py | 166 | 3.5625 | 4 | N = list(input())
flag = False
for i, n in enumerate(N):
if flag:
N[i] = '9'
elif n == '4':
flag = True
N[i] = '3'
print(''.join(N))
|
f37da08cf483fcb92d3cef28d52a510f128564ad | malaybiswal/python | /hackerrank/bigsorting.py | 211 | 3.765625 | 4 | n = int(input().strip())
unsorted = []
unsorted_i = 0
for unsorted_i in range(n):
unsorted_t = str(input().strip())
unsorted.append(unsorted_t)
unsorted.sort(key = int)
for val in unsorted:
print(val)
|
f6c418fbc9348d342328e8aba17cbd643f19e2d0 | smohamed7/pythonbasics | /passwordsettingtask.py | 426 | 4.25 | 4 | #An application that asks a user a string password
#if the characters are less than five print too short
#if the characters are greater than five show too long
password = str(input("type in your password:"))
if len(password)<5:
print("yours password is too short")
elif len(password)>15:
print("password too long")
elif len(password) >=5 and len(password) <=15:
print("success")
else:
print("INVALID")
#
|
db862addc2f5ed63335276eddbbf2723a46f511c | WhiskeyKoz/self.pythonCorssNave | /script/nave941.py | 1,220 | 4.28125 | 4 | from collections import Counter
def choose_word(file_path, index):
"""
the function return tuple of The number of different words in the file
that is, does not include repetitive words and word in index was the function was collected
:param file_path: path to txt file
:type: str
:param index: index in a word in txt file
:type: int
:return:tuple of The number of different words in the file
that is, does not include repetitive words and word in index was the function was collected
:rtype: int and str
"""
with open(file_path, "r") as x:
redeing = x.read()
redeing = redeing.split(" ")
for i in range(0, len(redeing)):
redeing[i] = "".join(redeing[i])
x = Counter(redeing)
none_duplicates_list = " ".join(x.keys())
len_list = none_duplicates_list.split(" ")
len_redeing = len(redeing)
while index > len_redeing:
index -= len_redeing
end_tuple = (len(len_list), redeing[index-1])
return end_tuple
def maim():
print(choose_word(r"C:\Users\Admin\OneDrive\שולחן העבודה\file1.txt", 3))
if __name__ == '__main__':
maim() |
8683a4ff6f286a04f1d49df1783387580b012d97 | Samrat132/Printing_Format | /Lab3/fizz_buzz.py | 614 | 4.1875 | 4 | #Write a function called fizz_buzz that takes a number.
# If the number is divisible by 3, it should return “Fizz”.
# If it is divisible by 5, it should return “Buzz”.
# If it is divisible by both 3 and 5, it should return “FizzBuzz”.
# Otherwise, it should return the same number.
def fizz_buzz():
for fizz_buzz in range (50):
if fizz_buzz %3 ==0 and fizz_buzz % 5 ==0 :
print("FizzBuzz")
return
elif fizz_buzz % 5 ==0:
print("Buzz")
return
elif fizz_buzz % 3 ==0 :
print("Fizz")
return
fizz_buzz()
|
90f25bb9a3eee9abbc42a5acce5c254bbe634ad7 | Tonestheman95/Python | /bankaccount.py | 875 | 3.796875 | 4 | from fundamentals.oop.userswithbankaccount import Tonio
class Bankaccount:
def __init__(self,interest_rate = 0, balance = 0):
self.interest_rate = interest_rate
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(self.balance)
return self
def withdraw(self, amount):
if amount > self.balance:
print("INVALID TRANSACTION")
elif self.balance > 0:
self.balance -= amount
print(self.balance)
return self
def display_account_info(self):
print(self.balance)
return self
def yield_interest(self):
if self.balance > 0:
interest_Amount = self.interest_rate * self.balance
self.balance += interest_Amount
return self
Tonio = Bankaccount(.05,1000)
Tonio.deposit |
b5f0082f71fa6f494151141960e495bbe402b8d6 | j471n/Hacker-Rank | /30 Days of Code/7-Arrays.py | 495 | 4.125 | 4 | if __name__ == '__main__':
n = int(input())
#initializing array/list which will take input with spaces
arr = list(map(int, input().rstrip().split()))
arr.reverse() #to reverse the array
#we are using loop to print the array
for x in range(len(arr)):
print(arr[x],end=" ")
#we can use it like that
#>>>>>> print(arr, end=" ")
#but there an issue if we print like that it print like [1,2,3], which we don't want. |
52949e98dab2ff3210167666b56603f88b4f2565 | brdayauon/Competitive-Coding-11 | /reversePolishNotation.py | 1,212 | 3.734375 | 4 | # Time Complexity : O(N)
# Space Complexity : O(N)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Your code here along with comments explaining your approach
#array of strings
def getVal(arr):
if not arr:
return 0
stack = []
#assume array is always valid
for i in range(len(arr)):
#if it's an operator ( + - * /) we just do operations on the last two numbers from the stack
if arr[i] == '+':
val1 = stack.pop()
val2 = stack.pop()
stack.append(val1+val2)
elif arr[i] == '-':
val1 = stack.pop()
val2 = stack.pop()
stack.append(val2-val1)
elif arr[i] == '*':
val1 = stack.pop()
val2 = stack.pop()
stack.append(val1*val2)
elif arr[i] == '/':
val1 = stack.pop()
val2 = stack.pop()
stack.append(val2//val1)
#append number to stack
else:
stack.append(int(arr[i]))
return stack.pop()
arr = ["2", "1", "+", "3", "*"]
print(getVal(arr))
arr = ["4", "13", "5", "/", "+"]
print(getVal(arr))
|
4de56ac10a8ff41785076352726087816a520cb8 | hk1486/Python_master | /06_01_str.py | 3,501 | 4.15625 | 4 | # 문자열 함수들
# 대표적으로 문자열(str)은 많은 함수(메소드)들을 갖고 있습니다.
# str 의 대표적인 함수들 ==> split, join, replace, format
# https://docs.python.org/3/library/stdtypes.html#textseq
# upper(), lower() 대소문자 변환
str1 = 'apple'
print(str1, str1.upper(), str1.lower())
# str.join(), str.split() ---> 03_02 참조
#----------------------------------
# CSV : Comma Seperated Value
# TSV : TAB Seperated Value
data = "사과, 바나나, 파인애플, 포도, 복숭아"
print(data.split("'"))
print("\t".join(data.split()))
# replace 문자열 치환
data = '데이터 분석을 위한 파이썬 프로그래밍'
# 파이썬을 영어로 바꾸기
print(data.replace('파이썬', 'Python'))
# 문자열 원본은 변환되지 않는다.
print("replace 후 원본은 =>",data)
#split(), join() 으로 replace() 효과
print("Python".join(data.split('파이썬')))
print()
# index(), find()
#문자열 안에서 문자열 찾기
print("th" in "python")
data = "Hello Python"
# index() : 문자열을 발견한 위치 (인덱스)리턴
print(data.index('lo'))
# print(data.index('x')) 없는값을 찾으면 에러발생
print(data.find('lo'))
print(data.find('x')) # 없는값을 찾으려고 하면 -1 리턴
# count()
# 문자열 내에서 특정 문자열 패턴의 반복 횟수
data = 'asdasdasdasdasd'
print(data.count('a'))
print(data.count('sd'))
# startswith(), endswith()
# 문자열이 특정 문자열로 시작/종료하는지 여부
url = "www.naver.com"
print(url.startswith("http")) # F
if not url.startswith("http"):
url = "https://" + url
print(url)
print(url.endswith('.com')) # T
# ord() : 문자의 코드값(사전순)
# chr() : 코드의 문자값(사전순)
print(ord('a')) # a의 문자값 출력 97
print(chr(97)) # 97번 코드의 문자값 출력 a
print(ord('가')) # 한글도 나옴 사전순서.. 44032
# 문자열에 대해 비교연산자 작동함
# 코드(사전순)으로 비교
print('a' < 'b') # T
print('cable'<'bible') # F
print('가마우지'<"까마귀") # T
print('aAaA'<'AaAa') # F 대문자가 코드값이 더 작음
data = [
'aAaA', #1
'aaAA', #2
'AAaa', #3
'AaAa' #4
]
print(sorted(data)) # ['AAaa', 'AaAa', 'aAaA', 'aaAA'] 사전순 정렬
# 알파벳 개수
print("알파벳 개수",ord('z')-ord('a')+1) # 알파벳 개수26
print("한글 개수",ord('힣')-ord('가')+1) # 한글 개수 11172
# 연습
# 알파벳 소문자로 이루어진 리스트 작성
# List comprehension
# ['a','b',...'z']
alpa = [chr(i + ord('a')) for i in range(ord('z')-ord('a')+1)]
print(alpa) # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# 연습
word = "Alice in wonderland"
# 등장하는 알파벳의 개수 - > dict 결과 만들기
# Dict comprehension
# 대소문자 구분 안함
# hint : 알파벳 리스트, lower, upper, count
# 출력 예
# {'a': 2,
# 'c': 1,
# 'd': 2,
# 'e': 2,
# 'i': 2,
# 'l': 2,
# 'n': 3,
# 'o': 1,
# 'r': 1,
# 'w': 1}
result = {
ch : word.lower().count(ch) # 추출한 알파벳 : 워드.소문자변형.알파벳수
for ch in [chr(i + ord('a'))
for i in range(ord('z')-ord('a')+1)] # 알파벳 리스트에서 a부터 z까지 추출
if word.lower().count(ch) > 0 # 워드.소문자.알파벳수가 0보다 클때
}
print(result)
|
5e788077cb8480207acf3bf622b3f914f7bde9f6 | r4inm4ker/Kraken | /Python/kraken/core/maths/vec3.py | 12,439 | 3.515625 | 4 | """Kraken - maths.vec3 module.
Classes:
Vec3 -- Vector 3 object.
"""
import math
from kraken.core.kraken_system import ks
from math_object import MathObject
class Vec3(MathObject):
"""Vector 3 object."""
def __init__(self, x=0.0, y=0.0, z=0.0):
"""Initializes x, y, z values for Vec3 object."""
super(Vec3, self).__init__()
if ks.getRTValTypeName(x) == 'Vec3':
self._rtval = x
else:
self._rtval = ks.rtVal('Vec3')
if isinstance(x, Vec3):
self.set(x=x.x, y=x.y, z=x.z)
else:
self.set(x=x, y=y, z=z)
def __str__(self):
"""String representation of the Vec3 object.
Returns:
str: String representation of the Vec3 object.
"""
return "Vec3(" + str(self.x) + "," + str(self.y) + "," + str(self.z) + ")"
@property
def x(self):
"""Gets x value of this vector.
Returns:
float: X value of this vector.
"""
return self._rtval.x.getSimpleType()
@x.setter
def x(self, value):
"""Sets x value from the input value.
Args:
value (float): Value to set the x property as.
Returns:
bool: True if successful.
"""
self._rtval.x = ks.rtVal('Scalar', value)
return True
@property
def y(self):
"""Gets y value of this vector.
Returns:
float: Y value of this vector.
"""
return self._rtval.y.getSimpleType()
@y.setter
def y(self, value):
"""Sets y value from the input value.
Args:
value (float): Value to set the y property as.
Returns:
bool: True if successful.
"""
self._rtval.y = ks.rtVal('Scalar', value)
@property
def z(self):
"""Gets z value of this vector.
Returns:
float: Z value of this vector.
"""
return self._rtval.z.getSimpleType()
@z.setter
def z(self, value):
"""Sets y value from the input value.
Args:
value (float): Value to set the y property as.
Returns:
bool: True if successful.
"""
self._rtval.z = ks.rtVal('Scalar', value)
return True
def __eq__(self, other):
return self.equal(other)
def __ne__(self, other):
return not self.equal(other)
def __add__(self, other):
return self.add(other)
def __sub__(self, other):
return self.subtract(other)
def __mul__(self, other):
return self.multiply(other)
def __div__(self, other):
return self.divide(other)
def clone(self):
"""Returns a clone of the Vec3.
Returns:
Vec3: The cloned Vec3
"""
vec3 = Vec3()
vec3.x = self.x
vec3.y = self.y
vec3.z = self.z
return vec3
def set(self, x, y, z):
"""Sets the x, y, and z value from the input values.
Args:
x (float): Value to set the x property as.
y (float): Value to set the x property as.
z (float): Value to set the z property as.
Returns:
bool: True if successful.
"""
self._rtval.set('', ks.rtVal('Scalar', x), ks.rtVal('Scalar', y), ks.rtVal('Scalar', z))
return True
def setNull():
"""Setting all components of the vec3 to 0.0.
Returns:
bool: True if successful.
"""
self._rtval.setNull('')
return True
def equal(self, other):
"""Checks equality of this vec3 with another.
Args:
other (Vec3): other vector to check equality with.
Returns:
bool: True if equal.
"""
return self._rtval.equal('Boolean', other._rtval).getSimpleType()
def almostEqual(self, other, precision):
"""Checks almost equality of this Vec3 with another.
Args:
other (Vec3): other matrix to check equality with.
precision (float): Precision value.
Returns:
bool: True if almost equal.
"""
return self._rtval.almostEqual('Boolean', other._rtval, ks.rtVal('Scalar', precision)).getSimpleType()
def almostEqual(self, other):
"""Checks almost equality of this Vec3 with another
(using a default precision).
Args:
other (Vec3): other vector to check equality with.
Returns:
bool: True if almost equal.
"""
return self._rtval.almostEqual('Boolean', other._rtval).getSimpleType()
def component(self, i):
"""Gets the component of this Vec3 by index.
Args:
i (int): index of the component to return.
Returns:
float: Component of this Vec3.
"""
return self._rtval.component('Scalar', ks.rtVal('Size', i)).getSimpleType()
# Sets the component of this vector by index
def setComponent(self, i, v):
"""Sets the component of this Vec3 by index.
Args:
i (int): index of the component to set.
v (float): Value to set component as.
Returns:
bool: True if successful.
"""
self._rtval.setComponent('', ks.rtVal('Size', i),
ks.rtVal('Scalar', v))
def add(self, other):
"""Overload method for the add operator.
Args:
other (Vec3): other vector to add to this one.
Returns:
Vec3: New Vec3 of the sum of the two Vec3's.
"""
return Vec3(self._rtval.add('Vec3', other._rtval))
def subtract(self, other):
"""Overload method for the subtract operator.
Args:
other (Vec3): other vector to subtract from this one.
Returns:
Vec3: New Vec3 of the difference of the two Vec3's.
"""
return Vec3(self._rtval.subtract('Vec3', other._rtval))
def multiply(self, other):
"""Overload method for the multiply operator.
Args:
other (Vec3): other vector to multiply from this one.
Returns:
Vec3: New Vec3 of the product of the two Vec3's.
"""
return Vec3(self._rtval.multiply('Vec3', other._rtval))
def divide(self, other):
"""Divides this vector and an other.
Args:
other (Vec3): other vector to divide by.
Returns:
Vec3: Quotient of the division of this vector by the other.
"""
return Vec3(self._rtval.divide('Vec3', other._rtval))
def multiplyScalar(self, other):
"""Product of this vector and a scalar.
Args:
other (float): Scalar value to multiply this vector by.
Returns:
Vec3: Product of the multiplication of the scalar and this vector.
"""
return Vec3(self._rtval.multiplyScalar('Vec3', ks.rtVal('Scalar', other)))
def divideScalar(self, other):
"""Divides this vector and a scalar.
Args:
other (float): Value to divide this vector by.
Returns:
Vec3: Quotient of the division of the vector by the scalar.
"""
return Vec3(self._rtval.divideScalar('Vec3', ks.rtVal('Scalar', other)))
def negate(self):
"""Gets the negated version of this vector.
Returns:
Vec3: Negation of this vector.
"""
return Vec3(self._rtval.negate('Vec3'))
def inverse(self):
"""Get the inverse vector of this vector.
Returns:
Vec3: Inverse of this vector.
"""
return Vec3(self._rtval.inverse('Vec3'))
def dot(self, other):
"""Gets the dot product of this vector and another.
Args:
other (Vec3): Other vector.
Returns:
float: Dot product.
"""
return self._rtval.dot('Scalar', other._rtval).getSimpleType()
def cross(self, other):
"""Gets the cross product of this vector and another.
Args:
other (Vec3): Other vector.
Returns:
Vec3: Dot product.
"""
return Vec3(self._rtval.cross('Vec3', other._rtval))
def lengthSquared(self):
"""Get the squared length of this vector.
Returns:
float: Squared length oft his vector.
"""
return self._rtval.lengthSquared('Scalar').getSimpleType()
def length(self):
"""Gets the length of this vector.
Returns:
float: Length of this vector.
"""
return self._rtval.length('Scalar').getSimpleType()
def unit(self):
"""Gets a unit vector of this one.
Returns:
Vec3: New unit vector from this one.
"""
return Vec3(self._rtval.unit('Vec3'))
def unit_safe(self):
"""Gets a unit vector of this one, no error reported if cannot be
made unit.
Returns:
Vec3: New unit vector.
"""
return Vec3(self._rtval.unit_safe('Vec3'))
def setUnit(self):
"""Sets this vector to a unit vector and returns the previous
length.
Returns:
float: This vector.
"""
return self._rtval.setUnit('Scalar').getSimpleType()
def normalize(self):
"""Gets a normalized vector from this vector.
Returns:
float: Previous length.
"""
return self._rtval.normalize('Scalar').getSimpleType()
def clamp(self, min, max):
"""Clamps this vector per component by a min and max vector.
Args:
min (float): Minimum value.
max (float): Maximum value.
Returns:
bool: True if successful.
"""
return Vec3(self._rtval.clamp('Vec3', min._rtval, max._rtval))
def unitsAngleTo(self, other):
"""Gets the angle (self, in radians) of this vector to another one
note expects both vectors to be units (else use angleTo)
Args:
other (Vec3): other vector to get angle to.
Returns:
float: Angle.
"""
return self._rtval.unitsAngleTo('Scalar', other._rtval).getSimpleType()
def angleTo(self, other):
"""Gets the angle (self, in radians) of this vector to another one.
Args:
other (Vec3): other vector to get angle to.
Returns:
float: Angle.
"""
return self._rtval.angleTo('Scalar', other._rtval).getSimpleType()
# Returns the distance of this vector to another one
def distanceTo(self, other):
"""Doc String.
Args:
other (Vec3): the other vector to measure the distance to.
Returns:
bool: True if successful.
"""
return self._rtval.distanceTo('Scalar', other._rtval).getSimpleType()
def linearInterpolate(self, other, t):
"""Linearly interpolates this vector with another one based on a scalar
blend value (0.0 to 1.0).
Args:
other (Vec3): vector to blend to.
t (float): Blend value.
Returns:
Vec3: New vector blended between this and the input vector.
"""
return Vec3(self._rtval.linearInterpolate('Vec3', ks.rtVal('Scalar', t)))
def distanceToLine(self, lineP0, lineP1):
"""Returns the distance of this vector to a line defined by two points
on the line.
Args:
lineP0 (Vec3): point 1 of the line.
lineP1 (Vec3): point 2 of the line.
Returns:
float: Distance to the line.
"""
return self._rtval.distanceToLine('Scalar', lineP0._rtval, lineP1._rtval).getSimpleType()
def distanceToSegment(self, segmentP0, segmentP1):
"""Returns the distance of this vector to a line segment defined by the
start and end points of the line segment
Args:
segmentP0 (Vec3): point 1 of the segment.
segmentP1 (Vec3): point 2 of the segment.
Returns:
float: Distance to the segment.
"""
return self._rtval.distanceToSegment('Scalar', segmentP0._rtval, segmentP1._rtval).getSimpleType() |
0560c4b586cb481be5999ad8aa7d2721ac9c648e | ZuoQA/secure-svm | /test/test_time.py | 183 | 3.53125 | 4 | import datetime
a = datetime.datetime.now()
for i in range(5000):
for i in range(5000):
s = i * 2
b = datetime.datetime.now() - a
print(b)
print(b.seconds, b.microseconds) |
d81fd98be32ea6951833a77a1cba685be62e9ebb | Iam-El/Random-Problems-Solved | /NEW_FINAL_SYSTEM_DESIGN/FILE_SYSTEM.py | 1,830 | 3.609375 | 4 | class Folder:
def __init__(self, name, parent=None):
self.name = name
self.path = "/" + name
self.parent = parent
def set_name(self, name):
self.name = name
def set_path(self, path):
self.path = path
def get_name(self):
return self.name
def get_path(self):
return self.path
def get_full_path(self):
if self.parent is not None:
return self.parent.get_full_path() + self.path
else:
return self.path
class Directory(Folder):
def __init__(self, name, parent):
super().__init__(name, parent)
self.content = []
def create_file(self, file_name):
file = File(file_name, self)
self.content.append(file)
def create_folder(self, folder_name):
file = Directory(folder_name, self)
self.content.append(file)
def print_contents(self):
for f in self.content:
print(f.get_full_path())
def get_folder(self,folder_name):
for f in self.content:
if folder_name==f.get_name():
return f
class File(Folder):
def __init__(self, name, parent):
super().__init__(name, parent)
fileSystem = Directory("Home", None)
fileSystem.create_folder("ttgtgtgtgt")
fileSystem.print_contents()
folder=fileSystem.get_folder("ttgtgtgtgt")
folder.create_file("somefile")
folder.print_contents()
#
# fileSystem.create_file("elsy.py")
#
#
#
# fileSystem.print_contents()
# file1 = File("Elsy", fileSystem)
# file2 = File("Aaron", fileSystem)
# folder = Directory("NewFolder", fileSystem)
# file3 = File("Aaron4444", folder)
#
# print(fileSystem.get_full_path())
# print(file1.get_full_path())
# print(file2.get_full_path())
# print(folder.get_full_path())
# print(file3.get_full_path())
|
557bc4a8e2c39c22b4d12dbecd4faea5e43356f8 | Yaoaoaoao/LeetCode | /algorithms/125_valid_palindrome.py | 687 | 3.671875 | 4 | class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
# discussion implement
# str.isalnum()
# return newS == newS[::-1]
s = filter(lambda x: 48<=ord(x)<=57 or 97<=ord(x)<=122, list(s.strip().lower()))
if not s:
return True
left, right = 0, len(s)-1
while left<=right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
print Solution().isPalindrome("A man, a plan, a canal: Panama")
print Solution().isPalindrome(".")
print Solution().isPalindrome("a.") |
60ece6ba18f4212296142ad037079464947c7044 | leoCardosoDev/Python | /1-Curso-em-Video/01-Fundamentos-Python/03-Operadores-Aritimetico.py | 559 | 3.8125 | 4 | # 1 => ()
# 2 => **
# 3 => * / // %
# 4 => + -
n1 = int(input('Um valor: '))
n2 = int(input('Outro Valor: '))
s = n1 + n2
m = n1 * n2
d = n1 / n2
sb = n1 - n2
rd = n1 % n2
di = n1 // n2
ex = n1 ** n2
print('A Soma(+) vale: {}'.format(s))
print('A Multiplicação(*) vale: {}'.format(m))
print('A Divisão(/) vale: {:.3f}'.format(d))
print('A Subtração(-) vale: {}'.format(sb))
print('O Resto da divisão(%) vale: {}'.format(rd))
print('A Divisão Inteira(//) vale: {}'.format(di))
print('A Potência(**) de {} elevado a {} vale: {}'.format(n1,n2,ex))
|
64990c5d8afe04cbff853e0944fe410bed0ebd20 | CHAKFI/Python | /TP3/Ex2/ex2.2.py | 230 | 3.78125 | 4 | print('Programme de resoudre l_équation de type ax+b = 0')
I = input('Veuillez entrer la valeur de a \n')
a = int(I)
L = input('Veuillez entrer la valeur de b \n')
b = int (L)
x = -b/a
print('La solution de l_équation est : ',x) |
d01b2e77f4efda8ffd277637c72c46f3f050d4bd | lhj0518/shingu | /11월3일 수업/list2.py | 471 | 3.640625 | 4 | color = ['red','blue','green']
color2 = ['orange','black','white']
print color + color2
len(color)
color[0] = 'yellow'
print color*2
'blue' in color2
total_color=color+color2
for each_color in total_color:
print each_color
color.append("white")
color.extend(["black","purple"])
color.insert(0,"orange")
print color
['orange','yellow','blue','green','white','black','purple']
color.remove("white")
del color[0]
print color
['yellow','blue','green','black','purple']
|
24945c81ba140d8b6914671db114762b433b7805 | nbiadrytski-zz/python-training | /oop_coreyschafer_tutorial/decorators_getter_setter_deleter/decorator_getter_setter_deleter.py | 885 | 3.8125 | 4 | class Employee:
def __init__(self, first, last):
self.first = first
self.last = last
# email() is defined as method, but with @property decorator
# we can access it as attribute, so
# emp_1.email is a valid call
@property
def email(self):
return "{}.{}@company.com".format(self.first, self.last)
@property
def fullname(self):
return "{} {}".format(self.first, self.last)
@fullname.setter
def fullname(self, name):
first, last = name.split(' ')
self.first = first
self.last = last
@fullname.deleter
def fullname(self):
print("Delete name!")
self.first = None
self.last = None
emp_1 = Employee("John", "Smith")
emp_1.first = "Terry"
emp_1.fullname = "Jim T"
print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname)
del emp_1.fullname
print(emp_1.fullname)
|
46df754b3ae97d2a8b766f345112681b3dd0f5a0 | IliaLiash/python_start | /code_review/code_review_1.py | 515 | 3.5625 | 4 | #Number of non-negative numbers in the sequence and their product
#Before
'''
count = 0
p = 0
for i in range(1, 10):
x = int(input())
if x > 0:
p = p * x
count = count + 1
if count > 0:
print(x)
print(p)
else:
print('NO')
'''
#After
count = 0
p = 1
for i in range(1, 11):
x = int(input())
if 0 <= x <= 10**6:
p = p * x
count += 1
if -(10**6) <= x < 0:
continue
if count > 0:
print(count)
print(p)
else:
print('NO')
|
8d28b180e0a16f0b786001d9817aa545dae4382b | MaksimKatorgin/module17 | /task6.py | 589 | 4 | 4 | #Дан список из N целых чисел. Напишите программу, которая выполняет «сжатие списка» — переставляет все нулевые элементы
#в конец массива. При этом все ненулевые элементы располагаются в начале массива в том же порядке. Затем все нули из списка удаляются.
from random import randint as ri
l = [ri(-5, 5) for i in range(ri(10, 20))]
print(l)
l = [i for i in l if i]
print(l) |
99a3ab6b72dac716899ab303b3f14665f057a91b | philippezwietering/practicum-atp | /assignments/assignment1_3_1.py | 2,283 | 3.671875 | 4 | from unittest import *
import doctest
import io
from contextlib import redirect_stdout
def function_to_unittest(list):
ordered = []
for item in list:
if item < 0:
item *= -1
item += 1
if item % 2 == 1:
if not is_prime(item):
continue
ordered = insert(item, ordered)
return ordered
def insert(item, list):
for index in range(0, len(list)):
if list[index] > item:
list.insert(index, item)
break
else:
list.append(item)
return list
def is_prime(n):
if n < 1:
return False
elif n <= 3:
return True
elif n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i = i + 6
return True
class ExerciseTest(TestCase):
def setUp(self):
#TODO schrijf hier globale dingen die nodig zijn voordat de tests gedraait gaan worden.
self.testlist = [0, 1]
self.testnegativity = [-1, -5, -7]
self.testprime = [3, 5, 9]
self.testorder = [1, 2, 0]
pass # Pass om syntax errors te voorkomen in de notebook
#TODO definieer hieronder je tests
# LET OP: de functies die je als tests schrijft moeten in de naam met 'test' beginnen!
def test_1(self): # voorbeeld
testoutput = function_to_unittest(self.testlist)
self.assertEqual([0, 1], testoutput, "Function doesn't handle [0, 1] correctly")
pass # Pass om syntax errors te voorkomen in de notebook
def test_negativity(self):
testoutput = function_to_unittest(self.testnegativity)
self.assertEqual([2, 6, 8], testoutput, "Function doesn't handle negativity correctly")
pass
def test_prime(self):
testoutput = function_to_unittest(self.testprime)
self.assertEqual([3, 5], testoutput, "Function doesn't handle odd non-primes correctly")
def test_order(self):
testoutput = function_to_unittest(self.testorder)
self.assertEqual([0, 1, 2], testoutput, "Function doesn't handle order correctly")
test = ExerciseTest()
suite = TestLoader().loadTestsFromModule(test)
TextTestRunner().run(suite) |
7343499cf6653e12a4e61a8fcf12b67710b67597 | JacksonYu92/basic-calculator | /main.py | 562 | 4.21875 | 4 | def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide,
}
num1 = int(input("What's the first number?: "))
num2 = int(input("What's the second number?: "))
for symbol in operations:
print(symbol)
operation_symbol = input("Pick an operation from the line above: ")
answer = operations[operation_symbol](num1, num2)
print(f"{num1} {operation_symbol} {num2} = {answer}") |
d8e33788ee365ff0e993400b2ad11d64e221bfaf | deval-patel/Monopoly_Deal | /Monopoly_Deal/Deck.py | 895 | 3.796875 | 4 | import math
import random
import typing
from Card import *
from collections import deque
"""
This class holds a set of cards as a Deck.
"""
class Deck:
"""
===Private Attributes===
cards:
The cards in this deck at this time.
"""
cards: deque[Card]
def __init__(self) -> None:
self.cards = deque()
def shuffle(self) -> None:
for i in range(1000):
num1 = random.randint(0, len(self.cards))
num2 = random.randint(0, len(self.cards))
self.cards[num1], self.cards[num2] = self.cards[num2], self.cards[num1]
def draw(self) -> Card:
return self.cards.pop()
# TODO: Make generate method which initializes the Deck for the first time.
def generate(self) -> None:
pass
def add(self, item: Card):
self.cards.append(item)
|
b557ea1fec542be6933e419f8f0c2d7a74c1d054 | wilsonfr4nco/cursopython | /Modulo_Basico/Listas_manipulando/aula25_1.py | 663 | 3.96875 | 4 | """
Split, Join, Enumerate em Python
* Split - Dividir uma string # str divide transformando em lista
* Join - Juntar uma lista # str
* Enumerate - Enumerar elementos da lista # list / para objetos iteráveis
"""
string = 'O Brasil é o o o o país do progresso, o Brasil é bom'
lista = string.split(' ') # removeu os espaços e fez uma lista com as palavras em os espaços
lista2 = string.split(',')
print(lista)
print(lista2)
palavra = ''
contagem = 0
for valor in lista:
qtd_vezes = lista.count(valor)
if qtd_vezes > contagem:
contagem = qtd_vezes
palavra = valor
print(f'A plavra que apareceu mais vezes é {palavra} ({contagem}x)') |
b03b60fb1b230632706140814a585d1295cd5b5e | martincastro1575/python | /courseraPython/estructuraDatos/list_String.py | 587 | 4.03125 | 4 | nombre = 'Martin'
lista = list(nombre)
#La indexacion funciona para el string y la lista
nombre[0]
lista[0]
#El slicing funciona para string y lista
nombre[:4]
lista[:4]
#La funcion len funciona para ambas
len(nombre)
len(lista)
#El in funciona de igual forma
'r' in nombre
'r' in lista
#El not funciona de igual forma
'x' not in nombre
'x' not in lista
#Tambien podemos recorrer los string con for
for letra in nombre:
print(letra)
#Los string son inmutables pero podemos construir nuevos string a partir de string anteriores
new_name = nombre[:3] + 'i' + nombre[5:]# Marin |
44db5bc86b423e0f75151432c3745796ac2e1d33 | bokdoll/Algorithm | /Algorithm-이것이코딩테스트다/Chapter08-다이나믹 프로그래밍/1로 만들기.py | 834 | 3.515625 | 4 | # 2020/11/27 (금)
# [Chapter08-다이나믹 프로그래밍 실전문제] 1로 만들기
def solution():
x = int(input())
# 앞서 계산된 결과를 저장하기 위한 DP 테이블 초기화
d = [0] * 30001
# 다이나믹 프로그래밍 진행 (bottom-up)
for i in range(2, x + 1):
# 현재의 수에서 1을 빼는 경우
d[i] = d[i - 1] + 1
# 현재의 수가 2로 나누어 떨어지는 경우
if i % 2 == 0:
d[i] = min(d[i], d[i//2] + 1)
# 현재의 수가 3로 나누어 떨어지는 경우
if i % 3 == 0:
d[i] = min(d[i], d[i//3] + 1)
# 현재의 수가 5로 나누어 떨어지는 경우
if i % 5 == 0:
d[i] = min(d[i], d[i//5] + 1)
return d[x]
if __name__ == "__main__":
print(solution()) |
bac3b1060e8558c87abc0df3d89497e9ae41f872 | daniela-mejia/Python-Net-idf19- | /PhythonAssig/4-23-19Assigment3/4-23 Project6.py | 658 | 3.84375 | 4 | #This program input the number of packages, out put diacount and total
def main():
x=99
numPack= int(input(" Place enter the amount of packages purchased: "))
if 10>= numPack <=19 :
price= (x * numPack) * 0.20
elif 20>= numPack <=49 :
price=(x * numPack) * 0.30
elif 50>= numPack <=99 :
price=(x * numPack) * 0.40
elif numPack>= 100 :
price=(x * numPack) * 0.50
else:
price = 0
total = numPack * x - price
print(" Discount is : ", format(price, '.2f'))
print("Your Total : ", format(total, '.2f'))
main()
|
ba697db6bb8e339a539f89bdb3c63c487d0deb93 | alves-Moises/python_course_curso_em_video | /aula07_a.py | 311 | 3.75 | 4 | name = input('whats your name? ')
print(f'Nice to meet you, {name:^20}')
n = input('QUAL É SEU NOME?')
print(f'Prazer em te conhecer, {n}!') # sem espaços
print(f'Prazer em te conhecer, {n:^20}!') # com 20 espaços
a = int(input('Digite primeiro valor'))
b = int(input('Digie o segundo valor'))
print(a + b) |
f842c74c945acd59dba0f30973a5dea3a106b14b | mahtabfarrokh/SearchEngine | /Trie.py | 6,940 | 3.5625 | 4 | from tkinter import END
class Node :
def __init__(self , dWord , flag ):
self.data = dWord
self.Rc = None
self.Lc = None
self.next = None
self.flag = flag
self.address = []
class MyTrie :
def __init__(self ,fileOpen ):
self.root = Node("" ,0 )
self.listfileSearch = []
self.fileOpen = fileOpen
self. wordNum = 0
self.delList = []
def insertChild(self , word ,address ):
#add node
count =1
end =0 ;
current = self.root
for c in word.lower() :
if (count == len(word)) :
end = 1 ;
if(current.Lc is None) :
current.Lc = Node(c,end )
if (end ==1 ):
current.Lc.address.append(address)
current = current.Lc
elif (current.Rc is None) and (c != current.Lc.data) :
current.Rc = Node(c, end)
if (end ==1 ) :
current.Rc.address.append(address)
current.Lc.next= current.Rc
current = current.Rc
else :
cur2= current.Lc
x= 0
while(cur2 is not None ) :
if(cur2.data == c) :
x=1
if len(cur2.address) ==0 :
if (end ==1 ) :
cur2.address.append(address)
elif not address == cur2.address[len(cur2.address)-1] :
if (end ==1 ) :
cur2.address.append(address)
current = cur2
break
cur2 = cur2.next
if x ==0 :
c= Node (c,end)
current.Rc.next = c
current.Rc = c
current = c
count +=1
def visit (self, reroot , ch , listShow ,filename , p):
if reroot is not None :
ch= ch + reroot.data
if(reroot.flag == 1) :
if p==1 and reroot.address :
#for print all of tree nodes
s = ch + ' -> '
for a in reroot.address :
s = s + " " + a
self.fileOpen.writeList(listShow , s)
self.wordNum +=1
elif p==2 :
#for updating list
counter =0
for a in reroot.address :
if a ==filename :
reroot.address.pop(counter)
if len(reroot.address) == 0:
reroot.flag = 0
break
counter +=1
current = reroot.Lc
while (current is not None):
self.visit(current, ch , listShow, filename ,p)
current = current.next
def reSearchW (self , reroot , word , realW , p , listShow , filename ) :
# search word recursive
ch= word[0]
if ch == reroot.data :
if p ==2 :
self.delList.append(reroot)
if not word[1:]:
if p==1 :
first = 0
str =""
for a in reroot.address :
if first ==1 :
str = str + " , " + a
else:
first =1
str= a
self.fileOpen.writeList(listShow , str)
self.listfileSearch = reroot.address
return reroot
elif p==2 :
counter = 0
for f in reroot.address:
if f == filename:
reroot.address.pop(counter)
if len(reroot.address)==0 :
# reroot.flag = 0
for d in self.delList[::-1] :
if (d.Lc is None):
del d
elif (d.Lc is not None) :
d.flag = 0
break
for d in self.delList :
for a in d.address :
if a ==filename :
del a
break
del self.delList[:]
break
counter += 1
del reroot
else:
self.listfileSearch = reroot.address
return reroot
else :
current = reroot.Lc
while current is not None :
if(current.data == word[1]) :
return self.reSearchW( current ,word[1:] , realW , p, listShow , filename)
current = current.next
self.listfileSearch = []
return
def searchOneWord (self ,word , p ,listShow) :
char = word[0]
current = self.root.Lc
while current is not None :
if char == current.data :
return self.reSearchW(current , word , word , p , listShow , "" )
current = current.next
def isStopWord(self, word, stopwords):
if not word.isalpha():
return True
for w in stopwords:
if w.lower() == word.lower():
return True
return False
def searchOneLine(self, line , stopword , listShow):
# search line with function search word and then return th intersect of lists
first = 1
list1 = []
for w in line.split():
if (not self.isStopWord(w, stopword)):
if first == 1:
self.searchOneWord(w ,0 , listShow)
list1 = self.listfileSearch
first = 0
else:
self.searchOneWord(w , 0, listShow)
list2 = self.listfileSearch
list1 = list(set(list1).intersection(list2))
str = "answer : "
for a in list1:
str = str + " " + a
self.fileOpen.writeList(listShow, str)
def deleteNode(self, word, filename , listShow):
char = word[0]
current = self.root.Lc
while current is not None:
if char == current.data:
self.reSearchW(current, word, word, 2, listShow , filename)
current = current.next
return
def updeateNode (self,filename , listshow ) :
self.visit(self.root , "" , listshow , filename ,2 )
|
d5f43007d908260d0a7a4597ac23ce8e31972c59 | NiumXp/Algoritmos-e-Estruturas-de-Dados | /src/python/calculate_pi.py | 553 | 4.21875 | 4 | """ Implementaço de um algoritmo de cálculo do PI """
def calculate_pi(number):
"""
Implementação de um algoritmo de cálculo do PI.
Argumentos:
number: int.
Retorna o valor de PI.
"""
denominator = 1.0
operation = 1.0
pi = 0.0
for _ in range(number):
pi += operation * (4.0 / denominator)
denominator += 2.0
operation *= -1.0
return pi
if __name__ == '__main__':
n_terms = [10, 1000, 100000, 10000000]
for n in n_terms:
print(f'PI ({n}): {calculate_pi(n)}')
|
cc9c2990b09ca22ac296e0fdf99f9ad267873d4d | Katuri31/Problem_solving_and_programming | /Python/Lab_model_questions/q_6/using_numpy/6b_using_numpy.py | 675 | 4.21875 | 4 | # Write a program to perform addition of two square matrices(With NumPy)
import numpy as np
r1 = 3
c1 = 3
print("Enter the entries of 3*3 matrix in a single line (separated by space): ")
entries1 = list(map(int, input().split()))
matrix1 = np.array(entries1).reshape(r1, c1) #Matrix 1
print(matrix1)
r2 = 3
c2 = 3
print("Enter the entries of second 3*3 matrix in a single line (separated by space): ")
entries2 = list(map(int, input().split()))
matrix2 = np.array(entries2).reshape(r2, c2) #Matrix 2
print(matrix2)
print("The added matrix is:")
print(matrix1+matrix2) #Matrix addition
|
42eb20bc94f806b0e698f5041a6ee4249dacf2ea | kossy-inequality/Repository-of-Kossy | /mydate.py | 1,315 | 3.953125 | 4 | import datetime
import calendar
today = datetime.date.today()
todaydetail = datetime.datetime.today()
# 今日の日付
print('----------------------------------')
print(today)
print(todaydetail)
# 今日に日付:それぞれの値
print('----------------------------------')
print(today.year)
print(today.month)
print(today.day)
print(todaydetail.year)
print(todaydetail.month)
print(todaydetail.day)
print(todaydetail.hour)
print(todaydetail.minute)
print(todaydetail.second)
print(todaydetail.microsecond)
# 日付のフォーマット
print('----------------------------------')
print(today.isoformat())
print(todaydetail.strftime("%Y/%m/%d %H:%M:%S"))
print('----------------------------------')
#日付の計算
today = datetime.datetime.today()
#今日の日付
print(today)
#明日の日付
print(today + datetime.timedelta(days=1))
newyear = datetime.datetime(2010,1,1)
#2010/1/1の一週間後
print(newyear + datetime.timedelta(days=7))
#2010/1/1から今日までの日数
calc = today - newyear
#計算結果の戻り値は「timedelata」
print(calc.days)
print('----------------------------------')
#うるう年の判定
print(calendar.isleap(2015))
print(calendar.isleap(2016))
print(calendar.isleap(2017))
print(calendar.isleap(today.year))
print(calendar.leapdays(2010,2020))
|
511ce92179473ae2f6dcce55ab4252c8f0a04440 | khanhpdt/programming-pearls | /maximum_subarray_iterative.py | 1,090 | 3.90625 | 4 | # see [1, Exercise 4.1.5] for more details
def find_max_subarray(array):
max_subarray_low = 0
max_subarray_high = 0
max_subarray = array[0]
# sum of the elements from (max_index + 1) to the current index
max_subarray_end_at_current_index_low = 0
max_subarray_end_at_current_index = array[0]
for i in range(1, len(array)):
max_subarray_end_at_current_index += array[i]
if max_subarray_end_at_current_index < array[i]:
max_subarray_end_at_current_index = array[i]
max_subarray_end_at_current_index_low = i
# The maximum subarray is either the maximum one in [1..(i-1)] or the one ending at i.
# It is very important we know that the latter alternative ends at i.
if max_subarray_end_at_current_index > max_subarray:
max_subarray = max_subarray_end_at_current_index
max_subarray_low = max_subarray_end_at_current_index_low
max_subarray_high = i
return max_subarray_low, max_subarray_high, max_subarray
def main(array):
return find_max_subarray(array)
|
31ddf18c9a4a93476e3e2dcfd776c2b33b51f159 | anders-ahsman/advent-of-code | /2020/day11/main.py | 4,030 | 3.609375 | 4 | import sys
def read_floor():
return [list(line.rstrip()) for line in sys.stdin]
def part1(floor):
next_floor = [row[:] for row in floor]
while True:
for y in range(len(floor)):
for x in range(len(floor[y])):
count = occupied_count(floor, x, y)
if floor[y][x] == 'L' and count == 0:
next_floor[y][x] = '#'
elif floor[y][x] == '#' and count > 3:
next_floor[y][x] = 'L'
no_change = ''.join([''.join(row) for row in floor]) == ''.join([''.join(row) for row in next_floor])
if no_change:
return sum(row.count('#') for row in floor)
floor = [row[:] for row in next_floor]
def occupied_count(floor, x, y):
count = 0
if x > 0:
if floor[y][x - 1] == '#':
count += 1
if y > 0 and floor[y - 1][x - 1] == '#':
count += 1
if y + 1 < len(floor) and floor[y + 1][x - 1] == '#':
count += 1
if y > 0 and floor[y - 1][x] == '#':
count += 1
if y + 1 < len(floor) and floor[y + 1][x] == '#':
count += 1
if x + 1 < len(floor):
if floor[y][x + 1] == '#':
count += 1
if y > 0 and floor[y - 1][x + 1] == '#':
count += 1
if y + 1 < len(floor) and floor[y + 1][x + 1] == '#':
count += 1
return count
def part2(floor):
next_floor = [row[:] for row in floor]
while True:
for row in floor:
print(''.join(row))
print()
for y in range(len(floor)):
for x in range(len(floor[y])):
count = occupied_visible_count(floor, x, y)
if floor[y][x] == 'L' and count == 0:
next_floor[y][x] = '#'
elif floor[y][x] == '#' and count > 4:
next_floor[y][x] = 'L'
no_change = ''.join([''.join(row) for row in floor]) == ''.join([''.join(row) for row in next_floor])
if no_change:
return sum(row.count('#') for row in floor)
floor = [row[:] for row in next_floor]
def occupied_visible_count(floor, x, y):
count = 0
# north
y1 = y
while y1 > 0:
y1 -= 1
if floor[y1][x] == 'L':
break
if floor[y1][x] == '#':
count += 1
break
# south
y1 = y
while y1 + 1 < len(floor):
y1 += 1
if floor[y1][x] == 'L':
break
if floor[y1][x] == '#':
count += 1
break
# west
x1 = x
while x1 > 0:
x1 -= 1
if floor[y][x1] == 'L':
break
if floor[y][x1] == '#':
count += 1
break
# east
x1 = x
while x1 + 1 < len(floor[y]):
x1 += 1
if floor[y][x1] == 'L':
break
if floor[y][x1] == '#':
count += 1
break
# northwest
x1 = x
y1 = y
while x1 > 0 and y1 > 0:
x1 -= 1
y1 -= 1
if floor[y1][x1] == 'L':
break
if floor[y1][x1] == '#':
count += 1
break
# northeast
x1 = x
y1 = y
while x1 + 1 < len(floor[y]) and y1 > 0:
x1 += 1
y1 -= 1
if floor[y1][x1] == 'L':
break
if floor[y1][x1] == '#':
count += 1
break
# southeast
x1 = x
y1 = y
while x1 + 1 < len(floor[y]) and y1 + 1 < len(floor):
x1 += 1
y1 += 1
if floor[y1][x1] == 'L':
break
if floor[y1][x1] == '#':
count += 1
break
# southwest
x1 = x
y1 = y
while x1 > 0 and y1 + 1 < len(floor):
x1 -= 1
y1 += 1
if floor[y1][x1] == 'L':
break
if floor[y1][x1] == '#':
count += 1
break
return count
if __name__ == '__main__':
floor = read_floor()
print(f'Part 1: {part1(floor)}')
print(f'Part 2: {part2(floor)}')
|
a58caf45530fd1fabd4be9ef0414b576b08b2334 | kambehmw/algorithm_python | /atcoder/ABC/142/D_Disjoint_Set_of_Common_Divisors.py | 683 | 3.71875 | 4 | import math
def is_prime(n):
if n == 1: return True
for k in range(2, int(math.sqrt(n)) + 1):
if n % k == 0:
return False
return True
def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
# divisors.sort()
return divisors
A, B = map(int, input().split())
div1 = make_divisors(A)
# print(div1)
div2 = make_divisors(B)
nums = list(set(div1).intersection(set(div2)))
# print(nums)
nums = [x for x in nums if is_prime(x)]
# print(nums)
cnt = len(nums)
if cnt > 1:
print(cnt)
else:
print(1) |
a58c0ae845eba4f58b672df3c2b2536baea15c06 | AllanWong94/PythonLeetcodeSolution | /Y2017/M8/D12/Closest_BST_Value/Solution.py | 1,404 | 3.828125 | 4 | # Runtime: 69ms=>59 Beats or equals to 21%=>55%
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from Y2017.TreeNode import TreeNode
class Solution(object):
def closestValue(self, root, target):
return self.helper(root,target,root.val)
"""
:type root: TreeNode
:type target: float
:rtype: int
"""
def helper(self,root,target,temp):
if abs(temp - target) > abs(root.val - target):
temp = root.val
if root.val > target and root.left:
return self.helper(root.left, target,temp)
elif root.val < target and root.right:
return self.helper(root.right, target,temp)
return temp
# Runtime:52ms Fastest.
# def closestValue(self, root, target):
# """
# :type root: TreeNode
# :type target: float
# :rtype: int
# """
# a = root.val
#
# kid = root.left if root.val > target else root.right
#
# if not kid:
# return a
#
# b = self.closestValue(kid, target)
#
# if abs(a - target) > abs(b - target):
# return b
# else:
# return a
t=TreeNode(2147483647)
solution = Solution()
print(solution.closestValue(t,0.0))
|
78b480e5c55537e1ad1b01ca836194ff504ba54c | luchev/algorithms | /maximum-subarray/max-subarray-linear.py | 1,927 | 4.03125 | 4 | def maxsubarray(list):
"""
Find a maximum subarray following this idea:
Knowing a maximum subarray of list[0..j]
find a maximum subarray of list[0..j+1] which is either
(I) the maximum subarray of list[0..j]
(II) or is a maximum subarray list[i..j+1] for some 0 <= i <= j
We can determine (II) in constant time by keeping a max
subarray ending at the current j.
This is done in the first if of the loop, where the max
subarray ending at j is max(previousSumUntilJ + array[j], array[j])
This works because if array[j] + sum so far is less than array[j]
then the sum of the subarray so far is negative (and less than array[j]
in case it is also negative) so it has a bad impact on the
subarray until J sum and we can safely discard it and start anew
from array[j]
Complexity (n = length of list)
Time complexity: O(n)
Space complexity: O(1)
"""
if len(list) == 0:
return (-1, -1, 0)
# keep the max sum of subarray ending in position j
maxSumJ = list[0]
# keep the starting index of the maxSumJ
maxSumJStart = 0
# keep the sum of the maximum subarray found so far
maxSum = list[0]
# keep the starting index of the current max subarray found
maxStart = 0
# keep the ending index of the current max subarray found
maxEnd = 0
for j in range(1, len(list)):
if maxSumJ + list[j] >= list[j]:
maxSumJ = maxSumJ + list[j]
else:
maxSumJ = list[j]
maxSumJStart = j
if maxSum < maxSumJ:
maxSum = maxSumJ
maxStart = maxSumJStart
maxEnd = j
return (maxSum, maxStart, maxEnd)
def test():
result = maxsubarray([-2, 1, -3, 4, -1, 2, 1, -5, 4])
if result[0] == 6:
print("Success")
else:
print("Fail")
test() |
d8caa31f84000f971cac08a78066b6a0f7ef7b1d | chewbocky/Python | /addition.py | 608 | 4.125 | 4 | print("Please enter two numbers and I will add them togeather")
print("please type 'q' to quit")
while True:
first_number = input("\nFirst Number: ")
if first_number == 'q':
break
try:
first_number = int(first_number)
except ValueError:
print("Sorry, but you must enter a number.")
second_number = input("Second Number: ")
if second_number == 'q':
break
try:
second_number = int(second_number)
except ValueError:
print("Sorry, but you must enter a number.")
try:
answer = first_number + second_number
except TypeError:
pass
else:
print(answer)
|
c45568f70f902f68f5c2d1f75a29423ef68e520c | HoangAnhNguyen269/practicals_CP1404 | /practical/prac9/sort_files_1.py | 636 | 4.03125 | 4 | """
sort these files from FilesToSort into subdirectories for each extension.
"""
import os
import shutil
def main():
"""move files into subfolders with the same name as their extension."""
os.chdir("FilesToSort")
for filename in os.listdir('.'):
if os.path.isdir(filename):
continue
file_extension=filename.split('.')[-1] #split the file name and its extension by the '.'
try:
os.mkdir(file_extension)
except FileExistsError: #if the extension dir have been made already
pass
shutil.move(filename, '{}/{}'.format(file_extension,filename))
main() |
45a317bef2db3b77589fbcc7c12fbfe7237b0282 | AryanGanotra07/Computer-Graphics | /LabEvaluation2.py | 1,060 | 3.53125 | 4 | import time
from graphics import *
def trafficLights():
win = GraphWin()
rect = Rectangle(Point(60,20 ), Point(140,180))
rect.draw(win)
red = Circle(Point(100, 50), 20)
red.setFill("black")
red.draw(win)
yellow = Circle(Point(100, 100), 20)
yellow.setFill("black")
yellow.draw(win)
green = Circle(Point(100, 150), 20)
green.setFill("black")
green.draw(win)
color = "red"
lights = [ red, yellow, green ]
while True:
for i in range(len(lights)) :
light = lights[i]
light.setFill(color)
for l in lights:
if l!=light:
l.setFill("black")
# not sure what the update function for the screen is but you need to call it before you call time.sleep()
time.sleep(5)
if color == "red":
color = "yellow"
elif color == "yellow":
color = "green"
elif color == "green":
color = "red"
win.getMouse()
trafficLights()
|
423bd3e0383f6bff528649a7f6cbe4bbe9d6aca3 | Antonio-Rice/Pass-Generator | /genpass.py | 495 | 3.671875 | 4 | #!/usr/bin/python
# -*- coding: utf8 -*-
import random
import sys
for arg in sys.argv: 1
aide = """
Usage: python genpass.py <number of characters>
Example usage:
python genpass.py 8
"""
while True:
try:
int(arg)
break
except ValueError:
print(aide)
sys.exit(1)
lettre = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789!?+-_:;[]%#$&@")
n = 0
mdp = random.choice(lettre)
arg = int(arg)-1
while n < int(arg):
mdp = mdp+random.choice(lettre)
n = n+1
print (mdp)
|
3bb4efb2c30724e2ba6932e821da3ff5825936cd | rajibeee/Sample-Codes | /Algorithms/Assignment3/submission/source code/rajib dey Assignment 3.py | 5,721 | 3.703125 | 4 | from itertools import permutations
from random import randint
import numpy as np
import time
import matplotlib.pyplot as plt
LowestTimeBruteForce=[]
LowestTimeGreedy=[]
GreedyTimeList=[]
GreedyYaxis=[]
def randomTimeGenerator(number_of_campers, maximum_time = 100):
personset = set()
while number_of_campers > 0:
length_of_personset = len(personset)
p = (randint(1, maximum_time), randint(1, maximum_time), randint(1, maximum_time))
personset.add(p)
if len(personset) != length_of_personset:
number_of_campers -= 1
#print "Random Generated Set ====== \n ", personset # Uncomment to See how the Random Set looks like
return personset
def CalculateTimeToFinishAll(List_person):
startTime = 0
Finish_times = []
for k in List_person:
startTime += k[0]
Finish_times.append(startTime + k[1] + k[2])
#print "\n Finish time list=== \n", Finish_times
##print "max(Finish_times)=====", max(Finish_times)
return max(Finish_times)
def bruteForce(sets_of_person):
global LowestTimeBruteForce
i=0
timeforlist=[]
listforcombinations=[]
perm = permutations(sets_of_person) #get all possible combinations
#print " Trying the Bruteforce Method"
for permutation in perm:
i+=1
#print "Combination number", i , "=" #Uncomment this and the next line if you want to see the combinations
#print permutation
#print "Time needed for this combination is === ",CalculateTimeToFinishAll(permutation) , "\n \n" #Uncomment if you want to see time needed for each combination
timeforlist.append(CalculateTimeToFinishAll(permutation))
listforcombinations.append(permutation)
#print "Combination list====", listforcombinations
#print "List of all the time values for this set=== \n", timeforlist #Uncomment to see the List of all Time Values
index_for_min = np.argmin(timeforlist) # index for minimum value
#print "Best combination Number=" , index_for_min+1
LowestTimeBruteForce.append(timeforlist[index_for_min])
#print "Best Time for this set--according to BruteForce Method=====================", timeforlist[index_for_min]
#print "\nAs the lowest time among all of the time was chosen by the Brute-Force Method, Correctness of the Test case is Validated\n"
#print "\nAccording to Bruteforce Method, The best combination is \n", listforcombinations[index_for_min] ##Uncomment to see the best combination according to Brute-force
return "\n=======-------------Bruteforce Method Done------------============\n"
def GreedyAlgorithm(sets_of_person):
global LowestTimeGreedy
List_person = list(sets_of_person)
List_person.sort(key=lambda x:x[1]+x[2], reverse=True)
#print "\nBest Combination according to Greedy Algorithm ===== \n ", List_person ## Uncomment to see which combination was chosen by the Greedy Algorithm
LowestTimeGreedy.append(CalculateTimeToFinishAll(List_person))
#print "\nBest Time according to Greedy Algorithm ================",LowestTimeGreedy #Uncomment to see the Lowest time for the Greedy Algorithm
return "\n-------============ End of Greedy Algorithm ==============------ \n"
#testset=[(30,80,40),(25,40,20),(40,50,18)] # Tested with this at first
#print "Test Set [testSet]====== \n ", testset
def GenerateTestCases():
print " \n ................. Generating test cases with 1 to 10 Campers ...................\n"
print" \nFor 10 and 11 campers it takes around 7 and 82 seconds\nWhere 12 takes forever........Or gives a segmentation fault and Never finishes\n\n"
for r in range(1,11):
personset = randomTimeGenerator(r)
print GreedyAlgorithm(personset)
print bruteForce(personset)
print "\nFor Test Cases of campers 1 to 10---Best Time according to Greedy Algorithm ===\n",LowestTimeGreedy
print "For Test Cases of campers 1 to 10---Best Time according to BruteForce Method======\n", LowestTimeBruteForce
if LowestTimeBruteForce==LowestTimeGreedy:
print "\nThe Designed Algorithm is giving us the correct ans\n"
else:
print "\n \n Something is wrong \n \n"
N = 10
fig2 = plt.figure()
ind = np.arange(N)
width = 0.35
plt.bar(ind, LowestTimeBruteForce, width, label='Brute-Force')
plt.bar(ind + width, LowestTimeGreedy, width,label='Greedy Algorithm')
plt.gca().yaxis.grid(True) # Getting a Y axis grid
plt.ylabel('Lowest Unit-Time required to finish the Competition')
plt.xlabel('Number of Campers------>')
plt.title('Validaton of Correctness of Bruteforce method and Greedy Algorithm')
plt.xticks(ind + width / 2, ('1', '2', '3', '4', '5','6','7','8','9','10'))
plt.legend(loc='best')
#plt.show()
fig2.savefig('Validation of Correctness of the Brute-Force and Greedy Algorithm.png')
def GettingTimesForGreedy():
global GreedyTimeList
global GreedyYaxis
print "\n\n\n -------------- Testing the Time complexity of Greedy Algorithm -----------\n\n\n"
for n in range(1,1001):
personset=randomTimeGenerator(n)
start = time.clock() ##Start the timer
GreedyAlgorithm(personset)
end = time.clock() # End the timer
GreedyTimeList.append((end-start)*1000000) #Getting value in Micro-seconds
GreedyYaxis.append(n)
#print "Time List for Greedy Algorithm with increasing input size", GreedyTimeList # Uncomment to see the TimeList for Greedy with increasing input size
fig = plt.figure()
plt.title("Time Complexity of the Implemented Greedy Algorithm")
plt.xlabel('Number of Campers------>>>')
plt.ylabel('Time Complexity in Micro-seconds------>>>')
plt.plot(GreedyYaxis, GreedyTimeList, label ='Greedy Algorithm')
plt.grid()
plt.legend()
#plt.show()
fig.savefig('Time Complexity of Greedy Algorithm.png')
GenerateTestCases()
GettingTimesForGreedy()
|
4a85d0f47bcdd05a5fc491d1c365343aea60aac9 | sljcb/leedcode | /pathSum.py | 1,096 | 3.9375 | 4 | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a boolean
# def hasPathSum(self, root, sum):
# return self.checkPath(root, sum)
# def checkPath(self, node, sum):
# if node == None:
# return False
# if node.left == None and node.right == None:
# if sum == node.val:
# return True
# else:
# return False
# else:
# return self.checkPath(node.left, sum-node.val) or self.checkPath(node.right, sum-node.val)
def hasPathSum(self, root, sum):
if root == None:
return False
if root.left == None and root.right == None:
if sum == root.val:
return True
else:
return False
else:
return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)
|
f970ccab2492411710266f6fce74985a01f1aa0b | cja-smith/Python-scripts | /numberguessinggame.py | 2,346 | 3.9375 | 4 | from random import randint
def user_guess():
global NumberOfGuesses
while True:
print(f"You have {10-NumberOfGuesses} guesses left.")
guess = input()
try:
guess = int(guess)
if guess in range(101):
NumberOfGuesses+=1
return guess
else:
print("That's not within the range!")
except ValueError:
print("Try an integer!")
def checkandclues(guess,n):
#Gives clues based on higher/lower, range, factors, and multiples
if guess == n:
print("You got it!")
return True
elif guess in range(n-5,n+6,1):
print("Close!\nClue: You're within 5 of the number I'm thinking of!")
return False
elif guess > n:
print("Too high!")
if guess%n==0:
print("Clue: That guess is a multiple of the number I'm thinking of.")
else:
pass
return False
elif guess < n:
print("Too low!")
if n%guess==0:
print("Clue: That guess is a factor of the number I'm thinking of.")
else:
pass
return False
#game logic goes here
while True:
print("Hello! I am thinking of a number between 1 and 100, and you have 10 guesses to try and work out which number it is.\nGood Luck!")
n=randint(0,100)
play_game = input("Ready to begin? Type y or n")
if play_game.lower() == "y":
NumberOfGuesses=0
else:
break
while NumberOfGuesses<10:
if checkandclues(user_guess(),n):
NumberOfGuesses = 110 #break out of the while loop
break
#takes user input
#check and give clues
checkandclues(user_guess(),n)
if NumberOfGuesses==110:
print("Congratulations!")
replay = input("Would you like to play again? Type y or n")
if replay.lower() == "y":
continue
else:
break
else:
print(f"Sorry you used too many guesses! The number I was thinking of was {n}!")
replay = input("Would you like to play again? Type y or n")
if replay.lower() == "y":
continue
else:
break
|
a25f5bda55ef4d859ab9591e7ec6cb2e11dcd1b9 | ZeroILumi/Projetos_de_Teste_ver_0.0.1 | /Testes_Complexos/Projetos Python/aula6_Zero_ILumi_ver_1.0.py | 2,563 | 3.734375 | 4 | if __name__ == '__main__':
conjunto1 = {1, 2, 3, 4, 5}
conjunto2 = {5, 6, 7, 8}
conjunto_uniao_1_2 = conjunto1.union(conjunto2)
print('União do conjunto 1 com o conjunto 2:\n{conjunto_uniao_1_2}'
''.format(conjunto_uniao_1_2=conjunto_uniao_1_2))
conjunto_intersccao_1_2 = conjunto1.intersection(conjunto2)
print('Interscção entre o conjunto 1 eo conjunto 2:\n{conjunto_intersccao_1_2}'
''.format(conjunto_intersccao_1_2=conjunto_intersccao_1_2))
conjunto_diferenca_1_2 = conjunto1.difference(conjunto2)
print('Diferença entre o conjunto 1 eo conjunto 2:\n{conjunto_diferenca_1_2}'
''.format(conjunto_diferenca_1_2=conjunto_diferenca_1_2))
conjunto_diferenca_2_1 = conjunto2.difference(conjunto1)
print('Diferença entre o conjunto 2 eo conjunto 1:\n{conjunto_diferenca_2_1}'
''.format(conjunto_diferenca_2_1=conjunto_diferenca_2_1))
conjunto_diferenca_simetrica = conjunto1.symmetric_difference(conjunto2)
print('Diferença Simetrica entre o conjunto 1 eo conjunto 2:\n{conjunto_diferenca_simetrica}'
''.format(conjunto_diferenca_simetrica=conjunto_diferenca_simetrica))
conjunto_a = {1, 2, 3}
conjunto_b = {1, 2, 3, 4, 5}
conjunto_subset_a_b = conjunto_a.issubset(conjunto_b)
if conjunto_subset_a_b:
print('Conjunto A é uma sub-atribuição do conjunto B')
else:
print('Conjunto A não é uma sub-atribuição do conjunto B')
conjunto_subset_b_a = conjunto_b.issubset(conjunto_a)
if conjunto_subset_b_a:
print('Conjunto B é uma sub-atribuição do conjunto A')
else:
print('Conjunto B não é uma sup-atribuição do conjunto A')
conjunto_superset_b_a = conjunto_b.issuperset(conjunto_a)
if conjunto_superset_b_a:
print('Conjunto B é uma super-atribuição do conjunto A')
else:
print('Conjunto B não é uma super-atribuição do conjunto A')
conjunto_superset_a_b = conjunto_a.issuperset(conjunto_b)
if conjunto_superset_a_b:
print('Conjunto A é uma super-atribuição do conjunto B')
else:
print('Conjunto A não é uma super-atribuição do conjunto B')
lista_de_animais = ['cachorro', 'cachorro', 'gato', 'gato', 'elefante']
print(lista_de_animais)
conjunto_animais = set(lista_de_animais)
print(conjunto_animais)
lista_animais_2 = list(conjunto_animais)
print(lista_animais_2)
# conjunto = {1, 2, 3, 4}
# conjunto.add(5)
# conjunto.discard(2)
# print(conjunto) |
771314de2d4e13f67465e8e9d6da20021689ef1f | czs108/LeetCode-Solutions | /Medium/74. Search a 2D Matrix/solution (1).py | 971 | 4.03125 | 4 | # 74. Search a 2D Matrix
# Runtime: 44 ms, faster than 66.69% of Python3 online submissions for Search a 2D Matrix.
# Memory Usage: 14.9 MB, less than 32.98% of Python3 online submissions for Search a 2D Matrix.
class Solution:
# Row Iteration & Binary Search
def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:
def binary_search(nums: list[int], left: int, right: int) -> bool:
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return True
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return False
for i in range(len(matrix)):
min_val, max_val = matrix[i][0], matrix[i][-1]
if min_val <= target and target <= max_val:
return binary_search(matrix[i], 0, len(matrix[0]))
return False |
75035c77724c2299c63ee674d625b84cf710df7a | Claire56/leetcode | /Sorting.py | 835 | 4.0625 | 4 | def mergeSort(a):
if len(a)>1:
mid = len(a)//2
L =a[:mid]
R =a[mid:]
mergeSort(L)
mergeSort(R)
R_index =L_index = a_index=0
while L_index < len(L) and R_index <len(R):
if R[R_index]< L[L_index]:
a[a_index]=R[R_index]
R_index +=1
else:
a[a_index]=L[L_index]
L_index +=1
a_index +=1
#Checking if any. element was left
while R_index < len(R):
a[a_index]=R[R_index]
R_index +=1
a_index +=1
while L_index < len(L):
a[a_index]=L[L_index]
L_index +=1
a_index +=1
return a
print(mergeSort([5,8,1,9,10,3,9,2]))
#Bubble Sort
a = [5,8,10,9,10,3,9,2,1]
def bubble(a):
n = len(a)
swaps =0
for i in range(n,1,-1):
for j in range(1,i):
if a[j-1]< a[j]:
a[j],a[j-1] = a[j-1],a[j]
swaps +=1
return'sorted in {} swaps,Results:{}'.format(swaps,a)
print(bubble(a)) |
8aaa3c1143a12a1d5aafb48d207aa854dd18f339 | xjz1994/LeetCodeSolution | /Solution/Python/820. Short Encoding of Words.py | 627 | 3.5 | 4 | class Solution:
def minimumLengthEncoding(self, words):
"""
:type words: List[str]
:rtype: int
"""
root = dict()
leaves = []
for word in set(words):
cur = root
for i in word[::-1]:
cur[i] = cur = cur.get(i, dict())
leaves.append((cur, len(word)))
res = 0
for node, depth in leaves:
if len(node) == 0:
res += depth + 1
return res
words = ["time", "me", "bell"]
#words = ["time", "atime", "btime"]
s = Solution()
res = s.minimumLengthEncoding(words)
print(res)
|
7727cd72ef8d851ee11b61827178bf5040a11ff8 | leapfrogtechnology/lf-training | /Python/shresoshan/task1/store.py | 1,818 | 3.515625 | 4 | import sys
import argparse
from datetime import datetime
import csv
import operator
import os
#Convert to datetime type
def dob(value):
return datetime.strptime(value,'%d/%m/%Y')
#Calculate percentage
def calcpercentage(total, score):
return ((score/total)*100)
#Duplicate Check
def isDuplicate(args):
with open(args.store, mode='r') as csvfile:
csv_reader = csv.DictReader(csvfile)
for row in csv_reader:
if row["name"] == args.name and row["subject"]== args.subject: #Checking for Name and Subject
return True
return False
def writeFile(file, args):
thewriter = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
thewriter.writerow([args.name, args.dob, args.subject, args.total, args.score, calcpercentage(args.total,args.score)])
def addheader(file, args):
thewriter = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
thewriter.writerow(["name", "dob", "subject", "total", "score", "percentage"])
parser = argparse.ArgumentParser(description='Scoresheet')
parser.add_argument('name', type=str, help='Student Name')
parser.add_argument('dob', type=dob, help='Date of Birth dd/mm/yy')
parser.add_argument('subject', choices=['English','Mathematics','Nepali'], help='One of the subjects')
parser.add_argument('total', type=float, help='Total Score')
parser.add_argument('score', type=float, help='Marks Scored')
parser.add_argument("store", type=str, help="Enter filename")
args = parser.parse_args()
filename=args.store
if os.path.exists(filename):
file=open(filename,"a")
if isDuplicate(args):
print("Duplicate Record")
else:
writeFile(file, args)
else:
file = open(filename, "w")
addheader(file, args)
writeFile(file, args)
|
6a3b9e9f8f9e50fd04fb86bcbdccde3836331996 | nairoukh-code/CIS2001-Winter2020 | /Trees/Trees.py | 1,516 | 3.65625 | 4 | class Position:
def __init__(self, item, container, parent, children):
self.item = item
self.container = container
self.parent = parent
self.children = children
def get_item(self):
return self.item
class GenericTree:
def __init__(self, item, parent = None):
self.item = item
self.children = []
self.parent = parent
def is_root(self, position):
return position.parent == None
def parent(self, position):
return position.parent
def children(self, position):
return position.children
def is_leaf(self, position):
return len(position.children) == 0
def __len__(self):
length = 1
for child in self.children:
length += len(child)
return length
def is_empty(self):
return self.item == None
def root(self):
return Position(self.item, self, None, self.children)
def depth(self, position):
if self.is_root(position):
return 0
return 1 + self.depth(self.parent(position))
def height(self):
current_max = 0
for child in self.children:
child_height = 1 + child.height()
if child_height > current_max:
current_max = child_height
return current_max
def bad_height(self): # O(n^2) - touches ever position, and every leaf all the way back to root
return max(self.depth(p) for p in self.positions() if self.is_leaf(p) )
|
bf233e9fc8610167943438784e03cd9c04dcedff | vsmaxim/data-analysis-2021 | /utils.py | 6,530 | 3.765625 | 4 | import pandas as pd
from typing import Iterable
from matplotlib import pyplot as plt
import seaborn as sns
def get_stats_df(df: pd.DataFrame) -> pd.DataFrame:
"""
For given dataframe constructs new dataframe with numerical parameters as a rows,
and statitical values (such as mean, std, min, max and quartiles)
:param df: dataframe to perform analysis on
:return: dataframe with calculated statistics
"""
return df.describe().transpose().drop("count", axis=1)
def plot_distplot_matrix(df: pd.DataFrame, columns: Iterable[str], cols: int = 3):
"""
For given dataframe and columns plots multiple dist plots (histogram with density plots).
:param df: dataframe to plot graphics from
:param columns: columns to plot
:return: None
"""
rows = math.ceil(len(columns) / cols)
fig, ax = plt.subplots(rows, cols, figsize=(7 * cols, 6 * rows))
for index, column in enumerate(columns):
row, col = index // cols, index % cols
current_ax = ax[row, col] if rows > 1 else ax[col]
sns.distplot(ax=current_ax, a = df[column].dropna())
current_ax.set_title(column, fontsize=15)
current_ax.legend(loc='best')
plt.show()
def plot_histplot_matrix(df: pd.DataFrame, columns: Iterable[str], cols: int = 3):
"""
For given dataframe and columns plots multiple dist plots (histogram with density plots).
:param df: dataframe to plot graphics from
:param columns: columns to plot
:return: None
"""
rows = math.ceil(len(columns) / cols)
fig, ax = plt.subplots(rows, cols, figsize=(7 * cols, 6 * rows))
for index, column in enumerate(columns):
row, col = index // cols, index % cols
current_ax = ax[row, col] if rows > 1 else ax[col]
sns.histplot(ax=current_ax, data=df, x=column)
current_ax.set_title(column, fontsize=15)
current_ax.legend(loc='best')
plt.show()
import math
def convert_money_to_usd(v: str) -> float:
"""
For given money string (e.g. '123 RUR', '12345 $', '1000000 EUR')
return amount in USD. None is returned if it's not possible to construct the
current USD amount.
:param v: money string
:return: value of money in USD
"""
def convert_to_usd(currency: str, value: float) -> float:
if currency == "$":
return value
elif currency in CODE_TO_FIX:
currency = CODE_TO_FIX[currency]
elif currency not in CUR_TO_USD:
return math.nan
return value * CUR_TO_USD[currency]
if isinstance(v, str):
sign, value = v.split()
return convert_to_usd(sign, float(value))
return v
CODE_TO_FIX = {
"RUR": "RUB",
}
CUR_TO_USD = {
"USD": 1,
"EUR": 1.2118402047,
"GBP": 1.4006845827,
"INR": 0.0137824399,
"AUD": 0.7883143098,
"CAD": 0.7924177681,
"SGD": 0.7545853523,
"CHF": 1.1157317343,
"MYR": 0.2474983458,
"JPY": 0.0094902639,
"CNY": 0.1548768626,
"NZD": 0.7301028225,
"THB": 0.0333586689,
"HUF": 0.003381943,
"AED": 0.2722940776,
"HKD": 0.1289704651,
"MXN": 0.0489366225,
"ZAR": 0.0682113798,
"PHP": 0.0206182686,
"SEK": 0.1208031665,
"IDR": 0.0000711102,
"SAR": 0.2666666667,
"BRL": 0.1855273137,
"TRY": 0.1436680563,
"KES": 0.0091119342,
"KRW": 0.0009046443,
"EGP": 0.063769971,
"IQD": 0.0006851827,
"NOK": 0.1181922067,
"KWD": 3.3048885399,
"RUB": 0.0134995677,
"DKK": 0.1629504779,
"PKR": 0.0062939562,
"ILS": 0.3055822347,
"PLN": 0.2702568632,
"QAR": 0.2747252747,
"XAU": 1784.2410124212,
"OMR": 2.6007802341,
"COP": 0.0002799729,
"CLP": 0.0014110879,
"TWD": 0.0357843931,
"ARS": 0.0112165288,
"CZK": 0.04680645,
"VND": 0.0000430699,
"MAD": 0.1124380143,
"JOD": 1.4104372355,
"BHD": 2.6595744681,
"XOF": 0.0018474385,
"LKR": 0.005114581,
"UAH": 0.0357464238,
"NGN": 0.0026259926,
"TND": 0.3695449488,
"UGX": 0.0002727007,
"RON": 0.2485449275,
"BDT": 0.0117863604,
"PEN": 0.2738087773,
"GEL": 0.3028337685,
"XAF": 0.0018474385,
"FJD": 0.4928230145,
"VEF": 0.1001251564,
"VES": 5.823e-7,
"BYN": 0.3867822491,
"HRK": 0.1600880594,
"UZS": 0.0000950968,
"BGN": 0.619604058,
"DZD": 0.0075112429,
"IRR": 0.0000237952,
"DOP": 0.0173002952,
"ISK": 0.0077877701,
"XAG": 27.2720943618,
"CRC": 0.001631017,
"SYP": 0.0019501703,
"LYD": 0.2246022918,
"JMD": 0.0066763116,
"MUR": 0.0249401451,
"GHS": 0.1738338629,
"AOA": 0.0015326846,
"UYU": 0.0233701793,
"AFN": 0.0129467678,
"LBP": 0.0006633499,
"XPF": 0.0101552209,
"TTD": 0.1478084781,
"TZS": 0.0004314972,
"ALL": 0.0098035547,
"XCD": 0.370355154,
"GTQ": 0.1293308226,
"NPR": 0.0085738351,
"BOB": 0.1448212002,
"ZWD": 0.0027631943,
"BBD": 0.5,
"CUC": 1,
"LAK": 0.000106963,
"BND": 0.7545853523,
"BWP": 0.092329592,
"HNL": 0.0414984101,
"PYG": 0.0001499574,
"ETB": 0.0251261381,
"NAD": 0.0682113798,
"PGK": 0.2828970781,
"SDG": 0.0181446253,
"MOP": 0.1252140438,
"NIO": 0.0285246223,
"BMD": 1,
"KZT": 0.0023961865,
"PAB": 1,
"BAM": 0.619604058,
"GYD": 0.0047607716,
"YER": 0.0040325173,
"MGA": 0.0002660548,
"KYD": 1.219506224,
"MZN": 0.0133619192,
"RSD": 0.0103060961,
"SCR": 0.0471717396,
"AMD": 0.0019068067,
"SBD": 0.1249000495,
"AZN": 0.5882559629,
"SLL": 0.0000981972,
"TOP": 0.4348980443,
"BZD": 0.4962052774,
"MWK": 0.0012820538,
"GMD": 0.0194498024,
"BIF": 0.0005131827,
"SOS": 0.0017241011,
"HTG": 0.0131618359,
"GNF": 0.0000998941,
"MVR": 0.0647128781,
"MNT": 0.0003502253,
"CDF": 0.0005049127,
"STN": 0.0493838942,
"TJS": 0.0884291808,
"KPW": 0.0011111112,
"MMK": 0.00075245,
"LSL": 0.0682113798,
"LRD": 0.0057970507,
"KGS": 0.0118281587,
"GIP": 1.4006845827,
"XPT": 1278.9642231501,
"MDL": 0.0571428849,
"CUP": 0.0377358491,
"KHR": 0.0002467951,
"MKD": 0.0196779112,
"VUV": 0.0093198316,
"MRU": 0.0276788757,
"ANG": 0.5594404029,
"SZL": 0.0682113798,
"CVE": 0.0109897543,
"SRD": 0.0709912752,
"XPD": 2383.3351486403,
"SVC": 0.1142857143,
"BSD": 1,
"XDR": 1.4429134551,
"RWF": 0.0010249168,
"AWG": 0.5586592179,
"DJF": 0.0056179864,
"BTN": 0.0137824399,
"KMF": 0.0024632513,
"WST": 0.3959962895,
"SPL": 6.000000024,
"ERN": 0.0666666667,
"FKP": 1.4006845827,
"SHP": 1.4006845827,
"JEP": 1.4006845827,
"TMT": 0.2857642001,
"TVD": 0.7883143098,
"IMP": 1.4006845827,
"GGP": 1.4006845827,
"ZMW": 0.046021039
} |
17ae84136c2e1368ffd4b5d54dfdfe61a04de1c3 | mike006322/FrobeniusNumber | /NijenhuisAlgorithm/dijkstra.py | 1,340 | 3.78125 | 4 | from graphHeap import MikesGraphHeap
def dijkstra(graph, start=1):
"""
input graph of the form {node1: {node2: distance, node3: distance, ... }, ...}
output dictionary {node: shortest path from start to node}
"""
X = {start} # Vertices passed so far
A = {start: 0} # Computed shortest path distances
V = set(graph.keys())
M = MikesGraphHeap() # stores nodes in form node = (label, key)
# Dijkstra greedy score for nodes with edge from 1 is the values of the edges
heapFill = V - X - set(graph[start].keys()) # all of the nodes that 1 doesnt have an edge to, to have key of inf in M
M.heapify([(x, 10**6) for x in heapFill])
for node in graph[start]:
M.insert((node, graph[start][node]))
while X != V:
# find minimum A[v] + len(v,w) among edges (v,w) for all v in X and w not in X
# call it (vStar, wStar)
m = M.extract_min() # gives us (node, key)
X.add(m[0])
A[m[0]] = m[1]
# for each edge (m[0], v) out of m[0], a[m[0]][v] = distance to v
for v in graph[m[0]]:
if v in V - X:
M.heapList[0] = (0, 0)
vKey = dict(M.heapList)[v]
M.delete((v, vKey))
vKey = min(vKey, A[m[0]] + graph[m[0]][v])
M.insert((v, vKey))
return A
|
11678b8437700514831071fa243a4b990f961f05 | csouto/samplecode | /CS50x/pset7/finance/test.py | 104 | 3.671875 | 4 | n = [1, 2, 3, 4]
l = ['a', 'b', 'c', 'd']
for item in l:
print(n.item, end=" - ")
print(l.item) |
07308fddda82e20ced5c89709aad2f5c1f917ba4 | main7/station | /for_name.py | 533 | 3.640625 | 4 | # -*- unicode:utf-8 -*-
names=['Tom','Tim','Bob']
for name in names:
print(name)
#list
sum=0
for x in [1,2,3,4,5,6,7,8,9,10]:
sum=sum+x
print(sum)
#range(i)生成一个小于i的整数序列
sum=0
for x in list(range(101)):
sum+=x
print(sum)
sum=0
n=99
while n>0:
sum+=n
n-=2
print(sum)
n=1
while n<=100:
print(n)
n+=1
print('END')
n=1
while n<=100:
if n>10:
break
print(n)
n+=1
print('END')
n=1
while n<=100:
if n>10:
continue
print(n)
n+=1
print('END')
|
0b459d96dc303c0e1b34dd414f7a12772e617ca6 | Sid20-rgb/LabProject | /labfour/set_five.py | 260 | 4.0625 | 4 | '''5.Write a Python program to remove an item from a set if it is present in the set.'''
item = set([1, 2, 3, 4, 5, 6])
r = int(input("Enter a item to remove:"))
if r in item:
item.remove(r)
print(item)
else:
print("Not available in this set.") |
671550eae1ac21abec2ed4c40e1f837f79680e14 | Jinah1/lastName_pythagorean | /evenOrOddPt2.py | 155 | 4.3125 | 4 | x=int(input("Enter an integer and see if it is even or odd:"))
if x % 2 ==0:
print(x ,"is an even number")
else:
print(x ,"is not an even number")
|
a5dbdbb375ee5912dccc5369a00b4e47608eaeee | edoardochiavazza/Esempi-esame | /statistiche_comuni/statistiche_comuni.py | 3,810 | 3.96875 | 4 | # Soluzione proposta esercizio d'esame "Statistiche Comuni"
from typing import IO
FILE_COMUNI = 'elenco-comuni-italiani.csv'
FILE_REGIONI_SCELTE = 'regioni.txt'
def leggi_file():
"""
Legge gli interi dati sui comuni, e li salva in una lista di record.
Ciascun elemento della lista fa riferimento ad un comune, e contiene un dizionario con due chiavi:
'comune' e 'regione' (gli altri dati non sono rilevanti per questo esercizio)
:return: L'elenco di tutti i comuni e la relativa regione di appartenenza
"""
try:
file = open(FILE_COMUNI)
except IOError as error:
print('Impossibile aprire il file:\n' + str(error))
exit()
lista = []
prima = True
for linea in file:
if not prima: # salta la prima riga
try:
campi = linea.split(';')
comune = campi[6]
regione = campi[10]
# print(comune, regione)
record = {'comune': comune, 'regione': regione}
lista.append(record)
except IndexError:
print('Riga con numero di campi insufficiente (viene ignorata):\n' + linea)
else:
prima = False
file.close()
return lista
def regione_valida(elenco, regione):
"""
Verifica se il nome della regione è valido (è presente nella lista?)
:param elenco: Elenco completo dei dati dei comuni
:param regione: Nome della regione da controllare
:return: Booleano che indica se il nome della regione esiste
"""
valida = False
for record in elenco:
if record['regione'] == regione:
valida = True
break
return valida
def comuni_della_regione(elenco, regione):
"""
Estrae l'elenco di tutti i comuni di una determinata regione
:param elenco: Elenco completo dei dati dei comuni
:param regione: Nome della regione di cui estrarre i comuni
:return: Lista dei nomi dei comuni della regione indicata, restituita in ordine alfabetico
"""
comuni = []
for record in elenco:
if record['regione'] == regione:
comuni.append(record['comune'])
comuni.sort() # così li ho già in ordine alfabetico
return comuni
def più_corto(nomi):
"""
Data una lista di stringhe, restituisce la più corta presente nella lista. Qualora ve ne sia più di una
restituisce la prima.
:param nomi: Lista di stringhe
:return: Stringa più breve, o '' se la lista era vuota
"""
lun = 1000
corto = ''
for nome in nomi:
if len(nome) < lun:
lun = len(nome)
corto = nome
return corto
def più_lungo(nomi):
"""
Data una lista di stringhe, restituisce la più lunga presente nella lista. Qualora ve ne sia più di una
restituisce la prima.
:param nomi: Lista di stringhe
:return: Stringa più lunga, o '' se la lista era vuota
"""
lun = 0
lungo = ''
for nome in nomi:
if len(nome) > lun:
lun = len(nome)
lungo = nome
return lungo
def main():
elenco = leggi_file()
try:
regioni_scelte = open(FILE_REGIONI_SCELTE, 'r')
except IOError as ex:
print(f"Impossibile aprire il file {FILE_REGIONI_SCELTE}: {ex}")
exit()
for riga in regioni_scelte:
regione = riga.rstrip()
if regione_valida(elenco, regione):
comuni = comuni_della_regione(elenco, regione)
print(f'*** REGIONE {regione} ***')
print(f'Nella regione {regione} ci sono {len(comuni)} comuni')
print(f'Il nome più breve è {più_corto(comuni)} e quello più lungo è {più_lungo(comuni)}')
else:
print(f'Regione {regione} non valida')
regioni_scelte.close()
main()
|
4cfc10ee8fcd71d393e9ed1845c7f1487a2b17fb | arthurdamm/algorithms-practice | /leet/restore_ip_addresses.py | 1,064 | 3.875 | 4 | #!/usr/bin/env python3
"""
93. Restore IP Addresses
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
A valid IP address consists of exactly four integers (each integer is between 0 and 255) separated by single points.
Example:
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
"""
class Solution:
def restoreIpAddresses(self, s: str):
solutions = []
def dfs(parts, i):
if len(parts) == 4:
if i == len(s):
solutions.append(parts)
return
if i >= len(s):
return
dfs(parts + [s[i]], i + 1)
if len(s) - i >= 2 and s[i] != '0':
dfs(parts + [s[i:i+2]], i + 2)
if len(s) - i >= 3 and int(s[i:i+3]) <= 255:
dfs(parts + [s[i:i+3]], i + 3)
dfs([], 0)
return ['.'.join(solution) for solution in solutions]
input = "25525511135"
print("Solution to", input, Solution().restoreIpAddresses(input))
|
720852b5ae5fb0dd8a6153f524bbe8415e5d9798 | jose-brenis-lanegra/T08-Brenis.Niquen | /iteracion.py | 1,814 | 4.125 | 4 | #ejercicio01
str="jose"
for letra in str:
print(letra) #mostrar jose en forma vertical
#ejercicio02
str="antonio"
for letra in str:
print(letra) #mostrar antonio en forma vertical
#ejercicio03
str="remigio"
for letra in str:
print(letra) #mostrar remigio en forma vertical
#ejercicio04
str="brenis"
for letra in str:
print(letra) #mostrar brenis en forma vertical
#ejercicio05
str="lanegra"
for letra in str:
print(letra) #mostrar lanegra en forma vertical
#ejercicio06
str="giancarlo"
for letra in str:
print(letra) #mostrar giancarlo en forma vertical
#ejercicio07
str="rene"
for letra in str:
print(letra) #mostrar rene en forma vertical
#ejercicio08
str="martin"
letra_m=0
for letra in str:
if (letra=="m"):
letra_m+=1
print("la cantidad de m es:", letra_m) #mostrar la cantidad de m
#ejercicio09
str="eduardo"
letra_d=0
for letra in str:
if (letra=="d"):
letra_d+=1
print("la cantidad de d es:", letra_d) #mostrar la cantidad de d
#ejercicio10
str="lida"
letra_a=0
for letra in str:
if (letra=="a"):
letra_a+=1
print("la cantidad de m es:", letra_a) #mostrar la cantidad de a
#ejercicio11
str="del rosario"
letra_r=0
for letra in str:
if (letra=="r"):
letra_r+=1
print("la cantidad de r es:", letra_r) #mostrar la cantidad de r
#ejercicio12
str="antero"
letra_t=0
for letra in str:
if (letra=="t"):
letra_t+=1
print("la cantidad de t es:", letra_t) #mostrar la cantidad de t
#ejercicio13
str="thalia"
for letra in str:
print(letra) #mostrar thalia en forma vertical
#ejercicio14
str="francisco"
for letra in str:
print(letra) #mostrar francisco en forma vertical
#ejercicio15
str="valentino"
for letra in str:
print(letra) #mostrar valentino en forma vertical
|
f936c87794e1aadcb9750081c7e64e7c431feb15 | Juozapaitis/100daysOfCodeUdemy | /100 days of code/day 27/main.py | 1,071 | 4 | 4 | from tkinter import *
def button_clicked():
print("I got clicked! ")
new_text = input.get()
my_label.config(text = new_text)
window = Tk()
window.title("First GUI Program")
window.minsize(width = 500, height = 300)
# Label
my_label = Label(text = "Enter a label", font = ("Arial", 24, 'bold'))
my_label.pack()
# my_label["text"] = "New Text"
# my_label.config(text = "New Text")
# Entry
input = Entry(width = 10)
input.pack()
button = Button(text = "Click me", command = button_clicked)
button.pack()
window.mainloop()
# def add(*args):
# return sum(args)
# print(add(1, 2, 3))
# def calculate(n, **kwargs):
# print(kwargs)
# # for key, value in kwargs.items():
# # print(key)
# n += kwargs["add"]
# n *= kwargs["multiply"]
# print(n)
# calculate(2, add=3, multiply=5)
# class Car:
# def __init__(self, **kwargs):
# self.make = kwargs.get("make")
# self.model = kwargs.get("model")
# self.color = kwargs.get("color")
# my_car = Car(make="Nissan", model = "GTR")
# print(my_car.make) |
f769175237bbe70c5aebc6b6fdb6e9b7d6985022 | Shaftar/Fibonacci-Zahlen-1 | /Fibonacci-Zahlen-Rechner.py | 708 | 3.796875 | 4 | """Fibonacci Zahlem Rechner
Autor: Mohamad Shaftar
Datum: 25.09.2019
"""
f0 = 0 # Der alte Wert speichern
f1 = 1 # passt dem neuen wie alten wert ein
f2 = 1 # Der neue Wert speichern
zahl = int(input('Enter the number of output:'))
while zahl <= 0: # Eingabe überprüfen
zahl = int(input('Bitte geben Sie positive Zahlen ein:')) # Erneut Eingabe
continue # Wenn die bedienung wahr ist, soll weiter laufen
else: # Beginn der Berechnung
for i in range(zahl): # Iteratives Verfahren
i += 1 # Um genau Laüfe der Schleife zu bestimmen
print(f0) # Ausgabe
f0 = f1 # Erste Zahl
f1 = f2 # Zweite Zahl
f2 = f1 + f0 # Der neue Wert
|
23a08c61628f387bde57786871a905a37f517f32 | alicodermaker/public_code | /github_reminder/webclient/main/random_string.py | 299 | 4.09375 | 4 | import random
import string
def generator(stringLength):
"""Generate a random string with the combination of lowercase and uppercase letters """
letters = string.ascii_letters
return(''.join(random.choice(letters) for i in range(stringLength)))
if __name__ == '__main__':
print(generator(10)) |
92b91715166ad6beade18221771778f4a13b7c32 | esben2k/python3-basics | /list_of_numbers.py | 337 | 4.09375 | 4 | #list_of_numbers.py
# Converting numbers to list
numbers = list(range(1,6))
print(numbers)
# 2 = adding 2 up until 101
odd_numbers = list(range(1,101, 2))
print(odd_numbers)
squares = []
for value in range(1,11):
square = value ** 2
squares.append(square)
print(squares)
digits = [1,2,3,4,5]
print(sum(digits))
|
3b374071e4e3217255bc4f2553b2dbf389429d4f | IshteharAhamad/project | /aggregation.py | 523 | 3.828125 | 4 | class Salary:
def __init__(self,pay,reward):
self.pay = pay
self.reward = reward
def annual_salary(self):
return (self.pay*12) + self.reward
class Employee:
def __init__(self,name, position,sal):
self.name=name
self.position = position
self.sal = sal # here pass the object of the Salary class that is aggregation
def total_salary(self):
return self.sal.annual_salary()
sal = Salary(7777,2223)
emp = Employee("king","hr",sal)
print(emp.total_salary()) |
a92a9a64129040ef87806de395c61e511800d9d3 | zachherington/python-challenge | /PyBank/main.py | 3,252 | 3.515625 | 4 | # PyBank Plan of Attack:
# Resource data
# Col1: Date | MMM-YY | Min: 1/1/2010 | Max: 2/1/2017 |
# Col2: Profit/Losses | +/- # | Max: 1170593 | Min: -1196225 |
# Deliverables:
# 1. The total number of months included in the dataset
# 2. The net total amount of "Profit/Losses" over the entire period
# 3. The average of the changes in "Profit/Losses" over the entire period
# 4. The greatest increase in profits (date and amount) over the entire period
# 5. The greatest decrease in losses (date and amount) over the entire period
# 6. Write the results to a text file.
# HW Attempt: PyBank
# Import modules
import os
import csv
# Set the path
datapath = os.path.join('..','Resources', 'PyBank_Data.csv')
# Read the csv data
with open(datapath) as csvfile:
reader = csv.reader(csvfile, delimiter=",")
# Store header row
headers = next(reader)
# Create separate lists for the date and P/Ls field
dates = []
profits_losses = []
for row in reader:
dates.append((row[0]))
profits_losses.append((row[1]))
# Stores the P&L list as integers
profits_losses = [int(i) for i in profits_losses]
# 1. Number of entries
no_months = len(dates)
# 2. Loop to get the net profit from all entries
net_profit = 0
for x in profits_losses:
net_profit += x
# 3. Average Monthly Change
# (referenced stackoverflow: https://stackoverflow.com/questions/2400840/finding-differences-between-elements-of-a-list)
monthly_change = [j - i for i , j in zip(profits_losses[:-1],profits_losses[1:])]
# Total # of changes
num_changes = len(monthly_change)
#loop for find the sum of all changes
sum_change = 0
for x in monthly_change:
sum_change += x
avg_change = (sum_change / num_changes)
rd_avg = round(avg_change,2)
# 4. Find the max profit gain in a month
g_inc = max(profits_losses)
index_g_inc = profits_losses.index(g_inc)
date_g_inc = dates[index_g_inc]
# 5. Find the min and max profits
g_dec = min(profits_losses)
index_g_dec = profits_losses.index(g_dec)
date_g_dec = dates[index_g_dec]
# 6. Print the results and write to txt file
print("----------------------------")
print("Financial Analysis:")
print("")
print(f"Total # of Months: {no_months}")
print(f"Net Profit: ${net_profit}")
print(f"Average Monthly Change: ${rd_avg}")
print(f"Greatest Profit Increase: ${g_inc} in {date_g_inc}")
print(f"Greatest Profit Decrease: ${g_dec} in {date_g_dec}")
print ("----------------------------")
resultspath = os.path.join('..','Analysis', 'Results_pybank.txt')
with open(resultspath , "w") as text:
text.write("----------------------------")
text.write("\nFinancial Analysis:")
text.write("\n")
text.write(f"\nTotal # of Months: {no_months}")
text.write(f"\nNet Profit: ${net_profit}")
text.write(f"\nAverage Monthly Change: ${rd_avg}")
text.write(f"\nGreatest Profit Increase: ${g_inc} in {date_g_inc}")
text.write(f"\nGreatest Profit Decrease: ${g_dec} in {date_g_dec}")
text.write ("\n----------------------------") |
54f5f265a17006f9e9891029a4a72697a9c87be7 | ericnwin/Python-Crash-Course-Lessons | /Chapter 2+3 Intro + Variables + Strings/WorkingWithLists.py | 639 | 4.3125 | 4 |
cars = ['Honda', 'BMW', 'Mercedes']
## Adding items to Lists
cars.append("Toyota") #Added Toyota to end of list w/ .append
cars.insert(0 , "Fiat") #Added Fiat to position 0 w/ .insert
print (cars)
## Removing Items from Lists
del cars[2] #del removes the value of BMW
print (cars)
recent_purchase = cars.pop() #.pop removes the end of list item and retains the value
print (cars)
print ("The most recent thing I purchased was a " + recent_purchase)
too_expensive = "Mercedes"
cars.remove(too_expensive) #.remove uses the item name to delete it regardless of location
print (cars)
print(f"{too_expensive} is too expensive for me.")
|
03ad60997106cec7efe570954f62e1acea57d15d | nyahjurado/portfolio | /shapes2.py | 1,062 | 4.78125 | 5 | from turtle import *
import math
# Name your Turtle.
Moana= Turtle()
#color is the color of the shape
#number is the number of sides
#length is the length of sides
color = input('Enter color of shape: ')
number = input('Enter the number of sides: ')
#make number an integer
number1 = int(number)
length = input('Enter the length of the sides: ')
length1 = int(length)
#value of the angle of the shape
n = number1
number1 = number1 -2
number1 = number1*180
number1 = number1/n
number1 = 180-number1
#print the results of the math and the shape
print("Each exterior angle will be %d "%(number1))
print(" with %d sides"%(n))
# Set Up your screen and starting position.
Moana.penup()
setup(500,500)
Moana.setposition(0, 0)
### Write your code below:
#Draw desired shape with desired colour
Moana.pencolor(color)
Moana.pendown()
for x in range(0, 24):
for x in range(0, n):
Moana.forward(length1)
Moana.right(number1)
Moana.right(15)
Moana.penup()
# Close window on click.
exitonclick()
|
9f98f72c9cb8a94e09d849f5347738fbcb4d73cd | hooong/baekjoon | /leetcode/1413_minimum_value_to_get_positive_step_by_step_sum.py | 493 | 3.53125 | 4 | from itertools import accumulate
from typing import List
class Solution:
def minStartValue(self, nums: List[int]) -> int:
return -min(0, min(accumulate(nums))) + 1
def test():
solution = Solution()
assert solution.minStartValue([-3, 2, -3, 4, 2]) == 5
assert solution.minStartValue([1, 2]) == 1
assert solution.minStartValue([1, -2, -3]) == 5
assert solution.minStartValue([2, 3, 5, -5, -1]) == 1
assert solution.minStartValue([-5, -2, 4, 4, -2]) == 8
|
976dc8f0633e108a5d06766153129140e151c6cc | nidhiatwork/Python_Coding_Practice | /GrokkingCodingInterview/SlowFastPointers/find_cycle_start.py | 768 | 3.890625 | 4 | '''Given the head of a Singly LinkedList that contains a cycle, write a function to find the starting node of the cycle.
'''
from collections import Counter
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
def find_cycle_start(head):
slow,fast = head,head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow==fast:
break
if slow!=fast:
return None
fast = head
while slow!=fast:
slow=slow.next
fast=fast.next
return slow
head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5, ListNode(6))))))
head.next.next.next.next.next.next = head.next.next
print(find_cycle_start(head).val) |
4337a751536c78843ae0d8293544204a7f83f2ce | pkshiu/rpi-rotary-example | /rotate.py | 1,668 | 3.640625 | 4 | import time
from gpiozero import Button
# Replace these with your GPIO pin connections.
# ...
# ... [31] [33] [35] [37] [39]
# ... .... gpio13 gpio19 gpio26 gnd
PIN_A = 19
PIN_B = 26
PIN_SELECT = 13
class App():
"""
Simple example to listen for change of pin A on the encoder, and determine the direction
of rotation on reading pin B, whether pin B has "fired" before A.
"""
def __init__(self):
self.button_a = Button(PIN_A, pull_up=True)
self.button_b = Button(PIN_B, pull_up=True)
self.button_a.when_activated=self.pin_a
# center button. Use button class to debounce
self.select = Button(PIN_SELECT, pull_up=True)
self.select.when_pressed = self.selected
def pin_a(self, b):
"""
This is called when user rotate the encoder
"""
if not self.button_b.is_pressed:
print('Up')
else:
print('Down')
def selected(self):
"""
This is called when the center button is pressed.
"""
print('selected')
def rotation_sequence(self):
'''
Not quite figure this out...
Not used.
'''
a_state = self.button_a.is_pressed
b_state = self.button_b.is_pressed
r_seq = (a_state ^ b_state) | b_state << 1
return r_seq
def go(self):
# Note that this loop's wait frequency doesn't really matter.
# We are using events triggered by the raising edge of pin A
# to read the activity on the encoder.
while(1):
time.sleep(0.01)
if __name__ == '__main__':
app = App()
app.go()
|
be25a1b95be12a9277661e7419d5e7bb7fa68e08 | MingYanWoo/Leetcode | /151. 翻转字符串里的单词.py | 1,799 | 3.96875 | 4 | # 151. 翻转字符串里的单词
# 给定一个字符串,逐个翻转字符串中的每个单词。
# 示例 1:
# 输入: "the sky is blue"
# 输出: "blue is sky the"
# 示例 2:
# 输入: " hello world! "
# 输出: "world! hello"
# 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
# 示例 3:
# 输入: "a good example"
# 输出: "example good a"
# 解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
# 说明:
# 无空格字符构成一个单词。
# 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
# 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
# 进阶:
# 请选用 C 语言的用户尝试使用 O(1) 额外空间复杂度的原地解法。
class Solution:
def reverseWords(self, s: str) -> str:
trimStr = ''
for i in range(len(s)):
if s[i] != ' ':
trimStr += s[i]
else:
if (i > 0 and s[i-1] == ' ') or (i == 0):
continue
else:
trimStr += s[i]
if trimStr == '' or trimStr == ' ':
return ''
trimStr = trimStr[:-1] if trimStr[-1] == ' ' else trimStr
deque = []
i = 0
while i < len(trimStr):
temp = ''
while i < len(trimStr) and trimStr[i] != ' ':
temp += trimStr[i]
i += 1
deque.append(temp)
i += 1
res = ''
while deque:
word = deque[-1]
deque.pop()
res += word
res += ' '
return res[:-1] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.