blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
e84ea0ce2afb28b4bb2c13a0f8b44fbbb08788bc | aayanqazi/python-preparation | /A List in a Dictionary.py | 633 | 4.25 | 4 | from collections import OrderedDict
#List Of Dictionary
pizza = {
'crust':'thick',
'toppings': ['mashrooms', 'extra cheese']
}
print("You ordered a " + pizza['crust'] + "-crust pizza " +
"with the following toppings:")
for toppings in pizza['toppings']:
print ("\t"+toppings)
#Examples 2
favourite_languages= {
'jen': ['python', 'ruby'],
'sarah': ['c'],
' edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name,languages in favourite_languages.items():
print("\n"+name.title()+"'s favourite languages are :")
for language in languages:
print ("\t"+language.title()) |
2a5a3c3379ac23b7f50123e6e537dea5119119b0 | routedo/cisco-template-example | /configgen.py | 863 | 3.578125 | 4 | """
Generates a configuration file using jinja2 templates
"""
from jinja2 import Environment, FileSystemLoader
import yaml
def template_loader(yml_file, template_file, conf_file):
"""
This function generates a configuration file using jinja2 templates.
yml_file = Location of the file containing variables to use with the jinja2 template
template_file = Location of jinja2 template file
conf_file = Location to place generated config file.
"""
env = Environment(loader=FileSystemLoader('./'))
# Load variables from yml_file
with open(yml_file) as yfile:
yml_var = yaml.load(yfile)
template = env.get_template(template_file)
# Render template
out_text = template.render(config=yml_var)
# Write results of out_text to file
file = open(conf_file, 'w')
file.write(out_text)
file.close()
|
5a8e4bc36057b004f79a5172b0d7de1754fb3fa5 | BaburinAnton/GeekBrains-Python-homeworks | /Lesson 6/hw 3.py | 831 | 3.59375 | 4 | class Worker:
name = None
surname = None
position = None
profit = None
bonus = None
def __init__(self, name, surname, position, profit, bonus):
self.name = name
self.surname = surname
self.position = position
self.profit = profit
self.bonus = bonus
class Position(Worker):
def __init__(self, name, surname, position, profit, bonus):
super().__init__(name, surname, position, profit, bonus)
def get_full_name(self):
return self.name + self.surname
def get_full_profit(self):
self.__income = {'profit': self.profit, 'bonus': self.bonus}
return self.__income
technician = Position('Anton', 'Baburin', 'technician', 28000, 4000)
print(technician.get_full_name(), technician.get_full_profit()) |
194f4c01744ab1d09ed9ca3329624b6768e83b60 | BaburinAnton/GeekBrains-Python-homeworks | /Lesson 4/hw 4.py | 129 | 3.515625 | 4 | numbers = [14, 42, 1, 7, 13, 99, 16, 1, 70, 55, 14, 13, 1, 7]
list = [el for el in numbers if numbers.count(el)==1]
print(list) |
a322c9f894dc53a7e56f5f9bca0ee15d4e666209 | Glitchier/Python-Programs-Beginner | /Day 5/sum_of_even.py | 185 | 3.96875 | 4 | sum=0
for i in range(2,101,2):
sum+=i
print(f"Sum of even numbers: {sum}")
sum=0
for i in range(1,101):
if(i%2==0):
sum+=i
print(f"Sum of even numbers: {sum}") |
05a1e4c378524ef50215bd2bd4065b9ab696b80d | Glitchier/Python-Programs-Beginner | /Day 2/tip_cal.py | 397 | 4.15625 | 4 | print("Welcome to tip calculator!")
total=float(input("Enter the total bill amount : $"))
per=int(input("How much percentage of bill you want to give ? (5%, 10%, 12%, 15%) : "))
people=int(input("How many people to split the bill : "))
bill_tip=total*(per/100)
split_amount=float((bill_tip+total)/people)
final_bill=round(split_amount,2)
print(f"Each person should pay : ${final_bill}") |
f54e2970cd64a45890d02ba9b969257a46642e6f | Glitchier/Python-Programs-Beginner | /Day 9/auction.py | 799 | 3.765625 | 4 | from art import logo
from replit import clear
print(logo)
bid_dic={}
run_again=True
def high_bid(bid_dic_record):
high_amount=0
winner=""
for bidder in bid_dic_record:
bid_amount=bid_dic_record[bidder]
if(bid_amount>high_amount):
high_amount=bid_amount
winner=bidder
print(f"The winner is {winner} with a bid of ${high_amount}")
print("The auction start's here .....")
while(run_again):
key_name=input("Enter your name : ")
key_value=float(input("Enter your bid : $"))
bid_dic[key_name]=key_value
run_again_ch=input("Is there any another bidder? Type Yes or No\n").lower()
if(run_again_ch=="no"):
run_again=False
high_bid(bid_dic)
elif(run_again_ch=="yes"):
clear() |
e88c319709f2822abaea0703fdb94685f3c0de91 | litewhat/internal-linking | /Multiprocessing/m_threading.py | 885 | 3.578125 | 4 | import time
import threading
import multiprocessing
def calc_square(numbers):
print("Calculating square numbers")
for n in numbers:
time.sleep(0.2)
print(f"Square: {n*n}")
def calc_cube(numbers):
print("Calculating cube numbers")
for n in numbers:
time.sleep(0.2)
print(f"Square: {n*n*n}")
if __name__ == "__main__":
arr = [2, 3, 8, 9]
t = time.time()
# calc_square(arr)
# calc_cube(arr)
# t1 = threading.Thread(target=calc_square, args=(arr,))
# t2 = threading.Thread(target=calc_cube, args=(arr,))
p1 = multiprocessing.Process(target=calc_square, args=(arr,))
p2 = multiprocessing.Process(target=calc_cube, args=(arr,))
# t1.start()
# t2.start()
#
# t1.join()
# t2.join()
p1.start()
p2.start()
p1.join()
p2.join()
print(f"Done in: {time.time() - t}")
|
e6cad988204f288958eeb15f365d991b490f6a51 | SharonT2/Practica1IPC2 | /lista.py | 1,696 | 3.875 | 4 | from nodo import Nodo
class Lista():
def __init__(self):#métoedo constructor
#dos referencias
self.primero = None #un nodo primero que inserte el usuario
self.ultimo = None #un nodo que apunta al ultimo nodo
#Creando el primer nodo self, id, nombre, m, n, primero, fin
def insertar(self, ingrediente):
pizza="Pizza de "+ingrediente
nuevo = Nodo(pizza)
if self.primero is None: #si el primero está vacío
self.primero = nuevo #entonces el primero será igual al objeto que mandó el usuario
else: #si el primero no está vacío
tem = self.primero #temporal, para una referencia
while tem.siguiente is not None:#se ejecutará mientras el siguiente sea no sea nulo, cuando encuentre
tem = tem.siguiente #el siguiente que sea nulo
tem.siguiente=nuevo#ahora el siguiente del último nodo ya no será nulo, sino será el nuevo nodo
def eliminar(self):
try:
retorno = self.primero.ingrediente
if self.primero is not None:
if self.primero.siguiente is not None:
self.primero = self.primero.siguiente
else:
self.primero = None
print("Se ha entregado la pizza", retorno)
except:
print("Cola vacía, totalidad de ordenes entregadas")
def mostrar(self):
tem = self.primero#empezando por el principio
i=1
while tem is not None:
print(" |"+str(i)+")",tem.ingrediente+"| ", end=" ")
i+=1
#Listasube.mostrar()
tem = tem.siguiente
|
ad19b0f9e3453d3148f84f0545159d96b90055a1 | HarkTu/Coding-Education | /SoftUni.bg/Python Oop/03-ENCAPSULATION-exercise/01. Wild Cat Zoo.py | 6,196 | 3.546875 | 4 | class Lion:
def __init__(self, name, gender, age):
self.age = age
self.gender = gender
self.name = name
def get_needs(self):
return 50
def __repr__(self):
return f"Name: {self.name}, Age: {self.age}, Gender: {self.gender}"
class Tiger:
def __init__(self, name, gender, age):
self.age = age
self.gender = gender
self.name = name
def get_needs(self):
return 45
def __repr__(self):
return f"Name: {self.name}, Age: {self.age}, Gender: {self.gender}"
class Cheetah:
def __init__(self, name, gender, age):
self.age = age
self.gender = gender
self.name = name
def get_needs(self):
return 60
def __repr__(self):
return f"Name: {self.name}, Age: {self.age}, Gender: {self.gender}"
class Keeper:
def __init__(self, name, age, salary):
self.age = age
self.salary = salary
self.name = name
def __repr__(self):
return f"Name: {self.name}, Age: {self.age}, Salary: {self.salary}"
class Caretaker:
def __init__(self, name, age, salary):
self.age = age
self.salary = salary
self.name = name
def __repr__(self):
return f"Name: {self.name}, Age: {self.age}, Salary: {self.salary}"
class Vet:
def __init__(self, name, age, salary):
self.age = age
self.salary = salary
self.name = name
def __repr__(self):
return f"Name: {self.name}, Age: {self.age}, Salary: {self.salary}"
class Zoo:
def __init__(self, name, budget, animal_capacity,
workers_capacity): # in document says 'animlal_capacity'. 1 test fails without correction
self.animals = []
self.workers = []
self.name = name
self.__workers_capacity = workers_capacity
self.__animal_capacity = animal_capacity
self.__budget = budget
def add_animal(self, animal, price):
if len(self.animals) == self.__animal_capacity:
return "Not enough space for animal"
if price > self.__budget:
return "Not enough budget"
self.animals.append(animal)
self.__budget -= price
return f"{animal.name} the {type(animal).__name__} added to the zoo"
def hire_worker(self, worker):
if len(self.workers) < self.__workers_capacity:
self.workers.append(worker)
return f"{worker.name} the {type(worker).__name__} hired successfully"
return "Not enough space for worker"
def fire_worker(self, worker_name):
for worker_x in self.workers:
if worker_x.name == worker_name:
self.workers.remove(worker_x)
return f"{worker_name} fired successfully"
return f"There is no {worker_name} in the zoo" # on document there was mistaken double space on this line. 1 test fails without correction
def pay_workers(self):
sum_salary = sum([x.salary for x in self.workers])
if sum_salary > self.__budget:
return "You have no budget to pay your workers. They are unhappy"
self.__budget -= sum_salary
return f"You payed your workers. They are happy. Budget left: {self.__budget}"
def tend_animals(self):
sum_tend = sum([x.get_needs() for x in self.animals])
if sum_tend > self.__budget:
return "You have no budget to tend the animals. They are unhappy."
self.__budget -= sum_tend
return f"You tended all the animals. They are happy. Budget left: {self.__budget}"
def profit(self, amount):
self.__budget += amount
def animals_status(self):
result = ''
result += f"You have {len(self.animals)} animals\n"
result += f"----- {sum([1 for x in self.animals if type(x) == Lion])} Lions:\n"
result += '\n'.join([str(x) for x in self.animals if isinstance(x, Lion)])
result += f"\n----- {sum([1 for x in self.animals if isinstance(x, Tiger)])} Tigers:\n"
result += '\n'.join([x.__repr__() for x in self.animals if isinstance(x, Tiger)])
result += f"\n----- {sum(isinstance(x, Cheetah) for x in self.animals)} Cheetahs:\n"
result += '\n'.join([x.__repr__() for x in self.animals if isinstance(x, Cheetah)])
return result + '\n'
def workers_status(self):
result = ''
result += f"You have {len(self.workers)} workers\n"
result += f"----- {sum([1 for x in self.workers if type(x) == Keeper])} Keepers:\n"
result += '\n'.join([x.__repr__() for x in self.workers if isinstance(x, Keeper)])
result += f"\n----- {sum([1 for x in self.workers if isinstance(x, Caretaker)])} Caretakers:\n"
result += '\n'.join([x.__repr__() for x in self.workers if isinstance(x, Caretaker)])
result += f"\n----- {sum(isinstance(x, Vet) for x in self.workers)} Vets:\n"
result += '\n'.join([x.__repr__() for x in self.workers if isinstance(x, Vet)])
return result + '\n' # there is no new line in example solution. 1 test fails without correction
zoo = Zoo("Zootopia", 3000, 5, 8)
# Animals creation
animals = [Cheetah("Cheeto", "Male", 2), Cheetah("Cheetia", "Female", 1), Lion("Simba", "Male", 4),
Tiger("Zuba", "Male", 3), Tiger("Tigeria", "Female", 1), Lion("Nala", "Female", 4)]
# Animal prices
prices = [200, 190, 204, 156, 211, 140]
# Workers creation
workers = [Keeper("John", 26, 100), Keeper("Adam", 29, 80), Keeper("Anna", 31, 95), Caretaker("Bill", 21, 68),
Caretaker("Marie", 32, 105), Caretaker("Stacy", 35, 140), Vet("Peter", 40, 300), Vet("Kasey", 37, 280),
Vet("Sam", 29, 220)]
# Adding all animals
for i in range(len(animals)):
animal = animals[i]
price = prices[i]
print(zoo.add_animal(animal, price))
# Adding all workers
for worker in workers:
print(zoo.hire_worker(worker))
# Tending animals
print(zoo.tend_animals())
# Paying keepers
print(zoo.pay_workers())
# Fireing worker
print(zoo.fire_worker("Adam"))
# Printing statuses
print(zoo.animals_status())
print(zoo.workers_status())
|
32a6b5e833eb5d3a78e8f4b03444da335fe910cb | HarkTu/Coding-Education | /SoftUni.bg/Python Advanced/December 2020/GameOfWords.py | 1,068 | 3.59375 | 4 | initial = input()
size = int(input())
matrix = []
p_row = 0
p_column = 0
for row in range(size):
temp = input()
add_row = []
for column in range(len(temp)):
if temp[column] == 'P':
p_row = row
p_column = column
add_row.append('-')
continue
add_row.append(temp[column])
matrix.append(add_row)
directions = {'up': [-1, 0],
'down': [1, 0],
'left': [0, -1],
'right': [0, 1]
}
commands_count = int(input())
for _ in range(commands_count):
command = input()
next_row = p_row + directions[command][0]
next_column = p_column + directions[command][1]
if 0 <= next_row < size and 0 <= next_column < size:
p_row, p_column = next_row, next_column
if not matrix[next_row][next_column] == '-':
initial += matrix[p_row][p_column]
matrix[p_row][p_column] = '-'
else:
initial = initial[:-1]
matrix[p_row][p_column] = 'P'
print(initial)
for row in matrix:
print(*row, sep='')
|
c2853ed178330ec79e5ed687780430139a103c48 | HarkTu/Coding-Education | /SoftUni.bg/Python Advanced/August 2020/TaxiExpress.py | 504 | 3.75 | 4 | customers = [int(x) for x in input().split(', ')]
taxis = [int(x) for x in input().split(', ')]
time = sum(customers)
while customers and taxis:
customer = customers[0]
taxi = taxis.pop()
if taxi >= customer:
customers.remove(customers[0])
if customers:
print(
f"Not all customers were driven to their destinations\nCustomers left: {', '.join([str(x) for x in customers])}")
else:
print(f"All customers were driven to their destinations\nTotal time: {time} minutes")
|
14a7f65f931c18bf4e7fa39e421d1a688e47356c | rg3915/Python-Learning | /your_age2.py | 757 | 4.3125 | 4 | from datetime import datetime
def age(birthday):
'''
Retorna a idade em anos
'''
today = datetime.today()
if not birthday:
return None
age = today.year - birthday.year
# Valida a data de nascimento
if birthday.year > today.year:
print('Data inválida!')
return None
# Verifica se o dia e o mês já passaram;
# se não, tira 1 ano de 'age'.
if today.month < birthday.month or (today.month == birthday.month and today.day < birthday.day):
age -= 1
return age
if __name__ == '__main__':
birthday = input('Digite sua data de nascimento no formato dd/mm/yyyy: ')
birthday = datetime.strptime(birthday, '%d/%m/%Y')
if age(birthday):
print(age(birthday))
|
3ef31c99b25fbb7b23b367ef87e312753a13a3ab | Jiang-Xiaocha/Lcode | /searchMatrix.py | 1,226 | 3.8125 | 4 | '''
Description:
38. 搜索二维矩阵 II
写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。
这个矩阵具有以下特性:
每行中的整数从左到右是排序的。
每一列的整数从上到下是排序的。
在每一行或每一列中没有重复的整数。
样例
考虑下列矩阵:
[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
给出target = 3,返回 2
挑战
要求O(m+n) 时间复杂度和O(1) 额外空间
'''
class Solution:
"""
@param matrix: A list of lists of integers
@param target: An integer you want to search in matrix
@return: An integer indicate the total occurrence of target in the given matrix
"""
def searchMatrix(self, matrix, target):
# write your code here
if (len(matrix) == 0):
return 0
row = 0
col = len(matrix[0]) - 1
res = 0
while (col>=0 and row <=len(matrix)-1):
if matrix[row][col] == target:
res += 1
col = col - 1
if matrix[row][col] > target:
col = col - 1
if matrix[row][col] < target:
row = row + 1
return res |
a858c6ebc8e7f19176cdd4a2c880ff14e7f14011 | challengeryang/webservicefib | /client_sim/httpclientthread.py | 1,955 | 3.5 | 4 | #!/usr/bin/python
#
# author: Bo Yang
#
"""
thread to send requests to server
it picks up request from job queue, and then picks
up one available connection to send this request
"""
import threading
import Queue
class HttpClientThread(threading.Thread):
"""
Thread to send request to server. it's just a work thread,
and doesn't maintain any state
it picks up job from job queue, and get an available connection
from connection queue, finally send the request through this
connection
"""
def __init__(self, job_queue, connection_queue):
threading.Thread.__init__(self)
self.job_queue = job_queue
self.connection_queue = connection_queue
def run(self):
print '%s: starting' % self.getName()
num_request = 0
while True:
job = None
try:
# get job from job queue
job = self.job_queue.get(True, 3)
except Queue.Empty:
print '%s: no more jobs(sent %d requests), existing' \
% (self.getName(), num_request)
break
num_request += 1
# pick up a conenction from connection queue
conn = self.connection_queue.get(True)
#try:
msg = ""
if job['op'] == 'HEAD':
conn.HEAD(job['val'])
msg = job['op'] + " " + str(job['val'])
elif job['op'] == 'GET':
conn.GET(job['val'])
msg = job['op'] + " " + str(job['val'])
elif job['op'] == 'POST':
conn.POST(job['val'])
msg = job['op'] + " " + str(job['val'])
else:
msg = '%s unsupported operation' % job['op']
print "## " + msg
# put back the connection so other threads can
# use this connection as well
self.connection_queue.put(conn, True)
|
0b6c0ac5676c1071e9728bb00e8bd258ee40339d | yevheniir/python_course_2020 | /.history/1/test_20200606182729.py | 266 | 3.96875 | 4 | people = []
while True:
name = input()
if name == "stop":
break
if name == "show all":
print(people)
pe
print("STOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOP")
# for name in people:
# if name != "JoJo":
# print(name) |
8ca513cdf45e5f286a6fb29abbebdf69e1e84b44 | yevheniir/python_course_2020 | /l5/untitled-master/HW01_star_novela.py | 2,464 | 3.890625 | 4 | import random
print("Вітаю, Ви Колобок і Вас поставили на вікні простигати. Ваші дії:")
print("1 - втекти")
print("2 - залишитися")
a = input("Виберіть дію: ")
if a == "1":
print("Ви зустріли зайця. Ваші дії:")
print("1 - заспівати пісню і втекти")
print("2 - прикинутися пітоном")
print("3 - прикинутися мухомором")
elif a == "2" :
print("Вас з'їли дід та баба. Гра закінчена.")
quit()
else:
print("Виберіть 1 або 2. Гра закінчена.")
quit()
b = input("Виберіть дію: ")
if b == "1":
print("Ви втекли від зайця. Ви зустріли лисицю. Ваші дії")
print("1 - заспівати пісню і втекти.")
print("3 - сказати 'Я хворий на коронавірус'")
print("4 - сказати 'Я зроблений з ГМО зерна'")
elif b == "2" or b == "3":
y = random.choice([True, False])
if y == True:
print("Ви втекли від зайця. Ви зустріли лисицю. Ваші дії")
print("1 - заспівати пісню і втекти.")
print("3 - сказати 'Я хворий на коронавірус'")
print("4 - сказати 'Я зроблений з ГМО зерна'")
else:
print("Заєць Вам не повірив і Вас з'їв. Гра закінчена. ")
quit()
else:
print("Виберіть 1, 2 або 3. Гра закінчена.")
quit()
s = input("Виберіть дію: ")
if s == "1":
y = random.choice([True, False])
if y == True:
print("Ви втекли від лисиці. Гра закінчена.")
quit()
else:
print("Ви не втекли3"
" від лисиці і вона Вас з'їла. Гра закінчена.")
quit()
elif s == "2" or "3" or "4":
y = random.choice([True, False])
if y == True:
print("Лисиця Вам повірила і Ви втекли. Гра закінчена.")
quit()
else:
print("Лисиця Вам не повірила і з'їла. Гра закінчена. ")
quit()
else:
print("Виберіть 1, 2, 3, 4. Гра закінчена.")
quit() |
6c12b0a15ff48d7b1707f162d2f7c7c30a28ea02 | yevheniir/python_course_2020 | /.history/1/dz/1st_game_20200613180427.py | 1,110 | 3.75 | 4 | import time
import random
while True:
print("Вітаю у грі камінь, ножиці, бумага!")
time.sleep(2)
відповідь_до_початку_гри=input("Хочете зіграти?(Відповідати Так або Ні)")
if відповідь_до_початку_гри=="Так":
print("Чудово")
else:
print("Шкода")
time.sleep(9999999999999999999999999999999999999999999999999999999999999999999999999999999)
time.sleep(2)
input("Обирайте предмет.(Камінь-1st-1, Ножиці-2nd-2, чи Бумага-3d-3)")
first=Камінь=1
second=Ножиці=2
third=Бумага=3
ваша_відповідь = 1 or 2 or 3
1 < 3
2 > 1
3 < 2
відповідь_бота=(random.randint(1,3))
if ваша_відповідь<відповідь_бота:
print("Упс. Ви програли")
print(відповідь_бота)
else:
print("Ура ви виграли!")
print(відповідь_бота)
|
32bc00c8b8700da494e559fcd8e2558a43b93e03 | suminov/lesson2 | /lessonfor.py | 564 | 3.96875 | 4 | for x in range(10):
print(x+1)
print(
)
word = input('Введите любое слово: ')
for letter in word:
print(letter)
print(
)
rating = [{'shool_class': '4a', 'scores': [2, 3, 3, 5, 4]},
{'shool_class': '4b', 'scores': [2, 4, 5, 5, 4]},
{'shool_class': '4v', 'scores': [2, 2, 3, 5, 3]}]
a = 0
for result in rating:
print('Средний балл {} класса: {}'
.format(result['shool_class'], sum(result['scores'])/len(result['scores'])))
sum_scores += sum(result['scores'])/len(result['scores'])
print(sum_scores/len(rating)) |
edc0c851a098ede4bb3e4e026e4d0bb6f35451d9 | MDaalder/MIT6.00.1x_Intro_CompSci | /W06_AlgoComplexity_BigO/Sort variants bubble, selection, merge.py | 3,349 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 15 16:21:21 2019
@author: md131
Comparison of sorting methods and their complexities in Big Oh notation.
"""
""" Bubble sort compares consecutive pairs of elements. Overall complexity is O(n^2) where n is len(L)
Swaps elements in the pair such that smaller is first.
When reach the end of the list, start the sort again.
Stop when no more sorts have to be made. """
def bubbleSort(L):
swap = False
while not swap:
swap = True
for j in range(1, len(L)):
if L[j-1] > L[j]: # if L[j-1] is larger than L[j], put element L[j] to the left of L[j-1] by swapping their index values
swap = False
temp = L[j]
L[j] = L[j-1]
L[j-1] = temp
""" Selection sort. Overall complexity is O(n^2) where n is len(L)
1st step: extract the minimum element from the suffix, swap it with index 0 [0] and put into the prefix.
2nd step: extract the minimum element from the remainin sublist (suffix), swap it with index 1 [1], becomes the last element of the prefix.
prefix: L[0:i]
suffix: L[i+1, len(L)]
Always iterating up i. Prefix is always sorted, where no element is larger than in the suffix. """
def selectionSort(L):
suffixSt = 0
while suffixSt != len(L):
for i in range(suffixSt, len(L)):
if L[i] < L[suffixSt]:
L[suffixSt], L[i] = L[i], L[suffixSt] # L[suffixSt] is larger than L[i], swap the two. Put the lower value on the left of the list
suffixSt += 1
""" Merge Sort: overall complexity is O(n log n) where n is len(L)
Successively divide a large list into two halves until you have lists of length < 2. These are considered sorted.
Then compare the smallest value of two lists one at a time, and add the smallest value to the end of a new sublist. This is the merging part.
If a sublist is empty while comparing, add the remaining values from the other sublist to the result.
Then merge your new, but longer, sublists in the same way as above.
Repeat until you have a final sorted list. This essentially contains all of the merged, sorted sublists."""
# complexity O(log n), n is len(L)
def mergeSort(L):
if len(L) < 2: # base case, list of length < 2 is considered sorted
return L[:]
else:
middle = len(L)//2 # integer divide by two
left = mergeSort(L[:middle]) # divide the list and mergeSort again, until len(L) < 2
right = mergeSort(L[middle:]) # divide the list "
return merge(left, right) # requires the next function 'merge, conquer with the merge step
# complexity O(n), n is len(L)
def merge(left, right):
result = []
i, j = 0,0
while i < len(left) and j < len(right): # assumes right and left sublists are already ordered
if left[i] < right[i]:
result.append(left[i])
i += 1 # move indices for sublists depending on which sublist holds the next smallest element
else:
result.append(right[j])
j += 1
while (i < len(left)): # when the right sublist is empty, append the left one to it
result.append(left[i])
i += 1
while (j < len(right[j])):
result.append(right[j]) # when the left sublist is empty, append the right one to it
j += 1
return result |
00a3af0ce1ebf2608eddbc9264cedf965c1d27b7 | MDaalder/MIT6.00.1x_Intro_CompSci | /W07_Plotting/primes_list.py | 881 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 24 16:48:04 2019
@author: Matt
"""
""" returns a list of prime numbers between 2 and N
inclusive, sorter in increasing order"""
def primes_list(N):
'''
N: an integer
'''
primes = []
rangeNums = []
if N == 2:
primes.append(N)
return primes[:]
for i in range(N-1):
rangeNums.append(i+2)
for num in rangeNums:
for j in range(2,N):
prime = True
# print(num, j)
if num == j:
break
if num%j == 0:
prime = False
break
if prime == True:
primes.append(num)
# print(rangeNums[:])
# print(primes[:])
return primes[:]
print(primes_list(2)) |
77f89966c4fdf45f1d47c2165f85644ceb9f20fa | MDaalder/MIT6.00.1x_Intro_CompSci | /W02_Simple_Programs/Converting int to binary.py | 888 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 5 20:59:49 2019
@author: Matt
"""
# this program converts an integer number into a binary
# if binary 101 = 1*2**2 + 0*2**1 + 1*2**0 = 5
# then, if we take the remainder relative to 2 (x%2) of this number
# that gives us the last binary bit
# if we then divide 5 by 2 (5//2) all the bits get shifted right
# 5//2 = 1*2**1 + 0*2**0 = 10
# keep doing successive divisions; now remainder gets next bit, and so on
# we've converted to binary.
inNum = int(input('Enter an integer to convert to binary: '))
num = inNum
if num < 0:
isNeg = True
num = abs(num)
else:
isNeg = False
result = ''
if num == 0:
result = '0'
while num > 0:
result = str(num%2) + result
num = num//2
if isNeg:
result = '-' + result
print('The binary of your integer ' + str(inNum) + ' is ' + str(result))
|
5e0d0132cee8a9b3aa8f9a417eb8638d3f73ec82 | MDaalder/MIT6.00.1x_Intro_CompSci | /W02_Simple_Programs/polysum.py | 468 | 3.75 | 4 |
"""
@author: Matt
Function calculates the sum of the area and perimeter^2 of a regular polygon to 4 decimal points
A regular polygon has n sides, each with length s
n number of sides
s length of each side
"""
def polysum(n, s):
import math
area = (0.25*n*s**2)/(math.tan(math.pi/n)) # area of the polygon
perim = s*n # perimeter of the polygon
return round((float(area + perim**2)), 4) # returns the answer, to 4 decimal points |
e3b9c70022e232ae228e23a4ff155ae4da19cf69 | MDaalder/MIT6.00.1x_Intro_CompSci | /W04_GoodPractices/8 video example of raise.py | 678 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 20:37:50 2019
@author: Matt
"""
def get_ratios(L1, L2):
""" assumes L1 and L2 are lists of equal length of numbers
returns a list containing L1[i]/L2[i]"""
ratios = []
for index in range(len(L1)):
try:
ratios.append(L1[index]/float(L2[index]))
except ZeroDivisionError:
ratios.append(float('NaN')) # NaN = not a number
except:
raise ValueError('get_ratios called with bad arg')
return ratios
L1 = [1, 2, 3, 4]
L2 = [5, 6, 7, 8]
#L2 = [5, 6, 7, 0] #test case for div 0
#L2 = [5, 6, 7] # test case for bad argument len L1 != len L2
|
423a48d5272b44e2156d1f0966c70757007233aa | MDaalder/MIT6.00.1x_Intro_CompSci | /Midterm Problem 5.py | 1,991 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 24 16:38:25 2019
@author: Matt
"""
def uniqueValues(aDict):
'''
aDict: a dictionary
This function takes in a a dictionary, and returns a list
Keys in aDict map to integer values that are unique (values appear only once in aDict)
List of keys returned should be in increasing order.
If there are no unique values in aDict, the function should return an empy list
. '''
dummyList = []
dummyDict = {}
result = []
intValues = aDict.values() # gets values of dictionary
# keyValues = aDict.keys() # gets keys of dictionary
# print('Values in aDict', intValues)
# print('Keys in aDict', keyValues)
for t in intValues: # this will iterate through values of dictionary, and create key entries of int value k to keep a count of how many times that int comes up
if t in dummyDict: # if the value is already in the dictionary, add 1 to entry count
dummyDict[t] += 1
if t not in dummyDict: # if the value is not already in dict, create an entry
dummyDict[t] = 1
for k in dummyDict: # itereates through all int keys in the new dictionary (which are values in original dictionary)
if dummyDict[k] == 1: # if the value of that key is 1, that int is unique in the dictionary
dummyList.append(k) # add that int value to the list of unique dictionary values
for w in aDict: # iterates through keys in aDict
if aDict[w] in dummyList: # if the value of aDict[key] is in the dummyList of unique dictionary values
result.append(w) # record that aDict key to a list to be sorted and printed
result.sort()
return result
#aDict = {'a':1, 'b': 2, 'c': 4, 'd': 0, 'e': 3, 'f': 2}
# answer [0, 1, 3, 4]
#aDict = {1:1, 2: 2, 8: 4, 0: 0, 5: 3, 3: 2}
# answer [4, 5, 8]
aDict = {2: 0, 3: 3, 6: 1}
#answer [2, 3, 6]
print(uniqueValues(aDict))
|
81a509d34b1289560e111cfaf2103fe29f327009 | AlymbaevaBegimai/TEST | /2.py | 401 | 4 | 4 |
class Phone:
username = "Kate"
__how_many_times_turned_on = 0
def call(self):
print( "Ring-ring!" )
def __turn_on(self):
self.__how_many_times_turned_on += 1
print( "Times was turned on: ", self.__how_many_times_turned_on )
my_phone = Phone()
my_phone.call()
print( "The username is ", my_phone.username ) |
f8b1dd75c2283fec69c9236c52814a3c7ae31396 | romanzdk/books-recommender | /processing.py | 987 | 3.671875 | 4 | import pandas as pd
df = pd.read_csv('data/out.csv', sep=';')
def get_similar(book_name):
author_books = []
year_books = []
# get all books with the corresponding name
books = (
df[df['title'].str.contains(book_name.lower())]
.sort_values('rating_cnt', ascending = False)
)
if books.shape[0] > 0:
# get books of the same author
author = books.iloc[0,0]
author_books = (
df[df['author'] == author]
.sort_values('rating_avg', ascending = False)[:5]['title']
.to_list()
)
# get books within the year range
year = books.iloc[0,2]
year_range = 5
year_books = (
df[(df['year'] <= (year + year_range)) & (df['year'] >= (year - year_range))]
.sort_values('rating_avg', ascending = False)[:5]['title']
.to_list()
)
return {
'Author books':author_books,
'Year books':year_books
} |
7486bead68a7bf0c2e7d2a4ed289203a278be6b7 | bb-bb/KwantumNum | /task1.py | 1,557 | 3.5 | 4 | """
author: Geert Schulpen
Task 1; random disorder
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button
import random as random
g_AxColor = "lightgoldenrodyellow"
random.seed(1248)
def disorder(size,scale):
"""
A function that generates a disorder-potential
:param size: how big the matrix has to be
:param scale: how big the disorder has to be
:return: A square array of size size, which contains random entries on the main diagonal
"""
deltaHhatDiagonaal=[]
deltaHhatDiagonaal.append([random.random() for i in range(size)])*scale
deltaHhat=np.diagflat(deltaHhatDiagonaal) #aanmaken extra matrix
return(deltaHhat)
def task1():
gridSize = 400
t=1
box=1
big=1
medium=0.075
small=0.00125
standardHamilton=getHamiltonMatrix(gridSize,t)
deltaHamiltonSmall=disorder(gridSize,small)
deltaHamiltonMedium=disorder(gridSize,medium)
deltaHamiltonBig=disorder(gridSize,big)
valuesSmall,vectorsSmall=calculateEigenstate(standardHamilton+deltaHamiltonSmall, box)
valuesMedium,vectorsMedium=calculateEigenstate(standardHamilton+deltaHamiltonMedium, box)
valuesBig,vectorsBig=calculateEigenstate(standardHamilton+deltaHamiltonBig, box)
plotEigenstate(valuesSmall,vectorsSmall,box,'Task1, small disorder')
plotEigenstate(valuesMedium,vectorsMedium,box,'Task1, medium disorder')
plotEigenstate(valuesBig,vectorsBig,box,'Task1, big disorder')
task1()
|
18e1e68ed464494e6547e83b3c827fb322ddfa89 | Yrshyx/C | /python/第一题.py | 237 | 3.734375 | 4 | counter=0
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if i!=j and j!=k and i!=k:
print("{} {} {}".format(i,j,k))
counter +=1
print("共有{}种".format(counter))
|
507fdcb28060f2b139b07853c170974939267b63 | Abhinav-Rajput/CodeWars__KataSolutions | /Python Solutions/Write_ Number_in_Expanded_Form.py | 611 | 4.34375 | 4 | # Write Number in Expanded Form
# You will be given a number and you will need to return it as a string in Expanded Form. For example:
# expanded_form(12) # Should return '10 + 2'
# expanded_form(42) # Should return '40 + 2'
# expanded_form(70304) # Should return '70000 + 300 + 4'
def expanded_form(num):
strNum = str(num)
line = ''
for i in range(0,len(strNum)):
if strNum[i]=='0':
continue
line += strNum[i] + ''
for j in range(0,(len(strNum)-(i+1))):
line += '0'
line += ' + '
line = line[0:len(line)-3]
return line |
41159eb6bd04eeaf5593014c6820fcf7e30b5832 | Abhinav-Rajput/CodeWars__KataSolutions | /Python Solutions/spyGames.py | 437 | 3.5625 | 4 | def decrypt(code):
z = {0: ' '}
sum = 0
res = ''
arr = []
for i in range(1, 27):
z[i] = chr(i + 96)
codes = code.split()
for c in codes:
for a in c:
if a.isdigit():
sum += int(a)
if sum > 26:
sum = sum % 27
arr.append(sum)
sum = 0
for r in arr:
res += z[r]
return res
h = decrypt('x20*6<xY y875_r97L')
print(h)
|
8d6538986282bfbe541fe6e1d4a0b36920072f78 | jgarciagarrido/tuenti_challenge_7 | /challenge_4/solve.py | 758 | 3.84375 | 4 | def is_triangle(a, b, c):
return (a + b > c) and (b + c > a) and (a + c > b)
def perimeter(triangle):
return triangle[0] + triangle[1] + triangle[2]
def min_perimeter_triangle(n, sides):
sides.sort()
triangle = None
for i in xrange(1, n-1):
b = sides[i]
c = sides[i+1]
for j in xrange(0, i):
a = sides[j]
if is_triangle(a, b, c):
return perimeter((a, b, c))
return "IMPOSSIBLE"
if __name__ == '__main__':
t = int(raw_input())
for i in xrange(1, t + 1):
sides_line = [int(s) for s in raw_input().split(" ")]
n_sides = sides_line[0]
sides = sides_line[1:]
print "Case #{}: {}".format(i, min_perimeter_triangle(n_sides, sides))
|
6e71a0d9e1518351d493c96315b76817a7d0e214 | RickLee910/Leetcode_easy | /Array_easy/offer_16.py | 322 | 3.75 | 4 | class Solution:
#动态规划
def maxSubArray1(self, nums):
if nums == []:
return 0
else:
for i in range(1, len(nums)):
nums[i] = max(nums[i] + nums[i - 1], nums[i])
return max(nums)
sol = Solution()
a = [1,-1,-2,3]
print(sol.maxSubArray(a))
|
c6fe56f2f56e95e1c34fb75e533abc0917d46512 | RickLee910/Leetcode_easy | /Hash_easy/leetcode_349.py | 276 | 3.515625 | 4 | from collections import Counter
class Solution:
def intersection(self, nums1, nums2):
temp1 = Counter(nums1)
temp2 = Counter(nums2)
ans = []
for i in temp1.keys():
if temp2[i] >0:
ans.append(i)
return ans |
c8ad40f63b827bb6102c20bb82a510f35cd8a6bc | RickLee910/Leetcode_easy | /Array_easy/leetcode_88.py | 896 | 3.59375 | 4 | class Solution:
def merge(self, nums1, m, nums2, n):
for i in range(len(nums1)-m):
nums1.pop()
for j in range(len(nums2)-n):
nums2.pop()
nums1.extend(nums2)
nums1.sort()
def merge1(self, nums1, m, nums2, n):
temp = {}
temp1 = []
for i,x in enumerate(nums1):
if m == 0:
break
temp[x] = temp.get(x, 0) + 1
if i == m - 1:
break
for j, x in enumerate(nums2):
if n == 0:
break
temp[x] = temp.get(x, 0) + 1
if j == n - 1:
break
nums1.clear()
temp1 = list(temp.keys())
temp1.sort()
for j in temp1:
nums1.extend([j] * temp[j])
nums1 = [3,0,0]
m = 1
nums2 = [2,5,6,0,0]
n = 3
s = Solution()
s.merge(nums1,m,nums2,n)
print(nums1) |
3b2c8b6e23b557a1f8013f8ed9750ea72b72e3f7 | RickLee910/Leetcode_easy | /String_easy/inter_01.09.py | 650 | 3.8125 | 4 | class Solution:
#切片比较
def isFlipedString(self, s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
return s1 in (s2 + s2)
#循环判断
def isFlipedString1(self, s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
if s1 == '' and s2 == '':
return True
S2 = list(s2)
S1= list(s1)
for i in range(len(s2)):
if S2 == S1:
return True
else:
S2.append(S2.pop(0))
return False
s = Solution()
a = "waterbottl1"
b = "erbottlewat"
print(s.isFlipedString(a,b)) |
2eaa46e63db5e0cdec6028abf86595d8ebf0504d | RickLee910/Leetcode_easy | /Array_easy/inter_17.04.py | 261 | 3.53125 | 4 | import collections
class Solution:
def missingNumber(self, nums):
temp = collections.Counter(nums)
for i in range(len(nums) + 1):
if i not in temp:
return i
s = Solution()
a = [1,2,3,4,5]
print(s.missingNumber(a)) |
c58e8f35f2412cd9caf48ddb1330bf23bd631ee1 | RickLee910/Leetcode_easy | /Array_easy/leetcode_35.py | 626 | 3.703125 | 4 | class Solution:
#二分法
def searchInsert1(self, nums, target):
first, end = 0, len(nums)
while first < end:
mid = (first + end) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
first = mid + 1
else:
end = mid
return first
#利用list特性,巧妙计算
def searchInsert(self, nums, target):
for i in nums:
if i >= target:
return nums.index(i)
return len(nums)
a = [1,3,5,6]
sol = Solution()
print(sol.searchInsert(a, 4))
|
b68eff085bc7ac20fa2fb7b462af20e511fdcf29 | satishky18/VM-reservation-system | /28sept2021542PM-vm-inventory.py | 3,796 | 3.78125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
class Machine:
"""A sample Employee class"""
def __init__(self, ip, username, password, avalible, owner):
self.ip = ip
self.username = username
self.password = password
self.avalible = avalible
self.owner = owner
# In[13]:
import sqlite3
#from employee import Employee
conn = sqlite3.connect('server.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS machine (
ip varchar,
username text,
password text,
avalible boolean,
owner null
)""")
def insert_emp(emp):
with conn:
c.execute("INSERT INTO machine VALUES (:ip, :username, :password, :avalible, :owner)", {'ip': emp.ip, 'username': emp.username, 'password': emp.password, 'avalible': emp.avalible, 'owner': emp.owner})
def get_emps_by_avalible(avalible):
c.execute("SELECT * FROM machine WHERE avalible=:avalible", {'avalible': avalible})
return c.fetchall()
def get_emps_by_ip(ip):
c.execute("SELECT * FROM machine WHERE ip=:ip", {'ip': ip})
return c.fetchall()
def update_pay(ip, avalible, owner):
with conn:
c.execute("""UPDATE machine SET avalible = :avalible, owner = :owner
WHERE ip = :ip""",
{'ip': ip, 'avalible': avalible, 'owner': owner})
#def remove_emp(emp):
# with conn:
# c.execute("DELETE from employees WHERE first = :first AND last = :last",
# {'first': emp.first, 'last': emp.last})
emp_1 = Machine('192.168.1.2', 'satish', 'satish-password', 1, '' )
emp_2 = Machine('192.168.1.3', 'tim', 'tim-password', 1, '' )
emp_3 = Machine('192.168.1.4', 'sera', 'sera-password', 1, '' )
emp_4 = Machine('192.168.1.5', 'dan', 'dan-password', 1, '' )
emp_5 = Machine('192.168.1.6', 'scot', 'scot-password', 1, '' )
if c.execute("SELECT * FROM machine").fetchone():
print("data alrady exixt")
else:
insert_emp(emp_1)
insert_emp(emp_2)
insert_emp(emp_3)
insert_emp(emp_4)
insert_emp(emp_5)
#emps = get_emps_by_avalible('0')
#print(get_emps_by_avalible('0'))
#print(get_emps_by_ip('192.168.1.2'))
#update_pay('192.168.1.2', 0, 'sky')
#remove_emp(emp_1)
emps = get_emps_by_avalible(1)
print(emps)
#conn.close()
# In[12]:
import paramiko
while True:
x = input('''please write "new" for request for new machine or write "return" to return the machine
''')
if x == "new":
emps = get_emps_by_avalible('1')
if len(emps) == 0:
print ("no vm left try after some time.")
else:
i = input('enter your name: ')
j = list(emps[0])
#print(get_emps_by_avalible('0'))
k=emps[0]
print(i + " " + "your machine ip is"+"=" + j[0] + " " + "username is" + "=" + j[1] + " " + "password is" + "=" + j[2] )
update_pay(k[0], 0, i)
elif x == "return":
retip = input('please enter machine ip: ')
try:
emps = get_emps_by_ip(retip)
#emps = list(emps[0])
#print(emps)
except:
print("enter valid ip")
continue
k=emps[0]
update_pay(k[0], 1, '')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(emps[0], 22, emps[1], emps[2])
stdin, stdout, stderr = ssh.exec_command('rm -rf /tmp')
lines = stdout.readlines()
print(lines)
except:
print ("Unabele to conenct to the server")
else:
print("plesae provide valid response")
# In[ ]:
i=('192.168.1.2', 'satish', 'satish-password', 1, '')
print(i[0])
# In[ ]:
|
33f746a4c39d26398bed011515bcd32aef4630ab | ottohahn/OHNLP | /splitter/splitter.py | 1,365 | 3.84375 | 4 | #!/usr/bin/env python3
"""
A basic sentence splitter, it takes a text as input and returns an array of
sentences
"""
import re
INITIALS_RE = re.compile(r'([A-z])\.')
def splitter(text):
"""
Basic sentence splitting routine
It doesn't take into account dialog or quoted sentences inside a sentence.
"""
sentences = []
# First step remove newlines
text = text.replace('\n', ' ')
# we remove tabs
text = text.replace('\t', ' ')
# then we replace abbreviations
text = text.replace('Ph.D.', "Ph<prd>D<prd>")
text = text.replace('Mr.', 'Mr<prd>')
text = text.replace('St.', 'Mr<prd>')
text = text.replace('Mrs.', 'Mrs<prd>')
text = text.replace('Ms.', 'Ms<prd>')
text = text.replace('Dr.', 'Dr<prd>')
text = text.replace('Drs.', 'Drs<prd>')
text = text.replace('vs.', 'vs<prd>')
text = text.replace('etc.', 'etc<prd>')
text = text.replace('Inc.', 'Inc<prd>')
text = text.replace('Ltd.', 'Ltd<prd>')
text = text.replace('Jr.', 'Jr<prd>')
text = text.replace('Sr.', 'Sr<prd>')
text = text.replace('Co.', 'Co<prd>')
text = INITIALS_RE.sub('\1<prd>', text)
text = text.replace('.', '.<stop>')
text = text.replace('?', '?<stop>')
text = text.replace('!', '!<stop>')
text = text.replace('<prd>', '.')
sentences = text.split('<stop>')
return sentences
|
a597c668dda0375e97dbe33b4dce6d1cc42a8a69 | kernel-memory-dump/UNDP-AWS-2021 | /16-ec2/test-program.py | 1,984 | 3.6875 | 4 | import program
failed_tests = []
pass_tests = []
def test_max1_handles_same_number_ok():
a = 2
result = program.max1(a, a)
if result == a:
pass_tests.append('test_max1_handles_same_number_ok PASSED')
else:
failed_tests.append(f'test_max1_handles_same_number_ok FAILED: the returned value was not as expected, test expected: {a} but instead got {result}')
def test_max1_handles_different_number_ok():
a = 2
b = 3
result = program.max1(a, b)
if result == b:
pass_tests.append('test_max1_handles_different_number_ok PASSED')
else:
failed_tests.append(f'test_max1_handles_different_number_ok FAILED: the returned value was not as expected, test expected: {b} but instead got {result}')
def test_max1_handles_different_number_first_arg_ok():
a = 0
b = 3
expected = -1
result = program.max1(a, b)
if result == expected:
pass_tests.append('test_max1_handles_different_number_first_arg_ok PASSED')
else:
failed_tests.append(f'test_max1_handles_different_number_first_arg_ok FAILED: the returned value was not as expected, test expected: {expected} but instead got {result}')
def test_max1_handles_different_number_second_arg_ok():
a = 3
b = 0
expected = -1
result = program.max1(a, b)
if result == expected:
pass_tests.append('test_max1_handles_different_number_second_arg_ok PASSED')
else:
failed_tests.append(f'test_max1_handles_different_number_second_arg_ok FAILED: the returned value was not as expected, test expected: {expected} but instead got {result}')
test_max1_handles_same_number_ok()
test_max1_handles_different_number_ok()
test_max1_handles_different_number_first_arg_ok()
test_max1_handles_different_number_second_arg_ok()
# for each
# int i = 0; i < pass_tests.length; i++
# passed_test = pass_tests[i]
#
#
for passed_test in pass_tests:
print(passed_test)
for failed_test in failed_tests:
print(failed_test) |
b8ca7993c15513e13817fa65f892ebd014ca5743 | Satona75/Python_Exercises | /Guessing_Game.py | 816 | 4.40625 | 4 | # Computer generates a random number and the user has to guess it.
# With each wrong guess the computer lets the user know if they are too low or too high
# Once the user guesses the number they win and they have the opportunity to play again
# Random Number generation
from random import randint
carry_on = "y"
while carry_on == "y":
rand_number = randint(1,10)
guess = int(input("Try and guess the number generated between 1 and 10 "))
while guess != rand_number:
if guess < rand_number:
guess = int(input("Sorry too low! Try again.. "))
else:
guess = int(input("Sorry too high! Try again.. "))
print("Congratulations!! You have guessed correctly!")
carry_on = input("Do you want to play again? (y/n).. ")
print("Thanks for playing!") |
12c145181efc2ff5fba7113ad3be5dd4f8941369 | Satona75/Python_Exercises | /multiply_even_numbers.py | 210 | 3.96875 | 4 | def multiply_even_numbers(list):
evens = [num for num in list if num%2 == 0]
holder = 1
for x in evens:
holder = holder * x
return holder
print(multiply_even_numbers([1,2,3,4,5,6,7,8])) |
c069374b1d2c822c9a71b4c7c95ac5e7e3ca945f | Satona75/Python_Exercises | /RPS-AI.py | 1,177 | 4.3125 | 4 | #This game plays Rock, Paper, Scissors against the computer.
print("Rock...")
print("Paper...")
print("Scissors...\n")
#Player is invited to choose first
player=input("Make your move: ").lower()
#Number is randomly generated between 0 and 2
import random
comp_int=random.randint(0, 2)
if comp_int == 0:
computer = "rock"
elif comp_int == 1:
computer = "paper"
else:
computer = "scissors"
print("Computer has chosen: " + computer)
if player == "rock" or player == "paper" or player == "scissors":
if computer == player:
print("It's a tie!")
elif computer == "rock":
if player == "paper":
print("You Win!")
elif player == "scissors":
print("Computer Wins!")
elif computer == "paper":
if player == "scissors":
print("You Win!")
elif player == "rock":
print("Computer Wins!")
elif computer == "scissors":
if player == "rock":
print("You Win!")
elif player == "paper":
print("Computer Wins!")
else:
print("Something has gone wrong!")
else:
print("Please enter either rock, paper or scissors")
|
474ae873c18391c8b7872994da02592b59be369c | Satona75/Python_Exercises | /RPS-AI-refined.py | 1,977 | 4.5 | 4 | #This game plays Rock, Paper, Scissors against the computer
computer_score = 0
player_score = 0
win_score = 2
print("Rock...")
print("Paper...")
print("Scissors...\n")
while computer_score < win_score and player_score < win_score:
print(f"Computer Score: {computer_score}, Your Score: {player_score}")
#Player is invited to choose first
player=input("Make your move: ").lower()
if player == "quit" or player == "q":
break
#Number is randomly generated between 0 and 2
import random
comp_int=random.randint(0, 2)
if comp_int == 0:
computer = "rock"
elif comp_int == 1:
computer = "paper"
else:
computer = "scissors"
print("Computer has chosen: " + computer)
if player == "rock" or player == "paper" or player == "scissors":
if computer == player:
print("It's a tie!")
elif computer == "rock":
if player == "paper":
print("You Win!")
player_score += 1
elif player == "scissors":
print("Computer Wins!")
computer_score += 1
elif computer == "paper":
if player == "scissors":
print("You Win!")
player_score += 1
elif player == "rock":
print("Computer Wins!")
computer_score += 1
elif computer == "scissors":
if player == "rock":
print("You Win!")
player_score += 1
elif player == "paper":
print("Computer Wins!")
computer_score += 1
else:
print("Something has gone wrong!")
else:
print("Please enter either rock, paper or scissors")
if computer_score > player_score:
print("Oh no! The Computer won overall!!")
elif player_score > computer_score:
print("Congratulations!! You won overall")
else:
print("It's a tie overall")
|
44cbdbc57f54a30a0c711991f5d57e93c369acb3 | moon0331/baekjoon_solution | /others/10809.py | 232 | 3.84375 | 4 | import string
word = input()
result = []
for c in string.ascii_lowercase:
result.append(word.find(c))
print(*result)
print(*[input().find(c) for c in string.ascii_lowercase])
# print(*map(input().find,map(chr,range(97,123)))) |
7c2e2524d3de22c2feb4f5551ced1318ca102f87 | moon0331/baekjoon_solution | /programmers/Level 1/약수의 합.py | 120 | 3.53125 | 4 | def solution(n):
return sum(x for x in range(1, n+1) if n%x == 0)
print(solution(12) == 28)
print(solution(5) == 6) |
c2464adf389dca62e0d39b969f16c6c4197f6f20 | moon0331/baekjoon_solution | /programmers/Level 2/[1차] 프렌즈4블록.py | 1,712 | 3.59375 | 4 | def reverse_board(board): # (m,n)
new_board = [line[::-1] for line in list(map(list, zip(*board)))]
return new_board # (n,m)
def search_pop_blocks(m, n, board): # board (m,n) 들어올때 지워야 할 인덱스와 지워지는 블록 수 반환 (reverse될때 확인 필요)
erase_idx = [set() for _ in range(n)]
pop_idx = set()
for i in range(m-1):
for j in range(n-1):
if is_same(board, i, j):
erase_idx[i] |= {j, j+1}
erase_idx[i+1] |= {j, j+1}
pop_idx |= {(i, j), (i, j+1), (i+1, j), (i+1, j+1)}
n_pop_block = len(pop_idx)
return erase_idx, n_pop_block
def is_same(b, i, j):
four_blocks = {b[i][j], b[i+1][j], b[i][j+1], b[i+1][j+1]}
return not 0 in four_blocks and len(four_blocks) == 1
def pop_block(board, erase_idx_by_row, m):
for i, erase_idx in enumerate(erase_idx_by_row):
if not erase_idx:
continue
minval, maxval = min(erase_idx), max(erase_idx)
board[i][minval:maxval+1] = []
board[i] += [0 for _ in range(m-len(board[i]))]
def solution(m, n, board):
answer = 0
board = reverse_board(board)
while True:
erase_idx_by_row, n_pop_block = search_pop_blocks(n, m, board)
if n_pop_block:
answer += n_pop_block
pop_block(board, erase_idx_by_row, m)
continue
break
return answer
ms = [4, 6]
ns = [5, 6]
boards = [
["CCBDE", "AAADE", "AAABF", "CCBBF"],
["TTTANT", "RRFACC", "RRRFCC", "TRRRAA", "TTMMMF", "TMMTTJ"]
]
answers = [14, 15]
for m, n, board, answer in zip(ms, ns, boards, answers):
print(solution(m, n, board) == answer)
# 7번 10번 체크 필요 |
19830dddda2ffb1971d0360f0634d69e1d05754d | moon0331/baekjoon_solution | /programmers/Level 2/문자열 압축.py | 1,281 | 3.5625 | 4 | def get_new_subword_info(word=None):
return {'word':word, 'n_freq':1, 'init':False}
def subword_info_to_string(subword_info):
if subword_info['n_freq'] >= 2:
return str(subword_info['n_freq']) + subword_info['word']
else:
return subword_info['word']
def solution(s):
if len(s) == 1:
return 1
elif len(s)==2 or (len(s) == 3 and len(set(s)) == 1):
return 2
answer = float('inf')
for unit in range(1, len(s)//2+1):
words = [s[i:i+unit] for i in range(0, len(s), unit)]
result_word = ''
subword_info = get_new_subword_info(words[0])
for w in words[1:]:
if subword_info['word'] != w: # new word
result_word += subword_info_to_string(subword_info)
subword_info = get_new_subword_info(w)
else:
subword_info['n_freq'] += 1
result_word += subword_info_to_string(subword_info)
answer = min(answer, len(result_word))
return answer
answer_sheet = [
("aabbaccc", 7),
("ababcdcdababcdcd", 9),
("abcabcdede", 8),
("abcabcabcabcdededededede", 14),
("xababcdcdababcdcd", 17)
]
print(solution('a') == 1)
for x, y in answer_sheet:
print(solution(x) == y) |
83ec2cd0ebe74f598b82553c40dfaa4c3c041a87 | moon0331/baekjoon_solution | /others/8958.py | 149 | 3.5625 | 4 | def nth(x):
x = len(x)
return int(x*(x+1)/2)
N = int(input())
for _ in range(N):
txt = input().split('X')
print(sum(map(nth, txt))) |
95a921ad3f8564b509fdbed54dabeab02b55eaea | moon0331/baekjoon_solution | /programmers/Level 1/정수 제곱근 판별.py | 145 | 3.5 | 4 | def solution(n):
sqrt = n**0.5
return int((sqrt+1)**2) if sqrt == int(sqrt) else -1
print(solution(121) == 144)
print(solution(3) == -1) |
f648b2f6240acb7757aaa42fa3a3adebb3edd9c0 | moon0331/baekjoon_solution | /level2/1259.py | 144 | 3.625 | 4 | while True:
num = input()
if num == '0':
break
print('yes' if all(map(lambda x: x[0]==x[1], zip(num, num[::-1]))) else 'no') |
f566d4798eb7ba166d80406eedbf310cca8f5350 | moon0331/baekjoon_solution | /programmers/Level 1/내적.py | 157 | 3.703125 | 4 | def solution(a, b):
return sum([x*y for x, y in zip(a,b)])
print(solution([1,2,3,4], [-3, -1, 0, 2]) == 3)
print(solution([-1, 0, 1], [1, 0, -1]) == -2) |
f61b06360de5642bc8df6c24371f0c5a2a8b58e1 | moon0331/baekjoon_solution | /programmers/고득점 Kit/전화번호 목록.py | 634 | 3.828125 | 4 | '''
가장 짧은 숫자의 자리수 : n
number[:n] 에서부터 number[:] 까지 hash값 담아버림
'''
def solution(phone_book):
phone_book.sort(key=lambda x:len(x))
print(phone_book)
for i in range(len(phone_book)-1):
subword = phone_book[i]
words_rng = phone_book[i+1:]
for word in words_rng:
if word.startswith(subword):
return False
return True
phones = [
["119", "97674223", "1195524421"],
["123","456","789"],
["12","123","1235","567","88"]
]
returns = [False, True, False]
for p, r in zip(phones, returns):
print(solution(p) == r) |
ce5f9b82b4843c790112e72e2e9555ae29ead8ed | atikus/study1 | /mystudy/generator.py | 364 | 3.796875 | 4 | # bu fonk her yeni çağrılışında baştan başlıyor.
def deneme():
for i in range(5):
yield i*i*i
for j in deneme():
print(j)
for j in deneme():
print(j)
print("= "*40)
# bu bir kere kullanılıyor. ve kendini mem den siliyor.
generator = (x*x*x for x in range(5))
for j in generator:
print(j)
for j in generator:
print(j)
|
096e3e7959be263809b5f5c809e3a2e847771c19 | dkoriadi/query-plans-visualiser | /PlansFrame.py | 3,626 | 3.8125 | 4 | """
PlansFrame.py
This script is called by app.py to display multiple QEPs in tree format.
"""
import tkinter
import tkinter.scrolledtext
import MainFrame
class PlansPage(tkinter.Frame):
"""
This is the class that displays the plans page whereto view all possible QEPs. It is displayed as a
separate frame from the landing page. The QEPs may also be viewed on the CLI for convienience.
Methods
-------
displayPlans(planStrings)
Display all possible QEPs and actual QEP on GUI and CLI
"""
def onFrameConfigure(self, event):
"""
Update the scrollregion of the canvas to allow scrolling on the scrollbar
Parameters
----------
event: Tkinter event (in this case, left-click)
"""
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def displayPlans(self, planStrings):
# Display QEPs on GUI
self.label_plans.configure(state='normal')
# Remove previous plans
self.label_plans.delete('1.0', tkinter.END)
self.label_plans.insert('end', planStrings + '\n')
self.label_plans.configure(state='disabled')
def __init__(self, tk_parent_frame, tk_root_window, objLandingPage):
"""
Constructor of the PlansPage class
Parameters
----------
tk_parent_frame: tkinter.Frame
The parent Tkinter frame that is on top of the Tkinter window. Every Tkinter window must contain
a widget (the frame in this case) to be able to display UI.
tk_root_window: tkinter.Tk
The Tkinter root window which has one or more Tkinter frames created as objects. Switching the
Tkinter frame is done via the root window.
"""
tkinter.Frame.__init__(self, tk_parent_frame, width=300, height=300)
self.controller = tk_root_window
self.canvas = tkinter.Canvas(self, width=300, height=300)
self.canvas.pack(side=tkinter.LEFT, expand=True, fill=tkinter.BOTH)
self.frame = tkinter.Frame(self.canvas)
# Get the LandingPage object to pass variables
self.objLandingPage = objLandingPage
# Vertical scrollbar
self.yscroll = tkinter.Scrollbar(
self, command=self.canvas.yview, orient=tkinter.VERTICAL)
self.yscroll.pack(side=tkinter.RIGHT, fill=tkinter.Y,
expand=tkinter.FALSE)
self.canvas.configure(yscrollcommand=self.yscroll.set)
self.canvas.create_window((0, 0), window=self.frame, anchor="nw",
tags="self.frame")
# Horizontal scrollbar
self.xscroll = tkinter.Scrollbar(
self.canvas, orient='horizontal', command=self.canvas.xview)
self.xscroll.pack(side=tkinter.BOTTOM, fill=tkinter.X)
# Callback function for scrollbar
self.frame.bind("<Configure>", self.onFrameConfigure)
# Button created to allow user to go back to LandingPage
tkinter.Button(
self.frame, text="Back",
command=lambda: self.controller.showFrame(MainFrame.LandingPage)).grid(row=0, column=0, padx=(10, 0), pady=9)
"""Plans"""
self.label_plans_header = tkinter.Label(
self.canvas, text="Plans:", anchor="w")
self.label_plans_header.config(font=(None, 14))
self.label_plans_header.pack(padx=(10, 0), pady=(15, 0))
self.label_plans = tkinter.scrolledtext.ScrolledText(
self.canvas, wrap='word', state='disabled', width=130, height=100)
self.label_plans.pack(padx=(10, 10), pady=(10, 10))
|
19dbab140d55e0b7f892d66f08b9dc26ba5f4095 | timurridjanovic/javascript_interpreter | /udacity_problems/8.subsets.py | 937 | 4.125 | 4 | # Bonus Practice: Subsets
# This assignment is not graded and we encourage you to experiment. Learning is
# fun!
# Write a procedure that accepts a list as an argument. The procedure should
# print out all of the subsets of that list.
#iterative solution
def listSubsets(list, subsets=[[]]):
if len(list) == 0:
return subsets
element = list.pop()
for i in xrange(len(subsets)):
subsets.append(subsets[i] + [element])
return listSubsets(list, subsets)
print listSubsets([1, 2, 3, 4, 5])
#recursive solution
def sublists(big_list, selected_so_far):
if big_list == []:
print selected_so_far
else:
current_element = big_list[0]
rest_of_big_list = big_list[1:]
sublists(rest_of_big_list, selected_so_far + [current_element])
sublists(rest_of_big_list, selected_so_far)
dinner_guests = ["LM", "ECS", "SBA"]
sublists(dinner_guests, [])
|
d5b4078fc05372736115f67ea8044976fe1ab994 | dundunmao/LeetCode2019 | /680. Valid Palindrome II.py | 672 | 3.765625 | 4 | # 问一个string是不是palindrome,可以最多去掉一个char
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
l = 0
r = len(s)-1
while l < r:
if s[l] != s[r]:
return self.isPanlin(s,l,r-1) or self.isPanlin(s,l+1,r)
l += 1
r -= 1
def isPanlin(self,s,i,j):
while i < j:
if s[i] != s[j]:
return False
else:
i += 1
j -= 1
return True
if __name__ == '__main__':
s = Solution()
a = 'abbb'
print s.validPalindrome(a)
|
71dda13cd5f310acf20845a091a5663b7fbee6f6 | dundunmao/LeetCode2019 | /long_qomolangma.py | 708 | 3.625 | 4 | def qomolangma(array):
start = 0
res = 1
for i in range(len(array)):
if array[i] < array[start]:
res = max(res, i - start + 1)
start = i
if start == len(array) - 1:
return res
new_start = len(array) - 1
for j in range(len(array) - 1, start - 1, -1):
if array[j] < array[new_start]:
res = max(res, new_start - j + 1)
new_start = j
return res
array = [3,7,4,9,2,1,13] # 5
print(qomolangma(array))
array = [1, 99, 104, 400, 22, 15, 33]
print(qomolangma(array)) # 6
array = [1]
print(qomolangma(array)) # 1
array = [1, 2]
print(qomolangma(array)) # 2
array = [1, 2, 3, 4, 5, 6, 7]
print(qomolangma(array)) # 2
|
a0bb6c5c0a352812303e2dd732927dd21d487b6b | dundunmao/LeetCode2019 | /975. Odd Even Jump.py | 3,340 | 3.625 | 4 |
# 最后结果
import bisect
class Solution1:
def oddEvenJumps(self, A):
n = len(A)
odd_jump = [False] * n
even_jump = [False] * n
bst = SortedArray()
# base case
odd_jump[n - 1] = True
even_jump[n - 1] = True
bst.put(A[n - 1], n - 1)
# general case
for i in range(n - 2, -1, -1):
# odd跳的结果 (比它大的里面找最小的)
next_node = bst.find_next(A[i])
odd_jump[i] = next_node[0] != -1 and even_jump[next_node[1]]
# even跳的结果(比它小的里面找最大的)
pre_node = bst.find_prev(A[i])
even_jump[i] = pre_node[0] != -1 and odd_jump[pre_node[1]]
# 把cur加入当前bst
bst.put(A[i], i)
result = 0
# 看每个起点的odd跳的结果
for i in range(0, n):
if odd_jump[i]:
result += 1
return result
class SortedArray:
def __init__(self):
self.array = []
def put(self, val, index):
i = 0
while i < len(self.array):
if val <= self.array[i][0]:
break
i += 1
self.array.insert(i, [val, index])
def find_prev(self, val):
i = 0
while i < len(self.array):
if val <= self.array[i][0]:
if val == self.array[i][0]:
return self.array[i]
i -= 1
break
i += 1
if i == len(self.array):
i -= 1
if i < 0:
return [-1, -1]
while i > 0:
if self.array[i][0] != self.array[i-1][0]:
break
i -= 1
return self.array[i]
def find_next(self, val):
i = 0
while i < len(self.array):
if val <= self.array[i][0]:
if val == self.array[i][0]:
return self.array[i]
break
i += 1
if i > len(self.array) - 1:
return -1, -1
return self.array[i]
############
import bisect
class Solution0:
def oddEvenJumps(self, A):
n = len(A)
odd_jump = [False] * n
even_jump = [False] * n
bst = []
# base case
odd_jump[n - 1] = True
even_jump[n - 1] = True
bisect.insort_right(bst, A[n - 1])
# general case
for i in range(n - 2, -1, -1):
# odd跳的结果 (比它大的里面找最小的)
next_node = bisect.bisect_right(bst, A[i])
odd_jump[i] = next_node != len(bst) and even_jump[next_node]
# even跳的结果(比它小的里面找最大的)
pre_node = bisect.bisect_left(bst, A[i])
even_jump[i] = pre_node != 0 and odd_jump[pre_node]
# 把cur加入当前bst
bisect.insort_left(bst, A[i])
result = 0
# 看每个起点的odd跳的结果
for i in range(0, n):
if odd_jump[i]:
result += 1
return result
s = Solution0()
a = [2,3,1,1,4] # 3
print(s.oddEvenJumps(a))
a = [10,13,12,14,15] # 2
print(s.oddEvenJumps(a))
a = [5,1,3,4,2] # 3
print(s.oddEvenJumps(a))
a = [1,2,3,2,1,4,4,5] # 6
print(s.oddEvenJumps(a))
a = [5,1,3,4,2] #3
print(s.oddEvenJumps(a))
|
91fdacb3c856743643ffced2e2963efbb77224da | dundunmao/LeetCode2019 | /426. Convert BST to Sorted Doubly Linked List.py | 4,401 | 3.9375 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right
"""
class Solution(object):
def treeToDoublyList(self, root):
"""
:type root: Node
:rtype: Node
"""
if not root: return None
head, tail = self.helper(root)
return head
def helper(self, root):
'''construct a doubly-linked list, return the head and tail'''
head, tail = root, root
if root.left:
left_head, left_tail = self.helper(root.left)
left_tail.right = root
root.left = left_tail
head = left_head
if root.right:
right_head, right_tail = self.helper(root.right)
right_head.left = root
root.right = right_head
tail = right_tail
head.left = tail
tail.right = head
return head, tail
###################################
class Node:
def __init__(self, val):
self.val = val
self.left = None # pre
self.right = None # next
class Solution:
def treeToDoublyList(self, root: 'Node') -> 'Node':
if not root:
return None
res = self.dfs(root)
res.head.left = res.tail
res.tail.right = res.head
return res.head
def dfs(self, root):
# base case
if not root.left and not root.right:
res = NodeWrapper(root, root)
return res
# general case
if root.left:
left_wrapper = self.dfs(root.left)
left_wrapper.tail.right = root
root.left = left_wrapper.tail
else:
left_wrapper = NodeWrapper(None, None)
if root.right:
right_wrapper = self.dfs(root.right)
right_wrapper.head.left = root
root.right = right_wrapper.head
else:
right_wrapper = NodeWrapper(None, None)
head = left_wrapper.head if left_wrapper.head else root
tail = right_wrapper.tail if right_wrapper.tail else root
return NodeWrapper(head, tail)
class NodeWrapper:
def __init__(self, head, tail):
self.head = head
self.tail = tail
######简化base case
class Solution:
def treeToDoublyList(self, root: 'Node') -> 'Node':
if not root:
return None
res = self.dfs(root)
res.head.left = res.tail
res.tail.right = res.head
return res.head
def dfs(self, root):
# base case
if not root:
return NodeWrapper(None, None)
# general case
left_wrapper = self.dfs(root.left)
right_wrapper = self.dfs(root.right)
if left_wrapper.tail:
left_wrapper.tail.right = root
root.left = left_wrapper.tail
if right_wrapper.head:
right_wrapper.head.left = root
root.right = right_wrapper.head
head = left_wrapper.head if left_wrapper.head else root
tail = right_wrapper.tail if right_wrapper.tail else root
return NodeWrapper(head, tail)
class NodeWrapper:
def __init__(self, head, tail):
self.head = head
self.tail = tail
#######
class Solution:
def treeToDoublyList(self, root):
if root is None:
return None
wrapper = NodeWrapper(None, None)
self.dfs(root, wrapper)
wrapper.head.left = wrapper.tail
wrapper.tail.right = wrapper.head
return wrapper.head
def dfs(self, node, wrapper):
if node is None:
return
self.dfs(node.left, wrapper)
if wrapper.head is None:
wrapper.head = node
else:
wrapper.tail.right = node
node.left = wrapper.tail
wrapper.tail = node
self.dfs(node.right, wrapper)
class NodeWrapper:
def __init__(self, head, tail):
self.head = head
self.tail = tail
if __name__ == '__main__':
P = Node(4)
P.left = Node(2)
P.left.left = Node(1)
P.left.right = Node(3)
# P.left.right.left = TreeNode(6)
# P.left.right.right = TreeNode(7)
# P.left.right.right.right = TreeNode(8)
P.right = Node(5)
# P.right.left = TreeNode(6)
# P.right.right = TreeNode(6)
s = Solution1()
print(s.treeToDoublyList(P))
|
25f1ecffe70394a7cbaa66761d07d4f343301ab1 | dundunmao/LeetCode2019 | /1094. Car Pooling.py | 928 | 3.546875 | 4 | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
capacity_array = []
for trip in trips:
capacity_array.append(SeatCapacity(trip[0], trip[1], 1))
capacity_array.append(SeatCapacity(trip[0], trip[2], -1))
capacity_array.sort()
res = 0
seat = 0
for seat_cap in capacity_array:
if seat_cap.state == -1:
seat -= seat_cap.num
elif seat_cap.state == 1:
seat += seat_cap.num
res = max(res, seat)
return res <= capacity
class SeatCapacity:
def __init__(self, num, time, state):
self.num = num
self.time = time
self.state = state
def __le__(a, b):
if a.time == b.time:
return a.state < b.state
return a.time < b.time
s = Solution()
a = [[2,1,5],[3,3,7]]
b = 4
print(s.carPooling(a, b))
|
234a66bc28e80b148b555449f8a8c581e06c9854 | dundunmao/LeetCode2019 | /139. word break.py | 8,985 | 3.5625 | 4 |
# 给出一个字符串s和一个词典,判断字符串s是否可以被空格切分成一个或多个出现在字典中的单词。
#
# 您在真实的面试中是否遇到过这个题? Yes
# 样例
# 给出
#
# s = "lintcode"
#
# dict = ["lint","code"]
#
# 返回 true 因为"lintcode"可以被空格切分成"lint code"
class Solution:
# @param s: A string s
# @param dict: A dictionary of words dict
def wordBreak(self, s, dict):
# write your code here
if len(dict) == 0 and len(s) == 0:
return True
if s is None or len(s) == 0 or len(dict) == 0:
return False
can = [False for i in range(len(s)+1)]
can[0] = True
max_len = max(dict)
for i in range(1,len(s)+1):
for j in range(1,min(i,max_len)+1):
if not can[i - j]:
continue
word = s[(i-j):i]
if word in dict:
can[i] = True
break
return can[len(s)]
# time limit exceed
class Solution1:
# @param s: A string s
# @param dict: A dictionary of words dict
def wordBreak(self, s, dict):
if len(dict) == 0 and len(s) == 0:
return True
if s is None or len(s) == 0 or len(dict) == 0 :
return False
n = len(s)
f = [False for i in range(n)]
for k in range(n):
word = s[0:k+1]
if word in dict:
f[k] = True
for i in range(1,n):
for j in range(0,i):
word = s[j+1:i+1]
if word in dict and f[j]:
f[i] = True
return f[n-1]
#尽量优化版,仍超时;第一个不超时的办法,是j从后往前遍历
class Solution3:
# @param s: A string s
# @param dict: A dictionary of words dict
def wordBreak(self, s, dict):
if len(dict) == 0 and len(s) == 0:
return True
if s is None or len(s) == 0 or len(dict) == 0:
return False
n = len(s)
max_len = max([len(word) for word in dict])
f = [False for i in range(n)]
for k in range(n):
word = s[0:k + 1]
if word in dict:
f[k] = True
for i in range(1, n):
for j in range(0, i):
if f[j]:
word = s[j + 1:i + 1]
if len(word) <= max_len:
if word in dict:
f[i] = True
break
############
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
dictionary_set = set(wordDict)
res = [False for i in range(len(s))]
for i in range(len(s)):
if s[0: i + 1] in dictionary_set:
res[i] = True
continue
for j in range(0, i):
if res[j] and s[j + 1: i + 1] in dictionary_set:
res[i] = True
break
else:
res[i] = False
return res[len(s) - 1]
class Solution3:
def wordBreak(self, s: str, wordDict) -> bool:
dictionary_set = set(wordDict)
result = [None for i in range(len(s))]
return self.dfs(s, len(s) - 1, dictionary_set, result)
def dfs(self, s, i, dictionary_set, result):
if result[i] is not None:
return result[i]
if s[0: i + 1] in dictionary_set:
result[i] = True
return True
for p in range(0, i):
if self.dfs(s, p, dictionary_set, result) and s[p + 1: i + 1] in dictionary_set:
result[i] = True
return True
result[i] = False
return False
class Solution3:
def wordBreak(self, s: str, wordDict) -> bool:
dictionary_set = set(wordDict)
result = [None for i in range(len(s))]
return self.dfs(s, 0, dictionary_set, result)
def dfs(self, s, i, dictionary_set, result):
if result[i] is not None:
return result[i]
if s[i: len(s)] in dictionary_set:
result[i] = True
return True
for p in range(i + 1, len(s)):
if self.dfs(s, p, dictionary_set, result) and s[i: p] in dictionary_set:
result[i] = True
return True
result[i] = False
return False
class Solution3:
def wordBreak(self, s: str, wordDict) -> bool:
n = len(s)
dictionary_set = set(wordDict)
res = [False for i in range(n + 1)]
# base case
res[n] = True
# general case
for i in range(n - 1, -1, -1):
# a[i~n-1] 刚好在dictionary里
if s[i : n] in dictionary_set:
res[i] = True
# a[i~j-1]在dictionary里面,且a[j~n-1]可以break
for j in range(i + 1, n):
if res[j] and s[i : j] in dictionary_set:
res[i] = True
return res[0]
######trie
class Solution:
def wordBreak(self, s: str, wordDict):
n = len(s)
trie_word = Trie()
for word in wordDict:
trie_word.insert(word)
res = [False for i in range(n + 1)]
# base case
res[n] = True
# general case
for i in range(n - 1, -1, -1):
# a[i~n-1] 刚好在dictionary里
if trie_word.search(s[i: n]) == 1:
res[i] = True
continue
# a[i~j-1]在dictionary里面,且a[j~n-1]可以break
for j in range(i + 1, n):
if res[j]:
result = trie_word.search(s[i: j])
if result == False:
res[i] = False
break
elif result == True:
res[i] = True
break
return res[0]
# class Trie:
#
# def __init__(self):
# """
# Initialize your data structure here.
# """
# self.root = TrieNode()
#
# def insert(self, word: str) -> None:
# """
# Inserts a word into the trie.
# """
# cur_root = self.root
# for char in word:
# index = ord(char) - 97
# if cur_root.children[index] == None:
# cur_root.children[index] = TrieNode()
# cur_root = cur_root.children[index]
# cur_root.is_word = True
#
# def search(self, prefix: str) -> bool:
# """
# Returns if there is any word in the trie that starts with the given prefix.
# """
# cur_root = self.root
# for char in prefix:
# index = ord(char) - 97
# if cur_root.children[index] == None:
# return False
# cur_root = cur_root.children[index]
# if cur_root.is_word == True:
# return True
# return None
#
#
# class TrieNode:
# def __init__(self):
# self.children = [None] * 26
# self.is_word = False
######用trie的最优解
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
n = len(s)
trie_word = Trie()
for word in wordDict:
trie_word.insert(word)
res = [False for i in range(len(s))]
for i in range(len(s)):
cur_root = trie_word.root
flag = True
for j in range(i, -1, -1):
index = ord(s[j]) - 97
if cur_root.children[index] is None:
flag = False
break
cur_root = cur_root.children[index]
if cur_root.is_word and res[j-1]:
res[i] = True
break
if cur_root.is_word and flag:
res[i] = True
return res[len(s) - 1]
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
cur_root = self.root
reverse_word = list(word)[::-1]
for char in reverse_word:
index = ord(char) - 97
if cur_root.children[index] == None:
cur_root.children[index] = TrieNode()
cur_root = cur_root.children[index]
cur_root.is_word = True
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.is_word = False
if __name__ == "__main__":
x = Solution10()
s = "leetcode"
dict = ["leet","code"]
print(x.wordBreak(s, dict)) #T
s = 'applepenapple'
dict = ["apple", "pen"]
print(x.wordBreak(s, dict)) #T
s = 'catsandog'
dict = ["cats", "dog", "sand", "and", "cat"]
print(x.wordBreak(s, dict)) #F
|
a935afab319838c30d5e68573bae93e95da04ae2 | dundunmao/LeetCode2019 | /587. Erect the Fence.py | 1,263 | 3.515625 | 4 | class Solution:
def outerTrees(self, points):
point_array = []
for p in points:
point = Point(p[0], p[1])
point_array.append(point)
point_array.sort()
point_stack = []
for i in range(len(point_array)):
while len(point_stack) >= 2 and self.orientation(point_stack[-2], point_stack[-1], point_array[i]) > 0:
point_stack.pop()
point_stack.append(point_array[i])
for i in range(len(point_array) - 1, -1, -1):
while len(point_stack) >= 2 and self.orientation(point_stack[-2], point_stack[-1], point_array[i]) > 0:
point_stack.pop()
point_stack.append(point_array[i])
res = set()
for ele in point_stack:
res.add((ele.x, ele.y))
return res
def orientation(self, p, q, r):
return (q.y - p.y) * (r.x - p.x) - (q.x - p.x) * (r.y - p.y)
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(a, b): # 按x的从小到大排,如果相等,按y的从大到小
if a.x == b.x:
return b.y < a.y
return a.x < b.x
x = Solution()
p = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]
print(x.outerTrees(p))
|
cdfacc797df7c4d29f48907b1719e1a36522d1d9 | dundunmao/LeetCode2019 | /703. Kth Largest Element in a Stream.py | 1,008 | 3.8125 | 4 | import heapq
class KthLargest:
def __init__(self, k, nums):
self.top_k_min_heap = []
self.size = k
i = 0
while i < len(nums) and k > 0:
heapq.heappush(self.top_k_min_heap, nums[i])
i += 1
k -= 1
while i < len(nums):
if self.top_k_min_heap[0] < nums[i]:
heapq.heappop(self.top_k_min_heap)
heapq.heappush(self.top_k_min_heap, nums[i])
i += 1
def add(self, val: int) -> int:
if len(self.top_k_min_heap) < self.size:
heapq.heappush(self.top_k_min_heap, val)
elif self.top_k_min_heap[0] < val:
heapq.heappop(self.top_k_min_heap)
heapq.heappush(self.top_k_min_heap, val)
return self.top_k_min_heap[0]
# Your KthLargest object will be instantiated and called as such:
k = 3
nums = [5, -1]
obj = KthLargest(k, nums)
print(obj.add(2))
print(obj.add(1))
print(obj.add(-1))
print(obj.add(3))
print(obj.add(4))
|
dba0a491be622d41f73dd8c8b1294e2e2d0ad2fd | dundunmao/LeetCode2019 | /138 Copy List with Random Pointer .py | 4,754 | 3.625 | 4 |
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
# @param head: A RandomListNode
# @return: A RandomListNode
def copyRandomList(self, head):
# write your code here
if head is None:
return None
dummy = RandomListNode(0)
pre = dummy
# pre = newnNode
map = {}
while head is not None:
if map.has_key(head):
newNode = map.get(head)
else:
newNode = RandomListNode(head.label)
map[head] = newNode
pre.next = newNode
if head.random is not None: #这里别忘了
if map.has_key(head.random):
newNode.random = map.get(head.random)
else:
newNode.random = RandomListNode(head.random.label)
map[head.random] = newNode.random
pre = pre.next #这里别忘了.
head = head.next
return dummy.next
# 方法二,基本同上,但是先循环得到next,再循环一边得到random
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if head is None:
return head
nHead = RandomListNode(head.label)
old = head
new = nHead
hash = {}
hash[head] = nHead
while old.next != None:
old = old.next
new.next = RandomListNode(old.label)
new = new.next
hash[old] = new
old = head
new = nHead
while old != None:
if old.random != None:
new.random = hash[old.random]
old = old.next
new = new.next
return nHead
# 方法3: 先loop一遍,在每一个点后都复制一边这个node 1->1'->2->2'->3->3'->N这时候random都带上
# 再loop一遍,提取每一个新点和起箭头.
class Solution2:
# @param head: A RandomListNode
# @return: A RandomListNode
def copyRandomList(self, head):
# write your code here
if head is None:
return None
self.copyNext(head)
self.copyRandom(head)
return self.splitList(head)
def splitList(self, head):
newHead = head.next
while head is not None:
temp = head.next
head.next = temp.next
head = head.next
if temp.next is not None:
temp.next = temp.next.next
return newHead
def copyRandom(self, head):
while head is not None:
if head.next.random is not None:
head.next.random = head.random.next
head = head.next.next
def copyNext(self, head):
while head is not None:
newNode = RandomListNode(head.label)
newNode.random = head.random
newNode.next = head.next
head.next = newNode
head = head.next.next
class Node:
def __init__(self, x, next, random):
self.val = x
self.next = next
self.random = random
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if not head:
return None
self.copy_node(head)
self.copy_random(head)
res = self.split(head)
return res
def copy_node(self, head):
old = head
while old:
new = Node(old.val, None, None)
new.next = old.next
old.next = new
old = new.next
def copy_random(self, head):
cur = head
while cur and cur.next:
if cur.random:
cur.next.random = cur.random.next
cur = cur.next.next
def split(self, head):
dummy = Node(-1, None, None)
dummy.next = head
cur = dummy
while head and head.next:
cur.next = head.next
cur = cur.next
head.next = cur.next
head = head.next
return dummy.next
if __name__ == '__main__':
# P = RandomListNode(1)
# P.next = RandomListNode(2)
# P.next.next = RandomListNode(3)
# P.next.next.next = RandomListNode(4)
# P.random = P
# P.next.random = P.next.next
# P.next.next.random = P.next
# P.next.next.next.random = None
#
#
# s = Solution4()
# print(s.copyRandomList(P))
P = Node(1, None, None)
P.next = Node(2, None, None)
# P.next.next = RandomListNode(3)
# P.next.next.next = RandomListNode(4)
P.random = P.next
P.next.random = P.next
s = Solution4()
print(s.copyRandomList(P))
|
04cd7500781232849379a93fe63a29a96daaf347 | dundunmao/LeetCode2019 | /212. Word Search II.py | 5,797 | 3.984375 | 4 | # class TrieNode:
# def __init__(self):
# self.flag = False
# self.s = ''
# self.sons = []
# for i in range(26):
# self.sons.append(None)
#
#
# class Trie:
# def __init__(self):
# self.root = TrieNode()
# def insert(self, word):
# # Write your code here
# cur = self.root
# for i in range(len(word)):
# c = ord(word[i]) - ord('a')
# if cur.sons[c] is None:
# cur.sons[c] = TrieNode()
# cur = cur.sons[c]
# cur.s = word
# cur.flag = True
#
# # @param {string} word
# # @return {boolean}
# # Returns if the word is in the trie.
# def search(self, word):
# # Write your code here
# cur = self.root
# for i in range(len(word)):
# c = ord(word[i]) - ord('a')
# if cur.sons[c] is None:
# return False
# cur = cur.sons[c]
# return cur.flag
#
# class Solution:
# # @param board, a list of lists of 1 length string
# # @param words: A list of string
# # @return: A list of string
# def wordSearchII(self, board, words):
# result = []
# tree = Trie()
# for word in words:
# tree.insert(word)
# res = ''
# for i in range(len(board)):
# for j in range(len(board[i])):
# self.help(board,i,j,tree.root,result,res)
# return result
# def help(self,board,x,y,root,result,res):
# dx = [1, 0, -1, 0]
# dy = [0, 1, 0, -1]
# if root.flag is True:
# if root.s not in result:
# result.append(root.s)
# if x < 0 or x >= len(board) or y < 0 or y >= len(board[0]) or board[x][y]==0 or root is None:
# return
# if root.sons[ord(board[x][y]) - ord('a')]:
# for i in range(4):
# cur = board[x][y]
# board[x][y] = False
# self.help(board, x+dx[i], y+dy[i],root.sons[ord(cur) - ord('a')], result, res)
# board[x][y] = cur
################################
# 停在叶子
class Solution:
def findWords(self, board, words):
word_trie = Trie()
for word in words:
word_trie.insert(word)
res = set()
path = []
n = len(board)
m = len(board[0])
direction = [(-1, 0), (1, 0), (0, -1), (0, 1)]
visited = [[False for i in range(len(board[0]))] for j in range(len(board))]
for i in range(n):
for j in range(m):
cur = word_trie.root
char = board[i][j]
if cur.children[ord(char) - 97]:
self.dfs(cur, i, j, path, res, board, direction, visited)
return res
def dfs(self, node, row, col, path, res, board, direction, visited):
path.append(board[row][col])
char = board[row][col]
visited[row][col] = True
cur = node.children[ord(char) - 97]
if cur.is_word:
res.add(''.join(path))
for i, j in direction:
if 0 <= row + i < len(board) and 0 <= col + j < len(board[0]) and cur.children[ord(board[row + i][col + j]) - 97] and visited[row][col]:
self.dfs(cur, row + i, col + j, path, res, board, direction, visited)
path.pop()
visited[row][col] = False
#停在None
class Solution3:
def findWords(self, board, words):
word_trie = Trie()
for word in words:
word_trie.insert(word)
res = set()
path = []
n = len(board)
m = len(board[0])
direction = [(-1, 0), (1, 0), (0, -1), (0, 1)]
visited = [[False for i in range(len(board[0]))] for j in range(len(board))]
for i in range(n):
for j in range(m):
cur = word_trie.root
char = board[i][j]
self.dfs(cur, i, j, path, res, board, direction, visited)
return res
def dfs(self, node, row, col, path, res, board, direction, visited):
if row in [-1, len(board)] or col in [-1, len(board[0])] or node.children[ord(board[row][col]) - 97] is None or visited[row][col]:
return
path.append(board[row][col])
visited[row][col] = True
cur = node.children[ord(board[row][col]) - 97]
if cur.is_word:
res.add(''.join(path))
for i, j in direction:
self.dfs(cur, row + i, col + j, path, res, board, direction, visited)
path.pop()
visited[row][col] = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
cur_root = self.root
for char in word:
index = ord(char) - 97
if cur_root.children[index] is None:
cur_root.children[index] = TrieNode()
cur_root = cur_root.children[index]
cur_root.is_word = True
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.is_word = False
if __name__ == '__main__':
s = Solution3()
board = [
['d','o','a','f'],
['a','g','a','i'],
['d','c','a','n']
]
words =["dog", "dad", "dgdg", "can", "again"]
print(s.findWords(board, words))
board = [
['o', 'a', 'a', 'n'],
['e', 't', 'a', 'e'],
['i', 'h', 'k', 'r'],
['i', 'f', 'l', 'v']
]
words = ["oath", "pea", "eat", "rain"]
print(s.findWords(board, words))
Output: ["eat", "oath"]
board = [["a","b"], ["a","b"]]
words = ["ab"]
print(s.findWords(board, words))
board = [["b"], ["a"], ["b"], ["b"], ["a"]]
words = ["baa", "abba", "baab", "aba"]
print(s.findWords(board, words))
|
d51ee8447c2680177bab81e87d626fe4bc567024 | dundunmao/LeetCode2019 | /449. Serialize and Deserialize BST.py | 1,680 | 3.734375 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
res = self.dfs_serialize(root)
return ','.join(res)
def dfs_serialize(self, root):
if not root:
return []
else:
left = self.dfs_serialize(root.left)
right = self.dfs_serialize(root.right)
return left + right + [str(root.val)]
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if not data:
return None
data = [int(ele) for ele in data.split(',') if ele]
res = self.dfs_deserialize(data, float('-inf'), float('inf'))
return res
def dfs_deserialize(self, data, lower, upper):
if not data or data[-1] < lower or data[-1] > upper:
return None
val = data.pop()
root = TreeNode(val)
root.right = self.dfs_deserialize(data, val, upper) #右子树值在自己和上一层node之间
root.left = self.dfs_deserialize(data, lower, val) # 左子树值在上一层的node和自己之间
return root
# Your Codec object will be instantiated and called as such:
P = TreeNode(10)
P.left = TreeNode(5)
P.left.left = TreeNode(2)
P.left.right = TreeNode(7)
P.left.right.left = TreeNode(6)
P.right = TreeNode(12)
codec = Codec()
print(codec.serialize(P))
print(codec.deserialize(codec.serialize(P)))
|
c3192e3a235a580209903a4c70ee2b3c39978bde | dundunmao/LeetCode2019 | /124. Binary Tree Maximum Path Sum.py | 9,004 | 3.90625 | 4 | # 给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)
#
# 您在真实的面试中是否遇到过这个题? Yes
# 样例
# 给出一棵二叉树:
#
# 1
# / \
# 2 3
# 返回 6
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
# 用resultTyoe这个class
class ResultType(object):
def __init__(self, root2any, any2any):
self.root2any = root2any
self.any2any = any2any
class Solution1:
"""
@param root: The root of binary tree.
@return: An integer
"""
def maxPathSum(self, root):
# write your code here
result = self.helper(root)
return result.any2any
def helper(self, root):
if root is None:
return ResultType(float('-inf'), float('-inf'))
# Divide
left = self.helper(root.left)
right = self.helper(root.right)
# Conquer
root2any = max(0,max(left.root2any, right.root2any)) + root.val
any2any = max(left.any2any, right.any2any)
any2any = max(any2any,
max(0,left.root2any) +
max(0,right.root2any) +
root.val)
return ResultType(root2any, any2any)
# 不用resultTyoe这个class,这个方法最好
class Solution2(object):
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
any_any, root_any = self.helper(root)
return any_any
def helper(self, root):
if root is None:
return float('-inf'), float('-inf')
left_any_any, left_root_any = self.helper(root.left)
right_any_any, right_root_any = self.helper(root.right)
root_any = root.val + max(0, left_root_any, right_root_any)
any_any = max(left_any_any, right_any_any, root_any, root.val + left_root_any + right_root_any)
return any_any, root_any
class Solution:
"""
@param root: The root of binary tree.
@return: An integer
"""
def maxPathSum(self, root):
if not root:
return 0
ans = [float('-inf')] #在这里更新global的最大path-sum
self.helper(root,ans) #表现从root出发的最大path—sum(root-any)
return ans[0]
def helper(self,root,ans):
if not root:
return 0
l = max(0, self.helper(root.left, ans)) #左子树的root-any
r = max(0, self.helper(root.right, ans)) #右子树的root-any
sum = l + r + root.val #root这棵树的global的any-any
ans[0] = max(ans[0], sum) #更新
return max(l,r) + root.val #返回的是 root-any
#################################################3
# 2019 rockey
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
if not root:
raise ValueError('not valid input')
return self.dfs(root).max_sum
def dfs(self, root):
# base case
if not root.left and not root.right:
return Result(root.val, root.val)
# general case
res_left = Result(float('-inf'), float('-inf')) if not root.left else self.dfs(root.left)
res_right = Result(float('-inf'), float('-inf')) if not root.right else self.dfs(root.right)
max_sum = max(res_left.max_sum,
res_right.max_sum,
max(0, res_left.max_sum_to_root) + max(0, res_right.max_sum_to_root) + root.val
)
max_sum_to_root = max(root.val,
res_left.max_sum_to_root + root.val,
res_right.max_sum_to_root + root.val
)
return Result(max_sum, max_sum_to_root)
class Result:
def __init__(self, max_sum, max_sum_to_root):
self.max_sum = max_sum
self.max_sum_to_root = max_sum_to_root
#################################################3
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
if not root:
raise ValueError('not valid input')
return self.dfs(root).max_sum
def dfs(self, root):
# base case
if not root:
return Result(float('-inf'), float('-inf'))
# general case
res_left = self.dfs(root.left)
res_right = self.dfs(root.right)
max_sum = max(res_left.max_sum,
res_right.max_sum,
max(0, res_left.max_sum_to_root) + max(0, res_right.max_sum_to_root) + root.val
)
max_sum_to_root = max(root.val,
res_left.max_sum_to_root + root.val,
res_right.max_sum_to_root + root.val
)
return Result(max_sum, max_sum_to_root)
class Result:
def __init__(self, max_sum, max_sum_to_root):
self.max_sum = max_sum
self.max_sum_to_root = max_sum_to_root
#################################################3
# 16 个分支
import random
class MyTreeNode:
def __init__(self, val):
self.val = val
self.children = [None] * 16
class Result:
def __init__(self, max_sum, max_sum_to_root):
self.max_sum = max_sum
self.max_sum_to_root = max_sum_to_root
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
if not root:
raise ValueError('not valid input')
new_root = self.copy_tree(root)
return self.dfs(new_root).max_sum
def dfs(self, root):
# base case
if not root:
return Result(float('-inf'), float('-inf'))
# general case
max_sum_without_root = float('-inf')
biggest_sum_to_child = float('-inf')
bigger_sum_to_child = biggest_sum_to_child
for ele in root.children:
ele_res = self.dfs(ele)
max_sum_without_root = max(max_sum_without_root, ele_res.max_sum)
if ele_res.max_sum_to_root > biggest_sum_to_child:
bigger_sum_to_child = biggest_sum_to_child
biggest_sum_to_child = ele_res.max_sum_to_root
elif ele_res.max_sum_to_root > bigger_sum_to_child:
bigger_sum_to_child = ele_res.max_sum_to_root
total_max_sum = max(max_sum_without_root,
max(0, biggest_sum_to_child) + max(0, bigger_sum_to_child) + root.val
)
total_max_sum_to_root = max(root.val, biggest_sum_to_child + root.val)
return Result(total_max_sum, total_max_sum_to_root)
def copy_tree(self, root):
if not root:
return None
my_root = MyTreeNode(root.val)
my_root.children[random.randint(0, 7)] = self.copy_tree(root.left)
my_root.children[random.randint(0, 7) + 8] = self.copy_tree(root.right)
return my_root
################
# 16分支
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import random
class MyTreeNode:
def __init__(self, val):
self.val = val
self.children = [None] * 16
class Result:
def __init__(self, max_profit, max_profit_without_root):
self.max_profit = max_profit
self.max_profit_without_root = max_profit_without_root
class Solution:
def rob(self, root: TreeNode) -> int:
if not root:
return 0
new_root = self.copy_tree(root)
return self.dfs(new_root).max_profit
def dfs(self, root):
# base case
if not root:
return Result(0, 0)
# general case
child_max_profit_without_root_sum = 0
child_max_profit_sum = 0
for child in root.children:
child_res = self.dfs(child)
child_max_profit_without_root_sum += child_res.max_profit_without_root
child_max_profit_sum += child_res.max_profit
max_profit = max(child_max_profit_sum, root.val + child_max_profit_without_root_sum)
max_profit_without_root = child_max_profit_sum
return Result(max_profit, max_profit_without_root)
def copy_tree(self, root):
if not root:
return None
my_root = MyTreeNode(root.val)
my_root.children[random.randint(0, 7)] = self.copy_tree(root.left)
my_root.children[random.randint(0, 7) + 8] = self.copy_tree(root.right)
return my_root
if __name__ == '__main__':
# TREE 1
# Construct the following tree
# 5
# / \
# 3 6
# / \
# 2 4
P = TreeNode(1)
P.left = TreeNode(2)
s = Solution()
print(s.maxPathSum(P))
|
87dd5e40f48b6154f4ad565ae45304307fb13144 | dundunmao/LeetCode2019 | /241. Different Ways to Add Parentheses.py | 1,309 | 4.0625 | 4 | # Given a string of numbers and operators, return all possible results from computing all the different
# possible ways to group numbers and operators. The valid operators are +, - and *.
#
#
# Example 1
# Input: "2-1-1".
#
# ((2-1)-1) = 0
# (2-(1-1)) = 2
# Output: [0, 2]
#
#
# Example 2
# Input: "2*3-4*5"
#
# (2*(3-(4*5))) = -34
# ((2*3)-(4*5)) = -14
# ((2*(3-4))*5) = -10
# (2*((3-4)*5)) = -10
# (((2*3)-4)*5) = 10
# Output: [-34, -14, -10, -10, 10]
#
class Solution(object):
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
return self.dfs(input)
def dfs(self, input):
ans = []
for i in range(len(input)):
if input[i] == '+' or input[i] == '-' or input[i] == '*':
left = self.dfs(input[:i])
right = self.dfs(input[i + 1:])
for ele1 in left:
for ele2 in right:
if input[i] == '+':
ans.append(ele1 + ele2)
elif input[i] == '-':
ans.append(ele1 - ele2)
elif input[i] == '*':
ans.append(ele1 * ele2)
if ans == []:
ans.append(eval(input))
return ans
|
31df3f479fd5b5552b9a1396163008dc38abd9d6 | dundunmao/LeetCode2019 | /69. Sqrt(x).py | 1,323 | 3.859375 | 4 |
class Solution:
"""
@param x: An integer
@return: The sqrt of x
"""
def sqrt(self, x):
start = 1
end = x
while start+1 < end:
mid = start+(end-start)/2
if mid*mid <= x:
start = mid
else:
end = mid
if end*end <=x:
return end
return start
def mySqrt_leet(self, x):
"""
:type x: int
:rtype: int
"""
if x <= 0:
return 0
if x == 1:
return 1
start = 1
end = x
while start + 1 < end:
mid = (start+end)/2
if mid**2 == x:
return mid
elif mid**2 < x:
start = mid
else:
end = mid
return start
class SolutionNew:
def mySqrt(self, x: int) -> int:
if x <= 1:
return x
s = 0
e = x //2
while s + 1 < e:
m = s + (e - s) // 2
if m*m == x:
return m
elif m*m < x:
s = m
else:
e = m
if e * e <= x:
return e
else:
return s
if __name__ == "__main__":
x = 10
s = Solution()
print s.sqrt(x)
|
e7ea9a45373e0021b745e8e19d441139163e36e8 | dundunmao/LeetCode2019 | /1123. Lowest Common Ancestor of Deepest Leaves.py | 1,116 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:
res = Result()
self.dfs(root, 0, res)
return res.lca
# 返回的是当前node的左右子树的深度
def dfs(self, node, depth, res):
# 更新此树最大深度
res.deepest = max(res.deepest, depth)
if not node:
return depth
# 左边的最大深度
left = self.dfs(node.left, depth + 1, res)
# 右边的最大深度
right = self.dfs(node.right, depth + 1, res)
# 如果左右都到了最大深度,lca更新成当前node
# 如到叶子了,左右深度都是这个叶子的深度,都是最大深度,记录这个叶子为lca
# 再上一层,
if left == res.deepest and right == res.deepest:
res.lca = node
return max(left, right)
class Result:
def __init__(self):
self.lca = None
self.deepest = 0
|
910a21d1d3d13cfbaccf71ea77218b06a375d7fb | dundunmao/LeetCode2019 | /test.py | 31,321 | 3.578125 | 4 | # def water_flower(a, capacity):
# res = 0
# left = capacity
# for i in range(len(a)):
# if a[i] > left:
# res += i * 2
# left = capacity - a[i]
# if left < 0:
# return -1
# else:
# left -= a[i]
#
# return res + len(a)
#
# def compare_string1(a, b):
# a_array = a.split(',')
# b_array = b.split(',')
# res = []
# count_b = [] #表示b里每个str的num
# for i in b_array:
# count_b.append(count_min_char(i))
# count_a = [0] * 11 #index表示num,ele表示有几个str是这个num的
# for j in a_array:
# count = count_min_char(j)
# count_a[count] += 1
# #累加,表示有几个str是最少这个num的。
# for i in range(1, len(count_a)):
# count_a[i] = count_a[i] + count_a[i - 1]
# # num表示b里每个str的num,去a里要找比num小一个的num对应多少个str
# for num in count_b:
# res.append(count_a[num - 1])
# return res
#
# def count_min_char(string):
# array = [0] * 26
# for cha in string:
# array[ord(cha) - 97] += 1
# for i in range(len(array)):
# if array[i] > 0:
# return array[i]
#
#
# # 方法2
# def compare_string2(a, b):
# a_array = a.split(',')
# b_array = b.split(',')
# res = []
# for i in b_array:
# count = 0
# for j in a_array:
# if count_char(j, min(j)) < count_char(i, min(i)):
# count += 1
# res.append(count)
# return res
# def count_char(string, char):
# res = 0
# for ele in string:
# if ele == char:
# res += 1
# return res
# a = 'abcd,aabc,bd,efcfdcc'
# b = 'aaa,aa,a'
# print(compare_string1(a,b))
#
#
#
# a = [2,4,5,1,2]
# c = 6
# print(water_flower(a, c)) # 17
# a = [2,4,5,1]
# c = 6
# print(water_flower(a, c)) # 8
# a = [2, 4, 5]
# c = 6
# print(water_flower(a, c)) # 7
# a = [2, 2, 1, 1, 2]
# c = 3
# print(water_flower(a, c)) # 13
#
# import collections
# def continous_k(a, k):
# mini = min(a[:len(a) - k + 1])
# mini_index = []
# for i in range(len(a) - k + 1):
# if a[i] == mini:
# mini_index.append(i)
# res = float('inf')
# for ele in mini_index:
# res = min(res, trans_to_num(ele, a, k))
# res_array = collections.deque()
# while res > 0:
# res_array.appendleft(res % 10)
# res = res // 10
# return res_array
# def trans_to_num(ele, a, k):
# array = a[ele: ele + k]
# res = 0
# j = 0
# for i in range(len(array) - 1, -1, -1):
# res += array[i] * 10 ** j
# j += 1
# return res
# def continous_k(a, k):
# start_index = 0
# for i in range(len(a) - k + 1):
# if a[i] > a[start_index]:
# start_index = i
# return a[start_index: start_index + k]
# a = [1, 4, 3, 2, 5] #[4, 3, 2]
# k = 3
# print(continous_k(a, k))
# a = [1, 4, 3, 2, 5] #[4, 3, 2]
# k = 4
# print(continous_k(a, k))
# a = [3, 1, 2] #[3,22]
# k = 2
# print(continous_k(a, k))
#
# a = [10, 2, 1] #[10,2]
# k = 2
# print(continous_k(a, k))
#
# def solution(A, B):
# # write your code in Python 3.6
# if len(A) == 0 or len(B) == 0:
# return -1
# res = []
# # do not rotate first one
# # A is original, A[0] is target
# base_a = helper(A[0], A, B)
# if base_a != -1:
# res.append(base_a)
# # B is original, B[0] is target
# base_b = helper(B[0], B, A)
# if base_b != -1:
# res.append(base_b)
# # rotate first one, result needs + 1
# # A is original, B[0] is target
# base_a_rotate = helper(B[0], A, B)
# if base_a_rotate != -1:
# res.append(base_a_rotate + 1)
# # B is original, A[0] is target
# base_b_rotate = helper(A[0], B, A)
# if base_b_rotate != -1:
# res.append(base_b_rotate + 1)
#
# if len(res) == 0:
# return -1
# return min(res)
#
# def helper(target, original, totated):
# res = 0
# for i in range(1, len(original)):
# if original[i] != target and totated[i] == target:
# res += 1
# elif original[i] != target and totated[i] != target:
# res = -1
# break
# return res
# a = [2, 4, 6, 5, 2]
# b = [1, 2, 2, 2, 3]
# class SpreadSheet:
# def __init__(self, num_row, num_col):
# self.num_row = num_row
# self.num_col = num_col
# self.content = [['' for i in range(self.num_col)] for j in range(self.num_row)]
# self.record_width = [0 for i in range(self.num_col)]
#
# def edit_content(self, row, col, content):
# self.content[row][col] = content
# self.record_width[col] = max(self.record_width[col], len(content))
#
# def print_spreadsheet(self):
# for i in range(self.num_row):
# print('|'.join(self.content[i]))
#
# def print_pretty(self):
#
# for i in range(self.num_row):
# res = []
# for j in range(self.num_col):
# if len(self.content[i][j]) < self.record_width[j]:
# make_up = self.record_width[j] - len(self.content[i][j])
# res.append(self.content[i][j] + ' ' * make_up)
# else:
# res.append(self.content[i][j])
# print('|'.join(res))
# # def
# spread_sheet = SpreadSheet(4, 3)
# spread_sheet.edit_content(0,0,'bob')
# spread_sheet.edit_content(0,1,'10')
# spread_sheet.edit_content(0,2,'foo')
# spread_sheet.edit_content(1,0,'alice')
# spread_sheet.edit_content(1,1,'5')
#
# spread_sheet.print_spreadsheet()
# spread_sheet.print_pretty()
# spread_sheet.edit_content(1,0,'x')
# def aaa(a):
# res = 0
# for i in range(1, a + 1):
# if i % 15 == 0:
# res += i * 10
# elif i % 5 == 0:
# res += i * 3
# elif i % 3 == 0:
# res += i * 2
# else:
# res += i
# return res
#
# a = 1000
# print(aaa(a))
# def aaaa(a):
# res = []
#
# # index = ord('N') + 17
# # while index > 90:
# # index = index - 90
# # print(chr(index + 65 - 1))
# for i in range(1, 27):
# res = []
# for cha in string:
# index = ord(cha) + i
# if index > 90:
# while index > 90:
# index = index - 90
# res.append(chr(index + 65 - 1))
# else:
# res.append((chr(index)))
# print(i, ''.join(res))
#
#
# string = 'SQZUQ'
# print(aaaa(string))
# def aaa(a):
# count = 0
# for i in range(5000, 50000):
# ord(a[i])
# return count
# print(aaa('LFIHKRVHRMWRXZGVZURHHSLIGLUDZGVI'))
# A = [(-853388, -797447), (-442839, 721091), (-406140, 987734), (-55842, -980970),(-28064, -960562)
# (240773, -871287)
# (273637, 851940)
# (320461, 997514)
# (495045, -667013)
# (757135, -861866)
# (1148386, -439206)
# (1220903, 239470)
# import collections
# def check_function(sum_up):
# res = []
# queue = collections.deque()
# for i in range(0, sum_up):
# for j in range(0, sum_up + 1):
# if i + j == sum_up + 1:
# res.append((i, j))
# if i + 1 < sum_up and j - 1 < sum_up:
# queue.append((i + 1, j - 1))
# if i - 1 < sum_up and j + 1 < sum_up:
# queue.append((i - 1, j + 1))
#
# def find_arguments(f, z):
# x = 1
# y = 2 ** 32 - 1
# res = []
# while f(x, 1) <= z:
# y = bin_search(x, y, f, z)
# if y != -1:
# res.append([x, y])
# else:
# y = 2 ** 32 - 1
# x += 1
# return res
#
# def bin_search(x, last_y, f, z):
# left, right = 1, last_y - 1
# while left <= right:
# mid = (left + right) // 2
#
# if f(x, mid) == z:
# return mid
# elif f(x, mid) < z:
# left = mid + 1
# else:
# right = mid - 1
# return -1
# def f(x,y):
# return x + y
#
# z = 5
# print(find_arguments(f,z))
# class Product:
# def __init__(self, k ):
# self.a = []
# self.product = 1
# self.index_zero = -1
# self.k = k
# def add(self, x):
# self.a.append(x)
# size = len(self.a)
# if len(self.a) <= self.k:
# if x == 0:
# self.index_zero = size - 1
# return 0
# else:
# self.product *= x
# if self.index_zero != -1:
# return 0
# return self.product
# else:
# if x == 0:
# if self.a[size - k - 1] != 0:
# self.product = self.product // self.a[size - k - 1]
# self.index_zero = size - 1
# return 0
# else:
# self.product = self.product * x // self.a[size - k - 1] if self.a[size - k - 1] != 0 else self.product * x
# if size - self.index_zero <= k:
# return 0
# else:
# return self.product
# nums = [1, 3, 3, 6, 5, 7, 0, -3, 6, -3]
# k = 3
# s = Product(k)
#
# # print(s.add(1))
# # print(s.add(3))
# # print(s.add(3))
# # print(s.add(6))
# print(s.add(5))
# print(s.add(7))
# print(s.add(0))
# print(s.add(0))
# print(s.add(6))
# print(s.add(-3))
# print(s.add(-3))
#####frog
# def frog_jump(a, k):
# f = [False for i in range(len(a))]
# f[0] = True
# for i in range(1, len(a)):
# if a[i] == 0:
# if f[i - 1] == True:
# f[i] = True
# if i - k >= 0 and f[i - k] == True:
# f[i] = True
# return f[-1]
#
# def frog_jump1(a, k1, k2):
# visited = [None for i in range(len(a))]
# return dfs(0, visited, k1, k2, a)
# def dfs(start, visited, k1, k2, a):
# if start == len(a) - 1:
# visited[start] = True
# return True
# if visited[start] is not None:
# return
# else:
# for i in range(k1, k2 + 1):
# if start + i < len(a) and a[start + i] == 0:
# if dfs(start + i, visited, k1, k2, a):
# visited[start] = True
# return True
# visited[start] = False
# return False
#
# # a = [0,0,1,1,0,0,1,1,0]
# # k = 3
# # print(frog_jump(a,k))
# a1 = [0,1,1,0,0,1,1,1,0]
# k1 = 3
# k2 = 4
# print(frog_jump1(a1,k1, k2))
# box and ball
# class BoxBall:
# def out_from(self, m, start):
# return self.helper(0, start, 'down', m)
# def helper(self, i, j, dir, m):
# if i == len(m) - 1:
# return j
# else:
# if m[i][j] == '\\':
# if dir == 'down':
# return self.helper(i, j + 1, 'right', m)
# elif dir == 'right':
# return self.helper(i + 1, j, 'down', m)
# else:
# return -1
# elif m[i][j] == '/':
# if dir == 'down':
# return self.helper(i, j - 1, 'left', m)
# elif dir == 'left':
# return self.helper(i + 1, j, 'down', m)
# else:
# return -1
# s = BoxBall()
# m = [['\\', '\\','\\','/','/'],['\\', '\\','\\','/','/'],['/','/','/','\\','\\'],['\\', '\\','\\','/','/'],['/','/','/','/','/']]
# start = 0
# print(s.out_from(m, start))
# def move_target(a, t):
# n = len(a)
# for i in range(n - 1, -1, -1):
# if a[i] == t:
# j = i - 1
# while j >= 0 and a[j] == t:
# j -= 1
# if j < 0:
# break
# a[i], a[j] = a[j], a[i]
# while i >= 0:
# a[i] = t
# i -= 1
# return a
# a = [1,2,4,2,5,7,3,7,3,5]
# t = 5
# print(move_target(a,t))
# def freq(a):
# for i in range(len(a)):
# if a[i] > 0:
# flag = True
# while flag:
# flag = False
# idx = a[i] - 1
# if idx != i:
# if a[idx] > 0:
# # swap
# a[i] = a[idx]
# a[idx] = -1
# flag = True
# else:
# a[i] = 0
# a[idx] -= 1
# else:
# a[idx] = -1
# return a
# a = [4,4,5,3,4,5]
# print(freq(a))
# class Calculate:
# def __init__(self):
# self.save = ''
# self.cur = ''
# self.operator = ''
# self.pre = ''
#
# def calculate(self, c):
# if c == '0' and self.cur == '':
# self.pre = c
# print('')
# elif c.isdigit():
# self.cur += c
# self.pre = c
# print(self.cur)
# elif c == '+' or c == '-':
# if self.pre == '+' or self.pre == '-':
# self.operator = c
# print(self.save)
# elif self.operator == '':
# self.save = self.cur
# self.cur = ''
# self.operator = c
# self.pre = c
# print(self.save)
# else:
# self.cur = str(self.oper())
# self.operator = c
# self.save = self.cur
# self.cur = ''
# self.pre = c
# print(self.save)
#
# def oper(self):
# if self.operator == '+':
# return int(self.save) + int(self.cur)
# elif self.operator == '-':
# return int(self.save) - int(self.cur)
# else:
# return ''
# s = Calculate()
#
# s.calculate('0')
# s.calculate('1')
# s.calculate('2')
# s.calculate('+')
# s.calculate('3')
# s.calculate('-')
# s.calculate('4')
# s.calculate('+')
# s.calculate('-')
# (s.calculate('2'))
# s.calculate('-')
# def matrix_one(a):
# left = len(a[0])
# for i in range(len(a)):
# for j in range(len(a[0])):
# if a[i][j] == 1 and j < left:
# left = j
# break
# return left
#
# def matrix_one1(a):
# left = len(a[0])
# end = len(a[0]) - 1
# for i in range(len(a)):
# if a[i][end] == 1:
# end = bianary_search(a[i], 0, end)
# continue
# return end
#
# def bianary_search(array, start, end):
# while start + 1 < end:
# mid = start + (end - start) // 2
# if array[mid] == 1:
# end = mid
# elif array[mid] == 0:
# start = mid
# if array[start] == 1:
# return start
# else:
# return end
#
# def matrix_one2(a):
# left = len(a[0]) - 1
# down = 0
# while left >= 0 and down < len(a):
# if a[down][left] == 1:
# left -= 1
# else:
# down += 1
#
# return left + 1
#
#
# # a = [[0,0,1,1], [0,0,0,1],[0,0,0,0],[0,1,1,1]]
# # print(matrix_one2(a))
#
# a = [[0,0,1,1,1], [0,0,0,1,1],[0,0,0,0,1],[1,1,1,1,1]]
# print(matrix_one2(a))
# import random
# def max_index(a):
# max_num = float('-inf')
# count = 0
# res = 0
# for i in range(len(a)):
# if a[i] > max_num:
# count = 1
# max_num = a[i]
# res = i
#
# elif a[i] == max_num:
# count += 1
# rdm = random.randint(1, count)
# if rdm == count:
# res = i
# return res
# a = [11,30,2,30,30,30,6,2,62,62]
# print(max_index(a))
# def binary_search(a, target):
# start = 0
# end = len(a) - 1
# while start + 1 < end:
# mid = start + (end - start) // 2
# if a[mid][0] == target:
# return mid
# elif a[mid][0] < target:
# start = mid
# else:
# end = mid
# return start if a[start][0] == target else end
# def subset_target_k(a, k):
# a.sort()
# end = len(a) - 1
# res = 0
# for i in range(0, len(a)):
# if a[i] > k:
# break
# if end <= i:
# res += 1
# else:
# while end > i and a[i] + a[end] > k:
# end -= 1
# res += 2 ** (end - i)
# return res
#
# a = [7,3,6,4,10]
# k = 10
#
# print(subset_target_k(a, k)) # 13
#
# a = [6,3,7,4,10,11]
# k = 10
# print(subset_target_k(a, k)) #13
#
# a = [1,2,3]
# k = 10
# print(subset_target_k(a, k)) # 7
# a = [4,5,3]
# k = 2
# print(subset_target_k(a, k)) # 0
# #duplicate
#
# a = [1,1,1]
# k = 10
# print(subset_target_k(a, k)) # 7
# class Multi():
# def multi_prime(self,nums):
# res = []
# if len(nums) == 0:
# return res
# product = 1
# pos = 0
# # nums.sort()
# self.helper(res, nums, pos, product)
# return res
# def helper(self, res, nums, pos, product):
# if product != 1:
# res.append(product)
# for i in range(pos, len(nums)):
# # if i != pos and nums[i] == nums[i-1]:
# # continue
# product *= nums[i]
# self.helper(res, nums, i+1, product)
# product //= nums[i]
# class Multi1:
# def multi_prime(self, a):
# res = []
# product = 1
# a.sort()
# self.dfs(a, 0, res, product)
# return res
#
# def dfs(self, a, start, res, product):
# if product != 1:
# res.append(product)
# for i in range(start, len(a)):
# # if i > start and a[i] == a[i - 1]:
# # continue
# product *= a[i]
# self.dfs(a, i + 1, res, product)
# product //= a[i]
#
# s = Multi1()
#
# a = [2,2,2]
# print(s.multi_prime(a))
# a = [2,3,5]
# print(s.multi_prime(a))
# def operator(s, target):
# temp = []
# res = []
# # array = [ele for ele in s]
# dfs(s, 0, 0, target, temp, res)
# return res
# def dfs(array, start, cur_sum, target, temp, res):
# if start == len(array):
# if cur_sum == target:
# res.append(''.join(temp))
# else:
# for i in range(start, len(array)):
# head = int(array[start: i + 1])
# if start == 0:
# temp.append(str(head))
# dfs(array, i + 1, cur_sum + head, target, temp, res)
# temp.pop()
# # "+"
# temp.append('+' + str(head))
# dfs(array, i + 1, cur_sum + head, target, temp, res)
# temp.pop()
# # "-"
# temp.append('-' + str(head))
# dfs(array, i + 1, cur_sum - head, target, temp, res)
# temp.pop()
# print(operator('123456789', 252))
#
#
#
#
# class Pocker:
# def __init__(self, p1, p2):
# self.p1 = {}
# self.rule = {'2':2,'J': 11, 'Q':12}
# for ele in p1:
# cur = self.rule[ele]
# if ele in p1:
# self.p1[cur] += 1
# else:
# self.p1[cur] = 1
# # 2:3,K:2
# self.p2 = {}
# def winner(self):
# # p1
# if self.straigt():
# return p1
# # p2
# self.straigt()
# # p1
#
# # maxi
# maxi_p1 = self.high(self, 'p1')
# maxi_p2 = self.high(self, 'p2')
# self.run('maxi', 'p1')
# self.run('maxi', 'p2')
# if maxi_p1 > maxi_p2:
# self.run('maxi', 'p1')
# return 'p1'
# else:
# self.run('maxi', 'p2')
# return 'p2'
#
#
# def straigt(self, p):
# # return T or F
#
# def three_kind
#
#
# def high(self, player):
# maxi = 0
# if player == 'p1':
# p = self.p1
# else:
# p = self.p2
# for ele in p:
# if ele > maxi:
# maxi = ele
# return maxi
# def CheckForSequence(arr, n, k):
# # Traverse the array from end
# # to start
# for i in range(n - 1, -1, -1):
# # if k is greater than
# # arr[i] then substract
# # it from k
# if (k >= arr[i]):
# k -= arr[i]
#
# # If there is any subsequence
# # whose sum is equal to k
# if (k != 0):
# return False
# else:
# return True
#
# # Driver code
#
#
# if __name__ == "__main__":
#
# A = [1, 3, 7, 15, 31]
# n = len(A)
#
# if (CheckForSequence(A, n, 18)):
# print(True)
# else:
# print(False)
#
# LinkedIn OA
# import collections
# def find_max_in_min(a, k):
# start = 0
# deque = collections.deque()
# res = float('-inf')
# for i in range(len(a)):
# cur = a[i]
# while len(deque) > 0 and a[deque[-1]] >= cur:
# deque.pop()
# deque.append(i)
#
# if i - start + 1 > k:
# if start == deque[0]:
# deque.popleft()
# start += 1
# if i - start + 1 == k:
# res = max(res, a[deque[0]])
# return res
# # a = [8,2,4]
# # k = 2
# # print(find_max_in_min(a, k))
# a = [1,3,-1,-3,5,3,6,7,3]
# k = 3
# print(find_max_in_min(a, k))
#
# a = [1,2,3,4,5,4,3,2]
# k = 3
# print(find_max_in_min(a, k))
#
# a = [0,0,0]
# k = 2
# print(find_max_in_min(a, k))
# def arbitrary_shopping(a, tgt):
# start = 0
# i = start
# sum_up = 0
# res = float('-inf')
# while i < len(a):
# while i < len(a) and sum_up + a[i] <= tgt:
# sum_up += a[i]
# i += 1
# if sum_up == tgt:
# res = max(res, i - start)
#
# sum_up -= a[start]
# start += 1
# return res
# a = [2,3,5,1,1,2,1] # 4
# tgt = 5
# print(arbitrary_shopping(a, tgt))
#
# a = [1,1,1,3,2,1,2,1,1] # 4
# tgt = 5
# print(arbitrary_shopping(a, tgt))
# def threshold_alert(n, numCall, alertThreshold, preceding):
# start = 0
# sum_up = 0
# n = len(numCall)
# res = 0
# for i in range(n):
# sum_up += numCall[i]
# if i - start + 1 == preceding:
# if sum_up // preceding > alertThreshold:
# res += 1
# sum_up -= numCall[start]
# start += 1
# return res
#
# n = 8
# numCall = [2, 2, 2, 2, 5, 5, 5, 8]
# alertThreshold = 4
# preceding = 3
# print(threshold_alert(n, numCall, alertThreshold, preceding))
# def break_panlim(a):
# i = 0
# j = len(a) - 1
# while i <= j and a[i] == 'a':
# i += 1
# j -= 1
#
# if i >= j:
# return False
# else:
# return a[:i] + 'a' + a[i + 1:]
#
# a = 'a'
# print(break_panlim(a)) #F
# a = 'aba'
# print(break_panlim(a)) #F
# a = 'aaa'
# print(break_panlim(a)) # F
# a = 'abcba'
# print(break_panlim(a)) # 'aacba'
# def double(a, b):
# # a = set(a)
# # while b in set(a):
# # b *= 2
# for i in range(len(a)):
# if a[i] == b:
# b *= 2
# return b
# b = 2
# a = [1, 2, 4, 11, 12]
# print(double(a, b))
# def map(a):
# directions = [(-1,0), (0, 1),(1, 0),(0, -1)] #up,right,down,left
# row = 0
# col = 0
# dir = 0
# for i in range(4):
# for ele in a:
# if ele == 'G':
# row += directions[dir][0]
# col += directions[dir][1]
# if ele == 'R':
# dir = (dir + 1) % 4
# if ele == 'L':
# dir = (4 + dir - 1) % 4
# return row == 0 and col == 0 and dir == 0
#
# a = 'G'
# print(map(a))
# a = 'L'
# print(map(a))
# a = 'RG'
# print(map(a))
# a = 'GLLG'
# print(map(a))
# a = 'GL'
# print(map(a))
# a = 'GLG'
# print(map(a))
# a = 'GLGLRG'
# print(map(a))
# a = 'GLRG'
# print(map(a))
# a = 'RGRGLGL'
# print(map(a))
#
#
#
#
#
# comicBook
# coin
# coinsNeeded
# consOfferd
# def xxx(comicBook,coins, coinsNeeded, consOfferd ):
# res = 0
# for left in range(comicBook + 1):
# if left * coinsNeeded <= (comicBook - left) * consOfferd + coins:
# res = max(res, left)
# return res
#
# comicBook = 3
# coins = 6
# coinsNeeded = 4
# consOfferd = 5
# print(xxx(comicBook,coins, coinsNeeded, consOfferd))
# comicBook = 10
# coins = 10
# coinsNeeded = 1
# consOfferd = 1
# print(xxx(comicBook,coins, coinsNeeded, consOfferd))
# comicBook = 393
# coins = 896
# coinsNeeded = 787
# consOfferd = 920
# print(xxx(comicBook,coins, coinsNeeded, consOfferd))
# comicBook = 4
# coins = 8
# coinsNeeded = 4
# consOfferd = 3
# print(xxx(comicBook,coins, coinsNeeded, consOfferd))
# import random
#
#
# def selectKItems(stream, n, k):
# array = [0] * k
# # 先把前k个存array里
# for i in range(k):
# array[i] = stream[i]
# i = k
# while (i < n):
# # 从0到i随机取个数
# j = random.randrange(i + 1)
# # j 如果落在k里,求去替换 j 位置的数
# if (j < k):
# array[j] = stream[i]
# i += 1
# return array
# def getMinimumUniqueSum(arr):
# # Write your code here
# if arr is None or len(arr) == 0:
# return 0
#
# num_to_freq = [0 for i in range(11)]
# for i in range(len(arr)):
# num = arr[i]
# num_to_freq[num] += 1
# temp = 0
# not_fill = 0
# for i in range(1, 11):
# if temp == 0 and num_to_freq[i] == 0:
# not_fill += i
# elif num_to_freq[i] == 0:
# temp -= 1
# elif num_to_freq[i] > 1:
# temp += 1
# elif num_to_freq[i] == 1:
# continue
# print(not_fill)
# return (1 + 10) * 10 // 2 - not_fill
# a = [2,2,2,2,2]
# print(getMinimumUniqueSum(a))
# def shuidi(s):
# i = 0
# res = ''
# while i < len(s):
# count = 1
# while i < len(s) - 1 and s[i + 1] == s[i]:
# count += 1
# i += 1
# if ord(s[i]) - ord('a') + 1 > 9:
# res += (str(ord(s[i]) - ord('a') + 1)) + '#'
# else:
# res += (str(ord(s[i]) - ord('a') + 1))
# if count > 1:
# res += '(' + str(count) + ')'
# i += 1
# return res
#
# print(shuidi('back'))#21311#
# print(shuidi('fooood'))
# print(shuidi('aaabbbbaaaa'))
# print(shuidi('sheathery'))
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
#
# class Solution:
# def __init__(self):
# self.error = ''
#
# def ddd(self, a):
# aj = {}
# for ele in a:
# if ele[0] not in aj:
# aj[ele[0]] = [ele[1]]
# else:
# aj[ele[0]].append(ele[1])
# visited = set()
# head_set = {}
# for key, child in aj.items():
# if len(child) > 2:
# return 'E1'
# if key not in visited:
# pass_by = set()
# node = TreeNode(key)
# if not self.dfs(key, visited, aj, pass_by, node, head_set):
# return self.error
# head_set[key] = node
# if len(head_set) > 1:
# return 'E5'
# else:
# head = [ele for ele in head_set.values()][0]
# stack = []
# stack.append(head)
# res = []
# return self.dfs_tree(head)
# def dfs_tree(self, root):
# if not root:
# return ''
# else:
# left = self.dfs_tree(root.left)
# right = self.dfs_tree(root.right)
# return '(' + str(root.val) + left + right + ')'
#
#
# def dfs(self, cur, visited, aj, pass_by, node, head_set):
# if node.val in pass_by: # E3
# self.error = 'E3'
# return False
# elif node.val in head_set:
# head_set.remove(node.val)
# return True
# pass_by.add(node.val)
# if node.val in aj:
#
# for child in aj[node.val]:
# if child in head_set:
# new = head_set[child]
# elif child in visited:
# self.error = 'E2'
# return False
# else:
# new = TreeNode(child)
# if not node.left:
# node.left = new
# elif not node.right:
# node.right = new
# else:
# self.error = 'E1'
# return False
# if not self.dfs(child, visited, aj, pass_by, new, head_set):
# return False
# visited.add(node.val)
# return True
#
# s = Solution()
# a = [('A','C'), ('B','G'), ('C', 'H'), ('B', 'D'), ('C', 'E'), ('A', 'B'), ('E', 'F')]
# print(s.ddd(a))
# def frequency1(s):
# i = len(s) - 1
# end = i
# res = ''
# count = 1
# while i >= 0:
# if s[i] == ')':
# while s[i] != '(':
# i -= 1
# count = int(s[i + 1: end])
#
# i -= 1
# end = i
# else:
# count = 1
# if s[i] == '#':
# i -= 2
# ele = s[i:end]
# else:
# ele = s[i:end + 1]
# letter = chr(int(ele) + 97 - 1)
# for k in range(count):
# res = letter + res
# i -= 1
# end = i
# tem = [0] * 26
# for ele in res:
# index = ord(ele) - 97
# tem[index] += 1
# return ''.join([str(ele) for ele in tem])
#
#
#
# def frequency(s):
# i = len(s) - 1
# end = i
# count = 1
# tem = [0] * 26
# while i >= 0:
# if s[i] == ')':
# while s[i] != '(':
# i -= 1
# count = int(s[i + 1: end])
# i -= 1
# end = i
# else:
# count = 1
# if s[i] == '#':
# i -= 2
# ele = s[i:end]
# else:
# ele = s[i:end+1]
# index = int(ele) - 1
# tem[index] += count
#
# i -= 1
# end = i
# return tem
#
#
# print(frequency('25#16#16#18#93(5465)'))
# print(frequency('615#(4)4'))
# print(frequency('1(3)2(4)1(4)'))
# print(frequency('19#85120#8518#25#'))
# import collections
# def possible_word(s):
# q = collections.deque()
# hash = set()
# q.append((s, 0))
# hash.add((s, 0))
# res = []
# while q:
# cur, start = q.popleft()
# if start == len(cur):
# res.append(cur)
# continue
# i = start
# j = i + 1
# count = 1
# break_flag = False
# while j < len(cur):
# while j < len(cur) and cur[j] == cur[i]:
# count += 1
# j += 1
# if count > 2:
# new1 = cur[:i] + cur[i] + cur[j:]
# q.append((new1, i + 1))
# new2 = cur[:i] + cur[i] + cur[i] + cur[j:]
# q.append((new2, i + 2))
# break_flag = True
# break
# else:
# i += 1
# j = i + 1
# if not break_flag:
# res.append(cur)
# return res
#
# s = 'leetcooodeee'
# print(possible_word1(s))
#
# s = 'letcooooodee'
# print(possible_word1(s))
s = 'abcdefs'
for i in range(len(s)-1, -1, -2):
print(s[i])
|
016434f27aba32f18907f1c6918f17d48ab3d279 | dundunmao/LeetCode2019 | /71. Simplify Path.py | 2,223 | 3.609375 | 4 |
class Solution(object):
def simplifyPath(self, path):
#把每个有效路径存places里,不存‘ ’和‘.’
places = [p for p in path.split("/") if p!="." and p!=""]
stack = []
for p in places: #对于存好的每个ele
if p == "..": #如果是‘..'就从stack里pop一个ele。如果不是就往stack里压入一个ele
if len(stack) > 0:
stack.pop()
else:
stack.append(p)
return "/" + "/".join(stack) #最后把stack用/join起来
class Solution1:
def simplifyPath(self, path: str) -> str:
res = []
i = 0
while i < len(path):
if path[i] == '/':
j = i + 1
# i占到一个'/', j找到下一个'/'
while j < len(path) and path[j] != '/':
j += 1
# 处理多个'/'
if j == i + 1:
i = j
# 处理有'/./'的情况
elif path[i + 1: j] == '.':
i = j
# 处理 '/../'的情况
elif path[i + 1: j] == '..':
if res:
res.pop()
i = j
# 其他情况,就是'/字母/'的情况
else:
res.append(path[i + 1: j])
i = j
res = '/'.join(res)
return '/' + res
#简化代码
class Solution2:
def simplifyPath(self, path: str) -> str:
res = []
i = 0
while i < len(path):
if path[i] == '/':
j = i + 1
while j < len(path) and path[j] != '/':
j += 1
if path[i + 1: j] == '..':
if res:
res.pop()
elif j != i + 1 and path[i + 1: j] != '.':
res.append(path[i + 1: j])
i = j
res = '/'.join(res)
return '/' + res
s = Solution2()
a = "/home//" # "/home/foo"
b = "/a/./b/../../c/" # "/c"
c = "/a/../../b/../c//.//"# "/c"
print(s.simplifyPath(a))
print(s.simplifyPath(b))
print(s.simplifyPath(c))
|
ca29c23ac842885b8661bbd34e8fd6a20bb16d83 | dundunmao/LeetCode2019 | /381. Insert Delete GetRandom O(1) - Duplicates allowed.py | 2,717 | 3.890625 | 4 | from random import choice
class RandomizedCollection:
def __init__(self):
"""
Initialize your data structure here.
"""
self.randomized_hash = {}
self.array = []
def insert(self, val: int) -> bool:
"""
Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
"""
if val in self.randomized_hash:
self.randomized_hash[val].append(len(self.array))
self.array.append(val)
return False
else:
self.randomized_hash[val] = [len(self.array)]
self.array.append(val)
return True
def remove(self, val: int) -> bool:
"""
Removes a value from the collection. Returns true if the collection contained the specified element.
"""
if val not in self.randomized_hash:
return False
else:
array_for_val = self.randomized_hash[val]
val_index = array_for_val.pop()
if len(array_for_val) == 0:
self.randomized_hash.pop(val)
if val_index == len(self.array) - 1:
self.array.pop()
return True
self.array[val_index], self.array[-1] = self.array[-1], self.array[val_index]
self.array.pop()
self.randomized_hash[self.array[val_index]].remove(len(self.array))
self.randomized_hash[self.array[val_index]].append(val_index)
return True
def getRandom(self) -> int:
"""
Get a random element from the collection.
"""
return choice(self.array)
# Your RandomizedCollection object will be instantiated and called as such:
obj = RandomizedCollection()
param_1 = obj.insert(10)
param_1 = obj.insert(10)
param_1 = obj.insert(20)
param_1 = obj.insert(20)
param_1 = obj.insert(30)
param_1 = obj.insert(30)
param_2 = obj.remove(10)
param_2 = obj.remove(10)
param_2 = obj.remove(30)
param_2 = obj.remove(30)
param_3 = obj.getRandom()
obj = RandomizedCollection()
param_1 = obj.insert(1)
param_1 = obj.insert(1)
param_2 = obj.remove(1)
param_3 = obj.getRandom()
obj = RandomizedCollection()
param_1 = obj.insert(1)
param_2 = obj.remove(2)
param_1 = obj.insert(2)
param_3 = obj.getRandom()
param_2 = obj.remove(1)
param_1 = obj.insert(2)
param_3 = obj.getRandom()
["RandomizedCollection","insert","insert","insert","insert","insert","insert","remove","remove","remove","remove","getRandom","getRandom","getRandom","getRandom","getRandom","getRandom","getRandom","getRandom","getRandom","getRandom"]
[[],[10],[10],[20],[20],[30],[30],[10],[10],[30],[30],[],[],[],[],[],[],[],[],[],[]]
|
51db392efffbfbbc86b4c8557660896b884de512 | dundunmao/LeetCode2019 | /199. Binary Tree Right Side View.py | 1,876 | 3.640625 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
from collections import deque
from collections import deque
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
q = deque()
q.append(root)
res = []
while q:
size = len(q)
for i in range(size):
cur = q.popleft()
if cur.left:
q.append(cur.left)
if cur.right:
q.append(cur.right)
res.append(cur.val)
return res
class Solution(object):
def rightSideView(self, root):
res = []
if root is None:
return res
right = self.rightSideView(root.right) #左子树的res
left = self.rightSideView(root.left) #右子树的res
res.append(root.val)
res.extend(right) #右子树的res全加入res里
for i in range(len(right), len(left)): #左子树多余的res全加入res里
res.append(left[i])
return res
#####
import collections
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
if not root:
return []
deque = collections.deque()
deque.append(root)
res = []
while len(deque):
size = len(deque)
res.append(deque[0].val)
for i in range(size):
cur = deque.popleft()
# 先加right再加left,这样每次for之前,只要把deque的第一个放res里就行
if cur.right:
deque.append(cur.right)
if cur.left:
deque.append(cur.left)
return res
|
ce3c6173edd8573af176473a0de58b581553e2ad | dundunmao/LeetCode2019 | /128. Longest Consecutive Sequence.py | 2,078 | 3.75 | 4 | # Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
#
# For example,
# Given [100, 4, 200, 1, 3, 2],
# The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
#
# Your algorithm should run in O(n) complexity.
# 麻烦的做法
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
num_to_count_set = set(nums)
node_list = {}
for value in num_to_count_set:
if value + 1 in num_to_count_set:
if value in node_list:
node_small = node_list[value]
else:
node_small = Node(value)
node_list[value] = node_small
if value + 1 in node_list:
node_big = node_list[value + 1]
else:
node_big = Node(value + 1)
node_list[value + 1] = node_big
node_small.next = node_big
node_big.pre = node_small
head_list = []
for node in node_list.values():
if node.pre == None:
head_list.append(node)
res = 1
for node in head_list:
length = 1
while node.next:
length += 1
node = node.next
res = max(res, length)
return res
class Node:
def __init__(self, val):
self.val = val
self.next = None
self.pre = None
##########################
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = set(nums)
maxlen = 0
while nums:
first = last = nums.pop()
while first - 1 in nums:
first -= 1
nums.remove(first)
while last + 1 in nums:
last += 1
nums.remove(last)
maxlen = max(maxlen, last - first + 1)
return maxlen
|
e23abce5463ea24cabd75aee1967d58369d52a85 | mattions/libNeuroML | /neuroml/examples/example5.py | 353 | 3.5 | 4 | """
This example shows how a morphology can be translated
such that the translated node moves to the new origin
and all other nodes move along with it
"""
import neuroml.morphology as ml
a=ml.Node([1,2,3,10])
b=ml.Node([4,5,6,20])
a.connect(b)
print a.morphology.vertices
b.translate_morphology([1,2,3])
print 'translated:'
print b.morphology.vertices
|
6108ea4b42d7de0e4059c54d6402e01bc56ba9de | jacobfdunlop/TUDublin-Masters-Qualifier | /binaryToDecimal.py | 424 | 3.984375 | 4 | user_num = input("Please Enter a binary number: ")
length = int(len(user_num))
power = ()
x = int()
z = int()
output = int()
while length >= 0:
z = int(user_num[length - 1])
if z == 1:
power = (2 ** x) * z
x += 1
length -= 1
output += power
else:
x += 1
length -= 1
print("Binary Number: ", user_num)
print(" Decimal Output: ", output)
|
9a6487e077eeefcb009581a7d4ad31284a4b064c | jacobfdunlop/TUDublin-Masters-Qualifier | /strings18.py | 368 | 3.796875 | 4 | user_str = input("Please enter a word: ")
while user_str != ".":
vowels = "aeiou"
if user_str[0] in vowels:
print(user_str + "yay")
else:
for a in range(len(user_str) + 1):
if user_str[a] in vowels:
print(user_str[a:] + user_str[0:a] + "ay")
user_str = "."
break
|
912a424503a40ee722d387c7e36c42d89154e97f | jacobfdunlop/TUDublin-Masters-Qualifier | /3.py | 170 | 3.890625 | 4 | speed = int(60)
birthday = bool(False)
if birthday == True:
speed -= 5
if speed <= 60:
print(0)
elif speed <= 80:
print(1)
else:
print(2)
|
efd37abad30060a9c670221bdf1beabb24d2fc08 | jacobfdunlop/TUDublin-Masters-Qualifier | /2.py | 299 | 3.90625 | 4 | temp = int(95)
summer = bool(True)
if (temp >= 60) and (temp <= 90) and (summer == (False)):
party = bool(True)
print(party)
elif (temp >= 60) and (temp <= 100) and (summer == (True)):
party = bool(True)
print(party)
else:
party = bool(False)
print(party)
|
fe94c67660a68772c4905710f2cf33d746899a4c | jacobfdunlop/TUDublin-Masters-Qualifier | /7.py | 117 | 4.0625 | 4 | usernum = int(input("Please enter a number: "))
if usernum % 2 == 0:
print("Even")
else:
print("Odd")
|
c593ca80cbc671e86d12f8d2ffaf0829fdb024ea | jacobfdunlop/TUDublin-Masters-Qualifier | /10.py | 470 | 4.1875 | 4 | usernum1 = int(input("Please enter a number: "))
usernum2 = int(input("Please enter another number: "))
usernum3 = int(input("Please enter another number: "))
if usernum1 > usernum2 and usernum1 > usernum3:
print(usernum1, " is the largest number")
elif usernum2 > usernum1 and usernum2 > usernum3:
print(usernum2, " is the largest number")
elif usernum3 > usernum1 and usernum3 > usernum2:
print(usernum3, " is the largest number")
|
0de459da4ba683c92fb56128f1eef870ab822c15 | jacobfdunlop/TUDublin-Masters-Qualifier | /calculator.py | 794 | 4.09375 | 4 |
check = bool(False)
while check == (False):
usernum1 = int(input("Please enter a number: "))
userop = str(input("Please enter an operator + - * or /: "))
usernum2 = int(input("Please enter a number: "))
if userop == "+":
answer = int(usernum1 + usernum2)
print(usernum1, "+", usernum2, "=", answer)
elif userop == "-":
answer = int(usernum1 - usernum2)
print(usernum1, "-", usernum2, "=", answer)
elif userop == "*":
answer = int(usernum1 * usernum2)
print(usernum1, "x", usernum2, "=", answer)
elif userop == "/":
answer = int(usernum1 / usernum2)
print(usernum1, "/", usernum2, "=", answer)
else:
print("Invalid response. Please Try Again")
|
5c98a2fc08bb815d3278866a9f32469c82a214cf | jacobfdunlop/TUDublin-Masters-Qualifier | /rev_secondword.py | 383 | 3.515625 | 4 | def reverse_second_word(user_str):
b = []
a = user_str.split(" ")
count = 0
for c in a:
if count % 2 != 0:
b.append(c[::-1])
count += 1
else:
b.append(c)
count += 1
print(' '.join(b))
string = "One thousand and eighty five hundred million euro"
reverse_second_word(string)
|
952e2170cc98d6d104decc89a0b26267b340624f | udrea/interplanetary-rover | /rover/rover.py | 4,697 | 3.765625 | 4 | from typing import List, Tuple
class PlanetGrid:
"""Class responsible for setting up the planet grid
"""
def __init__(self, grid_size: Tuple[int, int]) -> None:
self.m, self.n = grid_size # number of rows/columns of grid
self.grid = self.generate_grid()
def generate_grid(self) -> List[Tuple[int, int]]:
return [(x, y) for x in range(self.m) for y in range(self.n)]
def is_valid_grid(self):
if self.generate_grid():
return True
else:
return False
class Navigation(PlanetGrid):
"""Rover navigation commands
"""
ALLOWED_COMMANDS = ['F', 'B', 'L', 'R']
def __init__(
self, landing_position: Tuple[int, int, str], *args, **kwargs
) -> None:
self.landing_position = landing_position
super().__init__(*args, **kwargs)
def is_landing_position_valid(self) -> bool:
"""Check if landing position is inside the grid
"""
x_coord, y_coord, _ = self.landing_position
if (x_coord, y_coord) in self.grid:
return True
else:
return False
def calc_new_pos_vec(
self, current_position: Tuple[int, int, str], command: str
) -> Tuple[int, int, str]:
"""Compute new position vector based on current position and command
Args:
current_position (Tuple[int, int, str]): Current rover position
command (str): Command to execute ('F', 'B', 'L' or 'R')
"""
if self.is_landing_position_valid():
x_coord, y_coord, orientation = current_position
else:
raise Exception('Rover is off planet.')
if not self.is_valid_grid():
raise Exception('No planet for the rover to navigate on.')
if command in self.ALLOWED_COMMANDS:
if (command == 'F' and orientation == 'E') or (command == 'B' and orientation == 'W'):
x_coord += 1
elif (command == 'F' and orientation == 'W') or (command == 'B' and orientation == 'E'):
x_coord -= 1
elif (command == 'F' and orientation == 'N') or (command == 'B' and orientation == 'S'):
y_coord += 1
elif (command == 'F' and orientation == 'S') or (command == 'B' and orientation == 'N'):
y_coord -= 1
elif (command == 'L' and orientation == 'E') or (command == 'R' and orientation == 'W'):
orientation = 'N'
elif (command == 'L' and orientation == 'W') or (command == 'R' and orientation == 'E'):
orientation = 'S'
elif (command == 'L' and orientation == 'N') or (command == 'R' and orientation == 'S'):
orientation = 'W'
elif (command == 'L' and orientation == 'S') or (command == 'R' and orientation == 'N'):
orientation = 'E'
return self.wrap_around((x_coord, y_coord)) + (orientation,)
else:
raise Exception('Unrecognised command.')
def wrap_around(self, pos_coords: Tuple[int, int]) -> Tuple[int, int]:
"""Wrap around edges of grid if coordinates are outside
Args:
pos_coords (Tuple[int, int]): Position coordinates of rover
"""
m, n = max(self.grid)
x_coord, y_coord = pos_coords
if x_coord > m:
return (0, y_coord)
elif x_coord < 0:
return (m, y_coord)
elif y_coord < 0:
return (x_coord, n)
elif y_coord > n:
return (x_coord, 0)
else:
return pos_coords
class Rover(Navigation):
"""Class responsible for tracking rover movements
"""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
def begin_journey(
self, commands: List[str], obstacles: List[Tuple[int, int]]
) -> List[Tuple[int, int, str]]:
"""Execute rover movement commands and track its journey
Args:
commands (List[str]): List of commands to execute
obstacles (List[Tuple[int, int]]): Obstacles on the planet
"""
pos_vec = self.landing_position
journey_history = [pos_vec]
for command in commands:
new_pos_vec = self.calc_new_pos_vec(pos_vec, command)
xy_coord_pair = new_pos_vec[:2]
if xy_coord_pair in obstacles:
print(f'Last position: {pos_vec}')
raise Exception(f'Encountered obstacle at position: {new_pos_vec}')
else:
pos_vec = new_pos_vec
journey_history.append(pos_vec)
return journey_history
|
ff7a1bc5e6f0020f7dcaf65aa68eb1fd2ccb676f | kirankumarnallamalli/firstPyProject | /Sampletest.py | 561 | 3.890625 | 4 | #list
l1=["apple","Banana",1250,5000.23,"Kumar"]
print(l1)
l1.append("kiran")
print(l1)
l1.remove("kiran")
print(l1)
print(len(l1))
l1.reverse()
print(l1)
l1.pop(4)
print(l1)
#Tuples
t1=("Kiran",122,178.78,"Kiran",True,1234.56)
print(t1)
for t2 in t1:
print(t2)
print(len(t1))
x=list(t1)
print(x)
x.append("John")
print(x)
y=tuple(x)
print(y)
#Sets
S1={"Kiran","Kiran","JOhn",1234.67,8989}
print(S1)
S1.add("Watson")
print(S1)
#Dictionaries
thisdict={"Name":"Kiran","Age":31,"Sex":"Male"}
print(thisdict)
print(len(thisdict))
print((thisdict.keys()))
|
1d4b232ce7be7260fd8dc317a2fdb9cf13a35aef | bllxue090/210CT-Coursework | /basic_7.py | 238 | 3.875 | 4 |
def check_prime(n, x):
if(n<=1):
return False
if(x>=n):
return True
if(n%x==0):
return False
return check_prime(n,x+1)
if __name__ == '__main__':
n = 47
print check_prime(n, 2)
|
10f606d6afdf608dd51aa2641237550b75070466 | cryptogeekk/cryptography | /ceaser_encryption.py | 675 | 4.03125 | 4 | text=' ABCDEFGHIJKLMNOPQRSTUVWXYZ'
key=3
def caesar_encrypt(plain_text):
cipher_text=''
plain_text=plain_text.upper()
for l in plain_text:
index=text.find(l)
index=(index+key)%len(text)
cipher_text=cipher_text+text[index]
return cipher_text
def caesar_decrypt(cipher_text):
plain_text=''
for l in cipher_text:
index=text.find(l)
index=(index-key)%len(text)
plain_text=plain_text+text[index]
return plain_text
if __name__=="__main__":
encrypt=caesar_encrypt('This is an example')
print(encrypt)
decrypt=caesar_decrypt(encrypt)
print(decrypt) |
bf3011a8789935e977bf8f8965a53617627ffbe1 | abiodun0/amity-room-allocation | /tests/test_main.py | 5,083 | 3.84375 | 4 | import unittest
from models.people import *
from main import *
from models.room import *
class TestOfMainSpacesAllocation(unittest.TestCase):
"""
This are for testing the main.py class function and method
"""
def setUp(self):
"""
This is to setup for the rest of the testing the input
"""
self.andela = Building()
def test_to_check_all_all_lists_are_empty(self):
"""
This checks if the class is successfully initialized
"""
self.assertEqual(len(self.andela.spaces['offices']),0)
self.assertEqual(len(self.andela.spaces['livingspaces']),0)
def test_add_living(self):
"""
This checks for testing for adding more lving spaces
"""
self.andela.add_livingspace("Matrix")
self.assertEqual(len(self.andela.spaces['livingspaces']),1)
def test_add_office(self):
"""
This checks for testing for adding more office spaces
"""
self.andela.add_office("Joe")
self.assertEqual(len(self.andela.spaces['offices']),1)
def test_populate_spaces_with_rooms(self):
"""
Test for the randomly spaces method to make sure the offices length is up to 10
"""
self.andela.populate_spaces_with_rooms(10)
self.assertEqual(len(self.andela.spaces['offices']),10)
self.assertEqual(len(self.andela.spaces['livingspaces']),10)
def test_populate_from_files(self):
"""
Test if the employees are populated
"""
self.andela.populate_spaces_with_rooms()
self.andela.add_people_from_files("data/input.txt")
self.assertGreater(len(self.andela.employees),0)
def test_for_find_room_method(self):
"""
Test for add room as an instance of Amity
"""
self.andela.populate_spaces_with_rooms()
room = self.andela.find_room("offices","ROOM 2")
office = self.andela.find_room("livingspaces","ROOM 2")
self.assertIsInstance(room,Room)
def test_allocate_offices(self):
"""
Test the llocate method of the Spaces class
"""
self.andela.populate_spaces_with_rooms()
person = Fellow("Abiodun")
self.andela.allocate_to_space(person,"offices")
self.assertEqual(len(self.andela.allocated_people['offices']),1)
def test_for_get_unallocated_people_for_offices(self):
"""
This checks that there is a message for unallocated people for offices
"""
self.andela.populate_spaces_with_rooms()
self.andela.add_people_from_files("data/input.txt")
message = self.andela.get_unallocated_employee_for_office()
self.assertIsNotNone(message)
def test_for_get_unallocated_people_for_livings(self):
"""
This checks that there is a message for unallocated people for living space
"""
self.andela.populate_spaces_with_rooms()
self.andela.add_people_from_files("data/input.txt")
message = self.andela.get_unallocated_employee_for_living()
self.assertIsNotNone(message)
def test_for_print_all_occupants_name_filled(self):
"""
Test for print filled rooms names
"""
self.andela.populate_spaces_with_rooms(2)
self.andela.add_people_from_files("data/input.txt")
names = self.andela.print_occupants_names("livingspaces")
self.assertIsNone(names)
def test_for_find_room_function(self):
"""
Test for find room when the room is filled
"""
self.andela.populate_spaces_with_rooms(2)
self.andela.add_people_from_files("data/input.txt")
room_office = self.andela.find_room("offices","ROOM 2")
room_living = self.andela.find_room("livingspaces","ROOM 2")
self.assertIsInstance(room_living,Living)
self.assertIsInstance(room_office,Office)
def test_for_print_all_occupants_name_not_filled(self):
"""
Test for print not filled rooms names
"""
self.andela.populate_spaces_with_rooms(15)
self.andela.add_people_from_files("data/input.txt")
office = self.andela.print_occupants_names("offices")
self.assertIsNone(office)
def test_for_add_new_employee(self):
"""
Test for add new employee
"""
biodun = self.andela.add_new_employee("Abiodun Shuaib","FELLOW","Y")
self.assertIsInstance(biodun,Fellow)
def test_for_check_and_return_available_space(self):
"""
This check for return available spaces left in amity if there is any
"""
self.andela.populate_spaces_with_rooms(2)
office = self.andela.check_and_return_available_space("offices")
self.assertIsInstance(office,Room)
def test_for_check_and_return_available_spaces_filled(self):
"""
Check for if room is filled
"""
self.andela.populate_spaces_with_rooms(2)
self.andela.add_people_from_files("data/input.txt")
office = self.andela.check_and_return_available_space("offices")
self.assertNotIsInstance(office,Room)
self.assertGreater(self.andela.filled_spaces['offices'],0)
self.assertGreater(self.andela.filled_spaces['livingspaces'],0)
def test_for_get_all_rooms_and_occupants(self):
"""
Test for printable occupants of an office or living space
"""
all_spaces = self.andela.get_all_rooms_and_occupants()
office = self.andela.print_occupants_names("offices")
living = self.andela.print_occupants_names("livingspaces")
self.assertIsNone(all_spaces)
self.assertIsNone(office)
self.assertIsNone(living)
if __name__ == '__main__':
unittest.main() |
ebbb82d3b60fafbbd90fd254c7c813a99325b413 | KudoS1410/Fouriers | /p3.py | 2,021 | 3.671875 | 4 | """To make a moving point on a circle image"""
import cv2 as cv
import numpy as np
import math
import colorsys as cs
import random
page = np.zeros([512, 512, 3], np.uint8)
blank = page.copy()
time = 0
yplot = []
while True:
# reset the template each time we write a new screen
page = blank.copy()
# setting the drawing circle
center = (100, 256)
for i in range(3):
n = 2*i +1
radius = 50
radius = int(4 * radius/(n * math.pi))
# color = [0, 255, 255] # yellow
hue = i * 360 / 200
color = cs.hsv_to_rgb(hue, 100, 100)
color = [int(i%255) for i in color]
rand_col = [random.randrange(0, 255) for i in range(3)]
# print(color)
# color = [0, 255, 255]
# the base circle
cv.circle(img=page, center=center, radius = radius, color = rand_col, thickness= 4- i,lineType= cv.LINE_AA)
# finding the point to be shown
x = int(center[0] + radius * math.cos(n * time /20 + 0))
y = int(center[1] + radius * math.sin(n * time /20 + 0))
# page[y][x] = [255, 255, 255]
# plot the point
cv.circle(img = page, center=(x, y), radius= i % 5 + 1,color = color,thickness = -1,lineType=cv.LINE_AA )
center = (x, y)
yplot.append(center[1])
# draw the array of yplot
ax = 255
yplot.reverse()
cv.line(page, center, (255, yplot[0]), [255, 255, 255], lineType=cv.LINE_AA)
for i in range(len(yplot[:-1])):
value = yplot[i]
p1 = (ax, value)
p2 = (ax+2, yplot[i+1])
# cv.circle(page, (ax, value), 3, [255, 255, 255], -1, cv.LINE_AA)
if ax <= 510:
cv.line(page, p1, p2, [255, 255, 255], lineType=cv.LINE_AA)
ax += 1
else:
yplot.pop(i)
# print(len(yplot))
yplot.reverse()
cv.imshow('image', page)
k = cv.waitKey(50)
time += 1
if k == 27:
break
cv.destroyAllWindows() |
76425414b1d88727dc471850636025bccdfee408 | JackRDmacc/Final_Project | /ecommerce_project/Customer.py | 765 | 3.84375 | 4 | """Jack Reser
This program is an ecommerce store with a customer database and GUI
11/25/20"""
from ecommerce_project import Cart
class Customer:
"""class Customer"""
next_id = 1000
# Constructor
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
self.cust_id = self.next_id
self.next_id += 1
self.cart = Cart.Cart()
# This method calculates the new total price with tax and returns the total
def check_out(self):
total = self.cart.total_prices()
total = total * 1.07
return total
# This method outputs the customers name in the format of (lname, fname)
def name_output(self):
name = self.lname + ", " + self.fname
return name
|
993a0e034aba9cacecf504b877490a63e876604f | eloybarbosa/Desenvolvimento-Python-para-Redes-e-Sistemas-Operacionais | /AT/06/Servidor.py | 1,482 | 3.84375 | 4 | """
Escreva um programa cliente e servidor sobre TCP em Python em que:
O cliente envia para o servidor o nome de um diretório e recebe a lista de arquivos (apenas arquivos) existente nele.
O servidor recebe a requisição do cliente, captura o nome dos arquivos no diretório em questão e envia a resposta ao cliente de volta.
"""
#Servidor
import socket
import os
import pickle
socket_servidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
porta = 6666
socket_servidor.bind((host, porta))
socket_servidor.listen()
print("Servidor de nome", host, "esperando conexão na porta", porta)
while True:
(socket_cliente,addr) = socket_servidor.accept()
print("Conectado a:", str(addr))
print()
arquivo = socket_cliente.recv(1024)
print ('O cliente informou que quer a lista de arquivos (somente arquivos) do seguinte diretório: ', arquivo.decode('utf-8'))
print()
files=[]
if os.path.exists(arquivo):
arquivos = os.listdir(arquivo)
for i in range (len(arquivos)):
if os.path.isfile(arquivo + arquivos[i]) == True:
files.append(arquivos[i].decode('utf-8'))
print('No diretório informado contem os seguintes arquivos: ', files)
print()
resposta = pickle.dumps(files)
socket_cliente.send(resposta)
print('Lista de arquivos enviada para o cliente.')
else:
pass
socket_cliente.close()
|
7bef7916f76ce70d2ca19e5899b6b4e9f479a878 | farheenzaman01/computational-principles-in-python | /Entrance trackerFarheenZaman1.py | 2,027 | 4.09375 | 4 | # I created a progra for a user to sign in using their name a
#program records the number of people each user is signing in
#Program detects if the building is exceeding capacity
#proogram signs out user out of the system
#prpgram reports the signed in people (min/max) by one user
#declaring the function to ask the user for the number of sign is getting input
def entranceTracker():
try:
print("welcome to our service building, Please sign in")
name = str(input("Enter your name to sign in: "))
entry = float(input('Enter the number of people you want to sign in: '))
if 1 <= entry <= 5:#condiitonal variable to limit sign ins to minimum 5 people
return entry
else:#send invalid message if the user enters more than higher capacity
print('Error: Building cannot be occupied by more than 5 sign in')
return None
except:
print('Error: Invalid number')
def main():
repeat = 'y'
highest = 0
lowest = 0
total = 0
count = 0
while repeat == 'y':
entry = entranceTracker()
if entry == None: continue
if count == 0:
lowest = highest = entry
else:#declare that the building is at high capacity if the number is higher than 5
if highest < entry:
print('Currenty building is the highest capacity.'.format(entry))
highest = entry
elif lowest > entry:# declare vacancy for sign ins
print('There is more entry sign ins available .'.format(entry))
lowest = entry
total += entry
count += 1
repeat = input('Do you want to sign in more people?(y/n): ').lower() # asking the user for more input
#printing final output
print('Highest capacity recorded : {}'.format(highest))
print('Lowest capacity Recorded : {}'.format(lowest))
print("Enjoy your stay,Goodbye")
main()# ending the main function
|
06ed38941edbfc0f8d04c22ca71587b59b51df94 | farheenzaman01/computational-principles-in-python | /exam2.py | 2,699 | 4.03125 | 4 | #list created to store menue details
names = ['Coffee', 'Pizza', 'Burger', 'Fries', 'Donut']
costs = {"a":5.00, "b":6.00, "c":7.00, "d":8.00, "e":0}
status = {"default":"Confirmed", "a":"Prepared", "b":"On Delivery", "c":"Delivered", "d":"Cancelled"}
#following class and object is supposed to store the costs and names of food together
class Food(object):
def __init__(self, name, price):
self.name = name
self.price = price
def getprice(self):
return self.price
def __str__(self):
return self.name + ' : ' + str(self.getprice())
def buildmenu(names, costs):
menu = []
for i in range(len(names)):
menu.append(Food(names[i], costs[i]))
return menu
def report(orders, status):
print()
print(status + " Orders:")
count = 0
sum = 0
# for loop to check the status type in orders
for order in orders:
if status in orders[order]:
print(status + " order ", order, orders[order][0])
# sum of the orders
for value in orders[order][0]:
sum += value
count+= 1
else:
# print the report
print("There are %d orders in %s state"%(count, status))
if count!= 0:
print("Average order amount is $%1.2f"%(sum/count))
orders = {}
Foods = buildmenu(names, costs)
while choice != 0:
n = 1
for el in Foods:
print(n,'. ', el)
n = n + 1
print("Restaurant Ordering System")
print("1- Place an Order")
print("2- Change Order Status")
print("3- Report")
print("0- Exit")
choice = int(input("Choice:"))
while choice not in choices:
print("Invalid Choice!")
choice = int(input("Choice:"))
if choice == 1:
order = int(input("Order num?"))
while order in orders:
print("order number already in system")
order = int(input("Order #:"))
if choice == 2:
order = int(input("Order #:"))
if order not in orders:
print("Cannot find order")
else:
print("Status")
print("a- Prepared")
print("b- On Delivery")
print("c- Delivered")
print("d- Cancelled")
state = input("Set new order status: ")
if state not in status:
print("Invalid status!")
else:
orders[order][1] = status[state]
if choice == 3:
for key, value in status.items():
report(orders, value)
else:
print ("bye")
|
d9951e117fe7cd6107403eb6f7631f778561e8aa | farheenzaman01/computational-principles-in-python | /GIFT CARD TACKER.FARHEEN.py | 2,141 | 3.75 | 4 | def addgiftcard(code, giftcard_dic):#storing gift card ammount to the assigned codes to create a new card
if code < 10000:
print("Invalid code")
return
elif code >= 50000:
c = "$5"
elif code in range(40000, 50000):
c = "$4"
elif code in range(30000, 40000):
c = "$3"
elif code in range(20000, 40000):
c = "$2"
elif code in range(10000, 20000):
c = "$1"
if c in giftcard_dic:
giftcard_dic[c] += 1
def removegiftcard(code, giftcard_dic):#storing gift card ammount to the assigned codes for removal
if code < 10000:
print("Invalid code")
return
elif code >= 50000:
c = "$5"
elif code in range(40000, 50000):
c = "$4"
elif code in range(30000, 40000):
c = "$3"
elif code in range(20000, 40000):
c = "$2"
elif code in range(10000, 20000):
c = "$1"
if c in giftcard_dic:
giftcard_dic[c] -= 1
def report(giftcard_dic): #FUNCTION TO SHOW REPORT BASED OFF USERINPUT KEYS
c = n = tot = 0
print("You have:")
for key in giftcard_dic:
k = key
val = giftcard_dic[key]
print(" ",val,key+"-card")
c += val
d = int(key[-1])
tot += d*val
if val > 0:
n += 1
avg = tot/n
print("Total:",str(c)+" cards.")
print("Average:$" + str(round(avg,2)))
ch = 1
giftcard_dic = {"$5":0, "$4":0, "$3":0, "$2":0, "$1":0}
while ch != 0:
print()
print("Gift Card Tracker") #MAIN MENU
print("1- Add Gift Card")
print("2- Remove Gift Card")
print("3- Report")
print("0- Exit")
ch = input("Choice: ")
ch = int(ch)
if ch in range(0,4):#asking using for userinput for gift code
if ch == 1 or ch == 2:
code = input("Code: ")
code = int(code)
if ch == 1:#putting created function as output to user choices
addgiftcard(code, giftcard_dic)
elif ch == 2:
removegiftcard(code, giftcard_dic)
elif ch == 3:
report(giftcard_dic)
else:
print("Invalid ") |
20cad7654cd9b3f27d9263d17bf10871e75442fc | YuriiSynyavskiy/PythonForBeginnersRofl | /class.py | 3,634 | 3.5625 | 4 |
'''
#1
def sered(*args):
sum = 0
for i in args:
sum+=i
return sum/len(args)
print(sered(10,20,30))
#2
def myAbs(number):
return number if number>0 else number*(-1)
print(myAbs(-2))
print(myAbs(-4))
print(myAbs(2))
#3
def max(var_1, var_2):'''
#docstring
'''
return var_1 if var_1>=var_2 else var_2
print(max.__doc__, end=' ')
print(max(8,-2))
#4
from math import sqrt
from math import pi
def rectangleSquare(side_1, side_2):
return side_1*side_2
def triangleSquare(side_1,side_2,side_3):
p = (side_1+side_2+side_3)/2
return sqrt(p*(side_1-p)*(side_2-p)*(side_3-p))
def circleSquare(r):
return 4*pi*r*r
square = int(input('Input object - 1:rectanle 2:triangle 3:circle'))
if square == 1:
side_1 = int(input('Input 1 side of rectangle : '))
side_2 = int(input('Input 2 side of rectangle : '))
print('S = {0} * {1} = {2}'.format(side_1,side_2,rectangleSquare(side_1,side_2)))
elif square == 2:
side_1 = int(input('Input 1 side of triangle : '))
side_2 = int(input('Input 2 side of triangle : '))
side_3 = int(input('Input 3 side of triangle : '))
print('S = {0}'.format(triangleSquare(side_1,side_2,side_3)))
elif square == 3:
r = int(input('Input R of circle : '))
print('S = 4*\u03C0*{0}\U000000B2 = {1}'.format(r,circleSquare(r)))
else:
print('Unknown symbol')'''
#5
def sum(number):
sum=0
for i in number:
sum+=int(i)
return sum
print(sum(input('Input ur number : ')))
#6
def sum(a,b):
return a+b
def substract(a,b):
return a-b
def multiplicate(a,b):
return a*b
def divide(a,b):
if b==0:
raise ZeroDivisionError
else:
return a/b
def calc_main():
operation = input('* / - + :')
if operation == '*':
firstNumber = int(input('Input first number : '))
secondNumber = int(input('Input second number : '))
print('{0} * {1} = {2}'.format(firstNumber,secondNumber,multiplicate(firstNumber,secondNumber)))
elif operation =='/':
firstNumber = int(input('Input first number : '))
secondNumber = int(input('Input second number : '))
try:
print('{0} / {1} = {2}'.format(firstNumber, secondNumber, divide(firstNumber, secondNumber)))
except ZeroDivisionError:
print('Can not divide by 0')
elif operation =='+':
firstNumber = int(input('Input first number : '))
secondNumber = int(input('Input second number : '))
print('{0} + {1} = {2}'.format(firstNumber, secondNumber, sum(firstNumber, secondNumber)))
elif operation =='-':
firstNumber = int(input('Input first number : '))
secondNumber = int(input('Input second number : '))
print('{0} - {1} = {2}'.format(firstNumber, secondNumber, substract(firstNumber, secondNumber)))
else:
print('Unknown operation')
calc_main()
#7
from math import sqrt
def fib(number):
if number == 0:
return 0
elif number == 1:
return 1
else:
return fib(number - 1) + fib(number - 2)
for i in range(20):
print(fib(i), end=' ')
#8
def quadraticEquation(a,b,c):
return b*b-4*a*c
randomVar = input('\n Input like this a*x2+b*x1+c=d :')
a = int(randomVar[0])
b = int(randomVar[5])
c = int(randomVar[10]) - int(randomVar[12])
D = quadraticEquation(a,b,c)
print('\U0000221A D = ',sqrt(D))
if D >= 0:
print('x1 = {0} \n x2 = {1}'.format((-b + sqrt(D))/(2*a),(-b - sqrt(D))/(2*a)))
else:
print("D<0 this equation havеn't roots")
|
9e8651c2be2e81b9260ff07ec4f1c69d3de4ecfe | Uther88/metabol | /metabol.py | 3,003 | 4 | 4 | #---------------------------------------------------------------------------------#
# Программа для расчета скорости метаболизма и количества необходимых калорий #
# для поддержания актуальной массы тела в течении суток, в зависимости от уровня #
# дневной активности #
#---------------------------------------------------------------------------------#
# Функция для расчета для мужского организма
def man():
try:
weight = int(input("Ваш вес(кг): "))* 13.75
except ValueError:
print("Ошибка!")
weight = int(input("Ваш вес(кг): "))* 13.75
try:
height = int(input("Ваш рост(см): "))* 5
except ValueError:
print("Ошибка!")
height = int(input("Ваш рост(см): "))* 5
try:
age = int(input("Ваш возраст: "))* 6.76
except ValueError:
print("Ошибка!")
age = int(input("Ваш возраст: "))* 6.76
finally:
meta = int(66.47 + weight + height - age)
print("Скорость вашего метаболизма равна: " + str(meta))
print("Необходимое колличество калорий в сутки (в зависимости от физ. активности) состовляет от " + str(int(meta*1.2))+ " до " + str(int(meta*1.9)) + " калорий ")
# Функция для расчета для женского организма
def woman():
try:
weight = int(input("Ваш вес(кг): "))* 9.56
except ValueError:
print("Ошибка!")
weight = int(input("Ваш вес(кг): "))* 9.56
try:
height = int(input("Ваш рост(см): "))* 1.85
except ValueError:
print("Ошибка!")
height = int(input("Ваш рост(см): "))* 1.85
try:
age = int(input("Ваш возраст: "))* 4.68
except ValueError:
print("Ошибка!")
age = int(input("Ваш возраст: "))* 4.68
finally:
meta = int(655.1 + weight + height - age)
print("Скорость вашего метаболизма равна: " + str(meta))
print("Необходимое колличество калорий в сутки (в зависимости от физ. активности) состовляет от " + str(int(meta*1.2))+ " до " + str(int(meta*1.9)) + " калорий ")
# Основная функция запуска приложения
def func():
q = input("Какой ваш пол? (м/ж)")
if q == 'м':
man()
elif q == 'ж':
woman()
else:
print("Ошибка!")
func()
func()
|
267335a2b28e9bc77b99f0b288f5bbb6f5b4d763 | KelseySlavin/CIS104 | /Assignments/Lab1/H1P1.py | 524 | 4.15625 | 4 | first_name = input("What is your first name?: ")
last_name = input("What is your last name?: ")
age = int(input("What is your age?: "))
confidence=int(input("How confident are you in programming between 1-100%? "))
dog_age= age * 7
print("hello, " + first_name+ " " + last_name + " , nice to meet you! You might be " + str(age) + " in human years, but in dog year you are " +str(dog_age)+"." )
if confidence < 50:
print("I agree, programmers can't be trusted!")
else:
print("Writing good code takes hard work!")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.