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
|
---|---|---|---|---|---|---|
56e0e4a1cbb8f8b2d53b4af17cb27a6f5d89a4b6 | ValentinaToro/programacion | /Tarea4.py | 879 | 3.9375 | 4 | #
#En el primero deberán demostrar las 4 operaciones aritméticas, además de la operación módulo
# definiendo variables e imprimiéndolas en cada paso, usando f-strings.
print ("Primero definiré la variable,")
valor_global = 6
x = valor_global
print(x)
print(type(x))
print ("luego realizaré las cuatro operaciones más el cálculo del módulo.")
x = x + 4.0
print (x)
print(f"La primera operación, suma, da como resultado {x}, operando un int con un float, dando en resultado float.")
x = valor_global
x = x - 1
print (x)
print (f"La segunda operación, resta, da {x}.")
x = valor_global
x = x * 3
print (x)
print(f"La tercera operación, multiplicación, da {x}.")
x = valor_global
x = x / 2
print (x)
print (f"La cuarta operación, división, da como resultado {x}.")
x = valor_global
x = x % 2
print (x)
print (f"La quinta operación, módulo, da como resultado {x}.") |
434f750a381721dc3b0201f6379783617de388e5 | RafaelDavisH/Simple_Python_Projects | /Turtle Race/turtle_race.py | 2,099 | 4.5625 | 5 | #!/bin/python3
from turtle import *
from random import randint
# === Build the Race Track
# write(0) # turtle draws track markings for the race
# forward(100) # turtle draw a line using the turtle
# write(5) # turtle draws track markings for the race
# writing all the numbers in between to create markings
# write(0)
# # forward(20)
# # write(1)
# # forward(20)
# # write(2)
# # forward(20)
# # write(3)
# # forward(20)
# # write(4)
# # forward(20)
# # write(5)
# # forward(20)
speed(10) # speed up the turtle so it draws faster.
penup() # lifting the pen up or there will be a line drawn when moving the turtle
goto(-140, 140) # moving the turtle to the top left
# create the markings with a for loop
for step in range(16): # to get the turtle to print from 0 - 5 the range needs to be `range(6)`.
write(step, align='center') # center the numbers to the vertical lines.
right(90) # _
forward(10) # | draw vertical lines to create a track
pendown() # | right(90) makes the turtle turn right 90 degrees.
forward(150) # < Moving forward(10) before putting the pen down leaves a small
penup() # | gap between the number and the start of the line. After drawing
backward(160) # | the line you lift up the pen and go backward(160) the length of the line plus the gap.
left(90) # -
forward(20)
# ==== Racing turtles ====
# create turtles
# Turtle Rae
rae = Turtle()
rae.color('blue')
rae.shape('turtle')
# Turtle Bob
bob = Turtle()
bob.color('red')
bob.shape('turtle')
# Turtle Charlie
charlie = Turtle()
charlie.color('yellow')
charlie.shape('turtle')
# Turtle Lady
lady = Turtle()
lady.color('pink')
lady.shape('turtle')
# set turtles to the starting line.
rae.penup()
rae.goto(-160, 100)
rae.pendown()
bob.penup()
bob.goto(-160, 70)
bob.pendown()
charlie.penup()
charlie.goto(-160, 40)
charlie.pendown()
lady.penup()
lady.goto(-160, 10)
lady.pendown()
for turn in range(100):
rae.forward(randint(1, 5))
bob.forward(randint(1, 5))
charlie.forward(randint(1, 5))
lady.forward(randint(1, 5))
|
8e43eafecc87e72068201626ec08e0e6aed214da | franktank/py-practice | /goog/foobar/cake-is-not-a-lie.py | 572 | 3.734375 | 4 | """
Test cases
==========
Inputs:
(string) s = "abccbaabccba"
Output:
(int) 2
Inputs:
(string) s = "abcabcabcabc"
Output:
(int) 4
"""
abcabc
a -> bcabc
ab
if substring reduced to nothing -> return
1 +
else if not part of substring
res = 0
def answer(s):
res = 0
for i in range(1, len(s)):
if helper(s[:i], s[i:]):
res = max(res, len(s)/i)
return res
def helper(prev, cur):
if not cur:
return True
if prev == cur[:len(prev)]:
return helper(prev, cur[len(prev):])
else:
return False
|
6d59e2545d1afb35ce89656443eabc58dad1d4ca | wmakaben/AdventOfCode | /AoC_19/d01.py | 470 | 3.65625 | 4 | file = open("input/d01.txt", 'r')
def getFuel(mass):
return (mass // 3) - 2
totalFuel = 0
for mass in file:
totalFuel = totalFuel + getFuel(int(mass))
# Test Case: 654
# totalFuel = getFuel(1969)
# Test Case: 33583
# totalFuel = getFuel(100756)
print(totalFuel)
# 3231941
# Part 2
file = open("input/d01.txt", 'r')
totalFuel = 0
for mass in file:
fuel = getFuel(int(mass))
while fuel > 0:
totalFuel += fuel
fuel = getFuel(fuel)
print(totalFuel)
# 4845049 |
63ff361f0be9a71aebf581d9116b753c1ac2d2b4 | mertkanyener/Exercises | /file_overlap.py | 430 | 3.671875 | 4 | def read(file):
result = []
with open(file, 'r') as open_file:
lines = open_file.read().splitlines()
for line in lines:
result.append(int(line))
return result
def overlapping(list_one, list_two):
result = []
for i in list_one:
if i in list_two:
result.append(i)
return result
l = overlapping(read('primenumbers.txt'), read('happynumbers.txt'))
print(l)
|
fb192db966e11a8b657655c6c1d32aeed86816eb | AnhellO/DAS_Sistemas | /Ene-Jun-2022/francisco-alan-menchaca-merino/practica-6/composite.py | 1,988 | 3.859375 | 4 | from abc import ABC, abstractmethod
class FileSystem(ABC):
"""The base Component class declares common operations
for both simple and complex objects of a composition"""
@abstractmethod
def string_rep(self, file):
pass
class File(FileSystem):
"""The leaf class represents the end objects of a composition.
A leaf can't have any children.
Usually, it's children the Leaf objects that do the actual work,
whereas Composite objects only delegate to their sub-components."""
def __init__(self, file_name):
self.file_name = file_name
def string_rep(self):
return self.file_name + "\n"
# Component class
class Directory:
"""The Composite class represents the complex components that
may have children. Usually, the Composite objects delegate the
actual work to their children and then "sum-up" the result."""
def __init__(self, dir_name):
self.__dir_name = dir_name + "\\\n"
self.__childrens = []
def add(self, item):
self.__childrens.append(item)
def remove(self, item):
self.__childrens.remove(item)
def string_rep(self):
complete_root = "\n" + self.__dir_name
for item in self.__childrens:
complete_root += item.string_rep()
return complete_root
if __name__ == '__main__':
root_path = Directory("C:\\Users")
user_path = Directory("Alan")
root_path.add(user_path)
documents_dir = Directory("Documents")
desktop_dir = Directory("Desktop")
images_dir = Directory("Images")
user_path.add(documents_dir)
user_path.add(desktop_dir)
user_path.add(images_dir)
documents_dir.add(File("factory_method.py"))
documents_dir.add(File("r_programming.R"))
desktop_dir.add(File("Google Chrome"))
desktop_dir.add(File("Microsoft Edge"))
images_dir.add(File("Dog.png"))
images_dir.add(File("Cat.png"))
user_path.remove(images_dir)
print(root_path.string_rep())
|
ce265bbaaf7d98d128e7a27552fa352f575719f8 | portugol/decode | /Algoritmos Traduzidos/Python/Algoritmos traduzidos[Filipe]/ex6.py | 380 | 3.9375 | 4 | imc = input('Digite o valor do IMC(Indice de Massa Corporal): ')
if int(imc)<20:
print('Abaixo do Peso')
elif int(imc)>=20 and int(imc) <=24:
print('Peso Ideal')
elif int(imc)>=25 and int(imc)<=39:
print('Excesso de Peso')
elif int(imc)>=30 and int(imc)<=39:
print('Obesidade')
elif int(imc)>39:
print('Obesidade Mórbida')
else:
print('Valor inválido')
|
3423b374ad7caac6ac092b49d036c0a560153810 | KKiim/Bachelor-Thesis-Leader-Follower-Analysis-in-Immersive-Analysis | /Python/Ana/compute_input.py | 745 | 3.5 | 4 | # compute_input.py
import sys
import json
import l_f_csv as lf # Local file
# Read data from stdin
def read_in():
lines = sys.stdin.readlines()
# Since our input would only be having one line,
# parse our JSON data from that
return json.loads(lines[0])
def main():
# get our data as an array from read_in()
l_f_param = read_in()
# print lines
list = lf.get_list(l_f_param)
# print ', '.join(list)
# Writing in File dows not work!
# with open('HALLOHALLO.csv', 'w', newline='') as csvfile:
# the_writer = csv.writer(csvfile)
# for i in range(0, len(list)):
# print "Hello"
# the_writer.writerow(list[i])
print(list)
# start process
if __name__ == '__main__':
main()
|
e4518cfdbcb296fd57a071c2634a48515e47378f | jack96harrison/PythonBeginner | /PythonPractice_Exercise7.py | 225 | 4.03125 | 4 | """
Take a variable of a list e.g a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Write one line of python that makes a new list with only the even elements
"""
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = a[1::2]
print(a)
print(b) |
c9052cdd2503b94a8d19d2fe47322ede0b3629b9 | pranavr11/school_scheduling | /realSchoolSchedule.py | 6,570 | 3.890625 | 4 | from datetime import datetime
'''
ERRORS TO BE FIXED WHEN I EVETUALLY REDO THIS a:
If the time is before school starts it registers next class as second blockNumber
You probably can't read this code anyway lol
'''
'''
1) Input what school day (A/B) it is today
2) Give me the name of my current class depending on the current time and day of the week.
3) Give me the time until my next class, and maybe some other times if I feel like it
'''
'''
1) have a dictionary of tuples of start time and end time
2)have a current class in a loop that keeps track of what class using time comparison
(until current_time is greater than blockNumber end time and less than blockNumber start time; blockNumber += 1)
3)The current class function returns what calss I am in , the end time, how many minutes are left, and the name of the class.
It will also take in the day(a or b) and return the classes based on that.
4)next_class gives me the start time of the class right after current class and the time until it starts.
5)If the final class end time is less than the current time: there are no more classes today
6) Maybe keep track of day of the week to say that there is no school on weekends and whether today is an a or b day
47) Have a 2 key dictionary of a and b with a list of all my classes, that will give me my current class depending on blockNumber
7)if current_time is greater than end time of blockNumber 1, blocknumber += 1
'''
class Schedule:
def __init__(self):
self.classTimes = [('7:30','8:30'), ('8:35','9:35'), ('9:40','10:40'), ('10:45', '11:45'), ('11:45', '12:15'), ('12:15', '12:25'), ('12:30', '12:50'), ('12:55', '13:15'),('13:20', '13:40'), ('13:45', '14:05')]
self.classNames = {"a":["Computer Science", "Web Design", "Spanish 3 Honors", "AP Physics 1", "Lunch", "Office Hours", "Computer Science", "Web Design", "Spanish 3 Honors", "AP Physics 1" ],
"b":["PE", "Geometry Honors", "US 1 Honors", "English Honors", "Lunch", "Office Hours","PE", "Geometry Honors", "US 1 Honors", "English Honors",]}
className = ""
self.schoolDay = "a"
self.blockNumber = 0
#current_time = datetime.now().time()
#self.current_time = "8:56"
#self.current_time = datetime.strptime(self.current_time, "%H:%M")
self.current_time = datetime.now().time()
self.current_time = self.current_time.strftime("%H:%M") #
self.current_time = datetime.strptime((self.current_time), "%H:%M")
print(self.current_time)
#schoolDay = input("Is today an A day or a B day?")[0].lower()
# current time with seconds, datetime format
# converts current time to string from datetime and truncates seconds, used for finding what class I'm in
def current_class(self, canPrint):
for classTime in self.classTimes:
start_time = datetime.strptime(self.classTimes[self.blockNumber][0], "%H:%M")
end_time = datetime.strptime(self.classTimes[self.blockNumber][1], "%H:%M")
final_class = datetime.strptime(self.classTimes[-1][1], "%H:%M")
initial_class = datetime.strptime(self.classTimes[0][0], "%H:%M")
self.ifGap = False
#print('current_time:', self.current_time, 'start_time:', start_time, 'end_time:', end_time,
#'initial_class:', initial_class, 'final_class:', final_class)
if self.current_time <= end_time and self.current_time >= start_time:
className = self.classNames[self.schoolDay][self.blockNumber]
if canPrint:
print("Your current class is " + className + ", block " + str(self.blockNumber+1) + self.schoolDay.upper() + "." )
break
elif self.current_time > final_class and self.current_time < datetime.strptime("23:59", "%H:%M"):
if canPrint:
print("School has ended for the day.")
self.blockNumber = 0
break
elif self.current_time >= datetime.strptime("00:00", "%H:%M") and self.current_time < initial_class:
if canPrint:
print("School hasn't started yet.")
self.blockNumber = 0
break
elif self.current_time >= end_time and self.current_time <= datetime.strptime(self.classTimes[self.blockNumber + 1][0], "%H:%M"):
if canPrint:
print("This is the gap between " + self.classNames[self.schoolDay][self.blockNumber] + " and " + self.classNames[self.schoolDay][self.blockNumber+1])
self.ifGap = True
break
else:
# print('else case')
self.blockNumber += 1
return self.blockNumber
# blockNumber = current_class() + 1
#FIX AFTER CURRENT TIME #office hours b
def next_class(self):
if self.ifGap:
self.blockNumber = s.current_class(False)
nextClassName = self.classNames[self.schoolDay][self.blockNumber+1]
remaining_time = datetime.strptime(self.classTimes[self.blockNumber+1][0], "%H:%M") - self.current_time
remaining_time = remaining_time.total_seconds()//60
if self.current_time > datetime.strptime(self.classTimes[-1][1], "%H:%M") and self.current_time < datetime.strptime("23:59", "%H:%M"):
print("No more classes")
else:
print("Your next class, " + str(nextClassName) + "(" + str(self.blockNumber+2) + str(self.schoolDay.upper()) + ")" + ","" will start in " + str(int(remaining_time)) + " minutes.")
print(self.blockNumber)
else:
self.blockNumber = s.current_class(False)+1
nextClassName = self.classNames[self.schoolDay][self.blockNumber]
remaining_time = datetime.strptime(self.classTimes[self.blockNumber][0], "%H:%M") - self.current_time
remaining_time = remaining_time.total_seconds()//60
# converts string back to datetime, this time without seconds
if self.current_time > datetime.strptime(self.classTimes[-1][1], "%H:%M") and self.current_time < datetime.strptime("23:59", "%H:%M"):
print("No more classes.")
else:
print("Your next class, " + str(nextClassName) + "(" + str(self.blockNumber+1) + str(self.schoolDay.upper()) + ")" + ","" will start in " + str(int(remaining_time)) + " minutes.")
s = Schedule()
s.current_class(True) # STILL works for now
s.next_class()
|
bc80f7d44bc17231af5990cbd5b786ec31911128 | vamazzuca/Mazzuca-MiniMax-Project | /Unbeatable Tic-Tac-Toe.py | 6,876 | 4.15625 | 4 |
# Initites the Tic Tac Toe Game
#Wriiten for Assignment 4 CMPUT 355 University of ALberta
# Written by Alex Mazzuca
def main():
ticTacToeGame()
return
# Runs Tic Tac Toe Game. Only the Human player can player X and plays against the ai O player
# Written by Alex Mazzuca
def ticTacToeGame():
gameBoard = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
gameBoardpositions = [" 1 ", " 2 ", " 3 ", " 4 " , " 5 ", " 6 ", " 7 ", " 8 ", " 9" ]
acceptableInputs = ["1","2","3","4","5","6","7","8","9"]
player = "X"
computer = "O"
turn = player
turnNumber = 0
print("Welcome to Tic Tac Toe. The player will go first and will be X.")
print("The Player will input wich position they will go based on this board.")
showBoard(gameBoardpositions)
while (turnNumber < 9):
#X Turn
if (turn == "X"):
print("It is your turn")
playerInput = checkInput(acceptableInputs, gameBoardpositions)
emptyPosition = checkPostion(playerInput, gameBoard)
while (emptyPosition == False):
print("Position Occupied")
playerInput = checkInput(acceptableInputs, gameBoardpositions)
emptyPosition = checkPostion(playerInput, gameBoard)
gameBoard[playerInput - 1] = " X "
showBoard(gameBoard)
winner = checkWin(gameBoard, turn)
if winner == "X":
print("X has won. Game Over!")
return
elif winner == "Tie":
print("Tie. Game Over!")
return
turnNumber += 1
turn = "O"
if turnNumber == 9:
break
#O Turn
elif (turn == "O"):
oPlaced = False
scoreBoard = gameBoard.copy()
for i in range(9):
minimaxGameBoard = gameBoard.copy()
if minimaxGameBoard[i] == " ":
minimaxGameBoard[i] = " O "
score = minimax(minimaxGameBoard, "O")
scoreBoard[i] = score
for i in range(9):
if (scoreBoard[i] == 1 and oPlaced == False):
gameBoard[i] = " O "
oPlaced = True
if oPlaced == False:
for i in range(9):
if (scoreBoard[i] == 0 and oPlaced == False):
gameBoard[i] = " O "
oPlaced = True
if oPlaced == False:
for i in range(9):
if (scoreBoard[i] == -1 and oPlaced == False):
gameBoard[i] = " O "
oPlaced = True
print("\n O's Move")
showBoard(gameBoard)
winner = checkWin(gameBoard, turn)
if winner == "O":
print("O has won. Game Over!")
return
elif winner == "Tie":
print("Tie. Game Over!")
return
turnNumber += 1
turn = "X"
if turnNumber == 9:
break
return
# Shows the current gameboard will all the current moves
# Written by Alex Mazzuca
def showBoard(gameBoard):
print(gameBoard[0] + '|' + gameBoard[1] + "|" + gameBoard[2])
print("---+---+---")
print(gameBoard[3] + '|' + gameBoard[4] + "|" + gameBoard[5])
print("---+---+---")
print(gameBoard[6] + '|' + gameBoard[7] + "|" + gameBoard[8])
return
# Check to see that the input is an integer from 1 to 9
# Written by Alex Mazzuca
def checkInput(acceptableInputs, gameBoardpositions):
playerInput = None
while (playerInput not in acceptableInputs):
playerInput = input("Enter your position you would like to go:")
playerInput = int(playerInput)
return playerInput
# Checks to see if there the position on the Board is taken up
# Written by Alex Mazzuca
def checkPostion(playerInput, gameBoard):
index = playerInput - 1
if (gameBoard[index] != " "):
return False
else:
return True
# Checks to see if either X or O has one or checks to see is there is
# a Tie
# Written by Alex Mazzuca
def checkWin(gameBoard, turn):
winner = None
if gameBoard[0] == gameBoard [1] == gameBoard[2] != " ":
winner = turn
elif gameBoard[0] == gameBoard [3] == gameBoard[6] != " ":
winner = turn
elif gameBoard[0] == gameBoard [4] == gameBoard[8] != " ":
winner = turn
elif gameBoard[6] == gameBoard [7] == gameBoard[8] != " ":
winner = turn
elif gameBoard[3] == gameBoard [4] == gameBoard[5] != " ":
winner = turn
elif gameBoard[1] == gameBoard [4] == gameBoard[7] != " ":
winner = turn
elif gameBoard[2] == gameBoard [5] == gameBoard[8] != " ":
winner = turn
elif gameBoard[2] == gameBoard [4] == gameBoard[6] != " ":
winner = turn
if (" " not in gameBoard):
winner = "Tie"
return winner
# Implementation of the MiniMax alogrthm that checks all the possible best moves for the AI
# Code adpated from URL: https://www.javatpoint.com/mini-max-algorithm-in-ai
# Written by Alex Mazzuca
def minimax(minigameBoard, turn):
winner = checkWin(minigameBoard, turn)
if winner != None:
if winner == "X":
return -1
elif winner == "O":
return 1
elif winner == "Tie":
return 0
if (turn == "X"):
bestScore = -99999
for i in range(9):
if (minigameBoard[i] == " "):
minigameBoard[i] = " O "
minimaxScore = minimax(minigameBoard, "O")
minigameBoard[i] = " "
bestScore = max(minimaxScore, bestScore)
return bestScore
elif (turn == "O"):
bestScore = 99999
for i in range(9):
if (minigameBoard[i] == " "):
minigameBoard[i] = " X "
minimaxScore = minimax(minigameBoard, "X")
minigameBoard[i] = " "
bestScore = min(minimaxScore, bestScore)
return bestScore
if __name__ == "__main__":
main() |
308b687ebf85ecb931656c0acd98c6b72f0899fc | mitamit/OW_Curso_Python | /diccionario.py | 801 | 4 | 4 | diccionario = {'a': True, 1: "esto es un string", (1,2): False} #las llaves son inmutables
#almacenar
diccionario['b'] = "nuevo string" #creamos clave valor
diccionario['a'] = False #si encuentra la llave actualiza sino crea
#obtener datos
valor = diccionario['a']
valor = diccionario.get('z', False) #sino encuentra z regresa False sino devuelve el valor
#eliminar
del diccionario[1]
print(diccionario)
print(valor)
llaves = diccionario.keys() #objeto iterable
llaves = list(diccionario.keys()) #convierte en array las llaves
valores = list(diccionario.values()) #convierte en array los valores
print(llaves)
print(valores)
diccionario2 = {2: "esto es string del segundo diccionario", "t": 239, 4: True}
diccionario.update(diccionario2) #diccionario2 se añade a diccionario
print(diccionario)
|
c21001d0c6c3369692c4ca01d7256d2e7d18a6b8 | keltoom/Python_programs | /algeria-states-game/main.py | 1,105 | 3.921875 | 4 | import turtle
import pandas
screen = turtle.Screen()
screen.title("ALGERIA States")
image = "algeria_states_blank.gif"
screen.addshape(image)
turtle.shape(image)
# def get_mouse_click_coor(x,y):
# print(x, y)
#
# turtle.onscreenclick(get_mouse_click_coor)
data = pandas.read_csv("48_states.csv")
states = data.state.to_list()
list_of_answers = []
while len(list_of_answers) < 50:
user_answer = screen.textinput(title=f"{len(list_of_answers)}/48 States",
prompt="What's the next state?").title()
if user_answer == "Exit":
missing_states = [state for state in states if state not in list_of_answers]
new_data = pandas.DataFrame(missing_states)
new_data.to_csv("states_to_learn.csv ")
break
if user_answer in states:
t = turtle.Turtle()
t.hideturtle()
t.penup()
state_data = data[data.state == user_answer]
t.goto(int(state_data.x), int(state_data.y))
t.write(state_data.state.item())
list_of_answers.append(user_answer)
# turtle.mainloop()
# screen.exitonclick()
|
c4c1a59329e38f93df04516d49e4723721d49268 | hyungook/python-basics | /100jun/04_test.py | 2,045 | 3.65625 | 4 | # while문
'''
# 10952
두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.
입력은 여러 개의 테스트 케이스로 이루어져 있다.
각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10)
입력의 마지막에는 0 두 개가 들어온다.
'''
while True:
a,b = map(int,input().split())
if a == 0 and b == 0:
break
else:
print(a+b)
'''
# 10951
두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.
입력은 여러 개의 테스트 케이스로 이루어져 있다.
각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10)
'''
while True:
try:
a,b = map(int, input().split())
print(a+b)
except:
break
'''
# 1110
0보다 크거나 같고, 99보다 작거나 같은 정수가 주어질 때 다음과 같은 연산을 할 수 있다. 먼저 주어진 수가 10보다 작다면 앞에 0을 붙여 두 자리 수로 만들고, 각 자리의 숫자를 더한다. 그 다음, 주어진 수의 가장 오른쪽 자리 수와 앞에서 구한 합의 가장 오른쪽 자리 수를 이어 붙이면 새로운 수를 만들 수 있다. 다음 예를 보자.
26부터 시작한다. 2+6 = 8이다. 새로운 수는 68이다. 6+8 = 14이다. 새로운 수는 84이다. 8+4 = 12이다. 새로운 수는 42이다. 4+2 = 6이다. 새로운 수는 26이다.
위의 예는 4번만에 원래 수로 돌아올 수 있다. 따라서 26의 사이클의 길이는 4이다.
N이 주어졌을 때, N의 사이클의 길이를 구하는 프로그램을 작성하시오.
첫째 줄에 N이 주어진다. N은 0보다 크거나 같고, 99보다 작거나 같은 정수이다.
'''
result = int(input())
num = result
count = 0
while True:
ten = num//10
one = num%10
res = int(ten)+int(one)
count += 1
num = int(str(num%10) + str(res%10))
if (result == num):
break
print(count)
|
58ddd3560e1c090ae6f492ea9d3b73810b8e9eaf | Kwon1995-2/BC_Python | /chapter7/myModule.py | 312 | 3.984375 | 4 | # def sum(n):
# sum = 0
# for i in range(1, n + 1):
# sum += i
# return sum
# def power(x, n):
# prod = 1
# for i in range(1, n + 1):
# prod = prod * x
# return prod
# if __name__ == '__main__':
# print('{0}'.format(__name__))
# print(sum(5))
# print(power(5,2))
|
63d53595ccb1f9e58e4bbf34f0d88d885ad41698 | aiifabbf/leetcode-memo | /941.py | 1,160 | 3.8125 | 4 | """
判断是否存在一个 :math:`i, 0 < i < n - 1` 使得长度为n - 1的array满足
.. math::
\left\{\begin{aligned}
a_0 < a_1 < ... < a_i \\
a_i > a_{i + 1} > ... > a_{n - 1} \\
\end{aligned}\right.
直观上来说就是判断一个array里面的值从左往右是否形成了一个峰。
"""
from typing import *
class Solution:
def validMountainArray(self, A: List[int]) -> bool:
if len(A) <= 2:
return False
else:
peekMet = False
for i, v in enumerate(A[1: -1], 1):
if A[i - 1] < v < A[i + 1]:
if peekMet:
return False
elif A[i - 1] < v > A[i + 1]:
if peekMet:
return False
else:
peekMet = True
elif A[i - 1] > v > A[i + 1]:
if not peekMet:
return False
else:
return False
else:
if peekMet:
return True
else:
return False |
15dbe3ed9061f88958789cf66972cd075aca2e42 | zichenchenzcc/Sudoku-Solver | /Sudoku Solver.py | 7,641 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 30 19:05:33 2020
@author: czc
"""
#The structure of the dic_up is:
#{Index,(Index before ranking,[(Sudoku coordinate),Index of chosen number in available number list,Condition,Length of available number list,Index of last step])}
import numpy as np
#Given the Sudoku, return how many numbers you can fill in for each blank space (available_matrix)
#And also the number list you can fill for each blank space(solution_matrix)
def sudoku_support(Sudoku):
available_matrix = np.zeros([9,9])
solution_matrix = {}
Sudoku_piece = []
for i in range(3):
for j in range(3):
Sudoku_piece.append(Sudoku[(3*i):(3*i + 3), (3*j):(3*j + 3)])
for i in range(9):
for j in range(9):
number_list = [1,2,3,4,5,6,7,8,9]
if Sudoku[i,j] != 0:
available_matrix[i,j] = 0
solution_matrix[i,j] = []
else:
piece = Sudoku_piece[i//3*3 + j//3].reshape(9,1)
for l in piece:
if l != 0:
number_list.remove(l)
number_appear = []
for m in Sudoku[i,:]:
if m !=0:
number_appear.append(m)
for n in Sudoku[:,j]:
if n !=0:
number_appear.append(n)
for p in number_appear:
repeat=0
for q in number_list:
repeat = repeat + (q == p)
if repeat != 0:
number_list.remove(p)
available_matrix[i,j] = len(number_list)
solution_matrix[i,j] = number_list
return available_matrix, solution_matrix
#While there are blank places that can only fill in one number, fill in those places and check whether there are other blank places that can fill in only one number come out. If yes, fill in all of them and keep doing.
def fill_only_value(Sudoku):
available_matrix, solution_matrix = sudoku_support(Sudoku)
while (np.sum(available_matrix==1)) !=0:
for i in range(9):
for j in range(9):
if available_matrix[i,j] == 1:
Sudoku[i,j] = solution_matrix[i,j][0]
available_matrix, solution_matrix = sudoku_support(Sudoku)
return Sudoku
#Update the fourth element in dictionary which means how many numbers can be fill in the corresponding place
def update_dic(dic_up,solution_matrix):
for i in range(len(dic_up)):
dic_up[i][1][3] = len(solution_matrix[dic_up[i][1][0]])
return dic_up
#If all the blank places have at least two choices, try each by each
def Sudoku_intermediate_solver(r,dic_up,copy,Sudoku):
available_matrix, solution_matrix = sudoku_support(Sudoku)
for i in range(r,len(dic_up)):
copy[i] = np.copy(Sudoku)
if dic_up[i][1][3] != 0:
for j in range(dic_up[i][1][3]):
if dic_up[i][1][2] == 0:
Sudoku[dic_up[i][1][0]] = solution_matrix[dic_up[i][1][0]][j]
available_matrix, solution_matrix = sudoku_support(Sudoku)
Sudoku = fill_only_value(Sudoku)
available_matrix, solution_matrix = sudoku_support(Sudoku)
if np.sum(Sudoku==0)+np.sum(available_matrix==0) ==81:
dic_up[i][1][1] = j
dic_up[i][1][2] = 1
dic_up[i][1][4] = i
dic_up = update_dic(dic_up,solution_matrix)
else:
Sudoku = np.copy(copy[i])
available_matrix, solution_matrix = sudoku_support(Sudoku)
if dic_up[i][1][2] == 0:
dic_up[i][1][2] = 2
dic_up[i][1][4] = dic_up[i-1][1][4]
break
else:
dic_up[i][1][4] = dic_up[i-1][1][4]
return i,dic_up,copy,Sudoku
def Sudoku_solver(Sudoku):
available_matrix, solution_matrix = sudoku_support(Sudoku)
s = 0
dic = {}
copy = {}
copy[-1] = np.copy(Sudoku)
for i in range(9):
for j in range(9):
if Sudoku[i,j] == 0:
dic[s] = [(i,j), 0, 0, len(solution_matrix[i,j]),0]
s= s + 1 #Build dictionary (dic_up)
dic_up= sorted(dic.items(), key=lambda d:d[1][3]) #Rank length of available number from smallest to largest
#Begin by trying the smallest
i,dic_up,copy,Sudoku = Sudoku_intermediate_solver(0,dic_up,copy,Sudoku)
while dic_up[i][1][2] == 2: #When there is error in continuing
dic_up[i][1][2] = 0
i = dic_up[i][1][4]
Sudoku = np.copy(copy[i])
available_matrix, solution_matrix = sudoku_support(Sudoku)
dic_up = update_dic(dic_up,solution_matrix)
while dic_up[i][1][1] >= dic_up[i][1][3] - 1: #When there is no choice for that step, back to last step
i = dic_up[i-1][1][4]
Sudoku = np.copy(copy[i])
available_matrix, solution_matrix = sudoku_support(Sudoku)
dic_up = update_dic(dic_up,solution_matrix)
Sudoku[dic_up[i][1][0]] = solution_matrix[dic_up[i][1][0]][dic_up[i][1][1] + 1]
available_matrix, solution_matrix = sudoku_support(Sudoku)
dic_up[i][1][1] = dic_up[i][1][1] + 1
dic_up = update_dic(dic_up,solution_matrix)
i,dic_up,copy,Sudoku = Sudoku_intermediate_solver(i+1,dic_up,copy,Sudoku)
solved_Sudoku = Sudoku.copy()
return solved_Sudoku
# %%%%
#Initial version (easy version)
Sudoku = np.array([[0,7,0,0,0,5,0,0,0],
[1,0,0,0,3,0,5,0,8],
[0,0,0,2,0,9,0,6,0],
[9,1,0,5,0,0,4,2,0],
[6,8,0,3,0,0,0,1,0],
[2,5,4,0,9,0,0,0,3],
[7,0,6,8,0,1,0,4,0],
[3,4,5,0,0,6,0,7,1],
[0,0,1,0,7,0,2,0,6]])
solved_Sudoku = Sudoku_solver(Sudoku)
print(solved_Sudoku)
# %%%%
#Difficult version
Sudoku = np.array([[0,7,0,0,0,5,0,0,0],
[0,0,0,0,3,0,5,0,8],
[0,0,0,2,0,9,0,6,0],
[0,1,0,5,0,0,4,0,0],
[0,0,0,0,0,0,0,0,0],
[0,5,4,0,9,0,0,0,3],
[0,0,6,8,0,1,0,4,0],
[0,0,5,0,0,6,0,7,1],
[0,0,1,0,0,0,0,0,6]])
solved_Sudoku = Sudoku_solver(Sudoku)
print(solved_Sudoku)
# %%%%
# Just delete [0,1] which is 7 from the above Sudoku and have different solution
Sudoku = np.array([[0,0,0,0,0,5,0,0,0],
[0,0,0,0,3,0,5,0,8],
[0,0,0,2,0,9,0,6,0],
[0,1,0,5,0,0,4,0,0],
[0,0,0,0,0,0,0,0,0],
[0,5,4,0,9,0,0,0,3],
[0,0,6,8,0,1,0,4,0],
[0,0,5,0,0,6,0,7,1],
[0,0,1,0,0,0,0,0,6]])
solved_Sudoku = Sudoku_solver(Sudoku)
print(solved_Sudoku)
#Blank Sudoku
#Sudoku = np.zeros([9,9])
#solved_Sudoku = Sudoku_solver(Sudoku)
#print(solved_Sudoku) |
de3961e72a774b1e04fed0f7d073703d3911055d | CSA-CWW/Repository | /Repository.py | 1,050 | 3.828125 | 4 | #Cameron Watts#
#11 9 17#
#Comp Sci 2017#
somethingss = 2332958532982340982094803498423
def letter_count():
while True:
word=input("Wut word?").lower()
print ("")
letter = input("What letter to count?").lower()
count = 0
for x in word:
if x == letter:
count = count + 1
print ("")
print(count)
print ("")
break
letter_count()
def word_count():
while True:
sent = input("Input some words")
sent_count = 1
if sent == "":
sent_count = 0
for x in sent:
if x == " ":
sent_count = sent_count + 1
print ("")
print (sent_count)
print ("")
break
word_count()
def run_count():
while True:
somethings = input("Letter(1) or word(2) count?")
print ("")
if somethings == "1":
letter_count()
if somethings == "2":
word_count()
run_count()
|
421673b18480123ade28ba68a0d35395f5c052c5 | momentum-cohort-2018-10/w2d3-pig-RDavis2005 | /pig.py | 2,520 | 3.984375 | 4 | import random
class Dice:
def __init__(self, side, number):
self.side = side
self.numbers = number
def __str__(self):
return "f{self.side}"
def __eq__(self, other):
return self.side == other.side
def roll(self):
"""rolls the dice and turns up a number """
roll = random.randint(1, 6)
return roll
d = dice()
turn = d.roll()
if turn == 1:
print "You lost all of your points!"
else:
print turn
class Score:
def __init__(self, dice):
self.turn_score = []
self.total_score = []
self.dice = dice
def add(self, roll):
"""adds individual scores to the score list"""
self.turn_score.append(roll)
def get_turn_score(self):
if self.dice.side == 1:
self.turn_score == 0
else:
return self.dice.side
def get_score(self):
for roll in self.turn_score:
return roll + (roll+1)
#total_turn_score == get_score(self)
def get_total_score(self):
total_score = 0
total_score = total_score + total_turn_score
class Player:
def __init__(self, human, computer, play, score, dice):
self.human = human
self.computer = computer
self.play = play
self.score = score
self.dice = dice
def __eq__(self, other):
return (self.human == other.human
and self.computer == other.computer)
def player_human_input():
rolls= input("R for Roll, H for Hold and P for Pass").lower()
return rolls
def player_human_play():
if input == "r":
print(dice.roll)
elif input == "h":
print(total_turn_score, total_score)
else:
print(total_turn_score, total_score)
def player_computer_play():
if total_score < 20:
turn_score == other.turn_score
else:
random.choice("r", "p")
class Game:
def __init__(self):
self.player_score = Score()
self.computer_score = Score()
#Random player is chosen to start the Game
#Player gets turn
#Player then rolls dice
#Dice lands on a side
#That side value is recorded for the player's score (in list)
#The player is prompted whether or not they want to pass or roll
#Turn with stay on player or switch players
#Create counter |
7b6ec29362d0001750f653ad56dbd655e2e4c761 | emergent/ProjectEuler | /Python/problem009.py | 773 | 3.65625 | 4 | #! /usr/bin/env python3
"""
Problem 9 - Project Euler
http://projecteuler.net/index.php?section=problems&id=9
"""
import math
def getPythagoreanTriplet(a):
for b in reversed(range(1, a)):
c = math.sqrt(a**2 - b**2)
if c.is_integer():
return (a, b, int(c))
else:
return (0, 0, 0)
if __name__ == "__main__":
x = 5
while True:
a, b, c = getPythagoreanTriplet(x)
if a > 0 and 1000 % (a + b + int(c)) == 0:
q = 1000 // (a + b + int(c))
a, b, c = map(lambda x: x * q, [a, b, c])
print("abc=" + str(a * b * c) + " (a,b,c)=" + str(list([a, b, c])))
break
elif (a + b + c) > 1000:
print(str(list([a, b, c])))
break
x += 1
|
296bda7e014db33834905ace5b3568a381bc7c39 | Tkod1/timepunch | /1.1.py | 1,288 | 3.828125 | 4 | import time
import sqlite3
print("Hello welcome to Time punch!")
time.sleep(1.5)
print("Are you a (n)New or (e)Existing user?")
member_choice = input()
def new_user():
try:
n_user_name = input("New Username: ")
n_user_password = input("New Password: ")
conn = sqlite3.connect('temp.db')
nsql = """ INSERT INTO USERSINFO
(username, password) VALUES ('{}', '{}');""".format(n_user_name, n_user_password)
cursor = conn.cursor()
cursor.execute(nsql)
conn.commit()
print("Insertion complete!")
cursor.close()
except sqlite3.Error as error:
print("Error while Inserting Data", error)
finally:
if conn:
conn.close()
print("Connection Closed Now")
def existing_user():
try:
cur = conn.cursor()
cursor.execute(""" SELECT * FROM USERSINFO; """)
for row in cursor.fetchall():
print(row)
except sqlite3.Error as error:
print("Error trying to search userinfo: ", error)
finally:
if conn:
conn.close()
print("Connection Closed Now")
conn = sqlite3.connect('temp.db')
cursor = conn.cursor()
if member_choice == 'e':
existing_user()
elif member_choice == 'n':
new_user()
|
08122b53866499c942667643633edd1c7d2f6a3a | tim-clifford/py-cipher | /src/dictionary.py | 2,788 | 4.03125 | 4 | '''
A few common functions for checking possible solutions
Functionality:
- Recursively check against a scrabble dictionary and list of one letter words and return a Boolean and the decrypted cipher
Sample Usage:
>>> from cipher import dictionary
>>> dictionary.filterIgnoreSpace(lambda x, a, b: a*(x - b), <affine cipher>, <list of possible shifts as (a,b)>)
<decrypted cipher>
Depends: cipher.core.shiftLinear, twl
'''
try:
from src.TWL06 import twl
from src.core import shiftLinear
except ImportError:
from TWL06 import twl
from core import shiftLinear
__debug = True
def filterIgnoreSpace(function,cipher,sortedShiftList,utf8=False):
'''
Runs recursiveCheck against a list of possible inputs with a function and returns a properly spaced string
and the correct inputs
>>> filterIgnoreSpace(lambda x, a, b: a*(x - b), "NGG NPX NGQ NJA", [(5,1),(2,4),(1,13)],utf8=True)
('attack at dawn', (1, 13))
>>> filterIgnoreSpace(lambda x, a, b: a*(x - b), bytearray("NGG NPX NGQ NJA","ascii"), [(5,1),(2,4),(1,13)])
('attack at dawn', (1, 13))
'''
for param in sortedShiftList:
input1 = shiftLinear(function,cipher,param[0],param[1],utf8=utf8)
if utf8: solution,output = recursiveCheck(input1.replace(" ",""))
else: solution,output = recursiveCheck(str(input1,"utf-8").replace(" ",""))
if solution:
return (output,param)
def recursiveCheck(cipher,index=0,length=1,partialSolution=''):
'''
Checks an input recursively against a scrabble dictionary (or 'a','i','o').
The input must have no spaces - so string.replace(" ","") should be used on the input.
In most cases it is better to use filterIgnoreSpace than recursiveCheck
>>> solution = "att ack atd awn"
>>> recursiveCheck(solution.replace(" ",""))
(True, 'attack at dawn')
'''
ONE_LETTER_WORDS = ['a','i','o']
word = cipher[index:index+length]
longerWord = cipher[index:index+length+1]
nextWord = cipher[index+length:index+length+1]
if twl.check(word) or word in ONE_LETTER_WORDS:
if index+length > len(cipher) - 1:
return True,(partialSolution+word)
elif twl.check(longerWord) or len(twl.children(longerWord)) > 0:
# TODO: find more elegant way of recursing
longer,partL = recursiveCheck(cipher,index,length+1,partialSolution)
next,partN = recursiveCheck(cipher,index+length,1,partialSolution+word+" ")
if longer: return longer,partL
else: return next,partN
else:
return recursiveCheck(cipher,index+length,1,partialSolution+word+" ")
elif twl.check(longerWord) or len(twl.children(longerWord)) > 0:
if index+length > len(cipher) - 1:
#print(partialSolution)
return True,(partialSolution+word)
return recursiveCheck(cipher,index,length+1,partialSolution)
else:
#print(partialSolution)
return False,""
def partialCheck(): raise NotImplementedError
|
41f00355980f5802a34b200c699ae909771681c6 | kawai-yusuke/class_review | /b_2.py | 614 | 3.84375 | 4 | class Customer:
def __init__(self, first_name, family_name, age):
self.first_name = first_name
self.family_name = family_name
self.toshi = age
def full_name(self):
print(f"{self.first_name} {self.family_name}")
def age(self):
print(self.toshi)
ken = Customer(first_name="Ken", family_name="Tanaka", age=15)
ken.age() # 15 という値を返す
tom = Customer(first_name="Tom", family_name="Ford", age=57)
tom.age() # 57 という値を返す
ieyasu = Customer(first_name="Ieyasu", family_name="Tokugawa", age=73)
ieyasu.age() # 73 という値を返す
|
ddee3bbf33277c543808845ed85e97516414bd60 | stevecatt/digitalwk2 | /test.py | 536 | 4.03125 | 4 | class Address:
def __init__(self,street,city,state):
self.steet = street
self.city = city
self.state = state
class User:
def __init__(self,first_name, last_name):
self.first_name = first_name
self.last_name = last_name
# list of addresses
self.addresses = []
user = User('John','Doe')
address1 = Address('Richmond Ave','Houston','TX')
address2 = Address('Holman St','Houston','TX')
user.addresses.append(address1)
user.addresses.append(address2)
print(user.addresses) |
0fbd26604402f1fc47d2e098dac76d5c97225d6d | gariepyt/cs325_project1 | /divide_conquer_example.py | 2,381 | 3.703125 | 4 | #divide and conquer solution for max subarray
#Written by Will Thomas
import time
import os
import csv
import sys
# Used for algorithm #3, returns larges sum found between two arrays
def maxMiddleSum(array, low, mid, high):
# Calculate max subarray on left side of current array
sum = 0
leftSum = 0
for i in range(mid, low-1, -1):
sum += array[i]
if sum > leftSum:
leftSum = sum
# Calculate max subarray on right side of the current array
sum = 0
rightSum = 0
for i in range(mid+1, high+1, 1):
sum += array[i]
if sum > rightSum:
rightSum = sum
return (leftSum + rightSum)
# Used for algorithm #3, returns maxSubArray sum
def maxSubArray(array, low, high):
# BASE CASE
if low == high:
return array[low]
mid = (low + high) / 2
# Return the maximum of left sum, right sum, and combined(middle) sum
return max(maxSubArray(array, low, mid), maxSubArray(array, mid+1, high),
(maxMiddleSum(array, low, mid, high)))
def main():
# rfname = "MSS_TestProblems.txt"
rfname = "MSS_TestProblems-1.txt"
wfname = "MSS_Results.txt"
# Check to see if file exists
fileCheck = os.path.isfile(rfname)
if (fileCheck == False):
print("ERROR: " + rfname + " not found.")
return 1
print("Program running")
# Create
with open(wfname, 'wt') as resultFile:
# Open the file and read each line by line
with open(rfname, 'rt') as fileArr:
# print ("File opened")
fStream = csv.reader(fileArr)
for row in fStream:
if (len(row) > 0):
row[0] = row[0].replace('[', '')
row[len(row) - 1] = row[len(row) - 1].replace(']', '')
row = list(map(int, row))
startTime = time.clock()
result = maxSubArray(row, 0, len(row)-1)
stopTime = time.clock()
resultTime = stopTime - startTime
print("Largest Result: " + str(result))
print("Running Time: " + str(resultTime))
resultFile.write("\nMax sum: " + str(result))
main()
|
db7c76daddf6d8a95014419f4ebacca42955934e | Sepulveda25/python | /09-list/16-list-as-queues.py | 746 | 4.1875 | 4 | #Using Lists as Queues
from collections import deque
color_list = deque(["Red", "Blue", "Green", "Black"])
color_list.append("White") # White arrive
print(color_list)
# deque(['Red', 'Blue', 'Green', 'Black', 'White'])
color_list.append("Yellow") # Yellow arrive
print(color_list)
#deque(['Red', 'Blue', 'Green', 'Black', 'White', 'Yellow'])
color_list.popleft() # The first to arrive now leaves 'Red'
print(color_list)
#deque(['Blue', 'Green', 'Black', 'White', 'Yellow'])
color_list.popleft() # The second to arrive now leaves 'Blue'
print(color_list)
#deque(['Green', 'Black', 'White', 'Yellow'])
print(color_list) # Remaining queue in order of arrival
#deque(['Green', 'Black', 'White', 'Yellow']) |
49558e140a3f48f8990fca8e0d49f1c932d9dc5b | JamieMagee/ProjectEuler | /python/041.py | 536 | 3.8125 | 4 | from itertools import permutations
def isprime(n):
if n == 2 or n == 3:
return True
if n < 2 or n % 2 == 0:
return False
if n < 9:
return True
if n % 3 == 0:
return False
r = int(n ** 0.5)
f = 5
while f <= r:
if n % f == 0:
return False
if n % (f + 2) == 0:
return False
f += 6
return True
pandigital = (int(''.join(str(d) for d in p)) for p in permutations(range(1, 8)))
print(max(p for p in pandigital if isprime(p)))
|
a00661a69b53cdc1e59837c4344ed15b31732080 | jjmuesesq/ALGORITMOS_2018-1 | /LABORATORIOS/LAB1/punto 3/MatrizPython/MultiMatriz.py | 2,053 | 3.65625 | 4 | """
@author: Jairo
"""
import time
import sys
start_time = time.time()
# INICIALIZAR MATRIZ DE (nxm)
def inicializar_mtx(n, m):
tmp = []
for i in range (n):
tmp.append([0]*(m))
return tmp
# IMPRIMIR UNA MATRIZ
def print_mtx(m):
for i in range(len(m)):
print(m[i])
# MULTIPLICA DOS MATRICES DE (nxm)
def mul_mtx(m1, m2):
# SE VERIFICA SI SE PUEDEN MULTIPLICAR
# LAS MATRICES
if(len(m1) != len(m2[0])):
print("NO SE PUEDEN MULTIPLICAR")
return [[1]]
else:
resultado = inicializar_mtx(len(m1), len(m2[0]))
for i in range (len(m1)):
for k in range (len(m2[0])):
for j in range (len(m2)):
resultado[i][k] += (m1[i][j]*m2[j][k])
#print("-->", i, "--",k)
#print("##########")
return resultado
#print_mtx(resultado)
# =============================================
print("==================================")
print("MATRICES DE (nxn)")
print("==================================")
print("Ingrese dimensión de la Matriz A: ")
a = int(input())
A=[]
for i in range(a):
fil = list(map(int, input().strip().split(' ')))
A.append(fil)
print_mtx(A)
print("==================================")
print("Ingrese dimensión de la Matriz B: ")
b = int(input())
B=[]
for j in range(b):
fil = list(map(int, input().strip().split(' ')))
B.append(fil)
print_mtx(B)
print("==================================")
print("Resultado Multiplicación: ")
print_mtx(mul_mtx(A, B))
print("--- %s seconds ---" % (time.time() - start_time))
'''
1 2 3 4 5 6 7 8 9 3
8 7 6 5 4 2 1 3 4 5
0 4 5 7 1 2 3 4 8 6
2 3 4 5 1 2 3 5 6 2
1 1 3 4 6 9 7 0 4 5
1 2 2 2 4 2 5 7 1 2
8 7 6 5 4 3 2 1 8 9
7 2 5 6 3 2 1 4 5 6
1 2 3 4 5 1 2 3 4 5
8 7 3 2 1 1 1 3 6 4
1 2 3 4 5 6 7 8 9 1
8 7 6 5 4 2 1 3 4 1
0 4 5 7 1 2 3 4 8 1
2 3 4 5 1 2 3 5 6 1
1 1 3 4 1 2 3 0 4 1
1 2 2 2 4 2 5 7 1 6
8 7 6 5 4 3 2 1 8 1
7 2 5 6 3 2 1 4 4 4
1 2 3 4 5 1 2 3 4 3
8 7 3 2 0 1 1 1 6 8
'''
|
a5aaf8ea18ddb682b06978c8e3114f2eeb319df4 | pranayagayitri/python-git-project | /main1.py | 62 | 3.640625 | 4 | m=5
n=6
if("n>m"):
print("n is big")
else:
print("m is big") |
52ab0c8139e4dfb80cf251cb4ed35efd1d56b498 | guohaoyuan/algorithms-for-work | /leetcode/高频面试/labuladong统计的高频面试题/268. 缺失数字 easy/missingNumber.py | 424 | 3.578125 | 4 | """
自身^自身=0
0^自身=自身
n是数组的length,我们初始化res = n
然后整个数组的index^数组每一个元素后^n
最后res剩下的数就是结果
"""
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
res = n
for i in range(n):
res ^= i ^ nums[i]
return res
|
70fd3daa46a392a692a6ef6900593af50a696f6b | diegojserrano/ISSD_Python | /Clase6/Equipo.py | 1,259 | 3.8125 | 4 | class Equipo:
def __init__(self, nombre):
self.nombre = nombre
self.jugados = 0
self.ganados = 0
self.empatados = 0
self.goles_recibidos = 0
self.goles_realizados = 0
def perdidos(self):
return self.jugados - self.ganados - self.empatados
def diferencia_goles(self):
return self.goles_realizados - self.goles_recibidos
def puntos(self):
return self.ganados * 3 + self.empatados
def __str__(self):
return self.nombre + ": " + str(self.puntos()) + " puntos "
class Liga:
def __init__(self):
self.equipos = []
def agregar_equipo(self,e):
self.equipos.append(e)
def primero(self):
mayor = self.equipos[0]
for e in self.equipos:
if e.puntos() > mayor.puntos():
mayor = e
return mayor
cantidad = int(input("Ingrese la cantidad de equipos: "))
liga = Liga()
for i in range(cantidad):
nombre = input("Ingrese el nombre del equipo: ")
eq = Equipo(nombre)
eq.ganados = int(input("Ingrese la cantidad de partidos ganados: "))
eq.empatados = int(input("Ingrese la cantidad de partidos empatados: "))
print(eq)
liga.agregar_equipo(eq)
print(liga.primero()) |
5d25a05321907b3f9d81ca94a8efa6295a155ade | Alireza-Helali/Design-Patterns | /FactoryMethod.py | 1,573 | 4.5625 | 5 | """
Factory method:
factory method is a creational design pattern
that provides an interface for creating an object
in superclass but allows subclasses to alter the
type of objects that will be created. it's a simply
a method that creates an object.
"""
from enum import Enum
from math import sin, cos
class CoordinateSystem(Enum):
CARTESIAN = 1
POLAR = 2
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f'x: {self.x}, y: {self.y}'
@staticmethod
def new_cartesian_point(x, y):
raise NotImplementedError
@staticmethod
def new_polar_point(rho, theta):
raise NotImplementedError
class PointFactory(Point):
@staticmethod
def new_polar_point(rho, theta):
return Point(rho * sin(theta), rho * cos(theta))
@staticmethod
def new_cartesian_point(x, y):
return Point(x, y)
if __name__ == '__main__':
p = PointFactory(2, 3)
print(p.new_polar_point(2, 1))
# --------------- OR ----------------
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f'x: {self.x}, y: {self.y}'
class PointFactory:
@staticmethod
def new_polar_point(rho, theta):
return Point(rho * sin(theta), rho * cos(theta))
@staticmethod
def new_cartesian_point(x, y):
return Point(x, y)
if __name__ == '__main__':
p1 = Point.PointFactory.new_polar_point(2, 1)
print(p1)
|
dce37eab83f5abc61700f57ef16fa7daa4ea1cd4 | jpromanonet/facultad_Programacion_TallerIntegrador | /02_Ejercicios_Resueltos/ejercicio_02_07.py | 484 | 3.609375 | 4 | lista = []
contador = 0
palabra = ''
print('Ingrese 10 palabras de a una por vez \n')
while contador < 10 :
palabra = input('ingrese palabra : ')
lista.append(palabra)
contador = contador + 1
Ultimapalabra = input('ingrese una ultima palabra: ')
if lista.count(Ultimapalabra) == 0 :
print('La palabra ' + Ultimapalabra +' no se encuentra repetida en la lista que ingreso')
print(lista)
else :
print('La palabra ' + Ultimapalabra + ' se encuentra repetida') |
5a8644af6dcb7fec954922c7d74a3e7f4e1b209d | Deanhz/normal_works | /算法题/Leetcode/easy/Reverse_Integer.py | 1,104 | 3.96875 | 4 | '''
7.
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer.
Your function should return 0 when the reversed integer overflows.
'''
class Solution(object):
def reverse(self, x): # by me
'''
:type x: int
:rtype: int
'''
num_list = list(str(x))
flag = False
if num_list[0] == '-':
flag = True
del num_list[0]
num_list.reverse()
if flag:
num_list.insert(0, '-')
num = int(''.join(num_list))
if abs(num) >= 2**31 - 1:
return 0
return num
def reverse2(self, x):
sign = -1 if x < 0 else 1
x *= sign
# eliminated leading zero in reversed integer
while x:
if x % 10 == 0:
x /= 10
else:
break
x = list(str(x))
x.reverse()
x = "".join(x)
x = int(x)
return sign * x
if __name__ == '__main__':
print(Solution().reverse2(-123))
|
73ba13da44056d236c1cf7a3bb07380d7943d1f7 | snow-sam/Cadastro-e-Importa-o | /Database.py | 669 | 3.890625 | 4 | import sqlite3
# Função para criar o Banco de Dados
def createDB():
db = sqlite3.connect('Ativos.db')
cs = db.cursor()
cs.execute(""" CREATE TABLE ativos (
simbolo TEXT NOT NULL PRIMARY KEY,
nome TEXT NOT NULL,
habilitado NUMBER NOT NULL
)""")
cs.execute(""" CREATE TABLE precos (
data TEXT NOT NULL,
preco REAL NOT NULL,
simbolo TEXT NOT NULL,
FOREIGN KEY (simbolo)
REFERENCES ativos (simbolo)
ON UPDATE CASCADE
ON DELETE CASCADE
)""")
# Criando o Banco de Dados
createDB()
|
1bae80075f9e9e6906fc93be608d1da664df5f2e | tuobulatuo/Leetcode | /src/ltree/uniqueBinarySearchTrees.py | 1,016 | 3.796875 | 4 | __author__ = 'hanxuan'
"""
Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
"""
def numTrees(n):
"""
:param n:
:return:
"""
return numTreesRecursive(1, n, {})
def numTreesRecursive(startN, endN, d):
"""
:param startN:
:param endN:
:return:
"""
if (startN, endN) in d:
return d[(startN, endN)]
if endN - startN <= 0:
d[(startN, endN)] = 1
return d[(startN, endN)]
ans = 0
for i in range(startN, endN + 1):
ans += numTreesRecursive(startN, i - 1, d) * numTreesRecursive(i + 1, endN, d)
d[(startN, endN)] = ans
return ans
if __name__ == '__main__':
print(numTrees(2))
print(numTrees(5))
print(numTrees(10))
|
bbe36d7093a69d701447be275c5e4d2c616bbcc7 | yvan674/minimal-mnist | /src/model/numpy_model.py | 2,679 | 3.90625 | 4 | """Numpy Model.
The model as a series of numpy operations.
"""
import numpy as np
class Linear:
def __init__(self, in_connections, out_connections):
"""A simple linear layer."""
self.weight = np.zeros([out_connections, in_connections])
self.bias = np.zeros([out_connections])
self.in_connections = in_connections
self.out_connections = out_connections
def __call__(self, x):
"""Calculates a linear function.
Args:
x (np.ndarray): input.
"""
# x = np.stack([x.reshape(self.in_connections)] * self.out_connections)
return np.dot(x, self.weight.T) + self.bias
def load_state_dict(self, key, value):
self.__setattr__(key[0], value)
class ReLU:
def __init__(self):
"""Creates a ReLU activation function."""
pass
def __call__(self, x):
"""Calculates using the ReLU activation function.
Args:
x (np.ndarray): input.
"""
return x.clip(min=0)
class Sequential:
def __init__(self, layers):
"""Creates a sequential function.
Args:
layers (list): List of layers to run through sequentially.
"""
self.layers = layers
def __call__(self, x):
for layer in self.layers:
x = layer(x)
return x
def load_state_dict(self, key, value):
params = key.split('.')
self.layers[int(params[0])].load_state_dict(params[1:], value)
class NumpyModel:
def __init__(self, in_connections: int, num_classes: int, first_layer: int,
second_layer: int):
"""Creates the network as a series of Numpy operations."""
self.in_connections = in_connections
self.fc0 = Sequential([Linear(in_connections, first_layer),
ReLU()])
self.fc1 = Sequential([Linear(first_layer, second_layer),
ReLU()])
self.fc2 = Linear(second_layer, num_classes)
def __call__(self, x):
"""Runs the input through the network.
Args:
x (np.ndarray): input.
"""
x = x.reshape([x.shape[0], self.in_connections])
x1 = self.fc0(x)
x2 = self.fc1(x1)
x3 = self.fc2(x2)
return x1, x2, x3
def load_state_dict(self, state_dict):
"""Loads the state dictionary"""
for k, v in state_dict.items():
params = k.split('.')
if len(params[1:]) > 1:
to_get = '.'.join(params[1:])
else:
to_get = [params[1]]
self.__getattribute__(params[0]).load_state_dict(to_get, v)
|
354517a92eb55bcc4482385e085689ea816046f2 | holmes27/open_cv | /drawing_functions.py | 748 | 3.53125 | 4 | import cv2
import numpy as np
#img=cv2.imread('lena.jpg',1)
img=np.zeros([512,512,3],np.uint8)# creating black image using np zeros method -[ height,width,3] , data type
img=cv2.line(img,(0,0),(255,255),(147,44,94),6) # image,start, end,(b,g,r) ,thickness
img=cv2.arrowedLine(img,(255,0),(255,255),(255,0,94),6)
img=cv2.rectangle(img,(0,0),(510,510),(147,0,0),20)# instead of 20 i.e. thickness if u give -1 it will fill the rectangle with given color
img=cv2.circle(img,(445,255),60,(0,252,0),-1)# centre,radius
font=cv2.FONT_HERSHEY_SIMPLEX
img=cv2.putText(img,'Hello',(10,500),font,4,(10,255,255),10,cv2.LINE_AA)#image,text,start,font face,font size,color, thickness,type of line
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows() |
d54a08168bef837e896f97e093efc582278acd5f | gaolinagproject/open_watch | /ESP32_python_pro/workSpace/testScript.py | 1,359 | 3.5625 | 4 | """
import _thread
import time
def test3Thread(description,count):
print(description)
i = 0
while i < count:
print("nihao"+str(i))
i = i+1
time.sleep(2)
_thread.start_new_thread(test3Thread,("wfgz",5))
"""
"""
import machine
interruptsCounter = 0
totalInterruptsCounter = 0
timer = machine.Timer(0) #新建立一个定时器对象 使用定时器0 0~3
def handleInterrupt(timer):
global interruptsCounter
interruptsCounter = interruptsCounter + 1
timer.init(period=1000,mode=machine.Timer.PERIODIC,callback = handleInterrupt)
while True:
if interruptsCounter>0:
state = machine.disable_irq()
interruptsCounter = interruptsCounter - 1
machine.enable_irq(state)
totalInterruptsCounter = totalInterruptsCounter + 1
print("interrupt has occurred:" + str(totalInterruptsCounter))
"""
import machine
interruptCounter = 0
totalInterruptsCounter = 0
def callback(pin):
global interruptCounter
interruptCounter = interruptCounter + 1
p25 = machine.Pin(25,machine.Pin.IN,machine.Pin.PULL_UP)
p25.irq(trigger=machine.Pin.IRQ_FALLING,handler=callback)
while True:
if interruptCounter > 0:
state = machine.disable_irq()
interruptCounter = interruptCounter - 1
machine.enable_irq(state)
totalInterruptsCounter = totalInterruptsCounter + 1
print("Interrupt"+ str(totalInterruptsCounter))
|
8ef292a851897bd2c28db8dad01509a151cad581 | staccato007/Spectrum-high | /PHpackage/input_.py | 857 | 3.640625 | 4 | def check_file_input_func(filepath):
#print('1 ', filepath)
filepath = repr(filepath) #转换为python字符串,忽略转义字符
#print('2 ', filepath)
filepath = filepath.replace('\\', '/') #替换反斜杠'\'
#print('3 ', filepath)
filepath = eval(filepath) #转换为普通字符串
#print('4 ', filepath)
filepath = filepath.rstrip('///') #去除末尾'/'
return filepath
def input_func():
print('请输入文件夹路径:', end=' ')
filepath = input()
filepath = check_file_input_func(filepath) #检查文件夹路径末尾是否有不合格的'\''/'
print('请输入文件数:', end=' ')
filenum = int(input())
print('请选择分类指标(输入数字:1-压力,2-温度,3-不分类):', end=' ')
class_type = int(input())
return filepath, filenum, class_type |
6a8670f245dd6a02ff0ca60840ab467051f2d8bf | AthinaKyriakou/mrbox | /utils/path_util.py | 275 | 3.515625 | 4 | import os
def customize_path(folder_path, filename):
return os.path.join(folder_path, filename)
def remove_prefix(prefix, filepath):
prefix = customize_path(prefix, '')
if filepath.startswith(prefix):
return filepath[len(prefix):]
return filepath
|
dc06731bc314cab3b962b7007ed1549dc603b378 | taufikfathurahman/DS_python | /Linked List/linkedListDeletion1.py | 1,475 | 4.28125 | 4 | # Node class
class Node:
# Consructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the begining
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
'''
Given a reference to the head of the list and a key
delete the first occure of the key in the list
'''
def deleteNode(self, key):
# Store head node
temp = self.head
# If head node itself holds the key to be deleted
if (temp is not None):
if (temp.data) == key:
self.head = temp.next
temp = None
return
'''
Search for the key to be deleted, keep track of the
previous node as node as we need to change 'prev.next'
'''
while (temp is not None):
if (temp.data == key):
break
prev = temp
temp = temp.next
# If the key was not present in linked list
if(temp == None):
return
# Unlink teh node from linked list
prev.next = temp.next
temp = None
# Utility funtion to print th linked list
def printList(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
if __name__ == '__main__':
llist = LinkedList()
llist.push(7)
llist.push(1)
llist.push(3)
llist.push(2)
print("Created linked list: ")
llist.printList()
llist.deleteNode(3)
print("Lined list after deletion: ")
llist.printList() |
1adbc681c308152ce77ec354f0ea75ce2873cd16 | yunusemrebaloglu/pyornekleri | /ders2/ikincidersilkkonu.py | 2,853 | 4.25 | 4 | """
a = True
print(a)
#tru
print(type(a))
#bool
print(1<0)
#false
print(0==0)
#true
b = None
print(b)
#none
print("AB'=2018"=="sad")
#false
print("e">"w")
#alfabetik sıralama için yapılabilir.
print(True < False)
#false döner
print(1>0 and "Murat"=="Murat")
#true
print(1>2 and "Murat"=="Murat")
#false
print(1>2 or "Murat"=="Murat")
#true
print(1>2 or "Murat"=="murat")
#false
print(not(1<2))
#false
print(not 0)
#true
a = 2
if(a ==2):
print(a)
#2 olur çıktısı çünkü koşul içerisinde bulunmaktadır.
print("asd")
#çıktıyı geçtik çünkü giridi de geçtik bu nun çıktısı ise direkt asd olur.
if(a ==2):
pass
#if boş kalmasın diye pass kullanılır break kullanılmaz .
yas = int(input("lütfen yaşınızı giriniz"))
if(yas>17):
print("a")
elif(yas>12):
print("b")
else:
print("c")
"""
"""
kadi = input("lütfen kıllanıcı adınızı giriniz:")
parola = input("lütfen parolanızı giriniz.")
k = "ab2018"
p = "12345"
if(kadi ==k and parola ==p ):
print("giriş yapıldı")
else:
print("giriş başarısız")
"""
"""
a = int(input("sayi:"))
b= int(input("ikincisayi:"))
c = input("hangi işlem(toplama,cikarma,bolme,carpma):")
if(c=="toplama"):
d=a+b
print("'{}' bu sayı ile {} bu sayının {}işleminin sonucu {}".format(a,b,c,d))
elif(c=="cikarma"):
d=a-b
print("'{}' bu sayı ile {} bu sayının {}işleminin sonucu {}".format(a, b, c, d))
elif(c=="carpma"):
d=a*b
print("'{}' bu sayı ile {} bu sayının {}işleminin sonucu {}".format(a, b, c, d))
elif(c=="bolme"):
d=a/b
print("'{}' bu sayı ile {} bu sayının {}işleminin sonucu {}".format(a, b, c, d))
else:
print("boyle bir islem bulunmamaktadir")
liste = [1,2,3,4,5,6,7]
for elaman in liste:
print("Elaman",elaman,sep="-")
liste = [1,2,3,4,5,6,7]
toplam = 0
for elaman in liste:
toplam+=elaman
print("{} toplam: {}".format(elaman, toplam))
for elaman in range(0,20):
toplam+=elaman
print("{} toplam: {}".format(elaman, toplam))
"""
"""
liste = [1,2,3,4,5,6,7,8,9]
for elaman in liste:
if elaman % 2 ==0:
print(elaman)
isim = "yunus emre"
for harf in isim:
print(harf*3)
"""
"""
liste = [(1,2),(3,4),(5,6),(7,8)]
for dön in liste:
print(dön)
for (i,j) in liste:
print(i,j,sep="\n")
"""
"""
#aşağıdakini dersten hariç isimlerin baş harfine göre çektim
liste2 = ["yunus","yusuf","hakan","hayat"]
for isim in liste2:
for harf in isim[0]:
if(harf=="y"):
print(isim)
#buraya kadar yaptım
"""
"""
if "a" in "sigara":
print("asd")
b = "sigara"
print(b.count("a"))
#kaç adet a olduğunu saydırdım
"""
"""
i =0
while (i<10):
if i % 2 != 0:
print("i 2 ye bölünemez")
i += 1
continue
print("i nin değeri", i)
i +=1
if i ==6:
break
"""
|
55d26dd6175764751871a32f464bfe9115f20b73 | EstevamPonte/Python-Basico | /PythonExercicios/mundo1/ex013.py | 111 | 3.5625 | 4 | n1 = int(input('Digite o aumento: '))
n2 = (n1 * 15)/100
print('Seu aumeento vai ficar por {}'.format(n1 + n2)) |
3663027cdd48c3abf79e280cf043c8df6d510b2e | billzxy/8PuzzleSolver | /project1.py | 7,337 | 3.875 | 4 | import sys
from copy import deepcopy
DIRECTIONS=[{1:"R",3:"D"}, # A list of dictionary, index of the list is the position of zero on the puzzle(Because only zero on the puzzle
{0:"L",2:"R",4:"D"}, # is allowed to perform a move). The position of zero has only limited directions to move: L R U D.
{1:"L",5:"D"}, # So the directions(to move) at specific positions are the values of the dictionary, and the keys are the
{0:"U",4:"R",6:"D"}, # corresponding destination (index of the target tile in the list).
{1:"U",3:"L",5:"R",7:"D"},
{2:"U",4:"L",8:"D"},
{3:"U",7:"R"},
{6:"L",4:"U",8:"R"},
{5:"U",7:"L"}
]
MAN_DISTANCES=[[0,1,2,1,2,3,2,3,4], # this is a list of lists(matrix), used to determine manhattan distance from A to B
[1,0,1,2,1,2,3,2,3], # usage: MAN_DISTANCES[A][B]
[2,1,0,3,2,1,4,3,3],
[1,2,3,0,1,2,1,2,3],
[2,1,2,1,0,1,2,1,2],
[3,2,1,2,1,0,3,2,1],
[2,3,4,1,2,3,0,1,2],
[3,2,3,2,1,2,1,0,1],
[4,3,2,3,2,1,2,1,0]
]
OPPOSITE_MOVES={"L":"R","R":"L","U":"D","D":"U","":""} # this is used for pruning the returning move
class State:
def __init__(self, statels, g, last, lstate, goal):
# no private members for simplicity
self.state = statels # stored as a list
self.lastMove = last # last move, e.g., "U", used to prune a returning move
self.lastState = lstate # reference to the last state
self.g = g # cost to get here
self.heuristic = 0 # heuristic value of the current state
self.f = 0 # utility function value
self.nextstates = [] # the collection of next states, heuristic value is the key, ref. to the State is value
self.goalState = goal # reference to goal state object
self.calcHeuristic() # automatically calculate heuristic and f after instanciated
def genNextStates(self):
"""
This method generates the next states and put into a list
:return:
"""
posZero = self.state.index(0)
for d in DIRECTIONS[posZero]:
if OPPOSITE_MOVES[self.lastMove] == DIRECTIONS[posZero][d]: # prune the returning move
continue
next = deepcopy(self.state)
next[posZero], next[d] = next[d], next[posZero] # swap the item in the list to make a move
nextState = State(next, self.g+1, DIRECTIONS[posZero][d], self, self.goalState)
self.nextstates.append(nextState)
def calcHeuristic(self):
"""
this method calculates the heuristic value and update utility f
:return:
"""
if self.goalState is None or self.state == self.goalState.state:
return
goalList = self.goalState.state
totalManDist = 0
for s in self.state:
for g in goalList:
if(self.state[s]==goalList[g]):
totalManDist += MAN_DISTANCES[s][g]
self.heuristic = totalManDist
self.f= self.heuristic+self.g
def __lt__(self, other):
"""
overloading less than to enable sorting on utility f
:param other:
:return:
"""
return (self.f < other.f)
def __eq__(self, other):
"""
overloading equal comparison in order to compare states
:param other:
:return:
"""
if isinstance(other, State):
return self.state == other.state
return False
def __ne__(self, other):
return not self.__eq__(other)
class Puzzle:
def __init__(self, initState, goalState):
self.goalstate = State(goalState,0, "", None, None)
self.initstate = State(initState,0, "", None,self.goalstate)
self.currstate = self.initstate
self.queue = [self.currstate] # this is the queue for visiting the next smallest utility f
self.goalpath = [] # this is a list for storing the goal path
self.visited=[self.currstate.state] # this is a list to keep track of visited states
self.depth = 0
self.treesize = 1
def solvePuzzle(self):
"""
this function will go through the queue to find the goal path
:return:
"""
while self.queue:
self.queue.sort(key=lambda state: state.f)
self.currstate = self.queue.pop(0)
if(self.currstate.g>self.depth):
self.depth = self.currstate.g
if (self.currstate == self.goalstate):
self.goalpath = self.getGoalPath(self.currstate)
return
self.currstate.genNextStates()
self.treesize += len(self.currstate.nextstates)
for next in self.currstate.nextstates:
if next.state not in self.visited:
self.queue.append(next)
self.visited.append(next.state)
def getGoalPath(self, state):
"""
when the goal state is reached, this function traces back the states to generate the goal path
:param state:
:return:
"""
curr = state
path = []
while curr!=self.initstate:
path.insert(0,curr.lastMove)
curr = curr.lastState
return path
def getResult(self):
"""
this is for writing and printing; it generates a string that conforms to the format
:return:
"""
result = str(self.depth)+"\n"+str(self.treesize)+"\n"
for s in self.goalpath:
result += s+" "
return result
def main():
fname = sys.argv[1]
outname = sys.argv[2]
initState=[]
goalState=[]
try:
file = open(fname,"r") # file handling
except IOError:
print("File does not exist, or could not open file.")
sys.exit()
outf = open(outname,"w")
with file: # reads through the input file and takes whats useful
for i in range(0,3):
line = file.readline()
outf.write(line)
for s in line.rstrip().split(" "):
initState.append(int(s))
outf.write(file.readline())
for i in range(0,3):
line = file.readline()
outf.write(line)
for s in line.rstrip().split(" "):
goalState.append(int(s))
puzzle = Puzzle(initState,goalState) # initializes the puzzle object and solves puzzle, then presents
puzzle.solvePuzzle()
outf.write("\n\n"+puzzle.getResult())
outf.close()
def test():
"""
for testing purpose
:return:
"""
puzzle = Puzzle([2,8,3,1,6,4,7,0,5], [1,2,3,8,0,4,7,6,5])
puzzle.solvePuzzle()
print("\n\n" + puzzle.getResult())
puzzle = Puzzle([2,8,3,7,1,6,0,5,4], [1,2,3,8,0,4,7,6,5])
puzzle.solvePuzzle()
print("\n\n" + puzzle.getResult())
puzzle = Puzzle([1,0,6,4,2,3,7,5,8], [7,4,3,5,0,6,2,8,1])
puzzle.solvePuzzle()
print("\n\n" + puzzle.getResult())
puzzle = Puzzle([8,1,2,3,6,4,5,0,7], [4,2,1,8,7,0,3,5,6])
puzzle.solvePuzzle()
print("\n\n" + puzzle.getResult())
main()
#test()
|
42d37ae7e837cac8881e5041c972bcac0f825f98 | number09/atcoder | /abc077-a.py | 174 | 3.765625 | 4 | array1 = [a for a in input()]
array2 = [b for b in input()]
ar = [array1, array2]
r_array1 = array1[::-1]
if array2 == r_array1:
print("YES")
else:
print("NO")
|
bd1e95330e4c5e86328f3df9c99ac92ecc1a4d99 | vishsangale/codeKatas | /legacy_katas/data_structures/doubly_linked_list.py | 2,198 | 4.03125 | 4 | """Implementation of doubly linked list."""
import unittest
class DoublyLLNode(object):
def __init__(self, item, next=None, prev=None):
self.val = item
self.next = next
self.prev = prev
class DoublyLinkedList(object):
def __init__(self):
self.head = None
def find(self, item):
node = self.head
while node:
if node.val == item:
return True
node = node.next
return False
def add(self, item):
if not self.head:
self.head = DoublyLLNode(item)
else:
node = DoublyLLNode(item)
self.head.prev = node
node.next = self.head
self.head = node
def remove(self, item):
node = self.head
prev = node
while node:
if node.val == item:
if not node.next and node.prev:
prev.next = None
return True
if not node.next and not node.prev:
self.head = None
return True
if not node.prev:
self.head = self.head.next
self.head.prev = None
return True
prev.next = node.next
node.next.prev = prev
return True
prev = node
node = node.next
return False
def __str__(self):
str_val = ""
node = self.head
while node:
str_val += str(node.val) + "<-->"
node = node.next
str_val += "None"
return str_val
class TestDoublyLinkedListMethods(unittest.TestCase):
def test_simple(self):
ll = DoublyLinkedList()
self.assertEqual(None, ll.head)
ll.add(4)
self.assertEqual(True, ll.find(4))
ll.add(5)
ll.add("Pi")
ll.add(3.14)
ll.add("omega")
print(ll)
self.assertEqual(False, ll.remove("Omega"))
self.assertEqual(True, ll.remove("omega"))
self.assertEqual(3.14, ll.head.val)
ll.remove(4)
print(ll)
if __name__ == "__main__":
unittest.main()
|
d299e64f60410e0e5f5281e0386efe67d137ca7e | suyundukov/LIFAP1 | /TD/TD7/Code/Python/7.py | 539 | 3.546875 | 4 | #!/usr/bin/python
# Remplir un tableau avec les coefficients du triangle de Pascal
from math import factorial as fact
def combin(n, p):
res = int(fact(n) / (fact(p) * fact(n - p)))
return res
def triangle_pascal(tab):
for i in range(len(tab)):
for j in range(i + 1):
tab[i][j] = combin(i, j)
tab = [[[] for i in range(6)] for j in range(6)]
triangle_pascal(tab)
# Affichage de tableau
for k in range(len(tab)):
for m in range(k + 1):
print(tab[k][m], '', sep='\t', end='')
print('')
|
7a10c9601276cef6fe9c4410d053991be34645bd | arthurDz/algorithm-studies | /leetcode/linked_list_cycle.py | 778 | 4.0625 | 4 | # Given a linked list, determine if it has a cycle in it.
# To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
# Example 1:
# Input: head = [3,2,0,-4], pos = 1
# Output: true
# Explanation: There is a cycle in the linked list, where tail connects to the second node.
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def hasCycle(head):
if not head: return False
lis = []
while head.next:
if head in lis:
return True
lis.append(head)
head = head.next
return False |
e9cec1dd84c6484febd89d91f9597d0e14ce4e3c | ms-shakil/RegExp | /regexp_compile.py | 399 | 3.734375 | 4 | import re
text = "This is line . Date is 2021/02/21. And theres is another date: 2021-03-21. The Third and final dae is 2022/05/22."
date = re.compile(r"\d{4}[-/]\d{2}[-/]\d{2}") # complile regexp
result = date.findall(text)
print(result)
### american number verifiction with using compile
num = "415-555-4242"
number = re.compile(r"\d{3}-\d{3}-\d{4}")
result = number.findall(num)
print(result)
|
1e9338b4e4f4504d4d5b0385ad072dc1c2b57f1a | amirhadi3/HackerRank | /9_stairCase.py | 185 | 3.96875 | 4 | def staircase(n):
for i in range(1, n + 1):
print(f'%{n - i}s' % '', end='')
for j in range(1, i + 1):
print('#', end='')
print()
staircase(6)
|
ca763d4c9ec8b153a7d3c7b7d912d63cd0ee8262 | aaron-goshine/python-scratch-pad | /workout/two_word_random_password.py | 1,124 | 4.15625 | 4 | ##
# Generate a password by Concatenating two random words.
# The password will be between 8 and characters, and each word
# will be at least three letters long.
#
from random import randrange
WORD_FILE = "/usr/share/dict/words"
# Read all of the words from the files,
# only keeping those that are between 3 and 7
# characters in length, and store them in a list
#
words = []
inf = open(WORD_FILE, "r")
for line in inf:
# Remove the newline character
line = line.rstrip()
# Keep words that are between 3 and 7 letters long
if len(line) >= 3 and len(line) <= 7:
words.append(line)
# Close the file
inf.close()
# Randomly select the first word for
# the password. It can be any word.
first = words[randrange(0, len(words))]
first = first.capitalize()
# Keep selecting a second word until we fine one
# that doesn't make the password too long
password = first
while len(password) < 8 or len(password) > 10:
second = words[randrange(0, len(words))]
second = second.capitalize()
password = first + second
# Display the generated password
print("The random password is:", password)
|
5061551680e1ab63fd3312fc27752a5841f007c7 | anmolsingh8823000/yobro | /imports.py | 553 | 3.828125 | 4 | import random
def prefRandOut(list):
#initialising sum variable
sum = 0
#calculating the sum cumulative priorities of
for row in list:
sum = sum + row[1] #calculating sum of priorities
row.append(sum) #calculating cumulative priorities
#getting random float between 0 and the sum
r = random.uniform(0,sum)
#initialising variable i
i = 0
#iterating through each row
while (i<len(list)):
#checking if this row is selected by random variable
if(r<=list[i][2]):
#returning the chosen row
return list[i]
i = i + 1
|
11bf41e58672f2b1e635270f7bee85e26c6b93fa | Sveto4ek/Python_hw | /Homework_02.py | 6,768 | 3.90625 | 4 | # 1. Создать список и заполнить его элементами различных типов данных. Реализовать скрипт проверки
# типа данных каждого элемента. Использовать функцию type() для проверки типа. Элементы списка
# можно не запрашивать у пользователя, а указать явно, в программе.
# my_list = [50, 'word', 4.6, [5, 9], {56, 22}, {'age': 10}]
# for el in my_list:
# print(type(el))
# 2. Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы
# с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте.
# Для заполнения списка элементов необходимо использовать функцию input().
# list_02 = input('Введите элементы списка через пробел: ').split()
# for el in range(0, (len(list_02) // 2) * 2, 2):
# list_02[el], list_02[el + 1] = list_02[el + 1], list_02[el]
# print(list_02)
# 3. Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится
# месяц (зима, весна, лето, осень). Напишите решения через list и через dict.
# >>>Вариант 1 - список:
# try:
# month = int(input('Введите номер месяца: '))
# list_04 = ['Зима', 'Весна', 'Лето', 'Осень']
# if month in [1, 2, 12]:
# print(list_04[0])
# elif month in [3, 4, 5]:
# print(list_04[1])
# elif month in [6, 7, 8]:
# print(list_04[2])
# else:
# print(list_04[3])
# except ValueError:
# print('Введено не число!')
# >>>Вариант 2 - словарь:
# month = int(input('Введите номер месяца: '))
# my_dict = {1: 'Зима', 2: 'Зима', 3: 'Весна', 4: 'Весна', 5: 'Весна', 6: 'Лето', 7: 'Лето', 8: 'Лето', 9: 'Осень', 10: 'Осень', 11: 'Осень', 12: 'Зима'}
# print(my_dict.get(month))
# 4. Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки.
# Строки необходимо пронумеровать. Если слово длинное, выводить только первые 10 букв в слове.
# my_str = input('Введите текст: ')
# for ind, el in enumerate(my_str.split(), 1):
# print(ind, el[0:10])
# Реализовать структуру «Рейтинг», представляющую собой не возрастающий набор натуральных чисел.
# У пользователя необходимо запрашивать новый элемент рейтинга. Если в рейтинге существуют элементы
# с одинаковыми значениями, то новый элемент с тем же значением должен разместиться после них.
# Подсказка. Например, набор натуральных чисел: 7, 5, 3, 3, 2.
# Пользователь ввел число 3. Результат: 7, 5, 3, 3, 3, 2.
# my_list = [6, 4, 4, 2]
# while True:
# try:
# if input('Ввести еще число? да/нет ') == 'да':
# el = int(input('Введите натуральное число: '))
# my_list.append(el)
# else:
# my_list.sort(reverse=True)
# print(my_list)
# break
# except ValueError:
# print('Не число')
# *6. Реализовать структуру данных «Товары». Она должна представлять собой список кортежей. Каждый кортеж
# хранит информацию об отдельном товаре. В кортеже должно быть два элемента — номер товара и словарь с
# параметрами (характеристиками товара: название, цена, количество, единица измерения). Структуру нужно
# сформировать программно, т.е. запрашивать все данные у пользователя.
# Пример готовой структуры:
# [
# (1, {“название”: “компьютер”, “цена”: 20000, “количество”: 5, “eд”: “шт.”}),
# (2, {“название”: “принтер”, “цена”: 6000, “количество”: 2, “eд”: “шт.”}),
# (3, {“название”: “сканер”, “цена”: 2000, “количество”: 7, “eд”: “шт.”})
# ]
# Необходимо собрать аналитику о товарах. Реализовать словарь, в котором каждый ключ — характеристика
# товара, например название, а значение — список значений-характеристик, например список названий товаров.
# Пример:
# {
# “название”: [“компьютер”, “принтер”, “сканер”],
# “цена”: [20000, 6000, 2000],
# “количество”: [5, 2, 7],
# “ед”: [“шт.”]
# }
# my_list = []
# list_nm = []
# list_pr = []
# list_qty = []
# list_itm = []
# i = 1
# while True:
# if input('Ввести еще товар? да/нет ') == 'да':
# name = input('Название товара: ')
# price = input('Цена: ')
# qty = input('Количество: ')
# itm = input('Единица измерения: ')
# my_dict = {'Название': name, 'Цена': price, 'Количество': qty, 'Ед': itm}
# tpl = (i, my_dict)
# my_list.append(tpl)
# i += 1
# list_nm.append(name)
# list_pr.append(price)
# list_qty.append(qty)
# list_itm.append(itm)
# an_dict = {'Название': list_nm, 'Цена': list_pr, 'Количество': list_qty, 'Ед': list_itm}
# for good in my_list:
# print(good)
# print(an_dict)
# else:
# break
|
f9762dcf16eacaf244f0159118e491e2f34c48a5 | yymin1022/CAU-Computational-Thinking-and-Problem-Solving-Assignment1 | /문제1.py | 505 | 3.65625 | 4 | while 1:
inputNum = int(input('숫자를 입력하세요 : '))
if inputNum == 0:
print('프로그램을 종료합니다.')
break
elif inputNum < 0:
# 입력된 값이 음수인 경우, -1을 곱해 그 절대값을 출력
print('입력된 숫자의 음수이며, 절대값은 %d입니다.' %(inputNum * -1))
elif inputNum > 0:
# 입력된 값이 양수인 경우, 그대로 출력
print('입력된 숫자는 양수 %d입니다.' %inputNum) |
2600e284398562154ef53404819ed23a4f47a9d8 | adanfernandez/python-MUD | /src/command/Comprar.py | 2,027 | 3.875 | 4 | class Comprar_cura:
"""Compra de cura"""
def execute(self, jugador):
jugador.incrementar_objetos('cura')
precio_cura = list(filter(lambda x: isinstance(x, Cura), jugador.objetos_tienda))[0].precio
jugador.recargar_dinero(precio_cura * -1)
print("{} ha comprado una cura\n\n".format(jugador.nombre))
def __str__(self):
return "Comprar objeto cura"
class Comprar_paralisis:
"""Compra de parálisis"""
def execute(self, jugador):
jugador.incrementar_objetos('paralisis')
precio_paralisis = list(filter(lambda x: isinstance(x, Paralisis), jugador.objetos_tienda))[0].precio
jugador.recargar_dinero(precio_paralisis*-1)
print("{} ha comprado una parálisis\n\n".format(jugador.nombre))
def __str__(self):
return "Comprar objeto paralisis"
class Comprar_pasar_nivel:
"""Compra de Pasar Nivel"""
def execute(self, jugador):
jugador.incrementar_objetos('pasar_nivel')
precio_pasar_nivel = list(filter(lambda x: isinstance(x, Pasar_nivel), jugador.objetos_tienda))[0].precio
jugador.recargar_dinero(precio_pasar_nivel * -1)
print("{} ha comprado un pasar nivel\n\n".format(jugador.nombre))
def __str__(self):
return "Comprar objeto pasar nivel"
class Cura:
def __int__(self):
pass
def __init__(self, precio):
self.precio = precio
def get_accion_comprar(self):
return Comprar_cura()
def __str__(self):
return "Aplicar cura"
class Pasar_nivel:
def __int__(self):
pass
def __init__(self, precio):
self.precio = precio
def get_accion_comprar(self):
return Comprar_pasar_nivel()
def __str__(self):
return "Aplicar pasar nivel"
class Paralisis:
def __int__(self):
pass
def __init__(self, precio):
self.precio = precio
def get_accion_comprar(self):
return Comprar_paralisis()
def __str__(self):
return "Aplicar paralisis" |
ba71984f70432bdc9e9d20da070d70129cf8aa9f | ryangillard/misc | /leetcode/365_water_and_jug_problem/365_water_and_jug_problem.py | 1,909 | 3.53125 | 4 | class Solution(object):
def canMeasureWater(self, x, y, z):
"""
:type x: int
:type y: int
:type z: int
:rtype: bool
"""
# Quick return
if x == z or y == z or x + y == z:
return True
# Find smaller and larger buckets
if x <= y:
smaller = x
larger = y
else:
smaller = y
larger = x
z_smaller = 0
z_larger = 0
volume_set = set()
while True:
if z_smaller == 0:
# Fill smaller to full
z_smaller = smaller
if z_smaller + z_larger == z:
return True
volume_tuple = (z_smaller, z_larger)
if volume_tuple in volume_set:
return False
volume_set.add(volume_tuple)
# Pour smaller into larger
if z_larger + z_smaller <= larger:
# Completely pour smaller into larger, smaller is now empty
z_larger += z_smaller
z_smaller = 0
else:
# Partially pour smaller into larger, larger is now full
z_smaller -= (larger - z_larger)
z_larger = larger
if z_smaller + z_larger == z:
return True
volume_tuple = (z_smaller, z_larger)
if volume_tuple in volume_set:
return False
volume_set.add(volume_tuple)
# If larger is full
if z_larger == larger:
z_larger = 0
if z_smaller + z_larger == z:
return True
volume_tuple = (z_smaller, z_larger)
if volume_tuple in volume_set:
return False
volume_set.add(volume_tuple) |
38de7e22ef2f1867ffbf89d02124a0bb2aed9bcc | LeeKyuHyuk/leekyuhyuk.github.io-backup | /assets/file/2015-09-25-python_assignment3.py | 114 | 3.609375 | 4 | table = input()
num = 1
while num < 10:
print str(table) + ' x ' + str(num) + ' = ' + str(table * num)
num += 1
|
96bd8c15192f57c417e77e2c06e6775ab5c0b46f | jamwomsoo/Algorithm_prac | /dynamic_programming/백준/실버/피보나치함수_백준.py | 276 | 3.578125 | 4 | i# 메모리를 필요한만큼만....
def func(x):
one = [0,1]
zero = [1,0]
for i in range(2,x+1):
zero.append(zero[-1]+zero[-2])
one.append(one[-1]+one[-2])
print(zero[x],one[x])
for _ in range(int(input())):
n = int(input())
func(n) |
dd4801389db23386ced9b783b1e0f29db824be4b | yunussevin/Python | /input.py | 167 | 3.515625 | 4 | isim = input("İsminiz Nedir?\n",)
yaş = input("Yaşınızı öğrenebilir miyim?\n")
print("Merhaba", isim, end="!\n")
print("Demek", yaş,"yaşındasın...", end="!\n")
|
374d6260b906c523b6dae9fcb483af6924ea17b9 | cvam0000/hackerRank.pyhton.problems- | /listcomp.py | 336 | 3.9375 | 4 | x = int(input())
y = int(input())
z = int(input())
n = int(input())
list_in=[]
insert i e: Insert integer at position
.
print: Print the list.
remove e: Delete the first occurrence of integer
.
append e: Insert integer
at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.
|
9d974a2303335e4416411a7b8f145edc5d7b7d21 | AmbujaAK/practice | /python/ShortestToChar.py | 1,069 | 3.671875 | 4 | def shortestToChar(S,C):
l = []
ci = S.find(C)
for i in range(len(S)):
print("string now is : " , S[i:])
print("find e : ",S[i:].find(C))
if i > ci and S[i:].find(C) >= ci :
ci = S[i:].find(C)
print('i :',i)
print("ci : ",ci)
ele = abs(ci-i)
l.append(ele)
return l
print("\nEnter the string and char : ")
S = input()
C = input()
l = shortestToChar(S,C)
print(l)
'''
vector<int> shortestToChar(string S, char C) {
vector<int> position;
for(int i =0; i < S.size(); ++i){
if(S[i] == C){
position.push_back(i);
}
}
vector<int> result;
for(int i = 0; i < S.size();++i){
int mini = 2 * S.size() + 1;
for(int j = 0; j < position.size();++j){
int length = position[j] - i > 0 ? position[j] - i : i - position[j];
mini = mini > length ? length : mini;
}
result.push_back(mini);
}
return result;
}
'''
|
f9daa682a17957acae1dc1f69d7a41f0edffbf60 | symbooo/LeetCodeSymb | /demo/24.SwapNodesInPairs.py | 2,528 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
YES, WE CAN!
@Time : 2018/8/31 1:13
@Author : 兰兴宝 [email protected]
@File : 24.SwapNodesInPairs.py
@Site :
@Project : LeetCodeSymb
@Note : [describe how to use it]
"""
# Enjoy Your Code
class Solution:
"""
输入一个链表,每隔两个数交换一次。不允许直接交换节点的值,只可以使用常量额外空间
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
Your algorithm should use only constant extra space.
You may not modify the values in the list's nodes, only nodes itself may be changed.
"""
def symb(self, head):
"""
:type head: ListNode
:return: ListNode
"""
if not head or not head.next: # 输入为空或者之后一个元素,直接返回
return head
ans = head.next
before_last = None # 记录上次循环的最后一个节点
while head and head.next: # 当后续依然2个及以上的值时,继续下一次循环交换
first, next = head, head.next
if before_last: # 上一次循环最后一个节点链接到本次循环的第二个节点
before_last.next = next
next_next = next.next # 记录第二个元素的下一个节点
first.next, next.next = next.next, first
head = next_next
before_last = first
return ans
# 高赞答案
def swapPairs(self, head):
pre, pre.next = self, head
while pre.next and pre.next.next:
a = pre.next
b = a.next
pre.next, b.next, a.next = b, a, b.next
pre = a
return self.next
# Recursively 递归法
def swapPairs1(self, head):
if head and head.next:
tmp = head.next
head.next = self.swapPairs(tmp.next)
tmp.next = head
return tmp
return head
if __name__ == '__main__':
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
node = ListNode(1)
node.next = ListNode(2)
node.next.next = ListNode(3)
node.next.next.next = ListNode(4)
examples = [
node,
]
solution = Solution()
for example in examples:
print(example, solution.symb(example))
|
2f245fc690bd54ab1d97ef095f3ced930a637f59 | samby5/dataengineering | /PreWork_python-ds-practice/27_titleize/titleize.py | 418 | 3.953125 | 4 | def titleize(phrase):
"""Return phrase in title case (each word capitalized).
>>> titleize('this is awesome')
'This Is Awesome'
>>> titleize('oNLy cAPITALIZe fIRSt')
'Only Capitalize First'
"""
nl = phrase.split(' ')
o=[]
for i in nl:
o.append(i[0].upper()+i[1:].lower())
print(' '.join(o))
titleize('oNLy cAPITALIZe fIRSt')
titleize('this is awesome') |
ec12805c3627762025ed3061d16f3635af979057 | shaoqiongchan/Dynamic-Programming | /PriorityQueueDijkstra.py | 1,075 | 3.75 | 4 | import heapq
graph_dict = {'A': {'B': 5, 'C': 1},
'B': {'A': 5, 'C': 2, 'D': 1},
'C': {'A': 1, 'B': 2, 'D': 4, 'E': 8},
'D': {'B': 1, 'C': 4, 'E': 3, 'F': 6},
'E': {'C': 8, 'D': 3},
'F': {'D': 3},
}
def dijkstra(graph, s):
p_queue = [(0, s)]
visited = {s}
parent = {s: None}
distance = {s: 0}
while len(p_queue) > 0:
(dis, vertex) = heapq.heappop(p_queue)
visited.add(vertex)
print(vertex)
nodes = graph[vertex].keys()
for n in nodes:
if n not in visited:
if dis + graph[vertex][n] < distance.get(n, 100000):
heapq.heappush(p_queue, (dis + graph[vertex][n], n))
distance[n] = dis + graph[vertex][n]
parent[n] = vertex
return parent, distance
parent_dict, distance_dict = dijkstra(graph_dict, 'A')
print(parent_dict, distance_dict)
v = 'B'
while v is not None:
print(v)
v = parent_dict[v]
|
2ac1acf7deef80d25c68236d0f8fa9122793c9e5 | KellyPared/student_daniella | /main.py | 14,831 | 4.1875 | 4 | '''This is code written by a 6th grader. This student has had 4 weeks of coding. The assignment was to use:
loops, conditionals, input, f-strings and good variable names. There was no code limit.'''
while True:
title = "Life Simulator".center(50, "-")
print(title)
print("Welcome to life simulator.")
print("A game that simulates life!")
input("Press enter to continue.")
while True:
play_conf = input("Would you like a tutorial? (y or n to continue)").lower()
if play_conf == "y":
input("Press enter to begin the short tutorial.")
input("Press 'y' or 'n' for 'yes' or 'no'.")
input("Make the correct choices!")
print("Tutorial done! Have fun playing.")
input("And remember, make the right choices...")
break
elif play_conf == "n":
break
else:
print("sorry. I didn't get that, please type y or n.")
input("Ok! Welcome to Life Simulator. Press enter to start.")
print("Before we officially begin, we would like for you to answer questions.")
print("Who's life would you like to simulate?")
name = input("Please enter a name.")
print("Nice name! And a few more questions.")
while True:
pronoun = input(f"what gender is {name}? Please pick m, f, or x.")
if pronoun == "m":
pronoun_is = "he is"
pronoun_was = "he was"
pronoun_poss = "his"
pronoun_gen = "male"
pronoun_1 = "he"
pronoun_2 = "him"
break
elif pronoun == "f":
pronoun_is = "she is"
pronoun_was = "she was"
pronoun_poss = "her"
pronoun_gen = "female"
pronoun_1 = "she"
pronoun_2 = "her"
break
elif pronoun == "x":
pronoun_is = "they are"
pronoun_was = "they were"
pronoun_poss = "their"
pronoun_gen = "genderqueer"
pronoun_1 = "them"
pronoun_2 = "they"
break
else:
print("Sorry. I didn't get that. Please type m, f, or x.")
print("Thank you for answering! And lastly...")
location = input(f"Where is {name} located? Please enter a city in the US.")
print("I would love to live there!")
input(f"now loading you into {location}...")
print("Great! We're here.")
print("Since you know how to play, i'll leave you alone now.")
divider = "-".center(50, "-")
print(divider)
print(f"{name}'s life")
print(" ")
print(f"{name} was born in {location} on july 14, 1992.")
print(f"{pronoun_was} born into a nice family with 1 dad, 1 mom, and a brother.")
input("First choice ahead!")
input(f"-While {name}'s brother was feeding {name},")
input(f" he picked up peas with the pink fork he was feeding {name}")
input(f" The green balls looked disgusting to {name}.")
print(" What do you do?")
while True:
choice_food1 = input(
"(a) eat them anyways, (b) refuse to eat, or (c) flip the tray."
)
if choice_food1 == "a":
while True:
agup1a = input("Would you like to age up? y or n")
if agup1a == "y":
print(f"Great! {name} is now 2 years old.")
break
elif agup1a == "n":
print(f"Oopsies! Seems there was a glitch. {name} aged up anyways.")
print(f"Congradulations! {name} is now 2 years old.")
break
else:
print("Sorry. Didn't get that. please type 'y' or 'n'.")
break
elif choice_food1 == "b":
print(f"{name}'s brother shoved it into {pronoun_poss} moulth anyways.")
while True:
agup1b = input("Would you like to age up? (y or n)")
if agup1b == "y":
print(f"Great! {name} is now 2 years old.")
break
elif agup1b == "n":
print(f"Oopsies! Seems there was a glitch. {name} aged up anyways.")
print(f"Congradulations! {name} is now 2 years old.")
break
else:
print("Sorry. Didn't get that. please type 'y' or 'n'.")
break
elif choice_food1 == "c":
print("Oopsie! Seems there was a glitch in the system.")
print("The system thinks you picked b, and I cant seem to change it.")
input(f"Well, to make up for it, i'll age up {name}.")
print("Let's see what would happen if you picked b.")
print("NOW LOADING CHOICE_FOOD1B/C.py")
input("RUNNING...")
print(f"{name}'s brother shoved it into {pronoun_poss} moulth anyways.")
while True:
agup1c = input("Would you like to age up? (y or n)")
if agup1c == "y":
print(f"Great! {name} is now 2 years old.")
break
elif agup1c == "n":
print(f"Oopsies! Theres another glitch! {name} aged up anyways.")
print(f"Congradulations! {name} is now 2 years old.")
break
else:
print("Sorry. Didn't get that. please type 'y' or 'n'.")
break
else:
print("Sorry, Didn't get that. Please try again and type a, b, or c.")
print(f"Congrats! {name} aged up. Ready for a new choice?")
input("For your next choice, you get to choose wether you want it or not")
while True:
gamb_1 = input("Would you like to take a chance?")
if gamb_1 == "y":
print(f"{name} ate a crysanthemum.")
while True:
gamb_2 = input("would you like to take another chance?")
if gamb_2 == "y":
input(f"{name} found a cuboard.")
while True:
cupbo2 = input(f"Should {name} open it?")
if cupbo2 == "y":
print("Sorry. Didn't get that.")
input("Oh, seems theres been another glitch!")
input("Sorry.")
print("Let me load that again...")
("RUN CHOICE_FOOD1B/C.py")
print(">>>RUNNING")
cupbo2_dec = input(f"Should {name} open it?")
if cupbo2_dec == "y":
input("Ok.")
print(f"{name} opened the cupboard and found bleach.")
print("STOPRUN CHOICE_FOOD1B/C.py")
print("Yikes! If that kept on, it would've happened!")
break
elif cupbo2_dec == "n":
input("There seems to be another glitch!")
input("I'm sorry, but i'll make it up to you")
input(f"I'll age {name} up to make up or it.")
print("but we need to see")
print("what would happen if you picked yes.")
print("NOW LOADING CHOICE_FOOD1B/C.py")
input("RUNNING...")
print(f"{name} opened the cupboard and found bleach.")
print("STOPRUN CHOICE_FOOD1B/C.py")
print("Yikes! If that kept on, it would've happened.")
break
else:
print("sorry, I didn't get that. Type 'y' or 'n'")
elif cupbo2 == "n":
print("THANKSYO U")
print("Huh? that wasn't me. Must be another glitch.")
input("Gamble is over. No more chances are to be taken.")
break
else:
print("sorry, I didn't get that. Please type 'y' or 'n'.")
elif gamb_2 == "n":
print("Ok, I guess its better to play it safe")
input("especially when theres another life on the line")
input(f"And it's not like {name} is real anyways!")
break
else:
print("sorry, I didn't get that. Please type 'y' or 'n'.")
break
elif gamb_1 == "n":
print("Ok, I guess its better to play it safe")
input("especially when theres another life on the line")
input(f"And it's not like {name} is real anyways!!")
break
else:
print("sorry, I didn't get that. Please type 'y' or 'n'.")
print(f"Alright. {name} aged up! {pronoun_1} is now 5 years old")
input("Oh no! Theres been another glitch! Sorry.")
print(f"I'm sorry to say, but {name} has been aged up to 18 years old.")
print("And I can't seem to fix it!")
input(f"Since I can't fix it, and {name} is already aged up to 18...")
print(f"What college would you like {name} to attend?")
while True:
colle_nam1 = input("Harvard (h) or Yale (y)?")
if colle_nam1 == "h":
input(f"{name} didn't get accepted to Harvard.")
break
while True:
colle_fr1 = print("Would you like to try another college?")
if colle_fr1 == "y":
colle_nam2 = input("Yale (y)?")
input("It seems theres another glitch! I'm very sorry.")
print(f"{name} is now unemployed.")
break
elif colle_fr1 == "n":
print(f"Okay, {name} is now unemployed.")
break
else:
print("I didn't understand that. Please type 'y' or 'n'.")
break
elif colle_nam1 == "y":
input(f"{name} didn't get accepted to Yale.")
break
while True:
colle_fr1 = print("Would you like to try another college?")
if colle_fr1 == "y":
colle_nam2 = input("Harvard (h)?")
input("It seems theres another glitch! I'm very sorry.")
print(f"{name} is now unemployed.")
break
elif colle_fr1 == "n":
print(f"Okay, {name} is now unemployed.")
break
else:
print("I didn't understand that. Please type 'y' or 'n'.")
else:
print("Sorry. I didn't get that.")
input("Please type 'h' or 'y'.")
break
while True:
print(f"{name} is unemployed, would you like to give {pronoun_2} a career?")
print(f"What would you like {pronoun_2} to be?")
while True:
job_mcdo = input("Doctor (d), lawyer (l), or McDonalds Worker (m)?")
if job_mcdo == "d":
print(f"They didn't want {name} working as a doctor,")
print(f"because {pronoun_1} didn't go to college.")
input(f"{name}'s last resort was working at a McDonald's drive thru.")
print(f"{name} is now succesfully employed!")
break
elif job_mcdo == "l":
print("Oh no! It seems there has been another glitch!")
input("The option to choose lawyer is unavailable :(")
print("I'll reboot so you can take the doctor route instead.")
print("NOW LOADING MCDO_JOBS/C.py")
input("RUNNING...")
print("Now running doctor route!")
print(f"They didn't want {name} working as a doctor,")
print(f"because {pronoun_1} didn't go to college.")
input(f"{name}'s last resort was working at a McDonald's drive thru.")
print(f"{name} is now succesfully employed!")
break
elif job_mcdo == "m":
print(f"{name} is now employed and working at McDonalds.")
input("Though, you could've chosen a higher paying job...")
break
else:
print("Sorry. I didn't get that. Please choose d, l, or m.")
break
print("Another choice coming up!")
while True:
love_gen = input(f"What gender would you like {name}'s S/O to be?")
if love_gen == "m":
name_lo = 'Marco'
lo_is = "he is"
lo_was = "he was"
lo_poss = "his"
lo_gen = "male"
lo_1 = "he"
lo_2 = "him"
break
elif love_gen == "f":
name_lo = 'Amy'
lo_is = "she is"
lo_was = "she was"
lo_poss = "her"
lo_gen = "female"
lo_1 = "she"
lo_2 = "her"
break
elif love_gen == "x":
name_lo = 'Logan'
lo_is = "they are"
lo_was = "they were"
lo_poss = "their"
lo_gen = "genderqueer"
lo_1 = "them"
lo_2 = "they"
break
else:
print("Sorry. I didn't get that. Please type m, f, or x.")
input("Oh no! It appears there has been another glitch...")
print(f"{name} has been aged up to 22!")
print("I am so sorry for the inconvenience!")
input(f"It is currently {name} and {name_lo}'s wedding.")
print(f"You missed, but {name} was seeing someone. {lo_poss} name is {name_lo}")
input("Oh no....")
input("it appears that the couple didn't get their dog vaccinated and...")
print(f"While their dog was passing flowers, it want insane and bit {name}.")
print("I'm sorry, game over.")
print(title)
input("Thank you so much for playing!")
input("I hope you enjoyed this little code~")
print("But the game is over now...")
input(f"Good job on {name}'s life. Would you like to start again with someone new?")
while True:
y_n_last = input("press y or n for the last time.")
if y_n_last == 'n':
print("Play again anyways~")
print("Haha! Thank you for playing though!")
break
break
elif y_n_last == 'y':
print("Alright! Now restarting...")
break
else:
print("It's your last time answering, and you still dont know how to?")
print("Again, please type 'y' or 'n'.")
|
4eb82d66e4db4a1defcc42b6e6493ac4d6a4639d | matias18233/practicas_python | /entregable_8/trabajo_final.py | 10,951 | 3.6875 | 4 | # Nombre: Fernando Matías
# Apellido: Cruz
# Comisión: 1
from random import randrange
# Permite obtener un número de ID único (en un rango que va del 0 al 100)
def obtenerIndice():
global productos
control = False
while control == False:
indice = randrange(100)
repetido = False
if len(productos) == 0:
control = True
else:
for i in productos:
for j in i.values():
if j == indice:
repetido = True
break
else:
break
if (repetido == True):
break
if repetido == False:
control = True
return indice
# Permite agregar nuevos productos
def agregarProducto():
global productos
productosAux = dict.fromkeys(encabezadosProd, "")
for i in encabezadosProd:
if i == "id":
productosAux[i] = obtenerIndice()
elif i == "stock":
cadena = input(f"Ingrese {i}: ")
productosAux[i] = int(cadena)
else:
cadena = input(f"Ingrese {i}: ")
productosAux[i] = cadena
productos.append(productosAux)
print("- Se ha agregado correctamente el producto -")
print()
# Permite mostrar todos los productos existentes
def verProducto():
if len(productos) == 0:
print("- No hay registros para mostrar -")
return 0
for i in encabezadosProd:
print(i, end="\t\t")
print()
for i in productos:
for j in i.values():
print(j, end="\t\t")
print()
print()
# Permite mostrar todos los productos existentes para la venta
def verProductoVenta():
if len(productos) == 0:
print("- No hay registros para mostrar -")
return 0
for i in encabezadosProdVenta:
print(i, end="\t\t")
print()
for i in productos:
index = 0
for j in i.values():
if (index == 0) or (index == 1):
print(j, end="\t\t")
index = index + 1
print()
print()
# Permite eliminar los productos existentes (incluidas sus promociones)
def eliminarProducto():
global productos
print("Indique el valor de ID del registro a eliminar:")
verProducto()
encontrado = False
cadena = input() # Recuperamos el id del registro a eliminar
for i in productos:
for j in i.values():
if j == int(cadena):
encontrado = True
eliminarPromocion(int(cadena))
break
if encontrado == True:
productos.remove(i)
break
print("- Se ha eliminado correctamente el producto -")
print()
# Permite agregar una promoción a los productos existentes
def agregarPromocion():
global productos
print("Indique el valor de ID del registro a agregarle una promoción:")
verProducto()
encontrado = False
salir = False
indiceEncontrado = ""
precioEncontrado = ""
nombreEncontrado = ""
cadena = input() # Recuperamos el id y precio del registro que le cargaremos un precio de promoción
for i in productos:
index = 0
for j in i.values():
if (index == 0) and (j == int(cadena)):
indiceEncontrado = j
encontrado = True
elif (index == 1) and (encontrado == True):
nombreEncontrado = j
elif (index == 2) and (encontrado == True):
precioEncontrado = j
salir = True
if salir == True:
break
else:
index = index + 1
if salir == True:
break
promocionAux = dict.fromkeys(encabezadosProm, "")
for i in encabezadosProm:
if i == "id":
promocionAux[i] = indiceEncontrado
elif i == "nombre":
promocionAux[i] = nombreEncontrado
elif i == "precio":
promocionAux[i] = ((85 * float(precioEncontrado)) / 100)
promociones.append(promocionAux)
print("- Se ha agregado correctamente la promoción -")
print()
# Permite mostrar todas las promociones existentes
def verPromocion():
if len(promociones) == 0:
print("- No hay registros para mostrar -")
return 0
for i in encabezadosProm:
print(i, end="\t\t")
print()
for i in promociones:
for j in i.values():
print(j, end="\t\t")
print()
print()
# Permite eliminar las promociones existentes
def eliminarPromocion(index):
global productos
print("Indique el valor de ID del registro a eliminar:")
verProducto()
encontrado = False
# Recuperamos el id del registro a eliminar
cadena = index
for i in promociones:
for j in i.values():
if j == cadena:
encontrado = True
break
if encontrado == True:
promociones.remove(i)
break
print("- Se ha eliminado correctamente la promoción -")
print()
# Permite cargar automáticamente productos y promociones en el sistema
def cargaAutomatica():
producto = {"id":1, "nombre":"Pepsi", "precio":150, "stock":10}
productos.append(producto)
producto = {"id":2, "nombre":"Fideo", "precio":40, "stock":8}
productos.append(producto)
producto = {"id":3, "nombre":"Arroz", "precio":120, "stock":10}
productos.append(producto)
producto = {"id":4, "nombre":"Caldo", "precio":100, "stock":8}
productos.append(producto)
producto = {"id":5, "nombre":"Pollo", "precio":240, "stock":10}
productos.append(producto)
producto = {"id":6, "nombre":"Tomate", "precio":40, "stock":8}
productos.append(producto)
producto = {"id":7, "nombre":"Galleta", "precio":50, "stock":10}
productos.append(producto)
producto = {"id":8, "nombre":"Fernet", "precio":550, "stock":8}
productos.append(producto)
producto = {"id":9, "nombre":"Cerveza", "precio":110, "stock":10}
productos.append(producto)
producto = {"id":10, "nombre":"Puré", "precio":120, "stock":8}
productos.append(producto)
promocion = {'id': 10, 'nombre': 'Puré', 'precio': 102.0}
promociones.append(promocion)
promocion = {'id': 2, 'nombre': 'Fideo', 'precio': 34.0}
promociones.append(promocion)
promocion = {'id': 4, 'nombre': 'Caldo', 'precio': 85.0}
promociones.append(promocion)
promocion = {'id': 5, 'nombre': 'Pollo', 'precio': 204.0}
promociones.append(promocion)
# Permite realizar una venta
def realizarVenta():
global ventas
salir = False
finBusqueda = False
while salir == False:
print("Ingrese el valor de ID de uno de los productos siguientes:")
verProductoVenta()
cadena = input() # Recuperamos el id y precio del registro que le cargaremos un precio de promoción
encontrado = False
indiceEncontrado = ""
precioEncontrado = ""
nombreEncontrado = ""
for i in productos:
index = 0
for j in i.values():
if (index == 0) and (j == int(cadena)):
indiceEncontrado = j
encontrado = True
elif (index == 1) and (encontrado == True):
nombreEncontrado = j
elif (index == 2) and (encontrado == True):
precioEncontrado = controlarOferta(indiceEncontrado, j)
finBusqueda = True
if finBusqueda == True:
break
else:
index = index + 1
if finBusqueda == True:
break
print("Ingrese la cantidad de productos a comprar")
cadena = input()
ventasAux = dict.fromkeys(encabezadosVentas, "")
for i in encabezadosVentas:
if i == "id":
ventasAux[i] = indiceEncontrado
elif i == "nombre":
ventasAux[i] = nombreEncontrado
elif i == "precio":
ventasAux[i] = precioEncontrado
elif i == "cantidad":
ventasAux[i] = int(cadena)
elif i == "total":
ventasAux[i] = precioEncontrado * int(cadena)
ventas.append(ventasAux)
print("¿Desea vender otro producto?")
print(" 1 - Sí")
print(" 2 - No")
cadena = input()
if int(cadena) == 2:
verVentas()
print("Presione una tecla para continuar...")
cadena = input()
salir = True
else:
finBusqueda = False
# Permite mostrar todas las ventas existentes
def verVentas():
if len(ventas) == 0:
print("- No hay registros para mostrar -")
return 0
for i in encabezadosVentas:
print(i, end="\t\t")
print()
total = 0
for i in ventas:
index = 0
for j in i.values():
print(j, end="\t\t")
if index == 4:
total = total + j
index = index + 1
print()
print()
print("--------------------------------------")
print("El total es: $", total)
print()
def controlarOferta(indiceEncontrado, precio):
if len(promociones) == 0:
return precio
for i in promociones:
index = 0
encontrado = False
for j in i.values():
if j == indiceEncontrado:
encontrado = True
if (index == 2) and (encontrado == True):
precio = j
index = index + 1
return precio
productos = []
encabezadosProd = ["id", "nombre", "precio", "stock"]
encabezadosProdVenta = ["id", "nombre"]
promociones = []
encabezadosProm = ["id", "nombre", "precio"]
ventas = []
encabezadosVentas = ["id", "nombre", "precio", "cantidad", "total"]
cargaAutomatica()
salir = False
while salir == False:
print("--------------------------------------")
print("Ingrese el valor correspondiente a la opción seleccionada:")
print(" 1 - Agregar producto")
print(" 2 - Ver productos")
print(" 3 - Eliminar productos")
print(" 4 - Agregar promoción")
print(" 5 - Ver promoción")
print(" 6 - Eliminar promoción")
print(" 7 - Realizar venta")
print(" 8 - Ver última venta realizada")
print(" 9 - Salir del programa")
cadena = input()
if cadena == "1":
agregarProducto()
elif cadena == "2":
verProducto()
elif cadena == "3":
eliminarProducto()
elif cadena == "4":
agregarPromocion()
elif cadena == "5":
verPromocion()
elif cadena == "6":
print("Indique el valor de ID del registro a eliminar:")
verPromocion()
cadena = input()
eliminarPromocion(int(cadena))
elif cadena == "7":
realizarVenta()
elif cadena == "8":
verVentas()
elif cadena == "9":
salir = True |
37a9a2104ff27c590261f6461c175ae4e9923682 | cholu6768/Voting-Poll | /Voting_poll/voting.py | 1,782 | 3.796875 | 4 | import random
#These were some candidates in Mexico
candidates = ["AMLO", "Peña","Bronco","Calderon","Fox"]
school_1 = []
school_2 = []
school_3 = []
school_4 = []
school_5 = []
votes = []
#Inserting the votes in the lists of the schools
for vote in range(5):
num = random.randint(20, 100)
school_1.append(num)
for vote in range(5):
num = random.randint(20, 100)
school_2.append(num)
for vote in range(5):
num = random.randint(20, 100)
school_3.append(num)
for vote in range(5):
num = random.randint(20, 100)
school_4.append(num)
for vote in range(5):
num = random.randint(20, 100)
school_5.append(num)
#Summing the votes for every candidate
for vote in range(5):
if vote == 0:
vote1 = school_1[vote] + school_2[vote] + school_3[vote] + school_4[vote] + school_5[vote]
elif vote == 1:
vote2 = school_1[vote] + school_2[vote] + school_3[vote] + school_4[vote] + school_5[vote]
elif vote == 2:
vote3 = school_1[vote] + school_2[vote] + school_3[vote] + school_4[vote] + school_5[vote]
elif vote == 3:
vote4 = school_1[vote] + school_2[vote] + school_3[vote] + school_4[vote] + school_5[vote]
elif vote == 4:
vote5 = school_1[vote] + school_2[vote] + school_3[vote] + school_4[vote] + school_5[vote]
#Inserting the sum of votes per candidate en the list of votes
votes.append(vote1)
votes.append(vote2)
votes.append(vote3)
votes.append(vote4)
votes.append(vote5)
# Adding all the votes to the variable total
total = 0
for voto in votes:
total += voto
for vote in range(5):
print(candidates[vote] + " Number of votes:", end="")
print(votes[vote])
print(f"Respective porcentage: {round((votes[vote] / total)*100, 2)}%")
print()
|
d0148659feed69b27869c2caaf5c70a1f763477e | rvrn2hdp/informatorio2020 | /FuncionesComp/ejemploclosure.py | 1,509 | 4.1875 | 4 | # Closures()
# Se utiliza para que una función genere dinámicamente otra función y que esta nueva función
# pueda acceder a las variables locales aun cuando la función haya terminado
# Se utiliza para evitar el uso de variables globales y proporcionan alguna forma de ocultar datos.
# Se usan en conjunto con los decoradores que veremos mas adelante.
# Utilizan funciones anidadas para vincular o pasar datos a una función sin pasar necesariamente
# los datos a la función a través de parámetros.
# Un closure es causado por una función interna, pero no es la función interna.
# El closure funciona cerrando la variable local en el momento de ejecucion, pero que se mantiene después
# de que la ejecucion de la función haya terminado de ejecutarse.
# Veamos un ejemplo:
def mostrar_mensaje(nombre):
''' Esta función crea de forma dinámica
la función mostrar_nombre().
'''
def mostrar_nombre():
print('Hola, mi nombre es ' + nombre)
return mostrar_nombre # Retorno un objeto en lugar de llamar a la función
mostrar = mostrar_mensaje('Juanito González')
mostrar()
# En el ejemplo anterior la función mostrar_mensaje() crea y retorna una función,
# la función mostrar_nombre() es el closure.
'''
Condiciones que deben cumplirse para crear un cierre en Python:
- Debe haber una función anidada
- La función interna tiene que hacer referencia a un valor recibe la funcion externa (closure).
- La función closure tiene que devolver la función anidada.
''' |
ea0e43009430b046f9583c5fa7de128c949295a6 | TheDesTrucToRR/Hacktoberfest-2021 | /Python/find_the_number_of_ways.py | 1,124 | 3.8125 | 4 | '''
A man has money/coins in two different bags. He visits the market to buy some items.
Bag A has N coins and Bag B has M coins. The denominations of the money are given as
array elements in a[] and b[]. He can buy products only by paying an amount which is
an even number by choosing money from both the bags. The task here is to find the number
of ways the man can buy items such that the product of money from bothn bags is an even number.
The man has to pick one coin atleast from each bag to make an even number product.
Example:
Input:
3 - Value of N
3 - Value of M
{1,2,3} -- [a] elements a[0]-a[N-1], where each element input is separated by new line
{5,6,7} -- [b] elements b[0]-b[M-1], where each element input is separated by new line
Output:
5 - Number of ways he can get an even product of coins.
'''
n = int(input())
m = int(input())
a_list=[]
b_list=[]
for i in range(n):
a = int(input())
a_list.append(a)
for i in range(m):
b = int(input())
b_list.append(b)
ans=[]
for i in a_list:
for j in b_list:
mul = i*j
if mul % 2 ==0:
ans.append(mul)
print(len(ans)) |
ac73f1d6234175f04e74dbab1f1d3cfa7636436a | Gabi240400/car-service | /Domain/ValidateCard.py | 4,203 | 3.5625 | 4 | from Domain.CardCustomer import Card
from Exceptions.InvalidCNP import InvalidCNPException
from Exceptions.CardError import InvalidCustomerCardException
class CustomerCardValidator:
@staticmethod
def validate_customer_card(customer_card: Card):
"""
Function verify if an object respects some conditions and if it finds an irregularity raise an exception
:param customer_card: an CustomerCard object
:return: exceptions
"""
if not isinstance(customer_card.id_entity(), int):
raise InvalidCustomerCardException("ID = {} must be an int".format(customer_card.id_entity()))
if len("{}".format(customer_card.get_cnp())) != 13:
raise InvalidCNPException("CNP {} must be made out of 13"
" characters".format(customer_card.get_cnp()))
if len("{}".format(customer_card.get_name())) == 0:
raise InvalidCustomerCardException("Customer has to get a name ")
if len("{}".format(customer_card.get_surname())) == 0:
raise InvalidCustomerCardException("Customer has to get a name ")
if not isinstance(customer_card.get_cnp(), int):
raise InvalidCustomerCardException("CNP {} must be int".format(customer_card.get_cnp()))
if "/" not in customer_card.get_date_birth():
raise InvalidCustomerCardException("please use / for writing date")
if "/" not in customer_card.get_date_registered():
raise InvalidCustomerCardException("please use / for writing date")
if len("{}".format(customer_card.get_date_birth())) < 5:
raise InvalidCustomerCardException("Date is not valid")
if len("{}".format(customer_card.get_date_registered())) < 5:
raise InvalidCustomerCardException("Date is not valid")
birth_date = customer_card.get_date_birth().split(sep="/")
if len(birth_date) != 3:
raise InvalidCustomerCardException("Use only two /")
if int(birth_date[0]) < 1 or int(birth_date[0]) > 31:
raise InvalidCustomerCardException("Day {} must be between 1 and 31".format(int(birth_date[0])))
if int(birth_date[1]) < 1 or int(birth_date[1]) > 12:
raise InvalidCustomerCardException("Month {} must be between 1 and 12".format(int(birth_date[1])))
if int(birth_date[2]) > 2019:
raise InvalidCustomerCardException("Year cannot be in the future {}".format(int(birth_date[2])))
registration_date = customer_card.get_date_registered().split(sep="/")
if int(registration_date[0]) < 1 or int(registration_date[0]) > 31:
raise InvalidCustomerCardException("Day {} must be between 1 and 31".format(int(registration_date[0])))
if int(registration_date[1]) < 1 or int(registration_date[1]) > 12:
raise InvalidCustomerCardException("Month {} must be between 1 and 12".format(int(registration_date[1])))
if int(registration_date[2]) > 2019:
raise InvalidCustomerCardException("Year cannot be in the future {}".format(int(registration_date[2])))
if len(registration_date) != 3:
raise InvalidCustomerCardException("Use only two /")
if customer_card.id_entity() < 0:
raise InvalidCustomerCardException("The card id must be a positive")
@staticmethod
def validate_date(date):
"""
Function verify if a date id valid
:param date: string
:return: raise exceptions if the date doesn't respect some conditions
"""
date = date.split(sep="/")
if len(date) != 3:
raise InvalidCustomerCardException("Use only 2 /")
if int(date[0]) < 1 or int(date[0]) > 31:
raise InvalidCustomerCardException("Day {} must be between 1 and 31".format(int(date[0])))
if int(date[1]) < 1 or int(date[1]) > 12:
raise InvalidCustomerCardException("Month {} must be between 1 and 12".format(int(date[1])))
if int(date[2]) > 2019:
raise InvalidCustomerCardException("Year {} cannot be in the future".format(int(date[2])))
|
bf18ea472fd33162217b398e605224d6c30a958c | EricKoegel/learningpython | /Test/com/PracticeWork/fibonacci_sequence.py | 345 | 4.09375 | 4 | '''
Created on Feb 29, 2016
@author: michael.f.koegel
The entire purpose of this project
is to perform the fibonacci
sequence and practice skills
'''
#n = input("Please enter the sequence 'nth' value: ")
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
print(fib(35)) |
3e72f1af030d335778211f22bea01b9451bc6e21 | EDDchris2017/IAPractica1_Lopez201504100 | /src/algoritmo/Finalizacion.py | 2,392 | 3.515625 | 4 | from statistics import mode
class Finalizacion:
def __init__(self):
self.porcentaje = 65 # Criterio de porcentaje ( Criterio 1)
self.maximo_gen = 700 # Maximo de generaciones ( Criterio 2)
def verificarCriterio(self, criterio, poblacion, generacion):
result = None
if criterio == 1:
result = self.criterio1( poblacion, generacion)
elif criterio == 2:
result = self.criterio2( poblacion, generacion)
elif criterio == 3:
result = self.criterio3( poblacion, generacion)
return result
def criterio1(self, poblacion, generacion):
fin = None
ordenar_poblacion = poblacion
ordenar_poblacion = sorted(ordenar_poblacion)
cont = 1
lista_fitness = [o.fitness for o in ordenar_poblacion]
moda_fitness = mode(lista_fitness)
frecuencia_moda = lista_fitness.count(moda_fitness)
print("MODA : ",moda_fitness," ::","Frecuencia moda ",frecuencia_moda)
# Calcular porcentaje de acuerdo a la frecuencia de la moda
porcentaje = ( frecuencia_moda * 100 ) / len(poblacion)
print(porcentaje)
if int(porcentaje) >= int(self.porcentaje):
print("Finalizo el algoritmo !!!")
fin = min(ordenar_poblacion, key=lambda x: x.fitness)
return fin
# Cantidad Maxima de generaciones
def criterio2(self, poblacion, generacion):
fin = None
if generacion == self.maximo_gen:
fin = min(poblacion, key=lambda x: x.fitness)
return fin
def criterio3(self, poblacion, generacion):
fin = None
# Obtener listado de fitness
lista_fitness = [o.fitness for o in poblacion]
promedio = sum(lista_fitness) / float(len(lista_fitness))
print(" PROMEDIO :: ", promedio)
if promedio >= 0 and promedio <= 10:
fin = min(poblacion, key=lambda x: x.fitness)
return fin
def getCriterio(self, criterio):
if criterio == 1:
return str(self.porcentaje) + "% de la plobacion con valor fitness igual"
elif criterio == 2:
return str(self.maximo_gen) + " numero maximo de generaciones"
elif criterio == 3:
return "Valor promedio de fitness entre 0 y 1.5"
return "Retorno de Finalizacion indefinido"
|
0fb206e7e13d76ebc30180c0cc19381d9e582c28 | GMTrends/Python-Projects | /Python & PHP Files/Python/Read & Write file using SenseHat sensors/read_sensehat_data_random.py | 1,746 | 3.546875 | 4 | # read_sensehat_data_random.py
# sense_file.seek(0) <-- bytes of offset (location in the file)
# sense_file.tell() <-- location of the file pointer
# line_str = sense_file.readline() <-- reads one line at a time
from sense_hat import SenseHat
from time import sleep,time,ctime #ctime converts time to more readable format
def main():
file_opened = False
sense = SenseHat()
try:
filename = input("Enter the sensehat data filename\n")
sense_file = open(filename,"r")
file_opened = True
line_number = int(input("Enter the line number"))
while line_number >= 1:
sense_file.seek(0) # go to the beginning of the file
line_str = sense_file.readline()
for line in range(1,line_number):
line_str = sense_file.readline()
if not line_str:
break
if line_str:
line_str = line_str.strip() # strip off the new lines
data_line = line_str.split(',')
print("x = " + data_line[0])
print("y = " + data_line[1])
print("z = " + data_line[2])
print("time = " + data_line[3])
else:
print("Line at end of file: current location" + str(sense_file.tell()))
line_number = int(input("Enter the line number"))
except KeyboardInterrupt:
print("Exiting...")
except PermissionError: #do not have write permissions
print("Permission Error")
except IsADirectoryError:
print("Directory is specified and not a file")
except FileNotFoundError:
print("File not found")
finally:
if file_opened:
sense_file.close()
main()
|
7df01aea22a4b423b4ceb29e332234af5c733be1 | ravalrupalj/BrainTeasers | /Edabit/Sort_List_by_String_Length.py | 647 | 4.125 | 4 | #Sort a List by String Length
#Create a function that takes a list of strings and return a list, sorted from shortest to longest.
#All test cases contain lists with strings of different lengths, so you won't have to deal with multiple strings of the same length.
def sort_by_length(lst):
t= sorted(lst,key=len)
return t
print(sort_by_length(["Google", "Apple", "Microsoft"]))
#➞ ["Apple", "Google", "Microsoft"]
print(sort_by_length(["Leonardo", "Michelangelo", "Raphael", "Donatello"]))
#➞ ["Raphael", "Leonardo", "Donatello", "Michelangelo"]
print(sort_by_length(["Turing", "Einstein", "Jung"]))
#➞ ["Jung", "Turing", "Einstein"]
|
a0ae865182802ac5ab975a1dd228c349f7c76f0c | ngdeva99/Fulcrum | /Valid Parentheses.py | 517 | 3.78125 | 4 | class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
left = ['(', '{', '[']
right = [')', '}', ']']
stack = []
for letter in s:
if letter in left:
stack.append(letter)
elif letter in right:
if len(stack) <= 0:
return False
if left.index(stack.pop()) != right.index(letter):
return False
return len(stack) == 0
|
15b68baa72d48f6d0ddb25af69c33d5c5ea7033d | su-maxlee/Bioinfo09 | /W3/0705.py | 1,715 | 4.3125 | 4 | #! /usr/bin/env python
'''
#나중에 한번봐보자
a= 11
if (b:=a)>10:
print(f'the value of b is {b} and is greater than 10.')
'''
'''
#2 Variable my answer
import math
r=float(input('insert radius: '))
area= (r**2)*math.pi
print(f'The area of a circle with a radius of {r} is:',area)
'''
'''
#2 Variable t.answer
import math
import sys
#설명서
if len(sys.argv) != 2:
print(f"#usage: python {sys.argv[0]} [num]")
sys.exit()
r=int(sys.argv[1])
pi=math.pi
result = round(r**2*pi, 2)
print(result)
'''
'''
#3 Operator my answer
num1 = 3
num2 = 5
print(num1+num2)
print(num1-num2)
print(num1*num2)
print(num1/num2)
print(num1%num2)
print(num1**num2)
'''
'''
#4 if-else
import sys
if len(sys.argv)!=2:
print(f'#usage: python {sys.argv[0]} [num]')
sys.exit()
46 #4 if-else
num = int(sys.argv[1])
if num%2==0:
print(f'{num} is an even number')
else:
print(f'{num} is an odd number')
'''
'''
#5 if-elif-else
import sys
if len(sys.argv)!=2:
print(f'#usage: python {sys.argv[0]} [num]')
sys.exit()
num=int(sys.argv[1])
if num%3==0 and num%7==0:
print(f'{num} is a multiple of 21')
elif num%3==0:
print(f'{num} is a multiple of 3')
elif num%7==0:
print(f'{num} is a multiple of 7')
else:
print(f'{num} is not a multiple of 3 or 7')
'''
'''
#6 for
a=1
for i in range(1,11,1):
a*=i
print(a)
'''
'''
#7 multiple for
'''
'''
#8 While t.answer
import sys
n=int(sys.argv[1])
val = 1
while n>0:
val*=n
n-=1
print(val)
'''
#9 Function t.answer
def greet():
print('Hello, Bioinformatics')
def greet1(name):
print(f"Hello, {name}")
def greet2(num):
return num*2
greet()
greet1('max')
ret=greet2(3)
print(ret)
|
cbf18b7f7e8c22c4806a613afb7ba33fe5576908 | pablot30/misiontic-2022 | /ciclo-1/cc_unaleño.py | 967 | 3.71875 | 4 | # Laboratorio de Pruebas - Semana 1-2
# Tema: Centro Comercial Unaleño
# Autor: Pablo Jose Torres Mojica
def get_product_details():
product_name = input()
unit_cost = abs(int(input()))
retail_price = abs(int(input())) # precio de venta al público
stock = abs(int(input()))
return {'Product Name': product_name,
'Unit Cost': unit_cost,
'Retail Price': retail_price,
'Stock': stock}
def get_profit(product):
return product['Stock'] * (product['Retail Price'] - product['Unit Cost'])
def print_details(product):
print(f"""Producto: {product['Product Name']}
\rCU: ${product['Unit Cost']}
\rPVP: ${product['Retail Price']}
\rUnidades Disponibles: {product['Stock']}
\rGanancia: ${product['Profit']}""")
def main():
product = get_product_details()
product['Profit'] = get_profit(product)
print_details(product)
if __name__ == '__main__':
main()
|
e575a9a565a3eb2e683c92540b2f582c09578176 | aoeuidht/homework | /leetcode/313.SuperUglyNumber.py | 1,105 | 3.578125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
class Solution(object):
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
if not primes:
return 1
ugly_list = [1]
# in the heapq, every element is (value, current-val, offset-in-ugly-list)
prime_q = [(prime, prime, 0) for prime in primes]
ugly_len = 1
while ugly_len < n:
item = prime_q[0]
if item[0] > ugly_list[-1]:
ugly_list.append(item[0])
ugly_len += 1
update_item = (item[1] * ugly_list[item[2]+1], item[1], item[2] + 1)
heapq.heappushpop(prime_q, update_item)
return ugly_list[-1]
if __name__ == '__main__':
s = Solution()
print s.nthSuperUglyNumber(12, [2, 7, 13, 19])
print s.nthSuperUglyNumber(30, [3,5,13,19,23,31,37,43,47,53])
print s.nthSuperUglyNumber(100000, [7,19,29,37,41,47,53,59,61,79,83,89,101,103,109,127,131,137,139,157,167,179,181,199,211,229,233,239,241,251])
|
ba06bf292bed66a06a177cbf9318ce9becd6ffd8 | roblivesinottawa/OOP | /OOP/user_methods.py | 721 | 4 | 4 | # A User class with both instance attributes and instance methods
class User:
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
def full_name(self):
return f"{self.first} {self.last}"
def country(self, origin):
return f"{self.first} is from {origin}"
def interests(self, thing):
return f"{self.first} likes {thing}"
def birthday(self):
self.age += 1
return f"Happy {self.age}th, {self.first}"
user = User("Victoria", "Rossi", 34)
print(user.first, user.last)
print(user.country("Canada"))
print(user.interests("weed"))
print(user.age) #Print age before we update it
print(user.birthday()) #updates age
print(user.age) #Print new value of age
|
f7932d6a7004798fd1192fe0c2bea962e36e9efc | Hassan-Farid/PyTech-Review | /Computer Vision/Image Processing using OpenCV/Image Gradients/Scharr Gradient.py | 543 | 3.53125 | 4 | import cv2
import numpy as np
#Reading image from the Images folder
img = cv2.imread('.\Images\grid.jpg')
#Configuring settings for applying Scharr gradient
ksize = -1
ddepth = -1
#Applying scharr gradient on the image
x_sobel = cv2.Sobel(img, ddepth, dx=1, dy=0, ksize=ksize)
y_sobel = cv2.Sobel(img, ddepth, dx=0, dy=1, ksize=ksize)
#Displaying images on the screen
cv2.imshow('Original Image', img)
cv2.imshow('Horizontal Scharr Gradient', x_sobel)
cv2.imshow('Vertical Scharr Gradient', y_sobel)
cv2.waitKey(0)
cv2.destroyAllWindows() |
f494119893fbf022b5201d7a5cd039487e22a0b5 | asiftandel96/Object-Oriented-Programming | /Exception_Handling/Basics.py | 1,256 | 3.96875 | 4 | """Basic Example of Exception Handling"""
"""
class Ex_Operation:
def __init__(self, a, b):
try:
self.a = a
self.b = b
self.result = self.a / self.b
if self.result > 5:
print('The result is good')
elif self.result == 5:
print('Howrah!!!!')
else:
print('the result is ok')
except ZeroDivisionError:
print('The Denominator should be greater than zero')
except TypeError:
print('The Type should be specified correctly')
except Exception as ex:
print(ex)
finally:
print('------The Execution is done--------')
if __name__ == "__main__":
a = Ex_Operation(25, 5)
"""
"""Custom Exception Handling"""
class Error(Exception):
pass
class dobException(Error):
pass
def Ex():
year = int(input('Enter the year'))
age = 2021 - year
try:
if age <= 30 & age > 20:
print('The age is valid and you can apply for the exams')
else:
raise dobException
except dobException:
print('The age is not in the range and you cannot apply for exams')
if __name__ == "__main__":
Ex()
|
5a503a2b1f713f28b68ba168085101f89372deb5 | syeluru/MIS304 | /ExceptionHandler2.py | 1,155 | 3.9375 | 4 | # Program to process exceptions using functions
def main():
total_score = 0.0
scores_str = input("Enter numbers separated by spaces: ")
scores_list = scores_str.split()
print (scores_list)
try:
total_score = computeTotal(scores_list)
print (total_score)
except ValueError:
print("Enter numeric values.")
except Exception as ex:
print ("Some error occurred")
print(type(ex))
print (ex, "error, specifically.")
else:
print ("I'm in main")
print ("Everything looks good")
print ("I'm in the else of the main function")
print ("Total Score:", total_score)
finally:
print ("I'm in main")
print ("Finally, I'm here no matter what")
def computeTotal(scores_list):
total_score = 0.0
try:
i = 0
while (i < len(scores_list)):
total_score += int(scores_list[i])
i += 1
except ValueError:
print ("I'm in computeTotal function")
print ("Enter numeric values")
else:
print ("I'm in the else of computeTotal")
return total_score
# Call main
main()
|
f0737930d9272d721e8435b05000b2347c2c9fed | enriavil1/caculator | /calcultator.py | 3,712 | 3.84375 | 4 | from tkinter import *
root = Tk()
root.title("Calculator")
input_box = Entry(root, width = 50, borderwidth = 5)
input_box.grid(row = 0, column = 0, columnspan = 3, padx = 10, pady = 10)
def click(num):
box = input_box.get()
box += str(num)
input_box.delete(0, END)
input_box.insert(0, box)
def clear():
input_box.delete(0, END)
def add():
variable = input_box.get()
global first_num
first_num = int(variable)
global math
math = "add"
input_box.delete(0, END)
def substract():
variable = input_box.get()
global first_num
first_num = int(variable)
global math
math = "substract"
input_box.delete(0, END)
def divide():
variable = input_box.get()
global first_num
first_num = int(variable)
global math
math = "divide"
input_box.delete(0, END)
def multiply():
variable = input_box.get()
global first_num
first_num = int(variable)
global math
math = "multiply"
input_box.delete(0, END)
def equal():
if math == "add":
second_number = input_box.get()
input_box.delete(0,END)
result = first_num + int(second_number)
input_box.insert(0, str(result))
if math == "substract":
second_number = input_box.get()
input_box.delete(0,END)
result = first_num - int(second_number)
input_box.insert(0, str(result))
if math == "multiply":
second_number = input_box.get()
input_box.delete(0,END)
result = first_num * int(second_number)
input_box.insert(0, str(result))
if math == "divide":
second_number = input_box.get()
input_box.delete(0,END)
result = first_num / int(second_number)
input_box.insert(0, str(result))
#Buttons created
num_1 = Button(root, text= "1", padx = 90, pady = 30, command = lambda:click(1) )
num_2 = Button(root, text= "2", padx = 90, pady = 30, command = lambda:click(2) )
num_3 = Button(root, text= "3", padx = 90, pady = 30, command = lambda:click(3) )
num_4 = Button(root, text= "4", padx = 90, pady = 30, command = lambda:click(4) )
num_5 = Button(root, text= "5", padx = 90, pady = 30, command = lambda:click(5) )
num_6 = Button(root, text= "6", padx = 90, pady = 30, command = lambda:click(6) )
num_7 = Button(root, text= "7", padx = 90, pady = 30, command = lambda:click(7) )
num_8 = Button(root, text= "8", padx = 90, pady = 30, command = lambda:click(8) )
num_9 = Button(root, text= "9", padx = 90, pady = 30, command = lambda:click(9) )
num_0 = Button(root, text= "0", padx = 90, pady = 30, command = lambda:click(0) )
button_clear = Button(root, text= "clear", padx = 80, pady = 30, command = clear)
button_equal = Button(root, text= "=", padx = 90, pady = 30, command = equal)
button_minus= Button(root, text= "-", padx = 90, pady = 30, command = substract)
button_plus = Button(root, text= "+", padx = 90, pady = 30, command = add )
button_times = Button(root, text= "*", padx = 90, pady = 30, command = multiply )
button_divide = Button(root, text= "/", padx = 90, pady = 30, command = divide )
#Button inserting
num_0.grid(row = 4, column = 0)
button_clear.grid(row = 4, column = 1, columnspan = 1)
button_equal.grid(row = 4, column = 2)
button_divide.grid(row = 4, column = 3)
num_1.grid(row = 3, column = 0)
num_2.grid(row = 3, column = 1)
num_3.grid(row = 3, column = 2)
button_times.grid(row = 3, column = 3)
num_4.grid(row = 2, column = 0)
num_5.grid(row = 2, column = 1)
num_6.grid(row = 2, column = 2)
button_minus.grid(row = 2, column = 3)
num_7.grid(row = 1, column = 0)
num_8.grid(row = 1, column = 1)
num_9.grid(row = 1, column = 2)
button_plus.grid(row = 1, column = 3)
root.mainloop()
|
9d9bdcb6531ce7275b14fc8b121440d38a12ee1b | craighillelson/daily_focus | /functions.py | 2,351 | 4 | 4 | """Functions."""
import csv
import datetime
from datetime import datetime
from datetime import (date,
timedelta)
import pyinputplus as pyip
target_date = date(2021, 8, 7)
todays_date = date.today()
date_tasks_to_add = {}
dates_tasks = {}
def days_out(num_days):
"""Find the date a given number of days from the target date."""
return (target_date - timedelta(days=num_days)).isoformat()
def diff_dates():
"""Return the number of days between the target date and today."""
return abs((target_date - todays_date).days)
def get_target_date():
"""Import "target_date.txt" and return the date contained in the file."""
date_file = open("target_date.txt", "r")
imported_target_date = date_file.read()
datetime_obj = datetime.datetime.strptime(imported_target_date, "%Y-%m-%d")
return datetime_obj.date()
def greeting():
"""Greet user based on time of day."""
if datetime.now().hour >= 1 and datetime.now().hour < 6:
print("\nYou're up late.")
elif datetime.now().hour >= 6 and datetime.now().hour < 12:
print("\nGood morning!")
elif datetime.now().hour >= 12 and datetime.now().hour < 17:
print("\nGood afternoon!")
else:
print("\nGood evening!")
def open_csv_pop_dct():
"""Open csv and populate a dictionary with its contents."""
dct = {}
with open("dates_tasks.csv", newline="") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
dct[row["date"]] = row["task_start_of_day"]
return dct
def output_dct(dct):
"""Output contents of dictionary."""
print("\ndate, focus")
for date, task in dct.items():
print(date, task)
def prompt_user_for_target_date(user_prompt):
"""Prompt user for target date."""
return pyip.inputDate(user_prompt, formats=["%Y-%m-%d"])
def prompt_user_for_task(user_prompt):
"""Prompt user for input."""
return input(f"\n{user_prompt}")
def write_dct_to_csv(file, dct):
"""Write dictionary to csv."""
with open(file, "w") as out_file:
out_csv = csv.writer(out_file)
out_csv.writerow(["date", "task_start_of_day"])
for today, task in dct.items():
keys_values = (today, task)
out_csv.writerow(keys_values)
print(f'\n"{file}" exported successfully\n')
|
7458088428173f0761f53adc067d69e7e53b0fdb | nobodywhocares/hackerrank-hokum-py | /sorting.py | 12,211 | 4.4375 | 4 | def print_sorted(alg, a):
print(f"Printing {alg} Sorted Element List...")
for i in a:
print(i)
# Counting Sort:
#
# It is a sorting technique based on the keys i.e. objects are collected according to keys which are small integers.
# Counting sort calculates the number of occurrence of objects and stores its key values. New array is formed by adding
# previous key elements and assigning to objects.
#
# Complexity
#
# Time Complexity: O(n+k) is worst case where n is the number of element and k is the range of input.
# Space Complexity: O(k) k is the range of input.
#
# Limitation of Counting Sort
#
# It is effective when range is not greater than number of object.
# It is not comparison based complexity.
# It is also used as sub-algorithm for different algorithm.
# It uses partial hashing technique to count the occurrence.
# It is also used for negative inputs.
#
# Algorithm
#
# STEP 1 START
# STEP 2 Store the input array
# STEP 3 Count the key values by number of occurrence of object
# STEP 4 Update the array by adding previous key elements and assigning to objects
# STEP 5 Sort by replacing the object into new array and key= key-1
# STEP 6 STOP
# Python program for counting sort
# The main function that sort the given string arr[] in
# alphabetical order
def execute_sort_count(myList):
maxValue = 0
for i in range(len(myList)):
if myList[i] > maxValue:
maxValue = myList[i]
buckets = [0] * (maxValue + 1)
for i in myList:
buckets[i] += 1
i = 0
for j in range(maxValue + 1):
for a in range(buckets[j]):
myList[i] = j
i += 1
return myList
def execute_sort_count_char(arr):
# The output character array that will have sorted arr
output = [0 for i in range(256)]
# Create a count array to store count of inidividul
# characters and initialize count array as 0
count = [0 for i in range(256)]
# For storing the resulting answer since the
# string is immutable
ans = ["" for _ in arr]
# Store count of each character
for i in arr:
count[ord(i)] += 1
# Change count[i] so that count[i] now contains actual
# position of this character in output array
for i in range(256):
count[i] += count[i - 1]
# Build the output character array
for i in range(len(arr)):
output[count[ord(arr[i])] - 1] = arr[i]
count[ord(arr[i])] -= 1
# Copy the output array to arr, so that arr now
# contains sorted characters
for i in range(len(arr)):
ans[i] = output[i]
return ans
array_test = [10, 9, 7, 101, 23, 44, 12, 78, 34, 23]
print_sorted("Counting", execute_sort_count(array_test))
########################################################################################################################
# Bubble Sort:
#
# In Bubble sort, Each element of the array is compared with its adjacent element. The algorithm processes
# the list in passes. A list with n elements requires n-1 passes for sorting. Consider an array A of n elements
# whose elements are to be sorted by using Bubble sort. The algorithm processes like following.
#
# In Pass 1, A[0] is compared with A[1], A[1] is compared with A[2], A[2] is compared with A[3] and so on.
# At the end of pass 1, the largest element of the list is placed at the highest index of the list.
# In Pass 2, A[0] is compared with A[1], A[1] is compared with A[2] and so on.
# At the end of Pass 2 the second largest element of the list is placed at the second highest index of the list.
# In pass n-1, A[0] is compared with A[1], A[1] is compared with A[2] and so on. At the end of this pass.
# The smallest element of the list is placed at the first index of the list.
#
# Algorithm :
#
# Step 1: Repeat Step 2 For i = 0 to N-1
# Step 2: Repeat For J = i + 1 to N - I
# Step 3: IF A[J] > A[i]
# SWAP A[J] and A[i]
# [END OF INNER LOOP]
# [END OF OUTER LOOP
# Step 4: EXIT
#
# Complexity
# Scenario Complexity
# Space O(1)
# Worst case running time O(n2)
# Average case running time O(n)
# Best case running time O(n2)
def execute_sort_bubble_simple(a):
for i in range(0, len(a)):
for j in range(i + 1, len(a)):
if a[j] < a[i]:
temp = a[j]
a[j] = a[i]
a[i] = temp
def execute_sort_bubble_best(array):
n = len(array)
for i in range(n):
# Create a flag that will allow the function to
# terminate early if there's nothing left to sort
already_sorted = True
# Start looking at each item of the list one by one,
# comparing it with its adjacent value. With each
# iteration, the portion of the array that you look at
# shrinks because the remaining items have already been
# sorted.
for j in range(n - i - 1):
if array[j] > array[j + 1]:
# If the item you're looking at is greater than its
# adjacent value, then swap them
array[j], array[j + 1] = array[j + 1], array[j]
# Since you had to swap two elements,
# set the `already_sorted` flag to `False` so the
# algorithm doesn't finish prematurely
already_sorted = False
# If there were no swaps during the last iteration,
# the array is already sorted, and you can terminate
if already_sorted:
break
return array
array_test = [10, 9, 7, 101, 23, 44, 12, 78, 34, 23]
execute_sort_bubble_simple(array_test)
print_sorted("Bubble Simple", array_test)
array_test = [10, 9, 7, 101, 23, 44, 12, 78, 34, 23]
print_sorted("Bubble Best", execute_sort_bubble_best(array_test))
# Printing Sorted Element List . . .
# 7
# 9
# 10
# 12
# 23
# 34
# 34
# 44
# 78
# 101
########################################################################################################################
# Merge sort
#
# Merge sort is the algorithm which follows divide and conquer approach. Consider an array A of n number of elements.
# The algorithm processes the elements in 3 steps.
#
# If A Contains 0 or 1 elements then it is already sorted, otherwise, Divide A into two sub-array of equal number of elements.
# Conquer means sort the two sub-arrays recursively using the merge sort.
# Combine the sub-arrays to form a single final sorted array maintaining the ordering of the array.
#
# The main idea behind merge sort is that, the short list takes less time to be sorted.
# Complexity
# Complexity Best case Average Case Worst Case
# Time Complexity O(n log n) O(n log n) O(n log n)
# Space Complexity O(n)
# Example :
#
# Consider the following array of 7 elements. Sort the array by using merge sort.
#
# A = {10, 5, 2, 23, 45, 21, 7}
#
#
# Merge sort
# Algorithm
#
# Step 1: [INITIALIZE] SET I = BEG, J = MID + 1, INDEX = 0
# Step 2: Repeat while (I <= MID) AND (J<=END)
# IF ARR[I] < ARR[J]
# SET TEMP[INDEX] = ARR[I]
# SET I = I + 1
# ELSE
# SET TEMP[INDEX] = ARR[J]
# SET J = J + 1
# [END OF IF]
# SET INDEX = INDEX + 1
# [END OF LOOP]
# Step 3: [Copy the remaining
# elements of right sub-array, if
# any]
# IF I > MID
# Repeat while J <= END
# SET TEMP[INDEX] = ARR[J]
# SET INDEX = INDEX + 1, SET J = J + 1
# [END OF LOOP]
# [Copy the remaining elements of
# left sub-array, if any]
# ELSE
# Repeat while I <= MID
# SET TEMP[INDEX] = ARR[I]
# SET INDEX = INDEX + 1, SET I = I + 1
# [END OF LOOP]
# [END OF IF]
# Step 4: [Copy the contents of TEMP back to ARR] SET K = 0
# Step 5: Repeat while K < INDEX
# SET ARR[K] = TEMP[K]
# SET K = K + 1
# [END OF LOOP]
# Step 6: Exit
#
# MERGE_SORT(ARR, BEG, END)
#
# Step 1: IF BEG < END
# SET MID = (BEG + END)/2
# CALL MERGE_SORT (ARR, BEG, MID)
# CALL MERGE_SORT (ARR, MID + 1, END)
# MERGE (ARR, BEG, MID, END)
# [END OF IF]
# Step 2: END
def execute_sort_merge_impl(left, right):
# If the first array is empty, then nothing needs
# to be merged, and you can return the second array as the result
if len(left) == 0:
return right
# If the second array is empty, then nothing needs
# to be merged, and you can return the first array as the result
if len(right) == 0:
return left
result = []
index_left = index_right = 0
# Now go through both arrays until all the elements
# make it into the resultant array
while len(result) < len(left) + len(right):
# The elements need to be sorted to add them to the
# resultant array, so you need to decide whether to get
# the next element from the first or the second array
if left[index_left] <= right[index_right]:
result.append(left[index_left])
index_left += 1
else:
result.append(right[index_right])
index_right += 1
# If you reach the end of either array, then you can
# add the remaining elements from the other array to
# the result and break the loop
if index_right == len(right):
result += left[index_left:]
break
if index_left == len(left):
result += right[index_right:]
break
return result
def execute_sort_merge(array):
# If the input array contains fewer than two elements,
# then return it as the result of the function
if len(array) < 2:
return array
midpoint = len(array) // 2
# Sort the array by recursively splitting the input
# into two equal halves, sorting each half and merging them
# together into the final result
return execute_sort_merge_impl(
left=execute_sort_merge(array[:midpoint]),
right=execute_sort_merge(array[midpoint:]))
array_test = [10, 9, 7, 101, 23, 44, 12, 78, 34, 23]
print_sorted("Merge", execute_sort_merge(array_test))
def most_balanced_partition(parent, files_size):
def calcWeight(node, adj, files_size):
q = [node]
weight = 0
while q:
idx = q.pop()
weight += files_size[idx]
if idx in adj:
q.extend(adj[idx])
return weight
adj = {}
edges = []
for idx, p in enumerate(parent):
edges.append((p, idx))
if p in adj:
adj[p].append(idx)
else:
adj[p] = [idx]
print(adj, edges)
weight_tot = sum(files_size)
diff_min = sum(files_size)
for e in edges:
p, c = e
adj[p].remove(c)
w1 = calcWeight(c, adj, files_size)
diff_min = min(diff_min, abs(weight_tot - 2 * w1))
adj[p].append(c)
return diff_min
parent = [ -1, 0, 1, 2, 1, 0, 5, 2, 0, 0 ]
files_size = [ 8475, 6038, 8072, 7298, 5363, 9732, 3786, 5521, 8295, 6186 ]
print(most_balanced_partition(parent, files_size))
# Sample Output
# 4182
parent = [ -1, 0, 0, 0, 0, 3, 4, 6, 0, 3 ]
files_size = [ 298, 2187, 5054, 266, 1989, 6499, 5450, 2205, 5893, 8095 ]
print(most_balanced_partition(parent, files_size))
# Sample Output
# 8216
def hamilton(G, size, pt, path=[]):
print('hamilton called with pt={}, path={}'.format(pt, path))
if pt not in set(path):
path.append(pt)
if len(path)==size:
return path
for pt_next in G.get(pt, []):
res_path = [i for i in path]
candidate = hamilton(G, size, pt_next, res_path)
if candidate is not None: # skip loop or dead end
return candidate
print('path {} is a dead end'.format(path))
else:
print('pt {} already in path {}'.format(pt, path))
# loop or dead end, None is implicitly returned
def getMinCost(crew_id, job_id):
crew_id.sort()
job_id.sort()
minCnt = 0
for idx in range(len(job_id)):
minCnt += abs(crew_id[idx]-job_id[idx])
return minCnt
crews = [3, 1, 4, 6, 5]
jobs = [9, 8, 3, 15, 1]
print(getMinCost(crews, jobs))
|
c83146bf42bfc3036eb59359f040e3526f46967c | RandoNandoz/computer-science-11 | /nestedloops.py | 472 | 4.09375 | 4 | """
Randy Zhu
11-03-2020
Nested loops
"""
# for index in range(1, 4):
# for length in range(-3, 0):
# print(index, length)
# last_number = 6
# for row in range(1, last_number):
# for column in range(1, row + 1):
# print(column, end=' ')
# print("")
# import turtle
# my_turtle = turtle.Turtle()
# my_turtle.speed(5)
# for i in range(10, 101, 10):
# my_turtle.forward(i)
# my_turtle.left(90)
# turtle.done()
|
0da57bb50cdf9f5ee91c4e3fd4fd64156b76283c | hejnal/code-retreat-prep | /testing-python/tests/test_sum_unittest.py | 248 | 3.65625 | 4 | #!/usr/bin/env python
import unittest
class TestSum(unittest.TestCase):
def testSum(self):
self.assertEqual(sum([1, 2, 3]), 6, "should be 6")
def testSumTuple(self):
self.assertEqual(sum((1, 2, 3)), 6, "should be 6") |
70d756f8c425c1a069b4b5b10c746c30e4124614 | GouravSardana/chaoss-microtask | /microtask3.py | 1,140 | 3.578125 | 4 | import urllib.request, json
import csv
#https://api.github.com/repos/aimacode/aima-python/contributors (know about the contributors)
d={} #save all the required name and contribution in dict. form
with urllib.request.urlopen("https://api.github.com/repos/aimacode/aima-python/contributors") as url:
#open the link using urllib library
data=json.loads(url.read().decode()) #decode the json code ans save it to data
print(": Name : No Of Commits") #for table formation these are headers which is shown in the console
for r in data:
d[r['login']]= r['contributions']
print(":" ,r['login']," "*(20-len(r['login'])),":", #reads the names and how many contribution
str(r['contributions']))
with open('z.csv','w') as f: #open a csv file (readmode)
w = csv.writer(f,delimiter=',')
fieldnames = ['Name', 'No of commits'] #headers
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader() #set the headers into csv
for key,values in sorted(d.items()): #iterate through dict. (d)
w.writerow([key,values]) #write the required rows into csv
|
6edd7fc99f8408acecdd7309b2416fa89027bfa1 | nvanalfen/SudokuPuzzle | /Box.py | 1,212 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 19 01:30:57 2018
@author: nvana
"""
# Class used to represent a single box on a Sudoku grid that holds one number
class Box:
def __init__(self):
self.solved = False
self.value = 0
self.remaining = 1
self.possibilities = set((1,2,3,4,5,6,7,8,9))
self.x = -1
self.y = -1
# Sets the value in a box, marks it as solved, and clears the possibilities
def set_value(self, value):
self.value = value
self.temporary = value
if value >= 1 and value <= 9:
self.solved = True
self.remaining = 0
self.possibilities = set()
# Removes a possibility from the set of possibilities
# If only one possibility remains, set the value
def remove_possibility(self, value):
try:
self.possibilities.remove(value)
self.check_possibilities()
except:
pass
# Checks the possibilities and if only one remains, set the value
def check_possibilities(self):
if len(self.possibilities) == 1:
self.set_value(self.possibilities.pop()) |
6f9d33ee2df7ba91a628d7a288b0b7a9f29b0a04 | hwangse/python-A-to-Z | /3_variable_prac.py | 550 | 4.1875 | 4 | a=123.456789
print(int(a),float(a))
print()
b=3.14
b=str(b)
print(b,type(b))
b=int(float(b))
print(b,type(b))
b=float(b)
print(b,type(b))
print()
name,num,age=input("Enter 3 things : ").split()
print(name,num,age)
print()
age=int(age)
print("♥"*age)
print()
degree=float(input("본 프로그램은 섭씨를 화씨로 변환해주는 프로그램입니다\n\
변환하고 싶은 섭씨온도를 입력해주세요 : \n"))
print("\n=======================")
print("섭씨온도 ; %.1f" %(degree))
print("화씨온도 : %.2f" %((9/5)*degree+32))
|
7d3fa79cb95f79e6a8795d1a5415b9d3bc504b04 | aswathysoman97/LuminarPython | /pythondjangojuneclass/dob.py | 124 | 3.65625 | 4 | dob=input("birth year dd-mm-yy: ")
byr=dob.split("-")
today=int(input("recent year:"))
age=(today-int (byr[2]))
print(age)
|
48df38223667323269642ed9cce27e3fcfc4d5e0 | Benature/Computational-Physics-Course-Code | /chp8/波动方程/二阶差分_波动_总矩阵.py | 1,743 | 3.5 | 4 | # 二阶差分格式解法,使用一个数组u保存所有计算步骤结果.
import numpy as np
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import math
# %matplotlib notebook
# fixed parameters
c = 1.0 # speed of propagation, m/s
L = 1.0 # length of wire, m
# input parameters
alpha = 1.0 # 库兰特数
dx = 0.02
dt = 0.02
tmax = L/c*1.2
s = 0.02
x0 = 0.5
# construct initial data
N = 50
N2 = int(tmax/dt)
x = np.zeros(N+1)
u0 = np.zeros(N+1)
u1 = np.zeros(N+1)
u2 = np.zeros(N+1)
u = np.zeros((N2+3, N+1))
for i in range(N+1):
x[i] = i*dx
u0[i] = math.exp(-0.5*((x[i]-x0)/s)**2) # 0.0
u1[i] = math.exp(-0.5*((x[i]-x0)/s)**2) # 0.0
u[0, i] = math.exp(-0.5*((x[i]-x0)/s)**2)
u[1, i] = math.exp(-0.5*((x[i]-x0)/s)**2)
# preform the evolution
plt.figure()
plt.plot(x, u[0, :])
plt.ylim(-1.2, 1.2)
plt.xlabel('x (m)')
plt.ylabel('u')
plt.show()
# prepare animated plot
fig, ax = plt.subplots()
line, = ax.plot(x, u[0, :], '-k', animated=False)
ax.grid()
plt.ylim(-1.2, 1.2)
plt.xlabel('x (m)')
plt.ylabel('u (t, x)')
# preform the evolution
t = 0.0
i = 0
def update(frame):
global u0
global u1
global u2
global t
global i
if t < tmax:
for j in range(1, N): # skip the bound
u[i+2, j] = 2*(1-alpha**2)*u[i+1, j]-u[i, j] + \
alpha**2.0*(u[i+1, j-1]+u[i+1, j+1])
u2 = u[i+2, :]
t += dt
i += 1
plt.title('t = %6f' % t+' i = %6f' % i)
line.set_data(x, u2)
return line,
pam_ani = animation.FuncAnimation(fig, update, frames=range(N2),
interval=100, repeat=False, blit=False)
#pam_ani.save('heat_ftcs.gif', writer='pillow',fps=100)
plt.show()
|
f396cc089d241ed29488b916faddee29ecd2ad81 | codernoobi/python | /Python/introduction/strings.py | 502 | 4.1875 | 4 | txt=" Hello, world"
print(len(txt)) #string length
x=txt[1] #character in the index
print(x)
x=txt[2:4] #substring
print(x)
print(txt.strip()) #trim spaces
print(txt.upper()) #to upper case
print(txt.lower()) #to lower case
print(txt.replace("H","j")) #to replace
print(txt.split("e")) #splits at e
txt = "Hello World"[::-1] #reverse string
#Slice the String
print(txt)
def my_function(x):
return x[::-1]
mytxt = my_function("I wonder how this text looks like backwards")
print(mytxt) |
9d7a87ef2ae41caa73e83ce764e01e5edaaeaca5 | krab1k/aoc2020 | /18/evaluate.py | 1,216 | 3.515625 | 4 | import string
def e(op, s, arg):
if op == '+':
s += arg
else:
s *= arg
return s
def evaluate_expression(expr):
s = None
op = None
arg = None
length = len(expr)
i = 0
while i < length:
c = expr[i]
i += 1
if c == ' ':
continue
if c == '+':
op = '+'
if c == '*':
op = '*'
if c.isdigit():
arg = int(c)
if op is not None:
s = e(op, s, arg)
if c == '(':
j = i
p = 1
while p != 0:
if expr[j] == '(':
p += 1
elif expr[j] == ')':
p -= 1
j += 1
arg = evaluate_expression(expr[i:j -1])
i = j + 1
if op is not None:
s = e(op, s, arg)
if s is None:
s = arg
return s
def main():
expressions = []
with open('input.txt') as f:
for line in f:
expressions.append(line.strip())
s = 0
for expr in expressions:
s += evaluate_expression(expr)
print(s)
if __name__ == '__main__':
main()
|
6a5ea6e155f1132b9b37096552b6ef469e2af6db | rekonin332/pGUi | /gui/GUI_Simple.py | 1,442 | 3.53125 | 4 | '''
Created on 2017年5月25日
@author: Todd
'''
import tkinter as tk
from tkinter import Menu
from tkinter import ttk # themed Tk
from textwrap import fill
from turtledemo.nim import Stick
#funtions
#exit GUI clearly
def _quit():
win.quit()
win.destroy()
exit()
win = tk.Tk()
win.title("Python Projects")
# creating a Menu Bar
menuBar = Menu()
win.config(menu=menuBar)
# add menu items
fileMenu = Menu(menuBar, tearoff=0)
fileMenu.add_command(label="New")
fileMenu.add_separator()
fileMenu.add_command(label="Exit", command=_quit)
menuBar.add_cascade(label="File",menu=fileMenu)
helpMenu = Menu(menuBar, tearoff=0)
menuBar.add_cascade(label="Help", menu=helpMenu)
helpMenu.add_command(label="About")
# Tab control / notebook introduce here
tabControl = ttk.Notebook(win) #create tab control
tab1 = ttk.Frame(tabControl) #Create a tab
tabControl.add(tab1, text='Tab 1') #add the tab
tab2 = ttk.Frame(tabControl)
tabControl.add(tab2, text='Tab 2')
tabControl.pack(expand=1, fill="both") # pack to make visible
# we are creating a container frame to hold all other widgets
weather_conditions_frame = ttk.LabelFrame(tab1, text=' Current Weather Conditions ')
#using the tkinter grid layout manager
weather_conditions_frame.grid(column=0, row=0, padx=8, pady=14)
#Adding a Label
ttk.Label(weather_conditions_frame, text=" Location:").grid(column=0, row=0, sticky='w')
#start GUI
win.mainloop()
|
08780a9a9c1f8d9e0cf00a4e588766353c147d3b | Ryan-R-C/my_hundred_python_exercises | /Teoria/A21 2.py | 340 | 3.84375 | 4 | def somar(a=0,b=0,c=0):
s = a+b+c
return s
def par(n=0):
if n % 2 == 0:
return True
else:
return False
r1 = somar(3,2,5)
r2 = somar(2,2)
r3 = (6)
print(f"The results of the sums are {r1}, {r2} and {r3}.")
num = int(input("Type a num: "))
if par(num):
print("It's even!")
else:
print("It's odd!") |
1dbe913d1d6b8d477f1d6c40ea37b2cd9b6cac0d | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/1f310aa87ffa4dfb92e4e614ac79f7a9.py | 371 | 3.765625 | 4 | # -*- coding: utf-8 -*
GENERAL_ANSWER = u'Whatever.'
QUESTION_ANSWER = u'Sure.'
YELL_ANSWER = u'Woah, chill out!'
EMPTY_ANSWER = u'Fine. Be that way!'
def hey(sentence):
if not sentence.strip():
return EMPTY_ANSWER
if sentence.isupper():
return YELL_ANSWER
if sentence.endswith('?'):
return QUESTION_ANSWER
return GENERAL_ANSWER
|
b12285c6943c9db401b6fb7b646b4d1c330d1ea7 | sarathvad1811/ds_algo_prep | /basic_programs/number_reverse.py | 361 | 3.765625 | 4 | def num_reverse(num):
rev_num = 0
is_neg = num < 0
temp = num
mul = 1
if is_neg:
temp = abs(num)
mul = -1
while temp != 0:
rem = int(temp % 10)
rev_num = (rev_num * 10) + rem
# print(rem)
temp = int(temp / 10)
return mul * rev_num
print(num_reverse(123))
print(num_reverse(-123))
|
30d41c3f120bd72676e7f4bba528240413765457 | SaitejaP/InterviewBit | /arrays/maximum_unsorted_subarray.py | 1,505 | 3.609375 | 4 | # -*- coding: utf-8 -*-
# You are given an array (zero indexed) of N non-negative integers, A0, A1, …, AN-1.
# Find the minimum sub array Al, Al+1, …, Ar so if we sort(in ascending order)
# that sub array, then the whole array should get sorted.
# If A is already sorted, output -1.
class Solution:
# @param A : list of integers
# @return a list of integers
def subUnsort(self, A):
# check where the ascending order breaks
i = 0
while i < len(A)-1 and A[i] <= A[i+1]:
i += 1
# check where the descending order breaks
j = len(A) - 1
while j > 1 and A[j] >= A[j-1]:
j -= 1
# i loops till the end i.e., ascending
# order does not break, return [-1]
if i == len(A)-1:
return [-1]
# find the min and max elements
# in the damaged area
min_ele = A[i]
max_ele = A[i]
while i <= j:
if A[i] < min_ele:
min_ele = A[i]
if A[i] > max_ele:
max_ele = A[i]
i += 1
# find the position where min element can be inserted
i = 0
while i < len(A) and A[i] <= min_ele:
i += 1
# find the position where max element can be inserted
j = len(A) - 1
while j > 0 and A[j] >= max_ele:
j -= 1
return [i, j]
print Solution().subUnsort([16, 15, 16, 20])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.