blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
8f4cb8cbb8f0b0b47c32ae695ff90be71d0ddc32 | gioliveirass/atividades-pythonParaZumbis | /Lista de Exercicios I/Ex01.py | 219 | 3.953125 | 4 | # Exercicio 01
print('Exercicio 01: Calculando a Soma de dois números!')
n1 = int(input('Insira um número: '))
n2 = int(input('Insira outro número: '))
soma = n1 + n2
print(f'A soma dos números inseridos é {soma}') |
ad5a4b4510f4fba1c1439b99a4e4a6167709997c | lbtdne/Coffee-Machine | /coffee_machine.py | 3,078 | 3.984375 | 4 | machine_steps = ["Starting to make a coffee",
"Grinding coffee beans",
"Boiling water",
"Mixing boiled water with crushed coffee beans",
"Pouring coffee into the cup",
"Pouring some milk into the cup",
"Coffee is ready!"]
recipes_ = [[250, 0, 16, 1, -4], [350, 75, 20, 1, -7], [200, 100, 12, 1, -6]]
active_recipe = [0, 0, 0, 0, 0]
machine_levels = [400, 540, 120, 9, 550]
trig_end = False
def request_action():
global trig_end
print("Write action (buy, fill, take, remaining, exit):")
action_ = str(input())
if action_ == "buy":
recipe_selector()
make_coffee()
elif action_ == "fill":
fill_machine()
elif action_ == "take":
take_money()
elif action_ == "remaining":
print_levels()
elif action_ == "exit":
trig_end = True
def print_levels():
global machine_levels
print("The coffee machine has:")
print(str(machine_levels[0])
+ " of water")
print(str(machine_levels[1])
+ " of milk")
print(str(machine_levels[2])
+ " of coffee beans")
print(str(machine_levels[3])
+ " of disposable cups")
print(str(machine_levels[4])
+ " of money")
def fill_machine():
global machine_levels
message_ = ["Write how many ml of water do you want to add:",
"Write how many ml of milk do you want to add:",
"Write how many grams of coffee beans do you want to add",
"Write how many disposable cups of coffee do you want to add"]
for i in range(len(message_)):
print(message_[i])
machine_levels[i] = machine_levels[i] + int(input())
def how_many_cups():
global machine_levels
global active_recipe
cups_ = []
parts_ = ["water", "milk", "coffee beans", "cups"]
for i in range(len(active_recipe)):
if active_recipe[i] > 0:
cups_.append(float(machine_levels[i] / active_recipe[i]))
else:
cups_.append(float(1))
if min(cups_) < 1:
return parts_[cups_.index(min(cups_))]
else:
return "True"
def recipe_selector():
global recipes_
global active_recipe
print("What do you want to buy?\n"
"1 - espresso\n"
"2 - latte\n"
"3 - cappuccino:")
chosen_ = input()
if chosen_ == "back":
request_action()
else:
active_recipe = recipes_[int(chosen_) - 1]
def make_coffee():
global active_recipe
global machine_levels
if how_many_cups() == "True":
print("I have enough resources, making you a coffee!")
machine_levels = [machine_levels[i] - active_recipe[i] for i in range(len(machine_levels))]
else:
print("Sorry, not enough "
+ str(how_many_cups())
+ "!")
def take_money():
global machine_levels
print("I gave you $"
+ str(machine_levels[4]))
machine_levels[4] = 0
while not trig_end:
request_action()
else:
exit() |
296cc9fc649aec65aa297645babfe674d91232ad | DenVankov/Numerical-Methods | /Lab1/NM_1_1.py | 4,860 | 3.671875 | 4 | from random import randint
class MatrixException(Exception):
pass
def getCofactor(A, tmp, p, q, n): # Function to get cofactor of A[p][q] in tmp[][]
i = 0
j = 0
# Copying into temporary matrix only those element which are not in given row and column
for row in range(n):
for col in range(n):
if row != p and col != q:
tmp[i][j] = A[row][col]
j += 1
if j == n - 1:
j = 0
i += 1
def determinant(A, n):
D = 0
if n == 1:
return A[0][0]
tmp = [[0] * n for _ in range(n)] # Cofactors
sign = 1 # Plus or minus
for i in range(n):
getCofactor(A, tmp, 0, i, n)
D += sign * A[0][i] * determinant(tmp, n - 1)
sign = -sign
return D
def adjoin(A, n): # Сопряженная
adj = [[0] * n for _ in range(n)]
if n == 1:
adj[0][0] = 1
return
tmp = [[0] * n for _ in range(n)] # Cofactors
sign = 1 # Plus or minusn
for i in range(n):
for j in range(n):
getCofactor(A, tmp, i, j, n) # Cofactor A[i][j]
if (i + j) % 2 == 0:
sign = 1
else:
sign = -1
adj[j][i] = (sign) * (determinant(tmp, n - 1)) # transpose of the cofactor matrix
return adj
def inverse(A, B, n):
det = determinant(A, n)
if det == 0:
print("Singular matrix, can't find its inverse")
return False
adj = adjoin(A, n)
for i in range(n):
for j in range(n):
B[i][j] = adj[i][j] / det
return True
def transpose(A, n):
B = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
B[i][j] = A[j][i]
return B
def multi(M1, M2):
sum = 0 # сумма
tmp = [] # временная матрица
ans = [] # конечная матрица
if len(M2) != len(M1[0]):
raise MatrixException('Matrix can\'t be multiplied')
else:
row1 = len(M1) # количество строк в первой матрице
col1 = len(M1[0]) # Количество столбцов в 1
row2 = col1 # и строк во 2ой матрице
col2 = len(M2[0]) # количество столбцов во 2ой матрице
for k in range(0, row1):
for j in range(0, col2):
for i in range(0, col1):
sum = round(sum + M1[k][i] * M2[i][j], 8)
tmp.append(sum)
sum = 0
ans.append(tmp)
tmp = []
return ans
def show(A, n):
for i in range(0, n):
for j in range(0, n):
print("\t", A[i][j], " ", end="")
print("\n")
def LUP_solve(L, U, pi, b, n):
x = [0 for i in range(n)]
y = [0 for i in range(n)]
for i in range(n):
summ = 0
for j in range(i):
summ += L[i][j] * y[j]
y[i] = b[pi[i]] - summ
for i in range(n - 1, -1, -1):
sec_summ = 0
for j in range(i + 1, n):
sec_summ += U[i][j] * x[j]
x[i] = (y[i] - sec_summ) / U[i][i]
x = [round(x[i], 5) for i in range(len(x))]
return x
def LUP_decompose(A, n):
pi = [i for i in range(n)]
for k in range(n):
p = 0
for i in range(k, n):
if abs(A[i][k]) > p:
p = abs(A[i][k])
tmp_k = i
if p == 0:
raise MatrixException('Matrix is degenerate')
pi[k], pi[tmp_k] = pi[tmp_k], pi[k]
for i in range(n):
A[k][i], A[tmp_k][i] = A[tmp_k][i], A[k][i]
for i in range(k + 1, n):
A[i][k] = A[i][k] / A[k][k]
for j in range(k + 1, n):
A[i][j] = A[i][j] - A[i][k] * A[k][j]
return pi
def get_LU(A):
n = len(A)
L = [[0] * n for i in range(0, n)]
U = [[0] * n for i in range(0, n)]
for i in range(n):
L[i][i] = 1
for j in range(n):
if j < i:
L[i][j] = A[i][j]
else:
U[i][j] = A[i][j]
return L, U
if __name__ == '__main__':
print("Input demention of matrix: ")
n = int(input())
A = []
for i in range(n):
A.append(list(map(float, input().split())))
print("Start:")
show(A, n)
print("The Adjoint is :\n")
inv = [[0] * n for _ in range(n)]
adj = adjoin(A, n)
show(adj, n)
print("The Inverse is :\n")
if inverse(A, inv, n):
show(inv, n)
pi = LUP_decompose(A, n)
print("A after LUP:")
show(A, n)
L, U = get_LU(A)
print("L:")
show(L, n)
print("U:")
show(U, n)
print("A:\n")
R = multi(L, U)
show(R, n)
print("Solving:")
b = [-23, 39, -7, 30]
print(LUP_solve(L, U, pi, b, n))
|
69df0ffef277af6e3466541e8e07265ed79b960e | GGGomer/AoC2020 | /02/02b.py | 1,012 | 3.609375 | 4 | import re
def main():
f = open("./02input", 'r')
line = f.readline()
lowest_indices = []
highest_indices = []
characters = []
passwords = []
# Loop through all lines
while line:
# deconstruct line into elements for lists
decimals = re.findall(r'\d+', line)
lowest_indices.append(int(decimals[0]))
highest_indices.append(int(decimals[1]))
characters.append(re.search(r'[a-z]', line).group())
passwords.append(re.sub('\n',"",re.split(": ", line)[1]))
# Next line
line = f.readline()
# Assert if arrays are of same length
assert len(passwords) == len(lowest_indices)
assert len(passwords) == len(highest_indices)
assert len(passwords) == len(characters)
# Count correct passwords
correct_passwords = 0
for i in range(len(passwords)):
if((passwords[i][lowest_indices[i]-1] == characters[i])^(passwords[i][highest_indices[i]-1] == characters[i])):
correct_passwords += 1
print(correct_passwords)
if __name__ == "__main__":
main()
|
2d120b9d6eb107bbd9404e0a20c88b354f0944cc | aaskorohodov/Learning_Python | /Обучение/Range comprehension.py | 189 | 3.515625 | 4 | list = [eo * 2 for eo in range(10,1,-1) if eo % 2 != 1]
print(list)
words = ["hello", "hey", 'goodbey', "guitar", "piano"]
words2 = [eo + "." for eo in words if len(eo) < 7]
print(words2) |
ab1df5f6495bf2de81da4b47c6f82acf8b9645ae | aaskorohodov/Learning_Python | /Обучение/Set (множество).py | 477 | 4.15625 | 4 | a = set()
print(a)
a = set([1,2,3,4,5,"Hello"])
print(a)
b = {1,2,3,4,5,6,6}
print(b)
a = set()
a.add(1)
print(a)
a.add(2)
a.add(10)
a.add("Hello")
print(a)
a.add(2)
print(a)
a.add("hello")
print(a)
for eo in a:
print(eo)
my_list = [1,2,1,1,5,'hello']
my_set = set()
for el in my_list:
my_set.add(el)
print(my_set)
my_set = set(my_list)
print(my_set)
my_list = list(my_set)
print(my_list)
a = {"hello", "hey", 1,2,3}
print(5 in a)
print(15 not in a)
|
7e39b989796a5177bff5ea327f1566012aeb5a37 | aaskorohodov/Learning_Python | /Обучение/Вывод чисел меньше х.py | 189 | 3.59375 | 4 | a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for elem in a:
if elem < 5:
print(elem)
print([elem for elem in a if elem < 5])
b = 0
while a[b] < 5:
print(a[b])
b += 1 |
32b882820ebdb60f96270d0e908bc0ba2cf559f6 | aaskorohodov/Learning_Python | /Обучение/What do U want to eat.py | 266 | 4 | 4 | print("Введите выше имя, затем нажмите Entr")
name = input()
print(name + ", что вы хотите поесть?")
food = input()
print("")
print(name + ", немедленно идите в магизин и купите " + food + "!") |
f1aae24aa9c84713a937dace34fdbda5d367cb50 | aaskorohodov/Learning_Python | /Обучение/Думать на языке Питон/Is_sorted.py | 292 | 3.640625 | 4 | a = ['a', 'v', 'a']
b = [1, 2, 3, 5, 4]
def is_sorted(lis):
i = 0
for el in lis:
try:
if lis[i] <= lis[i+1]:
i = i + 1
else:
return False
except IndexError:
pass
return True
print(is_sorted(a)) |
f407b77eda6e4ceaf757b664a2cf0d03ec59337d | aaskorohodov/Learning_Python | /Обучение/Думать на языке Питон/Metathesis pair.py | 4,342 | 4.03125 | 4 | '''Ищет пары-метатезисы – такие слова, где перестановка дищь 2х букв дает другое слово'''
file = open('C:\word.txt')
words = ''
for eo in file:
words += eo
'''Превращаем файл в строку, где каждое слово идет с новой строки.'''
def anagrams(all_words):
'''
Ищем анаграмы, собирая их в словарь, где ключ = последовательность букв, а значение = последовательность слов,
которые можно собрать из этих букв.
1. Создаем пустой словарь
2. Для каждого элемента (строки) исходного списка (строки), вызываем функцию, которая вернет список букв,
из которых состоит это слово. Буквы возвращаются в алфавитном порядке, но их порядок роли не играет, он нужен,
чтобы сделать следующий шаг
3. Если этого набора букв еще нет в словаре, то кладем на место ключа, а значением кладем слово в виде списка.
4. Если набор букв уже есть в словаре, то кладем к нему в значение (в список) слово, из которого получились эти буквы.
'''
an_dict = {}
for el in all_words.split('\n'):
l = letters(el)
if l not in an_dict:
an_dict[l] = [el]
else:
an_dict[l].append(el)
return an_dict
def letters(word):
'''Берет слово и превращает его в набор букв, из которогоэто слово состоит. Буквы ставит в алфавитный порядок.'''
let = list(word)
let.sort()
let = ''.join(let)
return let
def metathesis_pair(words):
'''
Среди собранного ранее словаря ищет пары-метатезисы.
1. Берет исходный словарь и начинает перебирать списки (for ang in an_dict.values():)
2. Для каждого слова в списке, пребирает все прочие слова в списке
3. Если слова отличаются (причем первое меньше второго) и если разница между словами == 2 буквы, то вот наша пара.
*сравнивать слова (<) надо, чтобы пара не попала в выдачу дважды. Это условие дает возможность сравнить 2 слова
по разнице в 2 буквы первый раз, но переверни слова, и в выдачу они уже не попадут.
**для сравнения на 2 буквы вызывается другая функция
'''
global anagrams
an_dict = anagrams(words)
for ang in an_dict.values():
for word1 in ang:
for word2 in ang:
if word1 < word2 and word_difference(word1, word2) == 2:
print(word1, word2)
def word_difference(word1, word2):
'''
Сравнивает 2 слова, считает, на сколько букв они отличаются. Каждое различие == другая буква в том же месте слова.
1. Заводит счетчик различий
2. Сравнивает длину слов, если совпадает, то идет дальше
3. Зипует слова, делая список кортежей, где в каждом (кортеже) лежат по 1 букве из кождого слова
4. Берет кортеж и сравнивает быквы, если они не одинаковы, то добавляет в счетчик 1.
'''
count = 0
if len(word1) == len(word2):
for c1, c2 in zip(word1, word2):
if c1 != c2:
count += 1
return count
metathesis_pair(words) |
ffbda9f72900acc80ed03bf871db381d5ce5fc5e | aaskorohodov/Learning_Python | /Обучение/Думать на языке Питон/Avoids.py | 2,388 | 3.8125 | 4 | avoid_ths = input()
'''Принимает от пользователя набор стоп-букв'''
file = open('C:\word.txt')
'''открывает файл с большим количеством слов'''
words = ''
for eo in file:
words += eo
words = words.replace('\n', ' ')
'''собирает из файла строку со словами через пробел'''
def avoids(list, avoid_ths):
'''принимает набор слов и стоп слова. превращает набор слов в список.
Каждое слово из списка передает функции, которая принимает решение "есть ли стоп-буква в этом слове" и возвращает ответ remove, если слово надо убрать.
В случае ответа remove, ничего не происходит, а если ответ не приходит, то слово заносится в новый список.
*у меня не получилось убирать слова из старого списка, потому что в этом случае список начинает прыгать через слово.
**берет первое слово в списке, его надо убрать, убирает, берет второе слово в списке, но второе слово теперь третье (одно ведь убрали), и так пропускает слова.
в конце печатает получившийся список и длину этого списка (сколько там слов)'''
list = list.split()
list2 = []
for word in list:
if avoid_checker(word, avoid_ths) == 'remove':
pass
else:
list2.append(word)
print(list2)
print(len(list2))
def avoid_checker(word, avoid_ths):
'''Принимает слово и стоп-буквы, и то и другое строкой, стоп-буквы без пробелов. Берет каждую букву слова и сравнивает со стоп-буквами.
Если совпадает хоть с одной стоп-буквой, то возвращает remove'''
for letter in word:
if letter in avoid_ths:
return 'remove'
avoids(words, avoid_ths) |
db236bab002eac619047121dde53949450c3daf6 | aaskorohodov/Learning_Python | /Обучение/Dict counter 2.py | 680 | 3.625 | 4 | text = "привет привет привет пока пока здрасьте"
my_dict2 = {}
for eo in text.split():
my_dict2[eo] = my_dict2.get(eo, 0) + 1 #часть до знака = присваивает словарю ключ, часть справа присваивает значение, при этом...
#...get возвращает значение по ключу eo, чтобы его и присвоить, а если ключа нет, то присваивается 0. Ко всему добавляется 1, чтобы если ключ есть то +1, если нет, то 0+1
print(my_dict2) |
c6bfbae89417c7307e7ff93ea916db38b789ac6c | aaskorohodov/Learning_Python | /Обучение/Классы - наследование.py | 857 | 4.03125 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print("Person created")
def say_hello(self):
print(f"{self.name} say hello!")
class Student(Person):
def __init__(self, name, age, average_grade):
#Person.__init__(self, name, age)
super().__init__(name, age)
self.average_grade = average_grade
print("Student created")
def study(self):
print(f"{self.name} studies")
def say_hello(self):
super().say_hello()
print(f"Student with name: {self.name} say hello!")
class Teacher(Person):
pass
def introduce(person):
print("Now, a person will say hello")
person.say_hello()
people_qrr = [Student("Tom", 18, 3.5), Teacher("Katy", 45), Student("Bob", 26, 4.8)]\
for person in people_qrr:
introduce(person) |
9beefaee0cd2529075f223c1e2fb39871d45f24c | bjlovejoy/workoutPi | /challenge.py | 5,594 | 3.515625 | 4 | import os
import datetime
from time import time, sleep
from gpiozero import Button, RGBLED, Buzzer
from colorzero import Color
from oled import OLED
'''
Creates or appends to file in logs directory with below date format
Each line contains the time of entry, followed by a tab, the entry text and a newline
'''
def log_data(text):
today_date = str(datetime.date.today()).replace("-", "_")
hour_min = (datetime.datetime.now()).strftime("%H:%M")
log_path = "/home/pi/workoutPi/logs/error_log_" + today_date + ".txt"
append_write = "w"
if os.path.isfile(log_path):
append_write = "a"
with open(log_path, append_write) as log:
line = hour_min + "\t" + text + "\n"
log.write(line)
class Challenge:
def __init__(self, name, style, description, num_time_sec=60, lowest=True):
"""
name: name of the challenge to save to text file (str)
style: how long it takes to do activity ("stopwatch") or how many done in timeframe ("counter") (str)
num_time_sec: time for "counter" challenges (int)
description: text to output to OLED display for challenge (str)
lowest: if True, then lowest time (stopwatch) is highest score
"""
self.name = name.replace(" ", "_")
self.style = style
self.description = description
self.num_time_sec = num_time_sec
self.lowest = lowest
def save_results_counter(self, button, oled, led):
records_path = "/home/pi/workoutPi/records/" + self.name + ".txt"
edit_file = False
nums = list()
select = False
num = 0
while not select:
oled.show_num(num, "How many?")
button.wait_for_press()
held_time = time()
sleep(0.05)
while button.is_pressed:
if time() - held_time > 1.5:
led.color = Color("green")
select = True
sleep(0.05)
if not select:
num += 1
led.off()
if os.path.isfile(records_path):
with open(records_path, 'r') as rec:
nums = rec.readlines()
if num > int(nums[0].rstrip('\n')):
nums[2] = nums[1]
nums[1] = nums[0]
nums[0] = str(num) + '\n'
edit_file = True
elif num > int(nums[1].rstrip('\n')):
nums[2] = nums[1]
nums[1] = str(num) + '\n'
edit_file = True
elif num > int(nums[2].rstrip('\n')):
nums[2] = str(num) + '\n'
edit_file = True
if edit_file:
with open(records_path, "w") as rec:
rec.writelines(nums)
else:
edit_file = True
record = str(num) + '\n'
nums.append(record)
nums.append("0\n")
nums.append("0\n")
with open(records_path, "w") as rec:
rec.writelines(nums)
log_data("Challenge counter event saved: " + str(num) + "\tin list: " + str(nums))
log_data("Saved location: " + records_path)
oled.challenge_records(nums, "reps", edit_file)
def save_results_stopwatch(self, recorded_time, oled):
records_path = "/home/pi/workoutPi/records/" + self.name + ".txt"
edit_file = False
times = list()
if os.path.isfile(records_path):
with open(records_path, 'r') as rec:
times = rec.readlines()
if lowest:
if recorded_time < float(times[0].rstrip('\n')) or float(times[0].rstrip('\n')) == 0:
times[2] = times[1]
times[1] = times[0]
times[0] = str(recorded_time) + '\n'
edit_file = True
elif recorded_time < float(times[1].rstrip('\n')) or float(times[1].rstrip('\n')) == 0:
times[2] = times[1]
times[1] = str(recorded_time) + '\n'
edit_file = True
elif recorded_time < float(times[2].rstrip('\n')) or float(times[2].rstrip('\n')) == 0:
times[2] = str(recorded_time) + '\n'
edit_file = True
else:
if recorded_time > float(times[0].rstrip('\n')):
times[2] = times[1]
times[1] = times[0]
times[0] = str(recorded_time) + '\n'
edit_file = True
elif recorded_time > float(times[1].rstrip('\n')):
times[2] = times[1]
times[1] = str(recorded_time) + '\n'
edit_file = True
elif recorded_time > float(times[2].rstrip('\n')):
times[2] = str(recorded_time) + '\n'
edit_file = True
if edit_file:
with open(records_path, "w") as rec:
rec.writelines(times)
else:
edit_file = True
record = str(recorded_time) + '\n'
times.append(record)
times.append("0\n")
times.append("0\n")
with open(records_path, "w") as rec:
rec.writelines(times)
oled.challenge_records(times, "sec", edit_file)
|
aed5cd14882ef0a82e36f8b3bed9cf81748bd3ae | LeaderRushi/PythonForKids | /basic data.py | 455 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 25 11:54:29 2020
@author: giris
"""
subject_list = ['math', "science", "LASS", "PE"]
subject_list.append("music")
print (subject_list)
subject_list.remove("PE")
print (subject_list)
subject_list.sort()
print (subject_list)
teacher_list = ['Harder','Drake', 'Kirkman', 'Lidstrum']
print (teacher_list)
teacher_map = {'math':'Harder','science':'Drake'}
print(teacher_map['math'])
|
1ce5004cdc178694f616e2ea4eabe0f73c3581b2 | riterdba/magicbox | /cl9.py | 337 | 3.984375 | 4 | #!/usr/bin/python3
class Horse():
def __init__(self, name, color, rider):
self.name = name
self.color = color
self.rider = rider
class Rider():
def __init__(self, name):
self.name = name
riderr = Rider('Миша')
horsee = Horse('Гроза', 'черная', riderr)
print(horsee.rider.name)
|
9de3f927d4cd56dc1f3b0d3397cebad9b61f67a8 | riterdba/magicbox | /4.py | 426 | 3.6875 | 4 | #!/usr/bin/python3
#Определение високосного года.
x=input('Введите год:')
y=len(x)
x=int(x)
if (y==4):
if((x%4==0) and (x%100!=0)):
print('Год високосный')
elif((x%100==0) and (x%400==0)):
print('Год високосный')
else:
print('Год не високосный')
else:
print('Вы ввели неправильный год')
|
e0dd4c5a6ead7cd585d9d4cf387e6d4c8849accb | riterdba/magicbox | /cl11.py | 283 | 4.125 | 4 | #!/usr/bin/python3
class Square():
def __init__(self, a):
self.a = a
def __repr__(self):
return ('''{} на {} на {} на {}'''.format(self.a, self.a, self.a, self.a))
sq1 = Square(10)
sq2 = Square(23)
sq3 = Square(77)
print(sq1)
print(sq2)
print(sq3)
|
cf0e08f57baf9bb7b3e9a2f27acce377fdf33c1d | mayIlearnloopsbrother/Python | /chapters/chapter_7/ch7b.py | 400 | 3.890625 | 4 | #!/usr/bin/python3
#7-8 deli
sandwich_orders = ['ham', 'chicken', 'brocoli']
finished_sandwiches = []
while sandwich_orders:
sandwich = sandwich_orders.pop()
print("making you a " + sandwich.title() + " sandwich")
finished_sandwiches.append(sandwich)
print("\n")
print("following sandwiches have been made")
for finished_sandwich in finished_sandwiches:
print(finished_sandwich.title())
|
9f3e5247a1c58d8c2e625138306b8422bc430afc | mayIlearnloopsbrother/Python | /chapters/chapter_6/ch6a.py | 300 | 4.15625 | 4 | #!/usr/bin/python3
#6-5 Rivers
rivers = {
'nile': 'egypt',
'mile': 'fgypt',
'oile': 'ggypt',
}
for river, country in rivers.items():
print(river + " runs through " + country)
print("\n")
for river in rivers.keys():
print(river)
print("\n")
for country in rivers.values():
print(country)
|
81c1f5f69ba843cc0b996778d4f3993fbf497564 | mayIlearnloopsbrother/Python | /chapters/chapter_7/ch7a.py | 422 | 3.953125 | 4 | #!/usr/bin/python3
#7-4 Pizza Toppings
info = "enter pizza toppings "
info += "\n'quit' to finish: "
topps = ""
while topps != 'quit':
topps = input(info)
if topps != 'quit':
print("\nAdding " + topps + " to your pizza\n")
print("\n")
#7-5 Movie Tickets
age = input("age? ")
age = int(age)
if age < 3:
print("ticket is free")
elif age < 12:
print("$10 for a ticket")
elif age > 12:
print("$15 for a ticket")
|
06ce2b33b58fde002588bf8bdf6b93d7d7f3e94d | mayIlearnloopsbrother/Python | /chapters/chapter_6/ch6c.py | 693 | 3.90625 | 4 | #!/usr/bin/python3
#6-8 Pets
petname = { 'chicken':'bob'}
petname2 = {'giffare': 'rob'}
petname3 = { 'dinosaur':'phineas'}
petname4 = {'dog': 'ben'}
pets = [petname, petname2, petname3, petname4]
for pet in pets:
print(pet)
print("\n")
#6-9 Favorite Places
favorite_places = {
'bob': ['italy', 'jtaly', 'ktaly'],
'rob': ['england', 'fngland'],
'dob': ['france']
}
for name, place in favorite_places.items():
print(name + " favorite places " + str(place))
print("\n")
#6-10 favorite Numbers
favorite_numbers = {
'chad': [5,2,3,4],
'dhad': [7,3],
'ehad': [0],
'ghad': [1,2,3]
}
for name, number in favorite_numbers.items():
print(name + " favorite numbers: " + str(number))
|
ecf4b82877c2884532f159e46e16be8a1c6e029b | benbovy/4learners_python | /notebooks/Day2_AM1/temp_module.py | 1,086 | 3.765625 | 4 | absolute_zero_in_celsius = -273.15
def fahrenheit_to_kelvin(temperature):
"""This function turns a temperature in Fahrenheit into a temperature in Kelvin"""
return (temperature - 32) * 5/9 - absolute_zero_in_celsius
def kelvin_to_celsius(temperature):
"""This function turns a temperature in Kelvin into a temperature in Celsius
This string is a doc string. It uses triple quotes to allow line breaks and contains information about your function that is carried around. You can access it by calling help(function) for any function that provides it. May editors will also show it if you hover over the function."""
return temperature + absolute_zero_in_celsius
def fahrenheit_to_celsius(temperature):
temp_in_kelvin = fahrenheit_to_kelvin(temperature)
return kelvin_to_celsius(temp_in_kelvin)
absolute_zero_in_fahrenheit = fahrenheit_to_celsius(absolute_zero_in_celsius)
# The magic variable __name__ contains the name of the module.
# If the file is run as a script it instead is set to "__main__"
# print(f"You have loaded the module {__name__}")
|
83a49d59eecbcceefc04ab923b85f939e97f33f1 | brennannicholson/ancient-greek-char-bert | /data_prep/greek_data_prep/split_data.py | 2,172 | 3.78125 | 4 | """Splits the sentence tokenized data into train, dev and test sets. This script shuffles the sentences. As a result the dataset created this way can't be used for next sentence prediction."""
from greek_data_prep.utils import write_to_file
import random as rn
import math
def get_data(filename):
with open(filename, "r") as f:
data = f.read().splitlines()
return data
def split_data(data, train_split, val_split, test_split):
assert train_split + val_split + test_split == 1.0
train = []
val = []
test = []
# we want to be able to reproduce this split
rn.seed(42)
rn.shuffle(data)
nb_of_texts = len(data)
total_len = sum([len(text) for text in data])
print("Total number of chars: " + str(total_len))
train_target_len = math.floor(total_len * train_split)
val_target_len = math.floor(total_len * (train_split + val_split))
current_len = 0
train_end = 0
val_end = 0
for i, text in enumerate(data):
current_len += len(text)
if current_len < train_target_len:
# keep updating the train end index until current len >= train_target_len
train_end = i
if current_len > val_target_len:
val_end = i
# now that we're finished, correct the train_end index
train_end += 1
break
train = data[0 : train_end + 1]
val = data[train_end + 1 : val_end + 1]
test = data[val_end + 1 :]
assert len(train) + len(val) + len(test) == len(data)
train_len = sum([len(text) for text in train])
val_len = sum([len(text) for text in val])
test_len = sum([len(text) for text in test])
print(f"Train length: {train_len}")
print(f"Val length: {val_len}")
print(f"Test length: {test_len}")
return train, val, test
def ninty_eight_one_one_spilt():
filename = "char_BERT_dataset.txt"
print("Splitting data...")
data = get_data(filename)
train, val, test = split_data(data, 0.98, 0.01, 0.01)
write_to_file("train.txt", train)
write_to_file("dev.txt", val)
write_to_file("test.txt", test)
if __name__ == "__main__":
ninty_eight_one_one_spilt()
|
867d4f98f69124194b73b20d3bb442093e9445c9 | meldhose/profile_values | /profile_values/profile_encoding.py | 3,829 | 3.921875 | 4 | """Analysing the encoding styles"""
import pandas as pd
def encoding_analysis(df_column):
"""
Checks the encoding style of the strings and
Args:
df_column (pandas DataFrame): Input pandas DataFrame
Returns:
dict (dict)
"""
dict_encoding_analysis = {}
contains_unusual_char = info_compatible_encoding(df_column)
if contains_unusual_char:
df1, df2 = info_list_unusual_chars(contains_unusual_char, df_column)
# Storing the return values in dictionary
dict_encoding_analysis['contains_unusual_chars'] = contains_unusual_char
dict_encoding_analysis['unusual_strings'] = df1
dict_encoding_analysis['strings_with_unusual_chars'] = df2
return dict_encoding_analysis
def info_compatible_encoding(df_column):
"""
Returns if the given data frame has strings that
contain unusual characters.
Args:
df_column (pandas DataFrame): Input pandas DataFrame
Returns:
contains_unusual_char (bool)
"""
col_title = df_column.columns.get_values()[0]
contains_unusual_char = False
data_frame = df_column
for each in data_frame.iterrows():
curr_attr = each[1][col_title]
try:
curr_attr.encode('ascii')
except ValueError:
contains_unusual_char = True
break
# if "\\x" in ascii(curr_attr):
# contains_unusual_char = True
return contains_unusual_char
def info_list_unusual_chars(contains_unusual_char, df_column):
"""
Returns 2 lists of strings with unusual characters and strings along
with indicated unusual characters.
Args:
contains_unusual_char(bool): Input bool
df_column (pandas DataFrame): Input pandas DataFrame
Returns:
df1,df2 (tuple of pandas DataFrames)
"""
data_frame = df_column
col_title = df_column.columns.get_values()[0]
non_ascii_str = []
list_str_chr = []
if contains_unusual_char:
for each in data_frame.iterrows():
non_ascii_char_string = ''
curr_attr = each[1][col_title]
try:
curr_attr.encode('ascii')
except:
for letter in curr_attr:
if ord(letter) < 32 or ord(letter) > 126:
non_ascii_str += [curr_attr]
if non_ascii_char_string == '':
non_ascii_char_string = letter
else:
non_ascii_char_string = non_ascii_char_string + \
' , ' + letter
list_str_chr.append([curr_attr, non_ascii_char_string])
df1 = print_unusual_str(non_ascii_str)
df2 = print_mapping_unusual(list_str_chr)
return df1, df2
def print_unusual_str(list_unusual_strings):
"""
Returns a DataFrame of strings that contain unusual characters.
Args:
list_unusual_strings (list): Input list
Returns:
unusualStringsDataFrame (pandas DataFrame)
"""
unusual_strings_data_frame = pd.DataFrame(list_unusual_strings,
columns=['String'])
return unusual_strings_data_frame
def print_mapping_unusual(list_unusual_mapping):
"""
Returns a DataFrame with 2 columns of strings and the
unusual characters in each.
Args:
list_unusual_mapping (list): Input list
Returns:
stringsWithUnusualChar (pandas DataFrame)
"""
strings_with_unusual_char = pd.DataFrame(list_unusual_mapping,
columns=['String', 'Unusual Character'])
return strings_with_unusual_char
|
743f5fd285c9045048bbf81c376c7e4d39d13fc2 | bcarlier75/python_bootcamp_42ai | /day01/ex00/recipe.py | 2,439 | 3.859375 | 4 | class Recipe:
def __init__(self, name, cooking_lvl, cooking_time, ingredients, description, recipe_type):
# Init name
if isinstance(name, str):
self.name = name
else:
print('Type error: name should be a string')
# Init cooking_lvl
if isinstance(cooking_lvl, int):
if cooking_lvl in range(1, 6):
self.cooking_lvl = cooking_lvl
else:
print('Value error: cooking_lvl should be between 1 and 5')
else:
print('Type error: cooking_lvl should be an integer')
# Init cooking_time
if isinstance(cooking_time, int):
if cooking_time > 0:
self.cooking_time = cooking_time
else:
print('Value error: cooking_time should be a positive integer')
else:
print('Type error: cooking_time should be an integer')
# Init ingredients
flag = 0
if isinstance(ingredients, list):
for elem in ingredients:
if not isinstance(elem, str):
flag = 1
if flag == 0:
self.ingredients = ingredients
elif flag == 1:
print('Value error: at least one element of ingredients is not a string')
else:
print('Type error: ingredients should be a list')
# Init description
if description is not None:
if isinstance(description, str):
self.description = description
else:
print('Type error: description should be a string')
# Init recipe_type
if isinstance(recipe_type, str):
if recipe_type in ["starter", "lunch", "dessert"]:
self.recipe_type = recipe_type
else:
print('Value error: recipe_type should be "starter", "lunch" or "dessert"')
else:
print('Type error: recipe_type should be a string')
def __str__(self):
"""Return the string to print with the recipe info"""
txt = ""
txt = f'This is the recipe for {self.name}.\n' \
f'Cooking level: {self.cooking_lvl}\n' \
f'Cooking time: {self.cooking_time}\n' \
f'Ingredients: {self.ingredients}\n' \
f'This recipe is for {self.recipe_type}.\n' \
f'{self.description}\n'
return txt
|
9c051053eec8ffb84bc16b987c2fefa664e38415 | bcarlier75/python_bootcamp_42ai | /day00/ex04/operations.py | 1,290 | 3.953125 | 4 | from sys import argv
if len(argv) == 1:
print(f'Usage: python operations.py\n'
f'Example:\n'
f'\tpython operations.py 10 3')
elif len(argv) == 3:
try:
my_sum = int(argv[1]) + int(argv[2])
my_diff = int(argv[1]) - int(argv[2])
my_mul = int(argv[1]) * int(argv[2])
if int(argv[2]) != 0:
my_div = int(argv[1]) / int(argv[2])
my_mod = int(argv[1]) % int(argv[2])
else:
my_div = 'ERROR (div by zero)'
my_mod = 'ERROR (modulo by zero)'
print(f'Sum:\t\t {my_sum}\n'
f'Difference:\t {my_diff}\n'
f'Product:\t {my_mul}\n'
f'Quotient:\t {my_div}\n'
f'Remainder:\t {my_mod}')
except ValueError as e:
print(f'InputError: only numbers\n'
f'Usage: python operations.py\n'
f'Example:\n'
f'\tpython operations.py 10 3')
elif len(argv) > 3:
print(f'InputError: too many arguments\n'
f'Usage: python operations.py\n'
f'Example:\n'
f'\tpython operations.py 10 3')
elif len(argv) == 2:
print(f'InputError: too few arguments\n'
f'Usage: python operations.py\n'
f'Example:\n'
f'\tpython operations.py 10 3') |
aad16f725e29145b9217e9d0fd70d675fca9fc64 | bcarlier75/python_bootcamp_42ai | /day01/ex02/vector.py | 3,787 | 3.53125 | 4 | class Vector:
def __init__(self, values, size, my_range):
flag = 0
if values:
if isinstance(values, list):
for elem in values:
if not isinstance(elem, float):
flag = 1
if flag == 0:
self.values = values
self.length = int(len(self.values))
else:
print('The list should only contain float values.')
else:
print('Init error: expect a list of float for parameter values')
elif size:
if isinstance(size, int):
self.values = [float(i) for i in range(0, size)]
self.length = len(self.values)
else:
print('Init error: expect an integer for parameter size.')
elif my_range:
if isinstance(my_range, tuple) and len(my_range) == 2:
for elem in my_range:
if not isinstance(elem, int):
flag = 1
if flag == 0:
self.values = [float(i) for i in range(my_range[0], my_range[1])]
self.length = len(self.values)
else:
print('The tuple should only contain int values.')
else:
print('Init error: expect a tuple with 2 integer for parameter my_range.')
else:
print('Init error: expect either a list of float, an integer or tuple with 2 integer.')
def __add__(self, vec_or_scalar):
if isinstance(vec_or_scalar, Vector) and self.length == vec_or_scalar.length:
for i in range(0, self.length):
self.values[i] = self.values[i] + vec_or_scalar.values[i]
elif isinstance(vec_or_scalar, float):
for i in range(0, self.length):
self.values[i] = self.values[i] + vec_or_scalar
else:
print(f'Value error: {vec_or_scalar} is not an instance of class Vector or a float'
'or vectors have different length.')
def __radd__(self, vec_or_scalar):
pass
def __sub__(self, vec_or_scalar):
if isinstance(vec_or_scalar, Vector) and self.length == vec_or_scalar.length:
for i in range(0, self.length):
self.values[i] = self.values[i] - vec_or_scalar.values[i]
elif isinstance(vec_or_scalar, float):
for i in range(0, self.length):
self.values[i] = self.values[i] - vec_or_scalar
else:
print(f'Value error: {vec_or_scalar} is not an instance of class Vector or a float '
'or vectors have different length.')
def __rsub__(self, vec_or_scalar):
pass
def __truediv__(self, scalar):
if isinstance(scalar, float):
for i in range(0, self.length):
self.values[i] = self.values[i] / scalar
else:
print('Value error: scalar should be a float')
def __rtruediv__(self, vec_or_scalar):
pass
def __mul__(self, vec_or_scalar):
if isinstance(vec_or_scalar, Vector) and self.length == vec_or_scalar.length:
for i in range(0, self.length):
self.values[i] = self.values[i] * vec_or_scalar.values[i]
elif isinstance(vec_or_scalar, float):
for i in range(0, self.length):
self.values[i] = self.values[i] * vec_or_scalar
else:
print(f'Value error: {vec_or_scalar} is not an instance of class Vector or a float '
'or vectors have different length.')
def __rmul__(self, vec_or_scalar):
pass
def __str__(self):
pass
def __repr__(self):
pass
|
e65ff801f6792b85f1878d3520b994f2e9dfa682 | Ernestbengula/python | /kim/Task3.py | 269 | 4.25 | 4 | # Given a number , check if its pos,Neg,Zero
num1 =float(input("Your Number"))
#Control structures -Making decision
#if, if else,elif
if num1>0:
print("positive")
elif num1==0 :
print("Zero")
elif num1<0:
print(" Negative")
else:
print("invalid") |
1bf95b285168d5e332de9f082227a89833161fde | Ernestbengula/python | /kim/Payroll.py | 448 | 3.859375 | 4 | # create a payroll
#Gross_Pay
salary =float(input("Enter salary"))
wa =float(input("Enter wa"))
ha=float(input("Enter ha"))
ta =float(input("Enter ta"))
Gross_Pay =(salary+wa+ha+ta)
print("Gross Pay ", Gross_Pay)
#Deduction
NSSF =float(input("Enter NSSF"))
Tax =float(input("Enter Tax"))
Deductions=(NSSF+Tax)
print("Deductions: ", Deductions)
#formula Net_Pay =Gross_Pay-Deduction
Net_pay =Gross_Pay-Deductions
print("Your net_pay",Net_pay)
|
3e021c8066e885499ca01ada8d90b3dd60b956d7 | Gholamrezadar/data-structures | /Quera_3_HanoiTowers.py | 437 | 3.78125 | 4 | From = []
Aux = []
To = []
def hanoi(n, A, B, C):
if n==1:
B.append(A.pop())
show_towers()
return
hanoi(n-1, A, C, B)
B.append(A.pop())
show_towers()
hanoi(n-1, C, B, A)
def show_towers():
print(sum(From), sum(Aux), sum(To))
def fill_bars():
for i in range(n,0,-1):
From.append(i)
n = int(input())
fill_bars()
show_towers()
hanoi(n, From, To, Aux)
|
319365deb464f4b690e1066ca52e69c9ce2622a9 | Evgen8906/homework_modul_14 | /calc.py | 1,199 | 3.796875 | 4 | """calc v5.0"""
def input_number():
num=input("Vvedite chislo: ")
if num == '':
return None
try:
num=float(num)
except ValueError:
num = num
return num
def input_oper():
oper=input("Operaciya('+','-','*','/','^','**'): ")
if oper == '':
oper = None
return oper
def calc_me(x=None,y=None,oper=None):
if x is None:
return "ERROR: send me Number1"
if y is None:
return "ERROR: send me Number1"
if (not isinstance(x, (int, float))) or (not isinstance(y, (int, float))):
return "ERROR: now it is does not supported"
if oper=='*':
return x*y
elif oper=='/':
if y==0:
return "ERROR: Divide by zero!"
else:
return x/y
elif oper=='+':
return x+y
elif oper=='-':
return x-y
elif oper == '^' or oper == '**':
return x ** y
else:
return "ERROR: Uknow operation"
def body():
num1 = input_number()
oper = input_oper()
num2 = input_number()
result = calc_me(num1,num2,oper)
print(result)
if __name__=='__main__':
body()
|
de3d8e0821036c101002cdfb771f190f4e1eb5b7 | Armadillan/TensorFlow2048 | /pg_implementation.py | 16,201 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Class for a visual interface for the 2048 environment using pygame.
Playable by both humans and robots.
"""
import time
import os
import pygame
import numpy as np
class Game:
"""
Class for a visual interface for the 2048 environment using pygame.
Playable by both humans and robots.
Use arrow keys or WASD to control.
r restarts the game
b turns bot on or off
"""
# Whether the game always stays square with
# background color on the sides, or fills the
# whole window.
# Setting this to False currently results in font weirdness when
# the window is much taller than it's wide. It's fixable but I
# haven't had time to fix it yet.
SQUARE = True
BACKGROUND_COLOR = ("#bbada0") # Background color (duh?)
LIGHT_TEXT_COLOR = pygame.Color("#f9f6f2") # Lighter color of digits
DARK_TEXT_COLOR = ("#776e65") # Darker color of digits
# Which tiles to use the lighter font for
# All other tiles will use the darker font
VALUES_WITH_DARK_TEXT = (2, 4)
# Dictionary mapping tiles to their color
TILE_COLOR = {
0: ("#cdc1b4"),
2: pygame.Color("#eee4da"),
4: pygame.Color("#eee1c9"),
8: pygame.Color("#f3b27a"),
16: pygame.Color("#f69664"),
32: pygame.Color("#f77c5f"),
64: pygame.Color("#f75f3b"),
128: pygame.Color("#edd073"),
256: pygame.Color("#edcc62"),
512: pygame.Color("#edc950"),
1024: pygame.Color("#edc53f"),
2048: pygame.Color("#edc22e"),
"BIG": pygame.Color("#3c3a33") # Tiles bigger than 2048
}
def __init__(self, env, bot=None, bot_delay=0.1):
"""
Iniitalizes the object.
Parameters
----------
env : PyEnvironment or TFPyEnvironment
An environment from env.py,
possibly wrapped using TFPyEnvironment
bot : TFPolicy or PyPolicy or TFPyPolicy or equivalent, optional
A robot to play the game.
Must have an action(TimeStep) method that
returns and action compatible with the environment.
The default is None.
bot_delay : float, optional
The delay in seconds between bot moves. The default is 0.1.
Returns
-------
None.
"""
# Adds text to caption if there is no bot
if bot is None:
self.caption_end = " " * 10 + "NO BOT ATTACHED"
else:
self.caption_end = ""
self.env = env
self.bot = bot
self.bot_delay = bot_delay
# Initial size for the window
self.w = 600
self.h = 600
# Initializes pygame
pygame.init()
# Initializes fonts
self.initialize_fonts()
def initialize_fonts(self):
"""
Initializes fonts based on current screen size
Must be called every time screen size changes
"""
# Using the original font from 2048
self.tile_font_5 = pygame.font.Font(
os.path.join("assets", "ClearSans-Bold.ttf"),
int(self.h * 6/29 * 7/12)
)
self.tile_font_4 = pygame.font.Font(
os.path.join("assets", "ClearSans-Bold.ttf"),
int(self.h * 6/29 * 6/12)
)
self.tile_font_3 = pygame.font.Font(
os.path.join("assets", "ClearSans-Bold.ttf"),
int(self.h * 6/29 * 5/12)
)
self.tile_font_2 = pygame.font.Font(
os.path.join("assets", "ClearSans-Bold.ttf"),
int(self.h * 6/29 * 4/12)
)
self.tile_font_1 = pygame.font.Font(
os.path.join("assets", "ClearSans-Bold.ttf"),
int(self.h * 6/29 * 3/12)
)
# If that is not possible for some reason,
# Arial can be used:
# self.tile_font_5 = pygame.font.SysFont(
# "Arial", int(self.h * 5/29)
# )
# self.tile_font_4 = pygame.font.SysFont(
# "Arial", int(self.h * 4/29)
# )
# self.tile_font_3 = pygame.font.SysFont(
# "Arial", int(self.h * 3/29)
# )
# self.tile_font_2 = pygame.font.SysFont(
# "Arial", int(self.h * 2/29)
# )
# self.tile_font_1 = pygame.font.SysFont(
# "Arial", int(self.h * 1/29)
# )
self.gameover_font_1 = pygame.font.SysFont(
"Arial", int(self.h * (1/10)), bold=True
)
self.gameover_size_1 = self.gameover_font_1.size("GAME OVER")
self.gameover_text_1 = self.gameover_font_1.render(
"GAME OVER", True, (20,20,20)
)
self.gameover_font_2 = pygame.font.SysFont(
"Arial", int(self.h * (1/20),), bold=True
)
self.gameover_size_2 = self.gameover_font_2.size(
"Press \"r\" to restart"
)
self.gameover_text_2 = self.gameover_font_2.render(
"Press \"r\" to restart", True, (20,20,20)
)
def tile(self, x, y, n):
"""
Used to render tiles
Parameters
----------
x : int
x coordinate of tile.
y : int
y coordinate of tile.
n : int
Value of tile.
Returns
-------
pygame.Rect
Rectangle making up the tiles background.
pygame.Surface
The text (number) on the tile.
tuple
(x, y) coordinates of the text on the tile.
"""
# Coordinates of tile
rect_x = (x+1) * self.w/29 + x * self.w * (6/29)
rect_y = (y+1) * self.h/29 + y * self.h * (6/29)
# Rectangle object
rect = pygame.Rect(
rect_x, rect_y, self.w * (6/29), self.h * (6/29))
# Does not render text if the tile is 0
if not n:
text_render = pygame.Surface((0,0))
text_x = 0
text_y = 0
else:
# Get string from int and it's length
text = str(n)
l = len(text)
# Chooses color for text
if n in self.VALUES_WITH_DARK_TEXT:
text_color = self.DARK_TEXT_COLOR
else:
text_color = self.LIGHT_TEXT_COLOR
# Chooses font size based on length of text
if l < 3:
font = self.tile_font_5
elif l == 3:
font = self.tile_font_4
elif l == 4:
font = self.tile_font_3
elif l < 7:
font = self.tile_font_2
else:
font = self.tile_font_1
# Renders font
text_render = font.render(text, True, text_color)
# Gets size of text
size = font.size(text)
# Calculates text coordinates
text_x = (x+1) * self.w/29 \
+ (x+0.5) * self.w * (6/29) - size[0] / 2
text_y = (y+1) * self.h/29 \
+ (y+0.5) * self.h * (6/29) - size[1] / 2
return rect, text_render, (text_x, text_y)
def check_action(self, action):
"""
Checks whether action would change the state of the game
Parameters
----------
action : int
The action to to check. int in (0,1,2,3).
Returns
-------
bool
"""
modifiers = {
0: (0, -1),
1: (+1, 0),
2: (0, +1),
3: (-1, 0)
}
x_mod, y_mod = modifiers[action]
try:
board_array = self.env.current_time_step().observation.numpy()[0]
except AttributeError:
board_array = self.env.current_time_step().observation
for x in range(4):
for y in range(4):
try:
if board_array[y][x] != 0 and \
((board_array[y+y_mod][x+x_mod] == 0) or \
(board_array[y][x] == board_array[y+y_mod][x+x_mod])):
return True
except IndexError:
pass
return False
def main(self):
"""
Starts the game.
This is the main game loop.
"""
# Initial status
playing = True
gameover = False
bot_active = False
score = 0
moves = 0
# Gets initial game state
ts = self.env.reset()
# This is for compatibility with different types of environments
try:
# TF environments
board_array = ts.observation.numpy()[0]
except AttributeError:
# Py environments
board_array = ts.observation
# Environments with flat observations
board_array = np.reshape(board_array, (4,4))
# Keeps a counter of score and moves made in the caption
pygame.display.set_caption(
"2048" + " " * 10 + "Score: 0 Moves: 0" + self.caption_end
)
# Initializes window and a drawing surface
win = pygame.display.set_mode((self.w, self.h), pygame.RESIZABLE)
surface = win.copy()
# Main game loop
while playing:
moved = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
playing = False
break
if event.type == pygame.VIDEORESIZE:
# Handles window resizing
self.w, self.h = win.get_size()
# Sets width and height equal if SQUARE is True
if self.SQUARE:
if self.w > self.h:
self.w = self.h
else:
self.h = self.w
# Makes new drawing surface
surface = win.copy()
# Re-initalizes fonts based on new window size
self.initialize_fonts()
if event.type == pygame.KEYDOWN:
# Handles user input
if event.key == pygame.K_r:
#Restarts the game
ts = self.env.reset()
score = 0
moves = 0
moved = True
gameover = False
surface.fill(self.BACKGROUND_COLOR)
elif event.key == pygame.K_b:
# Turns bot off and on
if bot_active:
bot_active = False
pygame.display.set_caption(
"2048" + " " * 10 + f"Score: {int(score)}"
+ f" Moves: {moves}"
)
elif self.bot is not None:
bot_active = True
elif not gameover:
# Handles human player moves
action_keymap = {
pygame.K_UP: 0, pygame.K_w: 0,
pygame.K_RIGHT: 1, pygame.K_d: 1,
pygame.K_DOWN : 2, pygame.K_s: 2,
pygame.K_LEFT: 3, pygame.K_a: 3,
}
if event.key in action_keymap:
action = action_keymap[event.key]
if self.check_action(action):
ts = self.env.step(action)
moved = True
moves += 1
# Breaks loop if game is over
if not playing:
break
# Updates game state if a move has been made by the player
if moved:
try:
board_array = ts.observation.numpy()[0]
score += ts.reward.numpy()
except AttributeError:
board_array = ts.observation
score += ts.reward
board_array = np.reshape(board_array, (4,4))
# Handles bot movement
if not gameover:
if bot_active:
old_board = board_array.copy()
# Gets action from bot
actionstep = self.bot.action(ts)
action = actionstep.action
ts = self.env.step(action)
moves += 1
# Updates game state
try:
board_array = ts.observation.numpy()[0]
score += ts.reward.numpy()
except AttributeError:
board_array = ts.observation
score += ts.reward
board_array = np.reshape(board_array, (4,4))
# Checks if the board has changed
if not np.array_equal(old_board, board_array):
moved = True
# Waits before bot makes another move
time.sleep(self.bot_delay)
# Adds "- Bot" to caption
pygame.display.set_caption(
"2048 - Bot" + " " * 10 + f"Score: {int(score)}"
+ f" Moves: {moves}"
)
else:
# Updates caption without "- Bot"
pygame.display.set_caption(
"2048" + " " * 10 + f"Score: {int(score)}"
+ f" Moves: {moves}"+ self.caption_end
)
# Checks if the game is over
if ts.is_last():
gameover = True
# Draws all the graphics:
surface.fill(self.BACKGROUND_COLOR)
# Draws every tile
for x in range(4):
for y in range(4):
# Gets the tile "data"
n = board_array[y][x]
rect, text, text_coords = self.tile(x, y, n)
# Gets the color of the tile
try:
tile_color = self.TILE_COLOR[n]
except KeyError:
tile_color = self.TILE_COLOR["BIG"]
# Draws the background
pygame.draw.rect(
surface=surface,
color=tile_color,
rect=rect,
border_radius=int((self.w+self.h)/2 * 1/150)
)
# Blits the text surface to the drawing surface
surface.blit(text, text_coords)
# Displays "gameover screen" if game is over
if gameover:
x_1 = self.w / 2 - self.gameover_size_1[0] / 2
y_1 = self.h / 2 - self.h * 6/80
x_2 = self.w / 2 - self.gameover_size_2[0] / 2
y_2 = self.h / 2 + self.h * 1/30
surface.blit(self.gameover_text_1, (x_1, y_1))
surface.blit(self.gameover_text_2, (x_2, y_2))
# Fill window with background color
win.fill(self.BACKGROUND_COLOR)
# Blits drawing surface to the middle of the window
w, h = win.get_size()
if w > h:
win.blit(surface, ((win.get_width()-self.w)/2,0))
else:
win.blit(surface, (0, (win.get_height()-self.h)/2))
# Updates display
pygame.display.update()
# Quits pygame outside of the main game loop, if the game is over
pygame.quit()
if __name__ == "__main__":
# Plays the game without a bot attached :)
# from env import PyEnv2048
from env import PyEnv2048NoBadActions
# Creates Game object, passing an environment to the constructor
# game = Game(PyEnv2048())
game = Game(PyEnv2048NoBadActions())
# Starts the interface
game.main()
|
ff55c37cedb184c2d2c8399ca9717e775bd34e9c | txkxyx/atcoder | /practice/abc081a.py | 471 | 3.8125 | 4 | import sys
# 0 と 1 のみから成る 3 桁の番号 s が与えられます。1 が何個含まれるかを求めてください。
class ABC081():
def __init__(self, s):
self.s = s
def checkCount(self):
count = 0
for c in s:
if c == '1':
count += 1
return count
if __name__ == '__main__':
args = sys.argv
s = args[1]
abc081 = ABC081(s)
count = abc081.checkCount()
print(count) |
e326bc60c7ca49876b9948df9dc5758455a9ce64 | JianxiangWang/LeetCode | /70 Climbing Stairs/solution.py | 525 | 3.671875 | 4 | # encoding: utf-8
# dp[i] = dp[i-1] + dp[i-2]: 跨到第i台阶 == 从i-1跨过来的次数 + 从i-2跨过来的次数
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0: return 0
if n == 1: return 1
dp = [None] * n
dp[0] = 1
dp[1] = 2
for idx in range(2, n):
dp[idx] = dp[idx - 1] + dp[idx - 2]
return dp[n-1]
if __name__ == '__main__':
print Solution().climbStairs(3) |
42e46dadf6d6e53f7c42146761113cf4e6e3f848 | JianxiangWang/LeetCode | /129 Sum Root to Leaf Numbers/solution.py | 921 | 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 Solution(object):
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(node, s, res):
if node is None:
return
s += str(node.val)
if node.left is None and node.right is None:
res.append(int(s))
dfs(node.left, s, res)
dfs(node.right, s, res)
res = []
dfs(root, "", res)
return sum(res)
if __name__ == '__main__':
root = TreeNode(0)
a = TreeNode(1)
b = TreeNode(3)
c = TreeNode(4)
d = TreeNode(5)
e = TreeNode(6)
root.left = a
root.right = b
# a.left = c
# a.right = d
# c.left = e
print Solution().sumNumbers(root)
|
8eee6e6b52fd476f0de22c3e59cb37317597aa45 | JianxiangWang/LeetCode | /Intersection of Two Arrays II/solution.py | 842 | 3.71875 | 4 |
def intersect(nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
dict_num1_to_count = {}
dict_num2_to_count = {}
for x in nums1:
if x not in dict_num1_to_count:
dict_num1_to_count[x] = 0
dict_num1_to_count[x] += 1
for x in nums2:
if x not in dict_num2_to_count:
dict_num2_to_count[x] = 0
dict_num2_to_count[x] += 1
t = []
for common_num in dict_num1_to_count:
if common_num in dict_num2_to_count:
t.extend([common_num] * min(dict_num1_to_count[common_num], dict_num2_to_count[common_num]))
return t
if __name__ == '__main__':
nums1 = [1, 1]
nums2 = [1]
print intersect(nums1, nums2) |
9d12f4df1ade28b51f2f562ff900fbb75f808d11 | JianxiangWang/LeetCode | /203 Remove Linked List Elements/solution.py | 807 | 3.53125 | 4 | #encoding: utf-8
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
point = head
while point:
if point.next != None and point.next.val == val:
p = point
point = point.next
while point.next != None and point.next.val == val:
point = point.next
point = point.next
p.next = point
else:
point = point.next
if head != None and head.val == val:
head = head.next
return head
|
d2c1cd0d01c93d0c59ba25541031a78ce7e0bbe9 | JianxiangWang/LeetCode | /130 Surrounded Regions/solution.py | 2,024 | 3.578125 | 4 | # encoding: utf-8
class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if len(board) <= 0:
return
m, n = len(board), len(board[0])
visited = [[False]*n for x in range(m)]
for i in range(m):
for j in range(n):
if board[i][j] == 'O' and not visited[i][j]:
surrounded, union_filed = self.bfs(board, i, j, m, n, visited)
if surrounded:
for x, y in union_filed:
board[x][y] = 'X'
# flood fill, 使用bfs找到union field
# 判断他是不是被包围, 如果是,返回被包含区域
def bfs(self, board, x, y, m, n, visited):
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
union_filed = []
surrounded = True
# 放进queue之前,先visit
visited[x][y] = True
for i, j in [(x + d_i, y + d_j) for d_i, d_j in directions]:
#
if i < 0 or i >= m or j < 0 or j >= n:
surrounded = False
continue
union_filed.append((x, y))
queue = [(x, y)]
while queue:
i_, j_ = queue.pop(0)
# 将相邻节点放入queue
for i, j in [(i_ + d_i, j_ + d_j) for d_i, d_j in directions]:
#
if i < 0 or i >= m or j < 0 or j >= n:
surrounded = False
continue
if not visited[i][j] and board[i][j] == "O":
visited[i][j] = True
union_filed.append((i, j))
queue.append((i, j))
return surrounded, union_filed
if __name__ == '__main__':
board = [
["X", "X", "X", "O"],
["X", "O", "O", "X"],
["X", "O", "X", "O"],
["X", "X", "X", "X"]
]
Solution().solve(board)
print board |
9181573ba65b9aca1551f88c49f69650a2af4ad7 | JianxiangWang/LeetCode | /47 Permutations II/solution.py | 737 | 3.625 | 4 |
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def dfs(seq, ans, res):
seq = sorted(seq)
prev_x = None
for idx, x in enumerate(seq):
if x == prev_x:
continue
prev_x = x
ans_ = ans + [x]
tmp = seq[:idx] + seq[idx + 1:]
if tmp == []:
res.append(ans_)
dfs(tmp, ans_, res)
res = []
dfs(nums, [], res)
return res
# return list(map(list, set(res)))
if __name__ == '__main__':
print Solution().permuteUnique([3, 3, 0, 3]) |
ab061ca7ac9f33f8fd5f2e7c9e3c1530e59b2024 | alvdena/SWMM-EPANET_User_Interface | /src/core/inputfile.py | 15,166 | 3.515625 | 4 | import inspect
import traceback
from enum import Enum
class InputFile(object):
"""Input File Reader and Writer"""
def __init__(self):
self.file_name = ""
self.sections = []
self.add_sections_from_attributes()
def get_text(self):
section_text_list = []
try:
for section in self.sections:
try: # Make sure each section text ends with one newline, two newlines after join below.
section_text_list.append(section.get_text().rstrip('\n') + '\n')
except Exception as e1:
section_text_list.append(str(e1) + '\n' + str(traceback.print_exc()))
return '\n'.join(section_text_list)
except Exception as e2:
return(str(e2) + '\n' + str(traceback.print_exc()))
def set_text(self, new_text):
self.set_from_text_lines(new_text.splitlines())
def read_file(self, file_name):
try:
with open(file_name, 'r') as inp_reader:
self.set_from_text_lines(iter(inp_reader))
self.file_name = file_name
except Exception as e:
print("Error reading {0}: {1}\n{2}".format(file_name, str(e), str(traceback.print_exc())))
def write_file(self, file_name):
if file_name:
with open(file_name, 'w') as writer:
writer.writelines(self.get_text())
self.file_name = file_name
def set_from_text_lines(self, lines_iterator):
"""Read as a project file from lines of text.
Args:
lines_iterator (iterator): Produces lines of text formatted as input file.
"""
self.__init__()
self.sections = []
section_index = 1
section_name = ""
section_whole = ""
for line in lines_iterator:
if line.startswith('['):
if section_name:
self.add_section(section_name, section_whole, section_index)
section_index += 1
section_name = line.rstrip()
section_whole = line
else:
section_whole += line
if section_name:
self.add_section(section_name, section_whole, section_index)
section_index += 1
self.add_sections_from_attributes()
def add_sections_from_attributes(self):
"""Add the sections that are attributes of the class to the list of sections."""
for attr_value in vars(self).itervalues():
if isinstance(attr_value, Section) and attr_value not in self.sections:
self.sections.append(attr_value)
def add_section(self, section_name, section_text, section_index):
attr_name = InputFile.printable_to_attribute(section_name)
try:
section_attr = self.__getattribute__(attr_name)
except:
section_attr = None
new_section = self.find_section(section_name)
if section_attr is None: # if there is not a class associated with this name, read it as generic Section
if new_section is None:
new_section = Section()
new_section.name = section_name
new_section.index = section_index
new_section.value = section_text
new_section.value_original = section_text
else:
section_class = type(section_attr)
if section_class is list:
if new_section is None:
new_section = Section()
new_section.name = section_name
new_section.index = section_index
new_section.value_original = section_text
section_list = []
else:
section_list = new_section.value
list_class = section_attr[0]
for row in section_text.splitlines()[1:]: # process each row after the one with the section name
if row.startswith(';'): # if row starts with semicolon, the whole row is a comment
comment = Section()
comment.name = "Comment"
comment.index = section_index
comment.value = row
comment.value_original = row
section_list.append(comment)
else:
try:
if row.strip():
make_one = list_class()
make_one.set_text(row)
section_list.append(make_one)
except Exception as e:
print("Could not create object from row: " + row + "\n" + str(e))
new_section.value = section_list
else:
if new_section is None:
new_section = section_class()
if hasattr(new_section, "index"):
new_section.index = section_index
if hasattr(new_section, "value"):
new_section.value = section_text
if hasattr(new_section, "value_original"):
new_section.value_original = section_text
try:
new_section.set_text(section_text)
except Exception as e:
print("Could not call set_text on " + attr_name + " (" + section_name + "):\n" + str(e))
if new_section is not None and new_section not in self.sections:
self.sections.append(new_section)
if section_attr is not None:
self.__setattr__(attr_name, new_section)
def find_section(self, section_title):
""" Find an element of self.sections, ignoring square brackets and capitalization.
Args:
section_title (str): Title of section to find.
"""
compare_title = InputFile.printable_to_attribute(section_title)
for section in self.sections:
if hasattr(section, "SECTION_NAME"):
this_section_name = section.SECTION_NAME
else:
this_section_name = section.name
if InputFile.printable_to_attribute(str(this_section_name)) == compare_title:
return section
return None
@staticmethod
def printable_to_attribute(name):
"""@param name is as it appears in text input file, return it formatted as a class attribute name"""
return name.lower().replace(' ', '_').replace('[', '').replace(']', '')
class Section(object):
"""Any section or sub-section or value in an input file"""
field_format = " {:19}\t{}"
def __init__(self):
self.name = "Unnamed"
"""Name of the item"""
if hasattr(self, "SECTION_NAME"):
self.name = self.SECTION_NAME
self.value = ""
"""Current value of the item as it appears in an InputFile"""
self.value_original = None
"""Original value of the item as read from an InputFile during this session"""
self.index = -1
"""Index indicating the order in which this item was read
(used for keeping items in the same order when written)"""
self.comment = ""
"""A user-specified header and/or comment about the section"""
def __str__(self):
"""Override default method to return string representation"""
return self.get_text()
def get_text(self):
"""Contents of this section formatted for writing to file"""
txt = self._get_text_field_dict()
if txt:
return txt
if isinstance(self.value, basestring) and len(self.value) > 0:
return self.value
elif isinstance(self.value, (list, tuple)):
text_list = [self.name]
for item in self.value:
text_list.append(str(item))
return '\n'.join(text_list)
elif self.value is None:
return ''
else:
return str(self.value)
def _get_text_field_dict(self):
""" Get string representation of attributes represented in field_dict, if any.
Private method intended for use by subclasses """
if hasattr(self, "field_dict") and self.field_dict:
text_list = []
if self.name and self.name.startswith('['):
text_list.append(self.name)
if self.comment:
text_list.append(self.comment)
for label, attr_name in self.field_dict.items():
attr_line = self._get_attr_line(label, attr_name)
if attr_line:
text_list.append(attr_line)
if text_list:
return '\n'.join(text_list)
return '' # Did not find field values from field_dict to return
def _get_attr_line(self, label, attr_name):
if label and attr_name and hasattr(self, attr_name):
attr_value = getattr(self, attr_name)
if isinstance(attr_value, Enum):
attr_value = attr_value.name.replace('_', '-')
if isinstance(attr_value, bool):
if attr_value:
attr_value = "YES"
else:
attr_value = "NO"
if isinstance(attr_value, list):
attr_value = ' '.join(attr_value)
if attr_value or attr_value == 0:
return (self.field_format.format(label, attr_value))
else:
return None
def set_text(self, new_text):
"""Read properties from text.
Args:
new_text (str): Text to parse into properties.
"""
self.__init__() # Reset all values to defaults
self.value = new_text
for line in new_text.splitlines():
self.set_text_line(line)
def set_text_line(self, line):
"""Set part of this section from one line of text.
Args:
line (str): One line of text formatted as input file.
"""
# first split out any comment after a semicolon
comment_split = str.split(line, ';', 1)
if len(comment_split) == 2:
line = comment_split[0]
this_comment = ';' + comment_split[1]
if self.comment:
if this_comment in self.comment:
this_comment = '' # Already have this comment, don't add it again
else:
self.comment += '\n' # Separate from existing comment with newline
self.comment += this_comment
if not line.startswith('[') and line.strip():
# Set fields from field_dict if this section has one
attr_name = ""
attr_value = ""
tried_set = False
if hasattr(self, "field_dict") and self.field_dict:
(attr_name, attr_value) = self.get_field_dict_value(line)
else: # This section does not have a field_dict, try to set its fields anyway
line_list = line.split()
if len(line_list) > 1:
if len(line_list) == 2:
test_attr_name = line_list[0].lower()
if hasattr(self, test_attr_name):
attr_name = test_attr_name
attr_value = line_list[1]
else:
for value_start in (1, 2):
for connector in ('', '_'):
test_attr_name = connector.join(line_list[:value_start]).lower()
if hasattr(self, test_attr_name):
attr_name = test_attr_name
attr_value = ' '.join(line_list[value_start:])
break
if attr_name:
try:
tried_set = True
self.setattr_keep_type(attr_name, attr_value)
except:
print("Section.text could not set " + attr_name)
if not tried_set:
print("Section.text skipped: " + line)
def get_field_dict_value(self, line):
"""Search self.field_dict for attribute matching start of line.
Args:
line (str): One line of text formatted as input file, with field name followed by field value.
Returns:
Attribute name from field_dict and new attribute value from line as a tuple:
(attr_name, attr_value) or (None, None) if not found.
"""
if hasattr(self, "field_dict") and self.field_dict:
lower_line = line.lower().strip()
for dict_tuple in self.field_dict.items():
key = dict_tuple[0]
# if this line starts with this key followed by a space or tab
if lower_line.startswith(key.lower()) and lower_line[len(key)] in (' ', '\t'):
test_attr_name = dict_tuple[1]
if hasattr(self, test_attr_name):
# return attribute name and value to be assigned
return(test_attr_name, line[len(key) + 1:].strip())
return(None, None)
def setattr_keep_type(self, attr_name, attr_value):
"""Set attribute attr_name = attr_value.
If existing value of attr_name is int, float, bool, or Enum,
try to remove spaces and convert attr_value to the same type before setting.
Args:
attr_name (str): Name of attribute of self to set.
attr_value: New value to assign to attr_name.
"""
try:
old_value = getattr(self, attr_name, "")
if type(old_value) == int:
if isinstance(attr_value, str):
attr_value = attr_value.replace(' ', '')
setattr(self, attr_name, int(attr_value))
elif type(old_value) == float:
if isinstance(attr_value, str):
attr_value = attr_value.replace(' ', '')
setattr(self, attr_name, float(attr_value))
elif isinstance(old_value, Enum):
if not isinstance(attr_value, Enum):
try:
attr_value = type(old_value)[attr_value.replace('-', '_')]
except KeyError:
attr_value = type(old_value)[attr_value.upper().replace('-', '_')]
setattr(self, attr_name, attr_value)
elif type(old_value) == bool:
if not isinstance(attr_value, bool):
attr_value = str(attr_value).upper() not in ("NO", "FALSE")
setattr(self, attr_name, attr_value)
else:
setattr(self, attr_name, attr_value)
except Exception as e:
print("Exception setting {}: {}".format(attr_name, str(e)))
setattr(self, attr_name, attr_value)
|
5930c2407c62aeee242a0a1340e49d2372d27d0c | Vishnushetty14/assignments | /swapping_of_two_numbers.py | 109 | 3.875 | 4 | a=float(input("enter a value"))
b=float(input("enter b value"))
temp=a
a=b
b=temp
print("a=",a)
print("b=",b) |
c06b507656eb5fa8e0471507532ef4de8a3167d9 | easyra/Sprint-Challenge--Data-Structures-Python | /names/names.py | 1,548 | 3.546875 | 4 | import time
import sys
sys.path.append('../search')
#from binary_search_tree import BinarySearchTree
start_time = time.time()
class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
direction = "right" if value > self.value else 'left'
if getattr(self, direction) is None:
setattr(self, direction, BinarySearchTree(value))
return
else:
self = getattr(self,direction)
self.insert(value)
pass
def contains(self, target):
if target == self.value:
return True
if target < self.value:
if self.left is None:
return False
else:
self = self.left
elif target > self.value:
if self.right is None:
return False
else:
self = self.right
return self.contains(target)
def get_max(self):
while self.right is not None:
self = self.right
return self.value
pass
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n") # List containing 10000 names
bst_1 = BinarySearchTree(names_1[0])
for name in names_1[1:]:
bst_1.insert(name)
f.close()
f = open('names_2.txt', 'r')
names_2 = f.read().split("\n") # List containing 10000 names
f.close()
duplicates = []
for name in names_2:
if bst_1.contains(name):
duplicates.append(name)
end_time = time.time()
print (f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print (f"runtime: {end_time - start_time} seconds")
|
400be22da09455720e76805e79cda13b8e025a83 | PinkLego/MyPythonProjects | /InventYourOwnGamesWithPython/All projects/packages.py | 356 | 3.90625 | 4 | import random # generates random values
#members = ['Mary', 'John', 'Bob', 'Mosh']
#leader = random.choice(members)
#print(leader)
#for i in range(3):
#print(random.randint(10, 20))
class Dice:
def roll(self):
first = random.randint(1, 6)
second = random.randint(1, 6)
return first, second
dice = Dice()
print(dice.roll) |
2a048d0c0cd4709d4b9b856b03190105f8006cee | PinkLego/MyPythonProjects | /InventYourOwnGamesWithPython/All projects/Loops!!.py | 275 | 3.875 | 4 | Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> for x in range(0, 5):
print('hello')
hello
hello
hello
hello
hello
>>> print(list(range(10, 20)))
|
df441f7479925dbf77b009cd401a692876965abb | PinkLego/MyPythonProjects | /InventYourOwnGamesWithPython/All projects/Varibles.py | 429 | 3.890625 | 4 | print("Create your character")
name = input("What is you character called?")
age = input("How old is your character?")
strengths = input("What is your character's strenghts?")
weakness = input("What are your character's weaknesses?")
print("Your character's name is", name)
print("Your character is", age, "years old")
print("Strenghts:", strenghts)
print("Weaknesses", weaknesses)
print(name, "says, 'Thanks for creating me!'") |
b124c829284bc4aea81d34cfa8d487eadb6f180e | PinkLego/MyPythonProjects | /InventYourOwnGamesWithPython/All projects/Mass Defense.py | 1,373 | 3.734375 | 4 | #
#
#
#
import turtle
import random
wn = turtle.Screen()
wn.setup(1200, 800)
wn.bgcolor("black")
wn.title("Mass Defense Game")
class Sprite():
pen = turtle.Turtle()
pen.hideturtle()
pen.speed(0)
pen.penup()
def __init__(self, x, y, shape, color):
self.x = x
self.y = y
self.shape = shape
self.color = color
self.dx = 0
self.speed = 0
def render(self):
Sprite.pen.goto(self.x, self.y)
Sprite.pen.shape(self.shape)
Sprite.pen.color(self.color)
Sprite.pen.stamp()
def move(self):
self.x += self.dx
sprites = []
#Defenders
for _ in range(10):
x = random.randint(-500, -300)
y = random.randint(-300, 300)
sprites.append(Sprite(x, y, "circle", "blue"))
# Attackers
for _ in range(10):
x = random.randint(300, 500)
y = random.randint(-300, 300)
sprites.append(Sprite(x, y, "circle", "red"))
sprites[-1].heading = 180 #Left
sprites[-1].dx = -0.2
# Weapons
for _ in range(10):
x = -1000
y = -1000
sprites.append(Sprite(x, y, "circle", "light blue"))
# Main game loop
while True:
# Move
for sprite in sprites:
sprite.move()
#Render
for sprite in sprites:
sprite.render()
# Update the screen
wn.update()
# Clear the screen
Sprite.pen.clear()
wn.mainloop()
|
7737b93b5c93234ab9a28e8a3b6d3b23f740dd76 | abhiranjan-singh/DevRepo | /calculater.py | 383 | 4.1875 | 4 | def mutiply(x, y):
return x*y
print(mutiply(int(input("enter the 1st number ")),int(input("Enter the second number "))))
#m = int(input("enter the 1stnumber "))
#n = int(input("enter the second number "))
# print(mutiply(input("enter the 1st number"),input("enter the second number")))
#print(mutiply(m, n))
#print('m' + '*' + 'n' + '=' + mutiply(m, n))print(mutiply(m, n))
|
dce0cf3caa43263a93aba2b4cd1de6e10e2efb03 | rexos/python_data_mining | /fibonacci.py | 147 | 3.9375 | 4 | def fibonacci(n):
ary = [1,1]
for i in range(2,n):
ary.append(ary[i-1]+ary[i-2])
return ary[n-1]
print fibonacci(10)
|
356f25da7e3e31a653955de095d7a12392d3b331 | marclacerna/ormuco | /question_b.py | 560 | 3.796875 | 4 | class CheckInputs:
def __init__(self, input1, input2):
try:
self.input1 = float(input1)
self.input2 = float(input2)
except ValueError:
print('Both inputs must be a number')
def compare(self):
if self.input1 > self.input2:
return '{} greater than {}'.format(self.input1, self.input2)
elif self.input1 == self.input2:
return '{} is equal {}'.format(self.input1, self.input2)
else:
return '{} less than {}'.format(self.input1, self.input2) |
67ca1707453a15e4c6ea0983a8e11ee83b7c1b97 | agvaibhav/Dynamic-Programming | /rod_cutting_to_max_profit.py | 1,646 | 3.515625 | 4 | # rod cutting
# we are given profit of each length of rod
# we have to max profit
# recursion method
'''
def maxProfit(arr, totalLen):
if totalLen == 0:
return 0
best = 0
for len in range(1, totalLen+1):
netProfit = arr[len] + maxProfit(arr, totalLen-len)
best = max(best, netProfit)
return best
if __name__=='__main__':
totalLen = int(input())
priceOfEachLen = list(map(int,input().split()))
priceOfEachLen.insert(0,0)
print(maxProfit(priceOfEachLen, totalLen))
'''
# memoization method
'''
def maxProfit(arr, totalLen):
if totalLen == 0:
return 0
if memo[totalLen] != -1:
return memo[totalLen]
best = 0
for len in range(1, totalLen+1):
netProfit = arr[len] + maxProfit(arr, totalLen-len)
best = max(best, netProfit)
memo[totalLen] = best
return best
if __name__=='__main__':
totalLen = int(input())
priceOfEachLen = list(map(int,input().split()))
priceOfEachLen.insert(0,0)
memo = [-1]*(totalLen+1)
print(maxProfit(priceOfEachLen, totalLen))
'''
# bottom up (dp) method
def maxProfit(arr, totalLen):
for len in range(1, totalLen+1):
best = 0
for cut in range(1, len+1):
best = max(best, arr[cut] + dp[len-cut])
dp[len] = best
return dp[totalLen]
if __name__=='__main__':
totalLen = int(input())
priceOfEachLen = list(map(int,input().split()))
priceOfEachLen.insert(0,0)
dp = [0]*(totalLen+1)
print(maxProfit(priceOfEachLen, totalLen))
|
ea6180b91169567ad23ba823d65587a2151c76d2 | agvaibhav/Dynamic-Programming | /fibonacci_memoized.py | 373 | 4.03125 | 4 | def fib(n,lookup):
if n==0 or n==1:
lookup[n]=n
if lookup[n] is None:
lookup[n]=fib(n-1,lookup)+fib(n-2,lookup)
return lookup[n]
def main(n):
lookup=[None]*(n+1)
print("fibonacci number is:",fib(n,lookup))
if __name__=="__main__":
n=int(input("write the number you want to calculate fibonacci for:"))
main(n)
|
817ff7a48e120dde311d2efe4ed5af3653c3a421 | nan0445/Leetcode-Python | /Recover Binary Search Tree.py | 803 | 3.71875 | 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 recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
self.pre,self.n1,self.n2 = None,None,None
def helper(root):
if not root: return
helper(root.left)
if not self.pre: self.pre = root
if root.val<self.pre.val:
if not self.n1: self.n1 = self.pre
self.n2 = root
self.pre = root
helper(root.right)
helper(root)
self.n1.val,self.n2.val = self.n2.val,self.n1.val
|
3e6d1270046132f91ba5cadc072ca19307865178 | nan0445/Leetcode-Python | /Balanced Binary Tree.py | 660 | 3.75 | 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 isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
self.flag = True
def helper(root):
if not root: return 0
if not self.flag: return 0
l = helper(root.left)
r = helper(root.right)
if abs(l-r)>1:
self.flag = False
return 0
return max(l,r)+1
helper(root)
return self.flag
|
4513ff87de71790ef509b716ab2457c32241ac06 | nan0445/Leetcode-Python | /Power of Three.py | 250 | 3.8125 | 4 | class Solution:
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n<=0: return False
while n>1:
n, m = divmod(n, 3)
if m!=0: return False
return True
|
50fac474fbcefc14ff6ae95edde0ecce61f8ccd2 | nan0445/Leetcode-Python | /Binary Tree Right Side View.py | 654 | 3.609375 | 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 rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
def helper(root,k):
if not root: return
if k==0 or k==len(res): res.append([])
res[k].append(root.val)
helper(root.left,k+1)
helper(root.right,k+1)
helper(root,0)
ans = []
for i in range(len(res)):
ans.append(res[i][-1])
return ans
|
62edcf7046115e564e295034c50102711b71c688 | nan0445/Leetcode-Python | /Linked List Cycle II.py | 821 | 3.65625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head: return None
slow = fast = head
stack = set()
stack.add(slow)
flag = False
while fast and fast.next:
slow=slow.next
fast=fast.next.next
stack.add(slow)
if slow==fast:
flag = True
break
if not flag: return None
if slow==head: return head
slow = slow.next
while slow not in stack:
slow = slow.next
return slow
|
cff739a27abb4061b8d01e34d056580f77981790 | nan0445/Leetcode-Python | /Self Crossing.py | 599 | 3.5625 | 4 | class Solution:
def isSelfCrossing(self, x):
"""
:type x: List[int]
:rtype: bool
"""
if len(x)<=3: return False
flag = True if x[2] > x[0] else False
for i in range(3,len(x)):
if flag == False:
if x[i]>=x[i-2]: return True
else:
if x[i]<=x[i-2]:
flag = False
if i>=4 and x[i-2]-x[i-4]<=x[i]:
x[i-1] -= x[i-3]
elif i==3 and x[i-2]<=x[i]:
x[i-1] -= x[i-3]
return False
|
35b9c6dc1b7ce2b5b4a6d9d1f2ca09d4cf119735 | nan0445/Leetcode-Python | /Different Ways to Add Parentheses.py | 651 | 3.546875 | 4 | class Solution:
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
if input.isdigit(): return [int(input)]
res = []
def helper(n1, n2, op):
if op == '+': return n1 + n2
elif op == '-': return n1 - n2
elif op == '*': return n1 * n2
for i in range(len(input)):
if input[i] in "+-*":
l = self.diffWaysToCompute(input[:i])
r = self.diffWaysToCompute(input[i+1:])
res.extend([helper(ln, rn, input[i]) for ln in l for rn in r])
return res
|
e55d1042b514fb55cff0e831b1d83872cf4c550a | nan0445/Leetcode-Python | /Search Insert Position.py | 545 | 3.71875 | 4 | class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l,r = 0,len(nums)-1
if r==-1: return 0
while l<r:
mid = (l+r)//2
if target>nums[mid]:
l = mid + 1
elif target<nums[mid]:
r = mid
else: return mid
if nums[l]>target: return max(l,0)
elif nums[l]<target: return min(l+1,len(nums))
elif nums[l]==target: return l
|
d1b02071edd187ca634a03c63b86db4b7838b758 | nan0445/Leetcode-Python | /House Robber III.py | 488 | 3.71875 | 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 rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def helper(node):
if not node: return 0,0
l, r = helper(node.left), helper(node.right)
return max(l) + max(r), node.val + l[0] + r[0]
return max(helper(root))
|
9186c1fb4552a1b862f949cd36b35a126a90061f | nan0445/Leetcode-Python | /Remove Nth Node From End of List.py | 742 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
count = 0
dummy = ListNode(0)
dummy.next = head
while head!=None:
head = head.next
count+=1
ind = count - n
res = dummy
count = 0
while dummy!=None:
if count==ind:
dummy.next = dummy.next.next
dummy = dummy.next
else:
dummy = dummy.next
count+=1
return res.next
|
753690e49ef2149ccea76603a17de27766f9e8f6 | nan0445/Leetcode-Python | /Fraction to Recurring Decimal.py | 739 | 3.5 | 4 | class Solution:
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
if numerator*denominator<0: sign = '-'
else: sign = ''
numerator, denominator = abs(numerator), abs(denominator)
n, m = divmod(numerator, denominator)
ans = [sign, str(n)]
if m==0: return ''.join(ans)
ans.append('.')
dic = {}
while m!=0:
if m in dic:
ans.insert(dic[m],'(')
ans.append(')')
break
dic[m] = len(ans)
n, m = divmod(m*10, denominator)
ans.append(str(n))
return ''.join(ans)
|
26ff62a19dc23bb66d05ac34c2f87e6c2095a87c | nan0445/Leetcode-Python | /Word Search.py | 859 | 3.578125 | 4 | class Solution:
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
m = len(board)
n = len(board[0])
def helper(p,q,t,board,word):
if p<0 or p>=len(board) or q<0 or q>=len(board[0]) or board[p][q] != word[t]: return False
board[p][q] = '#'
if t == len(word)-1: return True
a1 = helper(p-1,q,t+1,board,word) or helper(p,q-1,t+1,board,word) or helper(p+1,q,t+1,board,word) or helper(p,q+1,t+1,board,word)
board[p][q] = word[t]
return a1
for i in range(m):
for j in range(n):
if board[i][j] == word[0]:
if helper(i,j,0,board,word): return True
return False
|
363fb60fab73ad320aac80101cf924305254ca94 | nan0445/Leetcode-Python | /Palindrome Pairs.py | 654 | 3.609375 | 4 | class Solution:
def palindromePairs(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
dic = {word: i for i, word in enumerate(words)}
res = []
for j, word in enumerate(words):
for i in range(len(word)+1):
if word[:i] == word[:i][::-1]:
w = word[i:][::-1]
if w != word and w in dic: res.append([dic[w],j])
if i>0 and word[-i:] == word[-i:][::-1]:
w = word[:-i][::-1]
if w != word and w in dic: res.append([j, dic[w]])
return res
|
0e0078f97b8be6d5e53b5da55670433ff1034a3b | chae-heechan/Python_Study | /3. 문자열/practice_2.py | 812 | 3.515625 | 4 | print("a" + "b")
print("a", "b")
# 방법 1
print("나는 %d살입니다." % 20) #굉장히 C스럽네
print("나는 %s를 좋아해요." % "파이썬")
print("Apple 은 %c로 시작해요." % "A")
# %s
print("나는 %s살입니다." % 20)
print("나는 %s색과 %s색을 좋아해요." % ("파란", "빨간"))
# 방법 2
print("나는 {}살입니다.".format(20))
print("나는 {}색과 {}색을 좋아해요.".format("파란", "빨간"))
print("나는 {1}색과 {0}색을 좋아해요.".format("파란", "빨간"))
# 방법 3
print("나는 {age}살이며, {color}색을 좋아해요.".format(age=20, color="빨간"))
print("나는 {age}살이며, {color}색을 좋아해요.".format(color="빨간", age=20))
# 방법 4
age = 20
color = "빨간"
print(f"나는 {age}살이며, {color}색을 좋아해요.") |
aebd7a8b4bfed4166b0c2294ab90c48acc6ce8df | chae-heechan/Python_Study | /3. 문자열/practice_1.py | 411 | 4.0625 | 4 | python = "Python is Amazing"
print(python.lower())
print(python.upper())
print(python[0].isupper())
print(len(python))
print(python.replace("Python", "Java"))
index = python.index("n")
print(index)
index = python.index("n", index + 1)
print(index)
print(python.find("Java")) # 없을 경우 return -1
# print(python.index("Java")) # 없을 경우 error 띄우고 종료
print("hi")
print(python.count("n")) |
dc24a69fde9b47505c07f6e16a95c9497be4763c | chae-heechan/Python_Study | /4. 자료구조/set.py | 662 | 3.859375 | 4 | # 집합 (set)
# 중복 안됨, 순서 없음
my_set = {1, 2, 3, 3, 3}
print(my_set)
java = {"유재석", "김태호", "양세형"}
python = set(["유재석", "박명수"])
# 교집합 (java와 python을 모두 할 수 있는 사람)
print(java & python)
print(java.intersection(python))
# 합집합 (java나 python을 할 수 있는 사람)
print(java | python)
print(java.union(python))
# 차집합 (java는 할 수 있지만 python은 할 수 없는 사람)
print(java - python)
print(java.difference(python))
# python을 할 수 있는사람이 늘어남
python.add("김태호")
print(python)
# java를 까먹음
java.remove("김태호")
print(java) |
c1423dde6c4d142d9028e4d6953e1293d1e0ae29 | Andrew4me/byte | /except/try_except.py | 273 | 3.5 | 4 | try:
text = input('Введите что-нибудь -->')
except EOFError:
print('Ну зачем вы сделали мне EOF?')
except KeyboardInterrupt:
print('вы отменили операцию')
else:
print('Вы ввели {0}' .format(text))
|
3c0a49d57c23bfcd8d38c64fefe23231efd6c5e7 | xswxm/Smart_Fan_for_Raspberry_Pi | /fan.py | 1,446 | 3.71875 | 4 | #!/usr/bin/python2
#coding:utf8
'''
Author: xswxm
Blog: xswxm.com
This script is designed to manage your Raspberry Pi's fan according to the CPU temperature changes.
'''
import RPi.GPIO as GPIO
import os, time
# Parse command line arguments
import argparse
parser = argparse.ArgumentParser(description='Manage your Raspberry Pi Fan intelligently!')
parser.add_argument('-i', '--interval', type=int,
help='The interval of each CPU temperature check (in seconds). default=5', default=5)
parser.add_argument('-p', '--pin', type=int,
help='Pin number of the Fan. default=24', default=24)
parser.add_argument('-t', '--temp_limit', type=int,
help='Fan will be turned on once the temperature is higher than this value (in celsius). default=60', default=60)
args = parser.parse_args()
interval = args.interval
pin = args.pin
temp = 0
temp_limit = args.temp_limit * 1000
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(pin, GPIO.OUT)
try:
while True:
# Acquire CPU temperature
with open('/sys/class/thermal/thermal_zone0/temp', 'r') as file:
temp = int(file.read())
# Turn on the fan if temp is larger than the limit value
if temp > temp_limit:
GPIO.output(pin, GPIO.HIGH)
# Turn off the fan if temp is smaller than the value - 2000
elif temp < temp_limit-5000:
GPIO.output(pin, GPIO.LOW)
# Sleep for few seconds
time.sleep(interval)
except KeyboardInterrupt:
GPIO.cleanup() |
1e894d45be1e1e01e00d89c35e8169d3b3ad5652 | DGEs2018/python_4_django | /functions.py | 197 | 3.546875 | 4 | import functiontobeimported
def multiplication(x, y, z):
return x*y*z
# def square(x):
# return x*x
for i in range(10):
print(f"The square of {i} is {functiontobeimported.square(i)}") |
43d6e2b5da96f94c5037c2a0d19a6330fb5febec | sebastiandifrancesco/web-scraping-challenge | /scrape_mars.py | 3,975 | 3.53125 | 4 | # --- dependencies and setup ---
from bs4 import BeautifulSoup
import pandas as pd
from splinter import Browser
import time
def init_browser():
# Set executable path & initialize Chrome browser
executable_path = {"executable_path": "./chromedriver.exe"}
return Browser("chrome", **executable_path, headless=False)
def scrape():
browser = init_browser()
# Visit NASA Mars news site
url = "https://mars.nasa.gov/news/"
browser.visit(url)
time.sleep(1)
# Parse results HTML using BeautifulSoup
html = browser.html
news_soup = BeautifulSoup(html, "html.parser")
slide_element = news_soup.select_one("ul.item_list li.slide")
slide_element.find("div", class_="content_title")
# Scrape the latest news title
title = slide_element.find("div", class_="content_title").get_text()
# Scrape the latest paragraph text
paragraph = slide_element.find("div", class_="article_teaser_body").get_text()
# Visit the NASA JPL Site
url = "https://data-class-jpl-space.s3.amazonaws.com/JPL_Space/index.html"
browser.visit(url)
# Click button with class name full_image
full_image_button = browser.find_by_xpath("/html/body/div[1]/div/a/button")
full_image_button.click()
# Parse results HTML with BeautifulSoup
html = browser.html
image_soup = BeautifulSoup(html, "html.parser")
featured_image_url = image_soup.select_one("body > div.fancybox-overlay.fancybox-overlay-fixed > div > div > div > div > img").get("src")
# Use base URL to create absolute URL
featured_image_url = f"https://www.jpl.nasa.gov{featured_image_url}"
# Visit the Mars facts site using pandas
mars_df = pd.read_html("https://space-facts.com/mars/")[0]
mars_df.columns=["Description", "Value"]
mars_df.set_index("Description", inplace=True)
html_table = mars_df.to_html(index=False, header=False, border=0, classes="table table-sm table-striped font-weight-light")
# Visit hemispheres website through splinter module
url = "https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars"
browser.visit(url)
# HTML object
html_hemispheres = browser.html
# Parse HTML with Beautiful Soup
soup = BeautifulSoup(html_hemispheres, 'html.parser')
# Retreive all items that contain Mars hemispheres information
items = soup.find_all('div', class_='item')
# Create empty list for hemisphere urls
hemisphere_image_urls = []
# Store the main_url
hemispheres_main_url = 'https://astrogeology.usgs.gov'
# Loop through the items previously stored
for i in items:
# Store title
title = i.find('h3').text
# Store link that leads to full image website
partial_img_url = i.find('a', class_='itemLink product-item')['href']
# Visit the link that contains the full image website
browser.visit(hemispheres_main_url + partial_img_url)
# HTML object of individual hemisphere information website
partial_img_html = browser.html
# Parse HTML with Beautiful Soup for every individual hemisphere information website
soup = BeautifulSoup( partial_img_html, 'html.parser')
# Retrieve full image source
img_url = hemispheres_main_url + soup.find('img', class_='wide-image')['src']
# Append the retrieved information into a list of dictionaries
hemisphere_image_urls.append({"title" : title, "img_url" : img_url})
# Store all values in dictionary
scraped_data = {
"news_title": title,
"news_para": paragraph,
"featuredimage_url": featured_image_url,
"mars_fact_table": html_table,
"hemisphere_images": hemisphere_image_urls
}
# --- Return results ---
return scraped_data |
71b154af653eadaf81bfb74ba900427383f54235 | yan-yf/pyhomework | /hanoi&fib.py | 284 | 3.9375 | 4 | def hanoi(n, A, B, C):
if n == 1:
print A, '->', B
else:
hanoi(n - 1, A, C, B)
print A, '->', B
hanoi(n - 1, C, B, A)
hanoi(5, 'A', 'B', 'C')
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib (n - 2)
print fib(6) |
a203f7b2a316c3f9eaef8f3ae9ab5d2abd3454cb | leftan/D07 | /HW07_ch10_ex06.py | 928 | 4.09375 | 4 | # I want to be able to call is_sorted from main w/ various lists and get
# returned True or False.
# In your final submission:
# - Do not print anything extraneous!
# - Do not put anything but pass in main()
def is_sorted(list_of_items):
try:
new_list = sorted(list_of_items)
except:
print('The list cannot be sorted.')
return None
if list_of_items == new_list:
return True
else:
return False
def main():
list_1 = ['apple', 'bear', 'cat']
list_2 = ['apple', 'bear', 'apples']
list_3 = [1,2,3]
list_4 = [1,45,3]
list_5 = ['APPLE', 'BEAR', 'APPLES']
list_6 = ['APPLE', 'BEAR', 'CAT']
print(is_sorted(list_1)) # True
print(is_sorted(list_2)) # False
print(is_sorted(list_3)) # True
print(is_sorted(list_4)) # False
print(is_sorted(list_5)) # False
print(is_sorted(list_6)) # True
if __name__ == main():
main() |
83c83339f9279481ccb83273ae84555c316e3fc6 | HelalChow/Data-Structures | /Labs/Lab 8.py | 1,135 | 3.875 | 4 | class ArrayStack:
def __init__(self):
self.data = []
def __len__(self):
return len(self.data)
def is_empty(self):
return len(self) == 0
def push(self, item):
self.data.append(item)
def pop(self):
if self.is_empty==0:
raise Exception("Stack is empty")
return self.data.pop()
def top(self):
if self.is_empty==0:
raise Exception("Stack is empty")
return self.data[-1]
def balanced_expression(str):
lst = []
for i in str:
lst.append(i)
opening = "([{"
closing = ")]}"
stack = ArrayStack()
for i in lst:
if i in opening:
stack.push(i)
elif i in closing:
prev = stack.pop()
if prev == '(' and i != ")":
return False
elif prev == "[" and i != "]":
return False
elif prev == '{' and i != '}':
return False
if stack.is_empty():
return True
else:
return False
print(balanced_expression("{{([])}}([])("))
print(balanced_expression("{{[(])}}"))
|
6219eeb03cac0b97952fe8e2599a006421073865 | HelalChow/Data-Structures | /Classwork/10/10-17 ADT.py | 878 | 3.90625 | 4 | def Algorithm():
pass
'''
***Stack ADT***
Data Model: Collection of items where the last element in is the first to come out (Last in, first out)
Operations:
s = Stack()
len(s)
s.is_empty()
s.push() #Adds Item
s.pop() #Removes last item and returns it
s.top() #Returns last item
'''
def print_reverse(str):
letters = Stack()
for i in str:
letters.push(i)
while(letters.is_empty() == False):
print(letters.pop(),end='')
print()
'''
***Polish Notation***
Infix Postfix Prefix
5 5 5
5+2 5 2 + + 5 2
5-(3*4) 5 34 * - - 5 * 3 4
(5-3)*4 5 3 - 4 * * - 5 3 4
((5+2)*(8-3))/4 5 2 + 8 3 - * 4 / / * + 5 2 - 8 3 4
''' |
8561124801f526b472e5f3b3182b7efccb6f1a0f | HelalChow/Data-Structures | /Labs/Lab 6.py | 1,454 | 3.71875 | 4 | def find_lst_max(lst):
if len(lst)==1:
return lst[0]
else:
hold = find_lst_max(lst[1:])
return max(lst[0],hold)
print(find_lst_max( [1,2,3,4,5,100,12,2]))
def product_evens(n):
if n==2:
return n
else:
if n%2==0:
return n*product_evens(n-2)
else:
return n*product_evens(n-1)
#print(product_evens(8))
def is_palindrome(str, low, high):
if low>=high:
return False
elif high - low == 2 or high-low ==1:
if str[low]==str[high]:
return True
else:
return False
else:
hold = is_palindrome(str,low+1,high-1)
if str[low]==str[high] and hold ==True:
return True
else:
return False
#print(is_palindrome("mam",0,2))
def binary_search(lst,val,low,high):
if high==low:
if lst[low]==val:
return lst.index(val)
else:
return
else:
mid = (high +low)//2
if lst[mid]>=val:
return binary_search(lst,val,low,mid)
else:
return binary_search(lst,val,mid+1,high)
lst=[1,2,3,4,5,6,7,8,9,10]
#print(binary_search(lst,5,0,9))
def nested_sum(lst):
sum = 0
for i in lst:
if isinstance(i, list):
sum = sum+ nested_sum(i)
else:
sum += i
return sum
#print(nested_sum( [1,[2,3,4]])) |
9f6eb2c3ca0d17db7a68b94e7ddd51b1a88592c8 | HelalChow/Data-Structures | /Labs/Lab 2.py | 1,964 | 3.78125 | 4 | class Polynomial:
def __init__(self,lst=[0]):
self.lst = lst
def __repr__(self):
poly = ""
for i in range(len(self.lst)-1,0,-1):
if i == 1:
poly += str(self.lst[i])+"x^"+str(i)+"+"+str(self.lst[0])
else:
poly += str(self.lst[i]) + "x^" + str(i)+"+"
count = poly.count("-")
for i in range(count):
minus=poly.find("-")
poly = poly[:minus-1]+poly[minus:]
return poly
def evaluate(self, val):
sum = 0
for i,j in enumerate(self.lst):
sum+=j*val**i
return sum
def __add__(self, other):
new = []
count=0
if len(self.lst)>len(other.lst):
for i in range(len(other.lst)):
sum=self.lst[i]+other.lst[i]
new.append(sum)
count=i+1
for i in range(count,len(self.lst)):
new.append(self.lst[i])
else:
for i in range(len(self.lst)):
sum=self.lst[i]+other.lst[i]
new.append(sum)
count=i+1
for i in range(count,len(other.lst)):
new.append(other.lst[i])
return Polynomial(new)
def __mul__(self, other):
new = [0]*(len(self.lst)+len(other.lst)-1)
for i,j in enumerate(self.lst):
for k,l in enumerate(other.lst):
new[i+k] += j*l
return Polynomial(new)
def derive(self):
new = []
for i,j in enumerate(self.lst):
new.append(j*i)
new.pop(0)
return Polynomial(new)
def main():
test1 = Polynomial([3,7,0,-9,2])
test2 = Polynomial([1,2])
test_eval = Polynomial([3, 7, 0, -9, 2]).evaluate(2)
test_add = test1+test2
mul = test1*test2
derive = Polynomial([3,7,0,-9,2]).derive()
print(derive)
main()
|
31a03d615d586ef55b70874d973d5a68cd1d4ae1 | HelalChow/Data-Structures | /Homework/HW3/hc2324_hw3_q3.py | 307 | 3.6875 | 4 | def find_duplicates(lst):
counter = [0] * (len(lst) - 1)
res_lst = []
for i in range(len(lst)):
counter[lst[i] - 1] += 1
for i in range(len(counter)):
if (counter[i] > 1):
res_lst.append(i + 1)
return res_lst
print(find_duplicates([0,2,2])) |
68ee8286c000c5c0512432a0d808be49dc8ab6a9 | HelalChow/Data-Structures | /Homework/HW2/hc2324_hw2_q6.py | 593 | 3.671875 | 4 | def two_sum(srt_lst, target):
curr_index = 0
sum_found = False
count =0
while(sum_found==False and curr_index < len(srt_lst)-1):
if (count >= len(srt_lst)):
count = 0
curr_index += 1
elif srt_lst[curr_index] + srt_lst[count] == target and curr_index != count:
sum_found = True
else:
count+=1
if sum_found==True:
return (curr_index, count)
else:
return None
def main():
srt_lst = [-2, 7, 11, 15, 20, 21]
target = 35
print(two_sum(srt_lst, target))
|
fe0871327bdc40129abafafc866406b13995f722 | MafihlwaK/Pre-Bootcamp-coding-Challenges-python- | /Task 11.py | 206 | 3.8125 | 4 | def common_characters():
str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
s1 = set(str1)
s2 = set(str2)
first = s1 & s2
print(first)
common_characters() |
4359dd4f67584016be61c50548e51c8117ee2bc7 | xpbupt/leetcode | /Medium/Complex_Number_Multiplication.py | 1,043 | 4.15625 | 4 | '''
Given two strings representing two complex numbers.
You need to return a string representing their multiplication. Note i2 = -1 according to the definition.
Example 1:
Input: "1+1i", "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.
Example 2:
Input: "1+-1i", "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.
'''
class Solution(object):
def complexNumberMultiply(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
t_a = self.get_real_and_complex(a)
t_b = self.get_real_and_complex(b)
c = self.calculate(t_a, t_b)
return c[0] + '+' + c[1] +'i'
def get_real_and_complex(self, c):
a = c.split('+')[0]
b = c.split('+')[1].split('i')[0]
return (int(a), int(b))
def calculate(self, a, b):
return (str(a[0]*b[0] - a[1]*b[1]), str(a[0]*b[1] + a[1]*b[0]))
|
f5368db904d1ec8e53ba06e9c529751ed9982f67 | jeevabalanmadhu/__LearnWithMe__ | /Machine Learning/Data science/DataScienceClass/PythonBasics/StringHandling.py | 7,782 | 3.9375 | 4 | #String handling
#isupper
'''
MyString="HELLO"
MyString1="HELLO%&^%&"
MyString2="HELLO%e"
result=MyString.isupper()
result1=MyString1.isupper()
result2=MyString2.isupper()
print(result)
print(result1)
print(result2)
output:
True
True
False
---------------------
#islower
MyString="hello"
MyString1="hello%&^%&"
MyString2="hello%E"
result=MyString.islower()
result1=MyString1.islower()
result2=MyString2.islower()
print(result)
print(result1)
print(result2)
output:
True
True
False
---------------------
#isspace
MyString=""
MyString1=" "
MyString2=" e"
result=MyString.isspace()
result1=MyString1.isspace()
result2=MyString2.isspace()
print(result)
print(result1)
print(result2)
MyString3=None
result3=MyString3.isspace()
print(result3)
output:
False
True
False
Traceback (most recent call last):
File "C:/Users/HP1/AppData/Local/Programs/Python/Python37/StringHandling.py", line 65, in <module>
result3=MyString3.isspace()
AttributeError: 'NoneType' object has no attribute 'isspace'
---------------------
#isdigit
MyString="52342423"
MyString1="2343242 "
MyString2="233423468e3222"
result=MyString.isdigit()
result1=MyString1.isdigit()
result2=MyString2.isdigit()
print(result)
print(result1)
print(result2)
MyString3=""
result3=MyString3.isdigit()
print(result3)
output:
True
False
False
False
---------------------
#istitle
MyString="Hello Python Class"
MyString1="hello Python Class"
MyString2="Hello python Class"
result=MyString.istitle()
result1=MyString1.istitle()
result2=MyString2.istitle()
print(result)
print(result1)
print(result2)
output:
True
False
False
---------------------
#isidentifier
MyString="Hello"
MyString1="hello8"
MyString2="_hello"
MyString3=" hello"
MyString4="^hello"
result=MyString.isidentifier()
result1=MyString1.isidentifier()
result2=MyString2.isidentifier()
result3=MyString3.isidentifier()
result4=MyString4.isidentifier()
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
True
True
True
False
False
---------------------
#isalpha
MyString="Hello"
MyString1="hello8"
MyString2="_hello"
MyString3=" hello"
MyString4="^hello"
result=MyString.isalpha()
result1=MyString1.isalpha()
result2=MyString2.isalpha()
result3=MyString3.isalpha()
result4=MyString4.isalpha()
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
True
False
False
False
False
---------------------
#isalnum
MyString="Hello"
MyString1="hello8"
MyString2="_hello"
MyString3=" hello"
MyString4="^hello"
result=MyString.isalnum()
result1=MyString1.isalnum()
result2=MyString2.isalnum()
result3=MyString3.isalnum()
result4=MyString4.isalnum()
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
True
True
False
False
False
---------------------
#upper
MyString="Hello python"
MyString1="hello8 Py"
MyString2="_hello"
MyString3=" hello"
MyString4="^hello"
result=MyString.upper()
result1=MyString1.upper()
result2=MyString2.upper()
result3=MyString3.upper()
result4=MyString4.upper()
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
HELLO PYTHON
HELLO8 PY
_HELLO
HELLO
^HELLO
---------------------
#swapcase
MyString="Hello pYthon"
MyString1="hello8 Py"
MyString2="_hELlo"
MyString3=" hello"
MyString4="^hellO"
result=MyString.swapcase()
result1=MyString1.swapcase()
result2=MyString2.swapcase()
result3=MyString3.swapcase()
result4=MyString4.swapcase()
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
hELLO PyTHON
HELLO8 pY
_HelLO
HELLO
^HELLo
---------------------
#capitalize
MyString="python Class"
MyString1="hello Python Class"
MyString2="Hello python Class"
MyString3="_hello"
MyString4=" hello"
result=MyString.capitalize()
result1=MyString1.capitalize()
result2=MyString2.capitalize()
result3=MyString3.capitalize()
result4=MyString4.capitalize()
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
Python class
Hello python class
Hello python class
_hello
hello
---------------------
#startswith
MyString="python Class"
MyString1="hello Python Class"
MyString2="Hello python Class"
MyString3="_hello"
MyString4=" hello"
result=MyString.startswith("he")
result1=MyString1.startswith("he")
result2=MyString2.startswith("he")
result3=MyString3.startswith("he")
result4=MyString4.startswith("he")
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
False
True
False
False
False
---------------------
#endswith
MyString="python CLASS"
MyString1="hello Python Class"
MyString2="Hello python"
MyString3="_hello class "
MyString4=" hello"
result=MyString.endswith("ss")
result1=MyString1.endswith("ss")
result2=MyString2.endswith("ss")
result3=MyString3.endswith("ss")
result4=MyString4.endswith("ss")
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
False
True
False
False
False
---------------------
#split
MyString="python CLASS"
MyString1="hello Python Class"
MyString2="HeLlo python"
MyString3="_hello class "
MyString4=" heLLo"
result=MyString.split("SS")
result1=MyString1.split("o")
result2=MyString2.split("s")
result3=MyString3.split("l")
result4=MyString4.split("L")
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
1
2
0
3
2
---------------------
#split
MyString="python CLASS"
MyString1="hello Python Class"
MyString2="HeLlo python"
MyString3="_hello class "
MyString4=" heLLo"
result=MyString.split("CL")
result1=MyString1.split(" ")
result2=MyString2.split("on")
result3=MyString3.split("L")
result4=MyString4.split("L")
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
['python ', 'ASS']
['hello', 'Python', 'Class']
['HeLlo pyth', '']
['_hello class ']
[' he', '', 'o']
---------------------
#rstrip
MyString="Hello pYthon "
MyString1="hello8 Py "
MyString2="_hELlo"
MyString3=" hello"
MyString4=" ^hellO"
result=MyString.rstrip()
result1=MyString1.rstrip()
result2=MyString2.rstrip()
result3=MyString3.rstrip()
result4=MyString4.rstrip()
print(result)
print(len(MyString))
print(len(result))
print(result1)
print(len(MyString1))
print(len(result1))
print(result2)
print(len(MyString2))
print(len(result2))
print(result3)
print(len(MyString3))
print(len(result3))
print(result4)
print(len(MyString4))
print(len(result4))
output:
15
Hello pYthon
15
12
hello8 Py
10
9
_hELlo
6
6
hello
6
5
^hellO
7
6
---------------------
#lrstrip
MyString="Hello pYthon "
MyString1="hello8 Py "
MyString2="_hELlo"
MyString3=" hello"
MyString4=" ^hellO"
result=MyString.rstrip()
result1=MyString1.rstrip()
result2=MyString2.rstrip()
result3=MyString3.rstrip()
result4=MyString4.rstrip()
print(result)
print(len(MyString))
print(len(result))
print(result1)
print(len(MyString1))
print(len(result1))
print(result2)
print(len(MyString2))
print(len(result2))
print(result3)
print(len(MyString3))
print(len(result3))
print(result4)
print(len(MyString4))
print(len(result4))
output:
Hello pYthon
15
15
hello8 Py
10
10
_hELlo
6
6
hello
6
5
^hellO
7
6
---------------------
#rstrip
MyString="Hello pYthon "
MyString1="hello8 Py "
MyString2="_hELlo"
MyString3=" hello"
MyString4=" ^hellO"
result=MyString.rstrip()
result1=MyString1.rstrip()
result2=MyString2.rstrip()
result3=MyString3.rstrip()
result4=MyString4.rstrip()
print(result)
print(len(MyString))
print(len(result))
print(result1)
print(len(MyString1))
print(len(result1))
print(result2)
print(len(MyString2))
print(len(result2))
print(result3)
print(len(MyString3))
print(len(result3))
print(result4)
print(len(MyString4))
print(len(result4))
output:
Hello pYthon
15
12
hello8 Py
10
9
_hELlo
6
6
hello
6
6
^hellO
7
7
|
4f4be5077a2ec1945975bc34b0c05c20af8e6600 | jeevabalanmadhu/__LearnWithMe__ | /Machine Learning/Data science/DataScienceClass/PythonBasics/OddOrEven.py | 527 | 4.0625 | 4 | #odd or even from 1-100
'''
####method: 1
myOddList=[]
myEvenList=[]
for i in range(1,101):
if(i%2==0):
print("even = {0}".format(i))
elif(i%2==1):
print("odd = {0}".format(i))
'''
###Method 2:
myOddList=[]
myEvenList=[]
for i in range(1,101):
if(i%2==0):
myEvenList.append(i)
elif(i%2==1):
myOddList.append(i)
print("Odd number from 1 - 100 are: ",myOddList)
print()
print("Even number from 1 - 100 are: ",myEvenList)
|
1c749cd9a5612b07f817fe9ae2b5df307e896ff1 | leonardo185/Data-Structures-using-Python | /binary_search.py | 527 | 3.78125 | 4 | def binarySearach(list, value):
first = 0
last = len(list) - 1
found = False
index = None
while(first <= last and not found):
midpoint = int((first + last)/2)
if(list[midpoint] == value):
found = True
index = midpoint + 1
else:
if(value < list[midpoint]):
last = midpoint - 1
else:
first = midpoint + 1
return index
list = [1,2,3,4,5,6,7,8,9]
print(binarySearach(list, 8))
|
eae2e47d12de9e59fcf8637f16e4349e78efa153 | Mystic67/Game-Mac-Gyver | /controller/events.py | 1,860 | 3.6875 | 4 | #! /usr/bin/python3
# -*-coding: utf-8-*-
import pygame
class Events:
'''This class listen the user inputs and set the game variables '''
main = 1
home = 1
game = 1
game_level = 0
game_end = 0
# self.listen_events()
@classmethod
def listen_game_events(cls, instance_sprite=None):
cls.instance_sprite = instance_sprite
for event in pygame.event.get():
if event.type == pygame.QUIT or event.type == pygame.KEYDOWN \
and event.key == pygame.K_ESCAPE:
cls.quit_game() # Quit the game
'''If user presse space bar, quit home screen and start game'''
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
cls.go_game() # Start de game
''' Listen the directory entry key if instance
of sprite is given as parameter'''
elif instance_sprite is not None:
if event.key == pygame.K_RIGHT:
cls.instance_sprite.move("right")
elif event.key == pygame.K_LEFT:
cls.instance_sprite.move("left")
elif event.key == pygame.K_UP:
cls.instance_sprite.move("up")
elif event.key == pygame.K_DOWN:
cls.instance_sprite.move("down")
@classmethod
def quit_game(cls):
cls.home = 0
cls.game = 0
cls.main = 0
cls.game_level = 0
@classmethod
def init_game(cls):
cls.home = 1
cls.game = 1
@classmethod
def go_game(cls):
cls.home = 0
cls.game_level = 1
cls.game_end = 0
@classmethod
def end_game(cls):
cls.game = 0
cls.game_end = 1
cls.home = 1
|
9e0d6c1a5ccda5e204d5ab171e22afc74f63261b | francico4293/Sudoku-Solver-v2 | /sudoku_board.py | 21,643 | 4.125 | 4 | # Author: Colin Francis
# Description: Implementation of the sudoku board using Pygame
import pygame
import time
from settings import *
class SudokuSolver(object):
"""A class used to solve Sudoku puzzles."""
def __init__(self):
"""Creates a SudokuSolver object."""
self._board = Board()
self._running = True
pygame.font.init()
def run(self) -> None:
"""
Load a blank puzzle board, input the puzzle, and run the solver.
:return: None.
"""
while self._running:
for event in pygame.event.get():
# check if the user is trying to exit
if event.type == pygame.QUIT:
self._running = False
# check for a grid square being selected
if event.type == pygame.MOUSEBUTTONDOWN:
if (BOARD_LEFT <= pygame.mouse.get_pos()[0] <= BOARD_LEFT + BOARD_WIDTH) and \
(BOARD_TOP <= pygame.mouse.get_pos()[1] <= BOARD_TOP + BOARD_HEIGHT):
self._board.set_selected_coords(mouse_pos()[0], mouse_pos()[1])
elif (BUTTON_LEFT <= pygame.mouse.get_pos()[0] <= BUTTON_LEFT + BUTTON_WIDTH) and \
(BUTTON_TOP <= pygame.mouse.get_pos()[1] <= BUTTON_TOP + BUTTON_HEIGHT):
self._board.click()
# check for a number being entered
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1 or event.key == pygame.K_KP1:
self._board.set_number_by_selected(1)
elif event.key == pygame.K_2 or event.key == pygame.K_KP2:
self._board.set_number_by_selected(2)
elif event.key == pygame.K_3 or event.key == pygame.K_KP3:
self._board.set_number_by_selected(3)
elif event.key == pygame.K_4 or event.key == pygame.K_KP4:
self._board.set_number_by_selected(4)
elif event.key == pygame.K_5 or event.key == pygame.K_KP5:
self._board.set_number_by_selected(5)
elif event.key == pygame.K_6 or event.key == pygame.K_KP6:
self._board.set_number_by_selected(6)
elif event.key == pygame.K_7 or event.key == pygame.K_KP7:
self._board.set_number_by_selected(7)
elif event.key == pygame.K_8 or event.key == pygame.K_KP8:
self._board.set_number_by_selected(8)
elif event.key == pygame.K_9 or event.key == pygame.K_KP9:
self._board.set_number_by_selected(9)
if self._board.solve():
self._solve()
self._board.update_board(pygame.mouse.get_pos()) # update the game board
pygame.display.update() # update the display
def _solve(self):
"""
Used to solve Sudoku puzzles.
:return:
"""
self._board.lock_presets()
row_index, col_index = 0, 0
start_time = time.perf_counter()
while not self._board.solved():
if col_index > 8:
col_index = 0
row_index += 1
self._board.set_selected_coords(BOARD_LEFT + (SQUARE_HEIGHT * col_index),
BOARD_TOP + (SQUARE_WIDTH * row_index)
)
if self._board.get_number(row_index, col_index) == '.' and not \
self._board.is_preset(row_index, col_index):
for number in range(1, 10):
if not self._board.in_row(row_index, str(number)) and not \
self._board.in_col(col_index, str(number)) and not \
self._board.in_square(row_index, col_index, str(number)):
self._board.set_number_by_index(row_index, col_index, str(number))
col_index += 1
break
else:
row_index, col_index = self._back_prop(row_index, col_index - 1)
elif not self._board.is_preset(row_index, col_index):
start_number = int(self._board.get_number(row_index, col_index)) + 1
for number in range(start_number, 10):
if not self._board.in_row(row_index, str(number)) and not \
self._board.in_col(col_index, str(number)) and not \
self._board.in_square(row_index, col_index, str(number)):
self._board.set_number_by_index(row_index, col_index, str(number))
col_index += 1
break
else:
self._board.set_number_by_index(row_index, col_index, '.')
row_index, col_index = self._back_prop(row_index, col_index - 1)
else:
col_index += 1
self._board.update_board(pygame.mouse.get_pos()) # update the game board
pygame.display.update() # update the display
end_time = time.perf_counter()
print("Solution Speed: {:.2f}s".format(end_time - start_time))
# self.print_board()
def _back_prop(self, row_index: int, col_index: int) -> tuple:
"""
Recursively moves backwards through the Sudoku puzzle until a non-preset
value less than 9 is found.
:param row_index: The current row index in the puzzle.
:param col_index: The current column index in the puzzle
:return: A tuple containing the row index and column index where the
non-preset value was found.
"""
if col_index < 0:
col_index = 8
row_index -= 1
# base case
if self._board.get_number(row_index, col_index) != '9' and not self._board.is_preset(row_index, col_index):
return row_index, col_index
if self._board.get_number(row_index, col_index) == '9' and not self._board.is_preset(row_index, col_index):
self._board.set_number_by_index(row_index, col_index, '.')
return self._back_prop(row_index, col_index - 1)
elif self._board.is_preset(row_index, col_index):
return self._back_prop(row_index, col_index - 1)
class Board(object):
"""Represents a Sudoku Board."""
def __init__(self):
"""Creates a Board object."""
self._screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
self._surface = pygame.Surface((BOARD_WIDTH, BOARD_HEIGHT))
self._screen.fill(WHITE)
self._surface.fill(WHITE)
self._button = Button(self._screen)
self._selected_square = [None] * 2
self._puzzle = [[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
]
self._puzzle_presets = None
pygame.display.set_caption('Sudoku Solver')
def update_board(self, mouse_position):
"""
Updates the state of the Sudoku Board.
:return: None.
"""
self._screen.blit(self._surface, (BOARD_LEFT, BOARD_TOP))
if self._selected_square != [None] * 2:
self._color_selected()
self._color_row()
self._color_col()
self._button.update(mouse_position)
self._place_numbers()
self._draw_grid()
def solve(self) -> bool:
return self._button.is_clicked()
def click(self):
self._button.click()
def get_number(self, row_index: int, col_index: int) -> str:
"""
Returns the number in the Sudoku puzzle found in the position specified by
`row_index` and `col_index`.
:param row_index: The index of the row to get the number from.
:param col_index: The index of the column to get the number from.
:return: The number corresponding to the specified row index and column
index.
"""
return self._puzzle[row_index][col_index]
def lock_presets(self):
self._puzzle_presets = self._find_presets()
def set_selected_coords(self, x_coord: int, y_coord: int) -> None:
"""
Sets the x-coordinate and y-coordinate of the selected square.
:param x_coord: The x-coordinate of the selected square.
:param y_coord: The y-coordinate of the selected square.
:return: None.
"""
self._selected_square[0], self._selected_square[1] = x_coord, y_coord
def set_number_by_selected(self, number: int) -> None:
"""
Sets the `number` in the puzzle row / col corresponding to the currently
selected square.
:param number: The number to set.
:return: None.
"""
if self._selected_square == [None] * 2:
return
row = (self._selected_square[1] - BOARD_TOP) // SQUARE_HEIGHT
col = (self._selected_square[0] - BOARD_LEFT) // SQUARE_WIDTH
self._puzzle[row][col] = str(number)
def set_number_by_index(self, row_index: int, col_index: int, number: str) -> None:
"""
Sets the square in the Sudoku puzzle corresponding to `row_index` and
`col_index`.
:param row_index: The index of the row to place the number in.
:param col_index: The index of the column to place the number in.
:param number: The number to place in the puzzle.
:return: None.
"""
self._puzzle[row_index][col_index] = number
def solved(self) -> bool:
"""
Searches each row in the Sudoku puzzle to determine if a solution has been
found.
:return: True if a solution has been found. Otherwise, False.
"""
if '.' in self._puzzle[0] or '.' in self._puzzle[1] or '.' in self._puzzle[2] or \
'.' in self._puzzle[3] or '.' in self._puzzle[4] or '.' in self._puzzle[5] or \
'.' in self._puzzle[5] or '.' in self._puzzle[7] or '.' in self._puzzle[8]:
return False
return True
def in_row(self, row_index: int, number: str) -> bool:
"""
Searches the Sudoku puzzle to see if `number` exists in the specified row index.
:param row_index: The row index in the Sudoku puzzle to search in.
:param number: The number to search for.
:return: True if the number is found in the row. Otherwise, False.
"""
if number in self._puzzle[row_index]:
return True
return False
def in_col(self, col_index: int, number: str) -> bool:
"""
Searches the Sudoku puzzle to see if 'number' exists in the specified column
index.
:param col_index: The column index in the Sudoku puzzle to search in.
:param number: The number to search for.
:return: True if the number is found in the column. Otherwise, False.
"""
for row in self._puzzle:
if row[col_index] == number:
return True
return False
def in_square(self, row_index: int, col_index: int, number: str) -> bool:
"""
Searches the Sudoku puzzle to see if the `number` exists in the square
region of the Sudoku board as indicated by the specified row index and
column index.
:param row_index: The row index of the Sudoku puzzle to search in.
:param col_index: The column index of the Sudoku puzzle to search
in.
:param number: The number to search for.
:return: True if the number is found in the square region. Otherwise,
False.
"""
squares = {1: self._puzzle[0][:3] + self._puzzle[1][:3] + self._puzzle[2][:3],
2: self._puzzle[0][3:6] + self._puzzle[1][3:6] + self._puzzle[2][3:6],
3: self._puzzle[0][6:] + self._puzzle[1][6:] + self._puzzle[2][6:],
4: self._puzzle[3][:3] + self._puzzle[4][:3] + self._puzzle[5][:3],
5: self._puzzle[3][3:6] + self._puzzle[4][3:6] + self._puzzle[5][3:6],
6: self._puzzle[3][6:] + self._puzzle[4][6:] + self._puzzle[5][6:],
7: self._puzzle[6][:3] + self._puzzle[7][:3] + self._puzzle[8][:3],
8: self._puzzle[6][3:6] + self._puzzle[7][3:6] + self._puzzle[8][3:6],
9: self._puzzle[6][6:] + self._puzzle[7][6:] + self._puzzle[8][6:]
}
if row_index == 0 or row_index == 1 or row_index == 2:
if 0 <= col_index < 3:
if number in squares[1]:
return True
return False
elif 3 <= col_index < 6:
if number in squares[2]:
return True
return False
else:
if number in squares[3]:
return True
return False
elif row_index == 3 or row_index == 4 or row_index == 5:
if 0 <= col_index < 3:
if number in squares[4]:
return True
return False
elif 3 <= col_index < 6:
if number in squares[5]:
return True
return False
else:
if number in squares[6]:
return True
return False
else:
if 0 <= col_index < 3:
if number in squares[7]:
return True
return False
elif 3 <= col_index < 6:
if number in squares[8]:
return True
return False
else:
if number in squares[9]:
return True
return False
def is_preset(self, row_index: int, col_index: int) -> bool:
"""
Determines whether a board value is a preset value or not.
:param row_index: The row corresponding to the value in the puzzle to check.
:param col_index: The column corresponding to the value in the puzzle to check.
:return: True if the value is preset. Otherwise, False.
"""
if self._puzzle_presets[row_index][col_index]:
return True
else:
return False
def _place_numbers(self) -> None:
"""
Places the numbers set in the puzzle onto the Sudoku Board.
:return: None.
"""
# TODO: Find a better way to center the number
for row_index, row in enumerate(self._puzzle):
for col_index, number in enumerate(row):
if number != ".":
font = pygame.font.SysFont('Arial', 30)
number_surface = font.render(number, True, BLACK)
self._screen.blit(number_surface,
(BOARD_LEFT + (SQUARE_WIDTH * col_index) + (SQUARE_WIDTH / 2) - 5,
BOARD_TOP + (SQUARE_HEIGHT * row_index) + (SQUARE_HEIGHT / 4) - 5
)
)
def _draw_grid(self) -> None:
"""
Draws the grid used in Sudoku on the Board.
:return: None.
"""
pygame.draw.rect(self._screen,
BLACK,
pygame.Rect(BOARD_LEFT, BOARD_TOP, BOARD_WIDTH, BOARD_HEIGHT),
width=3
)
self._draw_vert_grid_lines()
self._draw_horz_grid_lines()
def _draw_vert_grid_lines(self) -> None:
"""
Draws vertical grid lines on the Board.
:return: None.
"""
grid_count = 1
for x_coord in range(BOARD_LEFT + SQUARE_WIDTH, BOARD_WIDTH + BOARD_LEFT + SQUARE_WIDTH, SQUARE_WIDTH):
width = 1 if grid_count % 3 != 0 else 3
pygame.draw.line(self._screen,
BLACK,
(x_coord, BOARD_TOP),
(x_coord, BOARD_HEIGHT + BOARD_TOP),
width=width
)
grid_count += 1
def _draw_horz_grid_lines(self) -> None:
"""
Draws horizontal grid lines on the Board.
:return: None.
"""
grid_count = 1
for y_coord in range(BOARD_TOP + SQUARE_HEIGHT, BOARD_HEIGHT + BOARD_TOP + SQUARE_HEIGHT, SQUARE_HEIGHT):
width = 1 if grid_count % 3 != 0 else 3
pygame.draw.line(self._screen,
BLACK,
(BOARD_LEFT, y_coord),
(BOARD_LEFT + BOARD_WIDTH, y_coord),
width=width
)
grid_count += 1
def _color_selected(self) -> None:
"""
Colors the selected square.
:return: None.
"""
pygame.draw.rect(self._screen,
SQUARE_BLUE,
pygame.Rect(self._selected_square[0],
self._selected_square[1],
SQUARE_WIDTH,
SQUARE_HEIGHT)
)
def _color_row(self) -> None:
"""
Colors the row corresponding to the selected square.
:return: None.
"""
row_surface = pygame.Surface((BOARD_WIDTH, SQUARE_HEIGHT))
row_surface.set_alpha(100)
row_surface.fill(SQUARE_BLUE)
self._screen.blit(row_surface, (BOARD_LEFT, self._selected_square[1]))
def _color_col(self) -> None:
"""
Colors the column corresponding to the selected square.
:return: None.
"""
col_surface = pygame.Surface((SQUARE_WIDTH, BOARD_HEIGHT))
col_surface.set_alpha(100)
col_surface.fill(SQUARE_BLUE)
self._screen.blit(col_surface, (self._selected_square[0], BOARD_TOP))
def _find_presets(self) -> list:
"""
Iterates through the initial Sudoku puzzle and determines which values are preset and
which values are variable.
:return: A matrix (list-of-lists) containing boolean values - True for preset, False
for variable.
"""
preset_values = []
for row_index, row in enumerate(self._puzzle):
preset_row = []
for col_index, col_value in enumerate(row):
if col_value == '.':
preset_row.append(False)
else:
preset_row.append(True)
preset_values.append(list(preset_row))
preset_row.clear()
return preset_values
class Button(object):
""""""
def __init__(self, board):
""""""
self._clicked = False
self._board = board
def update(self, mouse_position: tuple) -> None:
"""
Updates the states of the Button.
:param mouse_position: The current position of the user's mouse.
:return: None.
"""
if (BUTTON_LEFT <= mouse_position[0] <= BUTTON_LEFT + BUTTON_WIDTH) and \
(BUTTON_TOP <= mouse_position[1] <= BUTTON_TOP + BUTTON_HEIGHT):
color = DARK_GREY
else:
color = LIGHT_GREY
self._draw_button(color)
self._button_text()
def is_clicked(self):
return self._clicked
def click(self):
self._clicked = True
def _draw_button(self, color: tuple) -> None:
"""
Draws the button on the screen.
:param color: The color of the button.
:return: None.
"""
pygame.draw.rect(self._board,
color,
pygame.Rect(BUTTON_LEFT,
BUTTON_TOP,
BUTTON_WIDTH,
BUTTON_HEIGHT)
)
def _button_text(self) -> None:
"""
Displays the text "Solve Puzzle" inside of the Button.
:return: None.
"""
font = pygame.font.SysFont('Arial', 20)
text_surface = font.render('Solve Puzzle', True, BLACK)
self._board.blit(text_surface, (BUTTON_LEFT + 15, BUTTON_TOP + 2))
if __name__ == "__main__":
sudoku_puzzle = [["5", "3", ".", ".", "7", ".", ".", ".", "."],
["6", ".", ".", "1", "9", "5", ".", ".", "."],
[".", "9", "8", ".", ".", ".", ".", "6", "."],
["8", ".", ".", ".", "6", ".", ".", ".", "3"],
["4", ".", ".", "8", ".", "3", ".", ".", "1"],
["7", ".", ".", ".", "2", ".", ".", ".", "6"],
[".", "6", ".", ".", ".", ".", "2", "8", "."],
[".", ".", ".", "4", "1", "9", ".", ".", "5"],
[".", ".", ".", ".", "8", ".", ".", "7", "9"]]
solve = SudokuSolver()
solve.run()
|
b716e509279d0f192f5128489d752690a4d303ed | subham09/Comp9021 | /Quizes/quiz 4.py | 3,442 | 3.625 | 4 | # Randomly fills a grid of size height and width whose values are input by the user,
# with nonnegative integers randomly generated up to an upper bound N also input the user,
# and computes, for each n <= N, the number of paths consisting of all integers from 1 up to n
# that cannot be extended to n+1.
# Outputs the number of such paths, when at least one exists.
#
# Written by Subham Anand for COMP9021
from random import seed, randint
import sys
from collections import defaultdict
def display_grid():
for i in range(len(grid)):
print(' ', ' '.join(str(grid[i][j]) for j in range(len(grid[0]))))
def get_paths():
global grid1
grid1 = list(grid)
zero = []
for i in range(height):
grid1[i].append(0)
grid1[i].reverse()
grid1[i].append(0)
grid1[i].reverse()
for i in range(width+2):
zero.append(0)
grid1.append(zero)
grid1.reverse()
grid1.append(zero)
grid1.reverse()
areas = {}
b = 0
global max_length
path = {}
counter = 0
for i in range(1,height+1):
for j in range(1,width+1):
if grid1[i][j] == 1:
if grid1[i][j+1] != 2 and grid1[i][j-1] != 2 and grid1[i+1][j] != 2 and grid1[i-1][j] != 2 :
counter += 1
areas[1] = counter
while max_length > 1:
for i in range(1,height+1):
for j in range(1,width+1):
if grid1[i][j] == max_length:
if grid1[i][j+1] != max_length + 1 and grid1[i][j-1] != max_length + 1 and grid1[i-1][j] != max_length + 1 and grid1[i+1][j] != max_length + 1 :
b = areas_of_region(max_length,i,j)
if max_length in areas:
areas[max_length] = areas[max_length] + b
else:
areas[max_length] = b
max_length -= 1
return areas
# Replace pass above with your code
# Insert your code for other functions
def areas_of_region(n,i,j,counter = 0, a = 0):
if grid1[i][j+1] == n-1 and n > 1:
if n-1 == 1 and n > 1:
a+=1
a += areas_of_region(n-1,i,j+1)
if grid1[i][j-1] == n-1 and n > 1:
if n-1 == 1 and n > 1:
a+=1
a += areas_of_region(n-1,i,j-1)
if grid1[i+1][j] == n-1 and n > 1:
if n-1 == 1 and n > 1:
a+=1
a += areas_of_region(n-1,i+1,j)
if grid1[i-1][j] == n-1 and n > 1:
if n-1 == 1 and n > 1:
a+=1
a += areas_of_region(n-1,i-1,j)
return a
try:
for_seed, max_length, height, width = [int(i) for i in
input('Enter four nonnegative integers: ').split()
]
if for_seed < 0 or max_length < 0 or height < 0 or width < 0:
raise ValueError
except ValueError:
print('Incorrect input, giving up.')
sys.exit()
seed(for_seed)
grid = [[randint(0, max_length) for _ in range(width)] for _ in range(height)]
print('Here is the grid that has been generated:')
display_grid()
#convert_grid()
paths = get_paths()
if paths:
for length in sorted(paths):
print(f'The number of paths from 1 to {length} is: {paths[length]}')
|
7000f0861768fb5c3cccb7e6dc7bc017190d456b | AlexseySukhanov/HomeWork3 | /Task_add_1.py | 360 | 3.734375 | 4 | flat=int(input("Введите номер квартиры "))
if flat<=144 and flat>0:
ent=int(flat/36-0.01)+1
floor=int(flat/4-0.01)+1-(ent-1)*9
print(f"Квартира находится в {ent} подъезде, на {floor} этаже")
else:
print("Квартиры с таким номером не существует в доме")
|
1def0b375d6b7f6d8ec10e58f8aefc784c923486 | Egan-eagle/python-exercises | /week1&2.py | 3,145 | 4.3125 | 4 | # Egan Mthembu
# A program that displays Fibonacci numbers using people's names.
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
name = "Mthembu"
first = name[0]
last = name[-1]
firstno = ord(first)
lastno = ord(last)
x = firstno + lastno
ans = fib(x)
print("My surname is", name)
print("The first letter", first, "is number", firstno)
print("The last letter", last, "is number", lastno)
print("Fibonacci number", x, "is", ans)
#COMMENT
Re: Week 2 task
by EGAN MTHEMBU - Saturday, 3 February 2018, 6:47 PM
C:\Users\egan\Desktop\fib.py\WEEK2>python test.py
My surname is Mthembu
The first letter M is number 77
The last letter u is number 117
Fibonacci number 194 is 15635695580168194910579363790217849593217
ord(c)
Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example,ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().
i.e
firstno = ord(first) M = 77
lastno = ord(last) U = 117
x = firstno + lastno = 194
Fibonacci number 194 is 15635695580168194910579363790217849593217
WEEK1 EXERCISE
# Egan Mthembu 24.01.2018
# A program that displays Fibonacci numbers.
def fib(n):
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
x = 19
ans = fib(x)
print("Fibonacci number", x, "is", ans)
Re: Fibonacci exercise responses
by EGAN MTHEMBU - Wednesday, 24 January 2018, 11:12 PM
Egan : E + N = 19, Fibonacci Number = 4181
C:\Users\ppc\Desktop\Fibonacci>python fib3.py
Fibonacci number 19 is 4181# Egan Mthembu
# A program that displays Fibonacci numbers using people's names.
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
name = "Mthembu"
first = name[0]
last = name[-1]
firstno = ord(first)
lastno = ord(last)
x = firstno + lastno
ans = fib(x)
print("My surname is", name)
print("The first letter", first, "is number", firstno)
print("The last letter", last, "is number", lastno)
print("Fibonacci number", x, "is", ans)
#COMMENT
#Re: Week 2 task
#EGAN MTHEMBU - Saturday, 3 February 2018, 6:47 PM
#My surname is Mthembu
The first letter M is number 77
The last letter u is number 117
Fibonacci number 194 is 15635695580168194910579363790217849593217
ord(c)
Given a string repord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().
i.e
firstno = ord(first) M = 77
lastno = ord(last) U = 117
x = firstno + lastno = 194
Fibonacci number 194 is 15635695580168194910579363790217849593217
##WEEK1 EXERCISE
# Egan Mthembu 24.01.2018
# A program that displays Fibonacci numbers.
def fib(n):
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
x = 19
ans = fib(x)
print("Fibonacci number", x, "is", ans)
Re: Fibonacci exercise responses
by EGAN MTHEMBU - Wednesday, 24 January 2018, 11:12 PM
Egan : E + N = 19, Fibonacci Number = 4181
Fibonacci number 19 is 4181
|
8fdad961a6692877342af74576cda9610090de77 | yuvraajsj18/CS50 | /intro/week6/tuple.py | 115 | 3.609375 | 4 | tuple = [
(1, 'a'),
(2, 'b'),
(3, 'c')
]
for num, alpha in tuple:
print(f"{alpha} - {num}") |
312c19e4e77b383d412b06a7ca482e7930e94b8a | yuvraajsj18/CS50 | /intro/week6/swap.py | 174 | 3.5625 | 4 | from cs50 import get_int
x = get_int("x = ")
y = get_int("y = ")
print(f"Before Swap: x = {x} & y = {y}")
x, y = y, x
print(f"After Swap: x = {x} & y = {y}")
|
29df6be4c64bd613e10323d60edf59d28f8b1386 | yuvraajsj18/CS50 | /intro/week6/hello1.py | 133 | 3.515625 | 4 | from cs50 import get_string
name = get_string("Name: ")
print("Hello,",name)
print(f"{name}, Hello!!!") # formated string output |
f27f0ec182b9da2d7ffac680b2c6cbab78494f9a | Sir-Benj/Python-First-Game | /enemy.py | 1,621 | 3.765625 | 4 | # Enemy Class
# Creating as a module.
# Creating the Enemy Class.
class Enemy:
"""For Each Enemy in the game"""
def __init__(self, name, hp, maxhp, attack, heal_count, heal, magic_count, magic_attack):
self.name=name
self.hp=hp
self.maxhp=maxhp
self.attack=attack
self.heal_count=heal_count
self.heal=heal
self.magic_count=magic_count
self.magic_attack=magic_attack
def __str__(self):
return "\t{}\n***********\nHP:{}\nMaxHP:{}\nAttack:{}\nHeal Count:{}\nHeal:{}\nMagic Count:{}\nMagic Attack:{}".format(self.name, self.hp, self.maxhp, self.attack, self.heal_count, self.heal, self.magic_count, self.magic_attack)
def is_alive(self):
return self.hp > 0
####################################################################################################################
# Function to unpack the enemy text file and create Enemy class objects to append to a list.
def enemy_unpack(file):
"""Creating all enemies from a text file"""
with open(file, "r") as f:
enemies = []
for line in f:
line = line.strip()
line = line.replace("/", "\n")
line = line.split("*")
name = line[0]
hp = int(line[1])
maxhp = int(line[2])
attack = int(line[3])
heal_count = int(line[4])
heal = int(line[5])
magic_count = int(line[6])
magic_attack = int(line[7])
enemy = Enemy(name, hp, maxhp, attack, heal_count, heal, magic_count, magic_attack)
enemies.append(enemy)
return enemies |
c5db71efe8b6a60f65ae9b00bb6b5258f468cf0c | ShamiliS/Java_Backup | /practice/funct2.py | 232 | 3.609375 | 4 | '''
Created on 4 Apr 2018
@author: SHSRINIV
'''
import function1
result = function1.calcuator_add(4, 5)
print("Addition:", result)
listofvalues = [3, 6, 7, 8, 2]
listresult = function1.listCheck(listofvalues)
print(listresult)
|
e25be21c2647af9c32be52f2891770f2b5177ece | ShamiliS/Java_Backup | /SimplePython/pException.py | 478 | 3.53125 | 4 | '''
Created on 9 Apr 2018
@author: SHSRINIV
'''
def KelvinToFahrenheit(temp):
result = 0
try:
assert(temp > 0), "Colder than absolute zero!"
except AssertionError:
print("AssertionError: Error in the input", temp)
except TypeError:
print(TypeError)
else:
result = ((temp - 273) * 1.8) + 32
print("")
return result
print(KelvinToFahrenheit(0))
print(KelvinToFahrenheit("test"))
print(KelvinToFahrenheit(273))
|
2f69991dd752fee0a0fe55ca276bc3b9db4ca8df | JacobRoyster/GroupMe | /GroupMeFunctions/RemoveFromGroup.py | 1,971 | 3.609375 | 4 | import requests
import json
import sys
"""
userToken should be a valid GroupMe user token. (string)
groupID should be a valid group that you have access to. (string)
userID should be a valid ID for the user you want to remove. If this userID is yours, you leave the group. (string)
purpose of this function is to remove someone (including yourself) from a group.
"""
def RemoveFromGroup(userToken, groupID, userID):
# Standard start for the request string for the GroupMe API
standardBeginning = "https://api.groupme.com/v3/groups"
# Assembling the request
response = requests.post( (standardBeginning + "/" + groupID + "/members/" + userID +"/remove?token=" +userToken ) )
# Printing response code. Response code key available at https://dev.groupme.com/docs/responses
# Additional info will be availabe if you print out the entire translated json package
print(response)
# It is possible to result in non bmp characters (such as emojiis)
# Non bmp characters will be mapped to � (oxfffd)
non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode +1), 0xfffd)
jsonInterpretedResponse = json.loads(response.text.translate(non_bmp_map))
# Printing out entire json resonse package
if (jsonInterpretedResponse['meta']['code'] < 400):
# We have a least sent a validly formatted packet and recieved a response
return()
else:
print(jsonInterpretedResponse)
raise ValueError("We have a packet with a meta code != 200")
def TestRemoveFromGroup():
# Load in my token, then use that token to view the groups
with open("C://Users//Public//Documents//groupmetoken.txt") as f:
userToken = f.read()
with open("C://Users//Public//Documents//groupmegroupid.txt") as f:
groupID = f.read()
with open("C://Users//Public//Documents//groupmetestdummyid.txt") as f:
testdummyid = f.read()
RemoveFromGroup(str(userToken),str(groupID),str(testdummyid))
|
70499b8516182a300a1a47dd14bb226fbaa7a696 | yzzyq/Machine-learning | /贝叶斯/病例预测/naiveBayes.py | 5,349 | 4.03125 | 4 | #贝叶斯算法
import csv
import random
import math
import copy
#整个流程:
##1.处理数据:从CSV文件载入数据,分为训练集和测试集
## 1.将文件中字符串类型加载进来转化为我们使用的数字
## 2.数据集随机分为包含67%的训练集和33%的测试集
##
##2.提取数据特征:提取训练数据集的属性特征,以便我们计算概率并作出预测
## 1.按照类别划分数据
## 2.写出均值函数
## 3.写出标准差函数
## 4.计算每个类中每个属性的均值和标准差(因为这里是连续型变量,也可以使用区间)
## 5.写个函数将上面过程写入其中
##
##3.预测
## 1.根据上述计算出的均值和方差,写出函数是计算高斯概率密度函数
## 2.计算值对每个类别的高斯概率分布
##
##3.单一预测:使用数据集的特征生成单个预测
## 1.比较那个类别的概率更大,就输出哪个
##
##4.评估精度:评估对于测试数据集的预测精度作为预测正确率
## 1.多重预测:基于给定测试数据集和一个已提取特征的训练数据集生成预测,就是生成了很多预测.
## 2.计算精度,看正确率
#加载数据
# 1. Number of times pregnant
# 2. Plasma glucose concentration a 2 hours in an oral glucose tolerance test
# 3. Diastolic blood pressure (mm Hg)
# 4. Triceps skin fold thickness (mm)
# 5. 2-Hour serum insulin (mu U/ml)
# 6. Body mass index (weight in kg/(height in m)^2)
# 7. Diabetes pedigree function
# 8. Age (years)
# 9. Class variable (0 or 1)
#加载数据
def loadData(fileName):
dataSet = []
with open(fileName) as file:
File = csv.reader(file,delimiter=',')
dataSet = list(File)
for i in range(len(dataSet)):
#将字符串转化为浮点数,数据量有点大
dataSet[i] = [float(x) for x in dataSet[i]]
return dataSet
#将数据集分为训练集和测试集
def splitDataSet(dataSet,splitRatio):
trainSetSize = int(len(dataSet)*splitRatio)
trainSet = []
#测试集
exeSet = dataSet
while len(trainSet) < trainSetSize:
index = random.randrange(len(exeSet))
data = copy.deepcopy(dataSet[index])
trainSet.append(data)
del exeSet[index]
return trainSet,exeSet
#按照类别划分数据,这里就是0和1
def splitDataSetByClass(dataSet):
dataClass = {}
for data in dataSet:
key = data[-1]
if key not in dataClass.keys():
dataClass[key] = []
del data[-1]
dataClass[key].append(data)
return dataClass
#因为数据中的数值都是连续型的
#计算均值
def averageData(dataSet):
return sum(dataSet)/len(dataSet)
#计算方差
def varianceData(dataSet):
aver = averageData(dataSet)
temp = 0.0
dataSetTemp = dataSet
for data in dataSet:
temp += math.pow(data - aver,2)+1
return math.sqrt(temp/(len(dataSet)+2))
#计算每个属性的均值和方差
def attributesNormal(dataSet):
dataClass = splitDataSetByClass(dataSet)
dataNormal = {}
#每个类别进行循环
for dataAttri in dataClass.keys():
data = dataClass[dataAttri]
dataNormal[dataAttri] = []
#每列元素组合在一起
dataAttribute = zip(*data)
#计算每列的均值和方差
for dataCol in dataAttribute:
attri = []
aver = averageData(dataCol)
variance = varianceData(dataCol)
attri.append(aver)
attri.append(variance)
dataNormal[dataAttri].append(attri)
print('dataNormal:',dataNormal)
return dataNormal
#计算每个属性高斯密度函数
def normalFunction(value,data):
aver = value[0]
variance = value[1]
temp = math.exp(-(float)(math.pow(data-aver,2))/(2*math.pow(variance,2)))
return (1/math.sqrt(2*(math.pi)*variance))*temp
#计算每个类别的每个属性密度函数值
def Normal(dataNormal,exeData):
bestLabel = None
bestScoer = 0.0
#比较俩个类别,谁大就是谁
for key in dataNormal.keys():
values = dataNormal[key]
normalClass = 1
for i in range(len(values)):
normalClass *= normalFunction(values[i],exeData[i])
if normalClass > bestScoer:
bestScoer = normalClass
bestLabel = key
return bestLabel
#模型的准确率
def accuracy(results,exeSet):
correctDecision = []
for data in exeSet:
print(data)
correctDecision.append(data[-1])
sumExeDataSet = len(exeSet)
correctNum = 0
#print(len(correctDecision))
#print(len(results))
for i in range(sumExeDataSet):
if correctDecision[i] == results[i]:
correctNum += 1
return correctNum/sumExeDataSet
#加载数据
dataSet = loadData('pima-indians-diabetes.csv')
#70%是训练集,30%是测试集
trainSet,exeSet = splitDataSet(dataSet,0.7)
#得出所有的属性的均值和方差
dataNormal = attributesNormal(trainSet)
#对每个数据计算结果
results = []
for exe in exeSet:
result = Normal(dataNormal,exe)
results.append(result)
#测试准确度
num = accuracy(results,exeSet)
print(num)
|
7da84a0ef5b3fad6a422adf7242707c31f07bbe7 | seales/EulerSolutions | /Solutions/Solution30.py | 1,152 | 3.859375 | 4 |
def get_nth_digit(number, n):
if n < 0:
return 0
else:
return get_0th_digit(number / 10**n)
def get_0th_digit(number):
return int(round(10 * ((number/10.0)-(number/10))))
def digit_count(number):
return len(str(number))
def nth_digit_sum_upper_bound(n):
i = 0
while digit_count(i)*9**n >= i:
i += 10
return i
def sum_digits_equals_nth_power(number, n):
if number < 2:
return False
summation = 0
for i in range(digit_count(number)):
summation += get_nth_digit(number, i) ** n
if summation > number:
return False
return summation == number
assert sum_digits_equals_nth_power(1634, 4)
assert sum_digits_equals_nth_power(8208, 4)
assert sum_digits_equals_nth_power(9474, 4)
assert not sum_digits_equals_nth_power(9574, 4)
def sum_of_numbers_with_nth_digit_sum_equality(n):
i = 0
bound = nth_digit_sum_upper_bound(n)
summation = 0
while i <= bound:
if sum_digits_equals_nth_power(i, n):
summation += i
i += 1
return summation
print sum_of_numbers_with_nth_digit_sum_equality(5)
|
8b7e67918be7f322b2243df81fec613e61815cbb | seales/EulerSolutions | /Solutions/Solution47.py | 2,021 | 3.71875 | 4 |
import math
def find_factors(n, factors):
if n == 1:
return factors
divisor = math.floor(math.sqrt(n))
# loop until integer divisor found
while (n/divisor) != int(n/(divisor*1.0)):
divisor -= 1
if int(divisor) == 1:
break
a = int(n/(divisor*1.0))
b = int(divisor)
a_is_prime = is_prime(int(n/(divisor*1.0)))
b_is_prime = is_prime(b)
if a_is_prime and a not in factors:
factors.append(a)
if b_is_prime and b not in factors:
factors.append(b)
if not a_is_prime and not b_is_prime:
return find_factors(a, find_factors(b, factors))
elif not a_is_prime and b_is_prime:
return find_factors(a, factors)
elif a_is_prime and not b_is_prime:
return find_factors(b, factors)
else:
return factors
def is_prime(n):
divisor = math.floor(math.sqrt(n))
while (n/(divisor)) != int(n/(divisor*1.0)):
divisor -= 1
if int(divisor) == 1:
return True
return divisor == 1
def first_of_consecutive_prime_factors(n):
index = 2
current_prime_factors = []
consecutive_prime_factor_count = 0
while True:
previous_number = index
current_prime_factors = find_factors(index, [])
if len(current_prime_factors) == n:
consecutive_prime_factor_count += 1
else:
consecutive_prime_factor_count = 0
if consecutive_prime_factor_count == n:
return index - n + 1
index += 1
### TEST IS PRIME METHOD ###
assert not is_prime(10)
assert is_prime(2)
assert is_prime(1)
assert is_prime(13)
assert not is_prime(15)
### TEST FIND FACTORS METHOD ###
factors_found = find_factors(4, [])
assert len(factors_found) == 1
assert 2 in factors_found
factors_found = find_factors(646,[])
assert len(factors_found) == 3
assert 19 in factors_found
assert 17 in factors_found
assert 2 in factors_found
print first_of_consecutive_prime_factors(4) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.