blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
ac896f90c9213c8bee169ffd3fbc74a6b4dc15e3 | ICS3U-Programming-JonathanK/Unit4-01-Python | /sum_of_numbers.py | 1,257 | 4.40625 | 4 | #!/usr/bin/env python3
# Created by: Mr. Coxall
# Created on: Sept 2019
# Modified by: Jonathan
# Modified on: May 20, 2021
# This program asks the user to enter a positive number
# and then uses a loop to calculate and display the sum
# of all numbers from 0 until that number.
def main():
# initialize the loop counter and sum
loop_counter = 0
sum = 0
# get the user number as a string
user_number_string = input("Enter a positive number: ")
print("")
try:
user_number_int = int(user_number_string)
print("")
except ValueError:
print("Please enter a valid number")
else:
# calculate the sum of all numbers from 0 to user number
while (loop_counter <= user_number_int):
sum = sum + loop_counter
print("Tracking {0} times through loop.".format(loop_counter))
loop_counter = loop_counter + 1
print("The sum of the numbers from"
"0 to {} is: {}.".format(user_number_int, sum))
print("")
if (user_number_int < 0):
print("{0} is not a valid number".format(user_number_int))
finally:
print("")
print("Thank you for your input")
if __name__ == "__main__":
main()
|
40c3562f1343fd9eab60a3a2a60c8378fd77c46a | garp55/RealPython | /sql/homew6cars.py | 1,758 | 3.875 | 4 | # INSERT Command with Error Handler
# import the sqlite3 library
import sqlite3
# create the connection object
with sqlite3.connect("cars.db") as connection:
c = connection.cursor()
c.execute("DROP TABLE IF EXISTS orders")
c.execute("""CREATE TABLE orders(Make TEXT, Model TEXT, Order_date DATETIME)""")
corders=[
('Ford','Fiesta','2014-01-15'),
('Ford','Fiesta','2014-01-25'),
('Ford','Fiesta','2014-01-25'),
('Ford','Focus','2014-02-11'),
('Ford','Focus','2014-02-11'),
('Ford','Focus','2014-02-12'),
('Ford','Capri','2014-04-15'),
('Ford','Capri','2014-05-16'),
('Ford','Capri','2014-06-17'),
('Honda','Civic','2014-07-15'),
('Honda','Civic','2014-07-16'),
('Honda','Civic','2014-07-17'),
('Honda','FRV','2014-12-15'),
('Honda','FRV','2014-12-23'),
('Honda','FRV','2014-12-25')
]
c.executemany("INSERT INTO orders VALUES(?, ?, ? )", corders)
# retrieve data
c.execute("SELECT * FROM inventory")
# fetchall() retrieves all records from the query
rows = c.fetchall()
# output the rows to the screen, row by row
for r in rows:
# output the car make, model and quantity to screen
print r[0], r[1], "\n", r[2]
# retrieve order_date for the current car make and model
c.execute("SELECT order_date FROM orders WHERE make=? and model=?",
(r[0], r[1]))
# fetchall() retrieves all records from the query
order_dates = c.fetchall()
# output each order_date to the screen
for order_date in order_dates:
print order_date[0]
|
ca301924c252766ed2dedc1d84c21f6bc034edd8 | baeseongsu/neural_programmer_iclr2016_implementation | /src/data_generators/question_generator.py | 1,845 | 3.59375 | 4 | """
This question generator currently generates only the following questions for the specified scenarios
- Single column experiment:
- sum
- count
- greater [number] sum
Each function will return a tuple in the format: (question_string, answer)
"""
import random
def generate_single_column_table_sum_all(table: [[int]]):
return 'sum', generate_single_column_table_sum_all_answer(table)
def generate_single_column_table_count_all(table: [[int]]):
return 'count', generate_single_column_table_count_all_answer(table)
def generate_single_column_table_sum_greater(table: [[int]], min_limit: int, max_limit: int):
pivot = random.randint(min_limit, max_limit)
return 'greater %d sum' % pivot, \
generate_single_column_table_sum_greater_answer(table, pivot)
def generate_single_column_table_count_lesser(table: [[int]], min_limit: int, max_limit: int):
pivot = random.randint(min_limit, max_limit)
return 'greater %d count' % pivot, \
generate_single_column_table_sum_greater_answer(table, pivot)
def generate_single_column_table_sum_all_answer(table: [[int]]):
return sum(table[0]), True
def generate_single_column_table_count_all_answer(table: [[int]]):
return len(table[0]), True
def generate_single_column_table_sum_greater_answer(table: [[int]], pivot: int):
return sum(list(map(lambda a: a if a > pivot else 0, table[0]))), True
def generate_single_column_table_count_lesser_answer(table: [[int]], pivot: int):
return len(list(map(lambda a: a if a < pivot else 0, table[0])))
QUESTION_GENERATION_FUNCTIONS = [
generate_single_column_table_sum_all,
# generate_single_column_table_count_all,
generate_single_column_table_sum_greater,
generate_single_column_table_count_lesser,
]
|
e811211d279510195df3bbdf28645579c8b9f6de | megler/Day8-Caesar-Cipher | /main.py | 1,497 | 4.1875 | 4 | # caesarCipher.py
#
# Python Bootcamp Day 8 - Caesar Cipher
# Usage:
# Encrypt and decrypt code with caesar cipher. Day 8 Python Bootcamp
#
# Marceia Egler Sept 30, 2021
from art import logo
from replit import clear
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
game = True
def caesar(cipher:str, shift_amt:int, direction:str) -> str:
code = ''
if direction == 'decode':
shift_amt *= -1
for i,value in enumerate(cipher):
if value in alphabet:
#find the index of the input in the alphabet
answer = alphabet.index(value)
answer += shift_amt
#if shift_amt pushes past end of alphabet, restart
#eg z(26) + shift(5) == 30 = (26 * 1) + 4
alpha_loop = alphabet[answer%len(alphabet)]
code += alpha_loop
else:
code += value
print(f"The {direction}d text is {code}")
print(logo)
#Allow game to continue until user says no
while game:
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
caesar(cipher=text, shift_amt=shift, direction=direction)
play = input("Do you want to play again?\n").lower()
if play == 'no':
print(f"Thanks for playing")
game = False
|
a49e475673aca80e243ec4470cec9b98a66e4372 | Telixia/leetcode-3 | /Medium/0095-Unique Binary Search Trees II/Recursion.py | 666 | 3.796875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
def helper(m: int, n: int) -> List[TreeNode]:
if m > n:
return [None]
ret = []
for val in range(m, n + 1):
for left in helper(m, val - 1):
for right in helper(val + 1, n):
ret.append(TreeNode(val, left, right))
return ret
return helper(1, n) if n > 0 else []
|
aa3d8000f0f08cde8d5f91a3815077103bf32213 | Cabarne/NumberProvider | /app.py | 957 | 3.59375 | 4 | from NumberProvider import NumberProvider
def positiveAction(number):
print("Got an positive number >>>", number)
def negativeAction(number):
print("Got an negative number >>>", number)
provider = NumberProvider()
provider.whenPositive(positiveAction)
provider.whenNegative(negativeAction)
provider.start()
########### Answers to Questions ##############
# Два раза повторяется "NumberProvider", потому что мы вызываем из модуля NumberProvider конкретно class NumberProvider, больше ничего. Одинаковое название файла с классом.
# Ошибка "AttributeError: 'NumberProvider' object has no attribute 'positiveCB'"? говорит что мы должны обратиться к атрибуту positiveCB через функцию whenPositive, чего сделано не было. Если я не ошибаюсь)
|
528af8c01eacc11530f15c90a29315866365c02a | jingkunchen/image_tools | /method/cluster.py | 4,974 | 3.5625 | 4 | import numpy as np
import random
import math
random.seed(1)
np.random.seed(1)
"""
函数功能:选择初始中心点
points: 数据集
pNum: 数据集样本个数
cNum: 选取聚类中心个数
"""
def initCenters(points, pNum, cNum):
#初始中心点列表
centers = []
#在样本中随机选取一个点作为第一个中心点
firstCenterIndex = random.randint(0, pNum - 1)
centers.append(points[firstCenterIndex])
#初始距离列表
distance = []
#对于每个中心点类别
for cIndex in range(1, cNum):
print("cIndex:",cIndex)
#sum为数据集中每个样本点和其最近的中心点的距离和
sum = 0.0
#遍历整个数据集
for pIndex in range(0, pNum):
print("pNum1:",pIndex)
#计算每个样本和最近的中心点的距离
dist = nearest(points[pIndex], centers, cIndex)
#将距离存到距离列表中
distance.append(dist)
#距离相加
sum += dist
#随机在(0,sum)中间取一个数值
ran = random.uniform(0, sum)
#遍历数据集
for pIndex in range(0, pNum):
print("pNum2:",pIndex)
#ran-=D(x)
ran -= distance[pIndex]
if ran > 0: continue
centers.append(points[pIndex])
break
return centers
"""
函数功能:计算点和中心之间的最小距离
point: 数据点
centers: 已经选择的中心
cIndex: 已经选择的中心个数
"""
def nearest(point, centers, cIndex):
#初始一个足够大的最小距离
minDist = 65536.0
dist = 0.0
for index in range(0, cIndex):
dist = distance(point, centers[index])
if minDist > dist:
minDist = dist
return minDist
"""
函数功能:计算点和中心之间的距离
point: 数据点
center:中心
"""
def distance(point, center):
dim = len(point)
if dim != len(center):
return 0.0
a = 0.0
b = 0.0
c = 0.0
for index in range(0, dim):
a += point[index] * center[index]
b += math.pow(point[index], 2)
c += math.pow(center[index], 2)
b = math.sqrt(b)
c = math.sqrt(c)
try:
return a / (b * c)
except Exception as e:
print(e)
return 0.0
def find_closest_centroids(X, centroids):
m = X.shape[0]
k = centroids.shape[0]
idx = np.zeros(m)
sse = 0
for i in range(m):
min_dist = 1000000
for j in range(k):
dist = np.sum((X[i, :] - centroids[j, :])**2)
if dist < min_dist:
min_dist = dist
idx[i] = j
sse += min_dist
return idx, sse
def compute_centroids(X, idx, k):
m, n = X.shape
centroids = np.zeros((k, n))
for i in range(k):
indices = np.where(idx == i)
centroids[i, :] = (np.sum(X[indices, :], axis=1) /
len(indices[0])).ravel()
return centroids
def run_k_means(X, initial_centroids, max_iters):
global sse
m, n = X.shape
k = initial_centroids.shape[0]
idx = np.zeros(m)
centroids = initial_centroids
for i in range(max_iters):
print("run_k_means:",i)
idx, sse = find_closest_centroids(X, centroids)
centroids = compute_centroids(X, idx, k)
return idx, centroids, sse
X_train = np.load("/Users/chenjingkun/Documents/data/skin/skin_health_train.npy")
X_train = X_train / 255.
print("X_train:",X_train.shape)
cluster_data = X_train.reshape(-1, 32 * 32 *3)
cluster_show = X_train
m = cluster_data.shape[0]
print(cluster_data.shape)
cluster_points = []
for i in range(m):
cluster_points.append(cluster_data[i, :])
cNum = 3
print("initial_centroids")
initial_centroids = np.array(initCenters(cluster_points, m, cNum))
max_iters = 3
print("run_k_means")
idx, centroids, sse = run_k_means(cluster_data, initial_centroids,
max_iters)
np.save("skin_centroids_3cluster.npy", centroids)
ones = np.ones((1, 32, 32, 1))
zeros = np.zeros((1, 32, 32, 1))
label_0 = np.concatenate((np.concatenate((ones, zeros), axis=3), zeros), axis=3)
label_1 = np.concatenate((np.concatenate((zeros, ones), axis=3), zeros), axis=3)
label_2 = np.concatenate((np.concatenate((zeros, zeros), axis=3), ones), axis=3)
if (int(idx[0]) == 0):
labels = label_0
if (int(idx[0]) == 1):
labels = label_1
if (int(idx[0]) == 2):
labels = label_2
for i in range(1, X_train.shape[0]):
if (int(idx[i]) == 0):
labels = np.concatenate((labels, label_0), axis=0)
if (int(idx[i]) == 1):
labels = np.concatenate((labels, label_1), axis=0)
if (int(idx[i]) == 2):
labels = np.concatenate((labels, label_2), axis=0)
print(labels.shape)
labeled_data = np.concatenate((X_train, labels), axis=3)
np.save("skin_labeled_data_3cluster.npy", labeled_data) |
9f86f06c28faabfe75a466030e3295e0eb6fde3c | hikmatullah-mohammadi/python_matplot-tutorial | /matplot_subplote.py | 1,099 | 3.703125 | 4 | import numpy as np
from matplotlib import pyplot as plt
# our x values
ages = np.arange(25, 36)
# All developers' salary
all_dev_salary = np.array([38496, 42000, 46752, 49320, 53200, 56000,\
62316, 63928, 67317, 68748, 73752])
##Python developers' salary
py_dev_salary = np.array([45372, 48876, 53850, 57287, 63016, 65998,\
70003, 70000,71496, 75370, 83640])
average_overall = 60306.3
# create subplots
'''we can have multiple figures as well by calling subplots method multiple times'''
fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, sharex=True, sharey=True)
# plot the data
ax1.plot(ages, all_dev_salary, label='All dev', linestyle='-',\
color='#33f9f3')
ax2.plot(ages, py_dev_salary, label='Py dev', linestyle='-.',\
marker='*')
# some specifications
ax1.set_title('Median salary of Developers')
ax2.set_xlabel('Ages')
ax1.set_ylabel('Salaries')
ax2.set_ylabel('Salaries')
ax1.legend(loc='upper left')
ax2.legend(loc='upper left')
ax1.grid(True)
# display the plots
plt.show()
|
81822a456ea62002f89ec79e7ec8de159a6cd6fe | xuehui3/00_tensorflow | /面试题/丑数计算.py | 1,865 | 3.609375 | 4 |
# def isUgly(self, num):
# """
# :type num: int
# :rtype: bool
# """
# if num < 1:
# return False
# while num % 2 == 0 or num % 3 == 0 or num % 5 == 0:
# if num % 2 == 0:
# num //= 2
# elif num % 3 == 0:
# num //= 3
# elif num % 5 == 0:
# num //= 5
# if num != 1 and num != 2 and num != 3 and num != 5:
# return False
# else:
# return True
'''
题目:我们把只含有因子2、3、5的数称为丑数。
例如6、8都是丑数,而14不是丑数,因为它含有因子7.
通常也把1当做丑数。编程找出1500以内的全部丑数。
注意:使用的算法效率应尽量高
后面的丑数肯定是已存在的丑数乘以2、3或者5,
找到比现有丑数大的且是最小的丑数作为下一个丑数(如何找是关键)。
用2分别从现有丑数中从前往后乘以丑数,找到第一个大于当前所有丑数的值以及位置,3、5同样如此,
再把他们相乘之后的结果做对比,取最小的。下次将从上一次的位置开始往下找,这样将不会出现冗余。
'''
# 前几位丑数 1,2,3,4,5,6,8,9,10
# import math
# a = math.inf
# # print(a)
# # print(type(a))
import time
def get_ugly_number():
list_null = []
start = time.time()
for i in range(10):
for j in range(10):
for k in range(10):
x = pow(2, i)*pow(3, j)*pow(5, k) # 0.0012402534484863281
# x = (2**i)*(3**j)*(5**k) #0.0024423599243164062
list_null.append(x)
# print(list_null)
a = sorted(list_null)
print(a)
stop = time.time()
interval = stop - start
print(interval)
if __name__ == '__main__':
get_ugly_number()
|
3ef69f8658812cf0ad75452b18906576778837ab | xuehui3/00_tensorflow | /面试题/矩阵旋转.py | 1,165 | 3.515625 | 4 | '''
写一个小程序,将形状位MxN的2维矩阵顺时针旋转K位
例如:将下面左边的 M=3 N=4 的矩阵,旋转 K=1位,得到右边3x4的矩阵
[[1, 2, 3, 4], [[10, 1, 2, 3],
[10, 11, 12, 5], >>>> [9, 12, 11, 4],
[9, 8, 7, 6]] [8, 7, 6, 5]]
'''
import numpy as np
# MxN 3x4
matrix = [[1, 2, 3, 4],
[10, 11, 12, 5],
[9, 8, 7, 6]]
matrix_arr = np.array(matrix)
M = matrix_arr.shape[0]
N = matrix_arr.shape[1]
# 第一行元素添加到列表
# list_1 = []
a = lambda M, N: M if M < N else N
b = a(M, N)
for k in range(b//2 + 1):
# 第k行元素添加
list_1 = matrix[k][:-1]
print(list_1)
list_1 = matrix[k][k:-1-k]
print('行数', list_1)
# 最右侧元素添加到列表(不含首尾两行)
for num_last in range(1+k, M-1-k):
list_1.append(matrix[num_last][N-1-k])
# 最后一行元素添加到列表
for i in matrix[M-1-k]:
list_1.append(i)
# 最左侧元素添加(不含首尾元素)
for num_first in range(1+k, M-1-k):
list_1.append(matrix[num_first][0])
print(list_1)
print(list_1)
|
ecd4c4395e7d0663c55c6db6fcf171712cd13d8a | litst/leetcode | /JumpGameII.py | 536 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 03 14:13:32 2015
@author: yzy
"""
def subJump(nums,step,ans):
maxStep = nums[0]
for i in range(1,maxStep+1):
if len(nums[i:]) == 1:
ans.append(step+1)
else:
if i < len(nums) and nums[i] != 0 :
subJump(nums[i:],step+1,ans)
nums = [6,2,6,1,7,9,3,5,3,7,2,8,9,4,7,7,2,2,8,4,6,6,1,3]
ans = []
subJump(nums,0,ans)
print min(ans)
|
de40b66919ca9d821843eb1c3e9a9c6843afe5ac | hhf-hd/Deep-learning-schedule | /Python/eg/eg37.py | 411 | 3.515625 | 4 | #!/usr/bin/python3
def Func():
N =10
L = []
print("please input 10 numbers")
for i in range(N):
x = int(input())
L.append(x)
for i in range(N):
k = i
minum = L[i]
for j in range(i+1,N):
if L[j] < minum:
k = j
minum = L[j]
temp = L[i]
L[i] = L[k]
L[j] = temp
print(L)
Func()
|
03839c78723e70f763d8009fea4217f18c3eff42 | agustinaguero97/curso_python_udemy_omar | /ex4.py | 1,624 | 4.15625 | 4 | """"Your teacher asked from you to write a program that allows her to enter student 4 exam result and then the program
calculates the average and displays whether student passed the semester or no.in order to pass the semester, the average
score must be 50 or more"""
def amount_of_results():
while True:
try:
count = int(input("type the amount of result to calculate the average: "))
if count <= 0:
raise Exception
return count
except:
print("input error, must be a number greater that 0 and a integer")
def result_input(count):
result_list = []
while True:
try:
note = int(input(f"type the {count}° note (o to 100): "))
if 0<= note and note <= 100:
result_list.append(note)
count -= 1
if count == 0:
break
else:
raise Exception
except:
print("invalid number, must go from 0 to 100")
return result_list
def prom(result):
sum = 0
for notes in result:
sum = sum + notes
promedio = int(sum/(len(result)))
print(f"the average of the results is: {promedio}")
return promedio
def pass_failed(average,score):
if average < score:
print("the student does not pass ")
if average >= score:
print("the student does pass")
if __name__ == '__main__':
count = amount_of_results()
result = result_input(count)
average = prom(result)
pass_failed(average,score=50) #here can modify the minimun average score of approval
|
7be5665d75207fd063846d31adfc0012aaeee891 | vlad-bezden/data_structures_and_algorithms | /data_structures_and_algorithms/quick_sort.py | 512 | 4.21875 | 4 | """Example of quick sort using recursion"""
import random
from typing import List
def quick_sort(data: List[int]) -> List[int]:
if len(data) < 2:
return data
pivot, left, right = data.pop(), [], []
for item in data:
if item < pivot:
left.append(item)
else:
right.append(item)
return quick_sort(left) + [pivot] + quick_sort(right)
if __name__ == "__main__":
data = random.sample(range(1000), 15)
print(data)
print(quick_sort(data))
|
ee7658e97cca85eba4ad74e159317abf372dd9e7 | vlad-bezden/data_structures_and_algorithms | /data_structures_and_algorithms/memory_allocation.py | 662 | 3.640625 | 4 | """
List allocation with teh same value using different techniques
Output:
first: 0.717055
second: 1.021743
third: 0.046112
forth: 0.005384
"""
from timeit import timeit
from itertools import repeat
import numpy
SIZE = 10000
INIT_VALUE = 0
def first():
"""Using itertools.repeat"""
return [x for x in repeat(INIT_VALUE, SIZE)]
def second():
"""Using range"""
return [INIT_VALUE for x in range(SIZE)]
def third():
return [INIT_VALUE] * SIZE
def forth():
"""Using numpy"""
return numpy.zeros(SIZE, numpy.int)
for x in [first, second, third, forth]:
t = timeit(stmt=x, number=1000)
print(f"{x.__name__}: {t:.6f}")
|
5783a9475fb0cfc254b115e15e390a0a07ff05e6 | vlad-bezden/data_structures_and_algorithms | /data_structures_and_algorithms/heap.py | 3,453 | 4.25 | 4 | """
Heap (min-heap) implementation example
"""
from random import sample
HEAP_SIZE = 20
class EmptyHeapError(Exception):
def __init__(self):
super().__init__("No elements in the heap")
class Heap:
def __init__(self):
self.__heap = [0]
@property
def size(self) -> int:
return len(self.__heap) - 1
def __len__(self) -> int:
return self.size
@property
def is_empty(self) -> bool:
return self.size <= 0
def insert(self, item: int) -> None:
self.__heap.append(item)
self.arrange(self.size)
def __iter__(self):
self.__current = 0
return self
def __next__(self):
self.__current += 1
if not self.is_empty:
return self.__heap[self.__current]
else:
raise StopIteration
def arrange(self, index: int) -> None:
"""Rebalances tree"""
parent_index = index // 2
if parent_index <= 0:
return
if self.__heap[index] < self.__heap[parent_index]:
self.__heap[index], self.__heap[parent_index] = (
self.__heap[parent_index],
self.__heap[index],
)
self.arrange(parent_index)
def _child_min_index(self, index: int) -> int:
"""Finds child min index that has min value
For instance two children 10, 6 with indexes 3, 4
will return index 4
"""
l_index = index * 2
r_index = l_index + 1
if self.size < r_index:
return l_index
return l_index if self.__heap[l_index] < self.__heap[r_index] else r_index
def sink(self, index: int) -> None:
"""Rebalances the tree when item is popped"""
child_index = self._child_min_index(index)
if self.size < child_index:
return
if self.__heap[child_index] < self.__heap[index]:
self.__heap[index], self.__heap[child_index] = (
self.__heap[child_index],
self.__heap[index],
)
self.sink(child_index)
def pop(self) -> int:
"""Pop root (lowest element) of the tree"""
if self.is_empty:
raise EmptyHeapError()
item = self.__heap[1]
# get latest element in the heap and put it to the root of the tree
last_item = self.__heap.pop()
if not self.is_empty:
self.__heap[1] = last_item
# rebalance a tree
self.sink(1)
return item
def clear(self):
self.__heap = [0]
def __repr__(self):
return str(self.__heap[1:])
def main():
heap = Heap()
assert heap.size == len(heap) == 0
assert heap.is_empty is True
items = [i for i in sample(range(100), HEAP_SIZE)]
for item in items:
heap.insert(item)
assert heap.size == len(heap) == HEAP_SIZE
print(f"items: {items}")
print(f"heap: {heap}")
heap.clear()
assert heap.is_empty is True
assert heap.size == 0
items = [4, 8, 7, 2, 9, 10, 5, 1, 3, 6]
for item in items:
heap.insert(item)
print(f"item: {item}, heap: {heap}")
while not heap.is_empty:
item = heap.pop()
print(f"item: {item}, heap: {heap}")
try:
heap.pop()
assert False, "Failed. There are no elements in the heap"
except EmptyHeapError as ex:
print(f"Exeption: {ex}")
if __name__ == "__main__":
main()
|
1c45df9c8c8efcbf2e8d61f00494b0940415055b | vlad-bezden/data_structures_and_algorithms | /data_structures_and_algorithms/max_sum_subarray.py | 696 | 3.90625 | 4 | """Maximum sum subarray problem.
In the array find subarray with the max value.
"""
from typing import List
def max_sum_subbarray(data: List[int]) -> int:
current_max = max_value = data[0]
for i in range(1, len(data)):
current_max = max(current_max + data[i], data[i])
max_value = max(max_value, current_max)
return max_value
if __name__ == "__main__":
tests = [
([3, 4, -9, 1, 2], 7),
([3, 4, -9, 5, 6], 11),
([1, 2, 3], 6),
([-1, -2, -3], -1),
]
for data, expected in tests:
actual = max_sum_subbarray(data)
assert expected == actual, f"{data = }, {expected = }, {actual = }"
print("PASSED!!!")
|
bc6ae6b22b1655f74273b8e90234a64224cafab3 | vlad-bezden/data_structures_and_algorithms | /data_structures_and_algorithms/grouper.py | 317 | 4.09375 | 4 | """
Groups list of items in tuples of size n
"""
from typing import Iterable, Any, Tuple
def grouper(data: Iterable[Any], n: int) -> Iterable[Tuple[Any]]:
iters = [iter(data)] * n
return zip(*iters)
if __name__ == "__main__":
print(list(grouper(range(9), 3)))
# [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
|
762d76a11f5bc7f780585d8a1f10bb32644223ad | vlad-bezden/data_structures_and_algorithms | /data_structures_and_algorithms/producer_consumer.py | 915 | 3.984375 | 4 | """
Producer - Consumer (pub-sub) example
"""
import threading
from queue import Queue
from time import sleep
from random import random
def producer(q, n):
"""Generates fibonacci number and put it in queue."""
a, b = 0, 1
while a <= n:
q.put(a)
print(f"Producer: {a}")
sleep(random())
a, b = b, a + b
q.put(None)
def consumer(q):
"""Consumer, reads data from the queue."""
while True:
num = q.get()
print(f"\nConsumer: {num}")
sleep(random())
q.task_done()
if num is None:
break
def main():
q = Queue()
threads = []
threads.append(threading.Thread(target=producer, args=(q, 1000)))
threads.append(threading.Thread(target=consumer, args=(q,)))
for t in threads:
t.start()
for t in threads:
t.join()
if __name__ == "__main__":
main()
print("DONE!!!")
|
ea235c2fd7caa1b5e0480457833099746d0666b6 | vlad-bezden/data_structures_and_algorithms | /data_structures_and_algorithms/is_bst.py | 1,200 | 3.875 | 4 | """Checks if Binary Search Tree (BST) is balanced"""
from __future__ import annotations
import sys
from dataclasses import dataclass
from typing import Optional
MAX_VALUE = sys.maxsize
MIN_VALUE = -sys.maxsize - 1
@dataclass
class Node:
value: int
left: Optional[Node]
right: Optional[Node]
@property
def is_leaf(self) -> bool:
return not self.left and not self.right
def is_bst(node: Optional[Node], min_value: int, max_value: int) -> bool:
if node is None:
return True
elif node.value < min_value or max_value < node.value:
return False
elif node.is_leaf:
return True
return is_bst(node.left, min_value, node.value) and is_bst(
node.right, node.value, max_value
)
if __name__ == "__main__":
node5 = Node(5, None, None)
node25 = Node(25, None, None)
node40 = Node(40, None, None)
node10 = Node(10, None, None)
# balanced tree
node30 = Node(30, node25, node40)
root = Node(20, node10, node30)
print(is_bst(root, MIN_VALUE, MAX_VALUE))
# unbalanced tree
node30 = Node(30, node5, node40)
root = Node(20, node10, node30)
print(is_bst(root, MIN_VALUE, MAX_VALUE))
|
57918b350250791dd1b4fc796c5c6539a3f3ece3 | sandeepkumar17212/texigroupapp | /caller.py | 100 | 3.546875 | 4 | def printname(name):
print("my name is "+name)
def addition(a,b,c):
d=a+b+c
print(d)
|
ac2df7a40f380c483abdff60c6d20a90fe6d74e3 | metalauren/InsightCodingChallenge | /src/insightsource.py | 1,761 | 3.796875 | 4 | tweetfile = open("tweet_input/tweets.txt", "r") # open file
alltweets = tweetfile.read() # read the file
tweets = alltweets.splitlines() # a list where each element is an tweet
runningmedians = []
wordsintweet = []
tweetdict = {}
def median(x):
x.sort()
mid = len(x) // 2
if len(x) % 2:
return x[mid]
else:
return (x[mid - 1] + x[mid]) / 2.0
for i in range(0, (len(tweets))): # loops over every tweet
tweets[i] = tweets[i].split() # splits each tweet into a list of words
for j in range(0, (len(tweets[i]))): # loops over each word in a single tweet
if tweets[i][j] not in tweetdict: # checks if it is already in the dictionary of words in tweets
tweetdict[tweets[i][
j]] = 1 # if it is not in the dictionary, puts word in dictionary with a value (i.e. count) of 1
else:
tweetdict[tweets[i][
j]] += 1 # if it is already in the dict, adds to the value associated with the word (i.e. adds 1 to the count)
wordsintweet.append(len(set(tweets[i]))) # maintains a list of unique word in each tweet
runningmedians.append(median(wordsintweet)) # maintains the running median unique words for each new tweet
keylist = list(tweetdict.keys()) # list of all the keys in the tweet dictionary.
keylist.sort() # sorts this list. NB: Doing this at the end so it only needs to be sorted once rather than iteratively during the for loop.
ft1 = open("tweet_output/ft1.txt", "w") # prints the word counts file
for key in keylist:
ft1.write('%-25s %5s\n' % (key, tweetdict[key]))
ft1.close()
ft2 = open("tweet_output/ft2.txt", "w") # prints the running medians file
for med in runningmedians:
ft2.write('%s\n' % (med))
ft2.close()
|
4e5596e77d9208a82a94e674f66464987144e8d0 | lakshay-saini-au8/PY_playground | /hackerrank/python/map_lambda.py | 324 | 3.953125 | 4 | # cube = lambda x: x*x*x
def cube(x):
return x*x*x
def fibonacci(n):
# return a list of fibonacci numbers
res = []
if n > 2:
res = [0, 1]
for i in range(2, n):
res.append(res[i-2]+res[i-1])
elif n == 1:
res = [0]
elif n == 2:
res = [0, 1]
return res
|
818bf1acf02cd1170b3c19290fcb10151599053e | lakshay-saini-au8/PY_playground | /hackerrank/ds/Array/left_rotation.py | 264 | 3.9375 | 4 | # https://www.hackerrank.com/challenges/array-left-rotation/problem
def rotateLeft(d, arr):
# Write your code here
if len(arr) == d:
return arr
else:
arr1 = arr[0:d]
arr2 = arr[d:]
arr2.extend(arr1)
return arr2
|
7d3a0be5b655e5b8dd2fd8dbd1ea768ff921b2a0 | lakshay-saini-au8/PY_playground | /hackerrank/ds/LinkedLists/find_merge.py | 461 | 3.890625 | 4 | # https://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-lists/problem?isFullScreen=true
# sol1
def findMergeNode(head1, head2):
temp1 = head1
while temp1 is not None:
temp2 = head2
while temp2 is not None:
if temp1 == temp2:
print("hello")
return temp1.data
else:
print("bye")
temp2 = temp2.next
temp1 = temp1.next
|
021b2c9563dd6903672c9ca23ecce35371e49ddc | lakshay-saini-au8/PY_playground | /hackerrank/ds/LinkedLists/del_at_pos.py | 507 | 3.828125 | 4 | # https://www.hackerrank.com/challenges/delete-a-node-from-a-linked-list/problem
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def deleteNode(head, position):
currentNode = head
if position == 0:
head = head.next
currentNode.next = None
return head
for _ in range(position - 1):
currentNode = currentNode.next
if currentNode is not None:
currentNode.next = currentNode.next.next
return head
|
7b8a4d89da37c947909b393a8a957cf759a4d7cc | lakshay-saini-au8/PY_playground | /random/sorting.py | 1,254 | 3.765625 | 4 | # def merge(left, right, a):
# i = 0
# j = 0
# k = 0
# while i < len(left) and j < len(right):
# if left[i] > right[j]:
# a[k] = right[j]
# k += 1
# j += 1
# else:
# a[k] = left[i]
# k += 1
# i += 1
# while i < len(left):
# a[k] = left[i]
# i += 1
# k += 1
# while j < len(right):
# a[k] = right[j]
# k += 1
# j += 1
# def merge_sort(a):
# if len(a) == 0 or len(a) == 1:
# return
# mid = len(a) // 2
# a1 = a[0:mid]
# a2 = a[mid:]
# merge_sort(a1)
# merge_sort(a2)
# merge(a1, a2, a)
# a = [10, 5, 3, 1, 7, 9, 4]
# merge_sort(a)
# print(a)
'''
quick sort
'''
def partition(arr, s, e):
pivot = e
i = s
j = s
while j < e:
if arr[j] < arr[pivot]:
arr[i], arr[j] = arr[j], arr[i]
i += 1
j += 1
arr[i], arr[pivot] = arr[pivot], arr[i]
return i
def quick_sort(arr, s, e):
if s >= e:
return
pivot = partition(arr, s, e)
quick_sort(arr, s, pivot-1)
quick_sort(arr, pivot+1, e)
arr = [10, 9, 8, 7, 1, 3, 5, 4, 2]
print(quick_sort(arr, 0, len(arr)-1))
print(arr)
|
ddaf839fe211a052a944aefe908e03e3c74665f0 | lakshay-saini-au8/PY_playground | /DSAlgo/merge_sort.py | 641 | 3.84375 | 4 | def merge(L, R, arr):
i = 0
j = 0
k = 0
l = len(L)
r = len(R)
while i < l and j < r:
if L[i] < R[j]:
arr[k] = L[i]
i = i+1
else:
arr[k] = R[j]
j = j+1
k = k+1
while(i < l):
arr[k] = L[i]
i += 1
k += 1
while(j < r):
arr[k] = R[j]
j += 1
k += 1
def merge_sort(arr):
if(len(arr) > 1):
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
merge(L, R, arr)
arr = [5, 45, 10, 4, 20, -1, -2]
merge_sort(arr)
print(arr)
|
4059405985761b3ae72fff1d6d06169cc35b1823 | lakshay-saini-au8/PY_playground | /random/day03.py | 678 | 4.46875 | 4 | #question
'''
1.Create a variable “string” which contains any string value of length > 15
2. Print the length of the string variable.
3. Print the type of variable “string”
4. Convert the variable “string” to lowercase and print it.
5. Convert the variable “string” to uppercase and print it.
6. Use colon(:) operator to print the index of string from -10 to the end(slicing).
7. Print the whole string using a colon(:) operator(slicing).
'''
string = "Hye, My Name is lakshay saini. we can connect https://www.linkedin.com/in/lakshay-saini-dev/"
print(len(string))
print(type(string))
print(string.lower())
print(string.upper())
print(string[-10:])
print(string[:]) |
ddafce18cadb24e46ae3e2c5ede9e5aa5f07660f | lakshay-saini-au8/PY_playground | /hackerrank/python/string_validator.py | 402 | 3.75 | 4 | # que https://www.hackerrank.com/challenges/string-validators/problem?isFullScreen=true
#solution
if __name__ == '__main__':
s = input()
print(any([True for c in s if(c.isalnum())]))
print(any([True for c in s if(c.isalpha())]))
print(any([True for c in s if(c.isdigit())]))
print(any([True for c in s if(c.islower())]))
print(any([True for c in s if(c.isupper())]))
|
1c682af5973580973d0c06ab1c46c413e1356a64 | lakshay-saini-au8/PY_playground | /hackerrank/algorithm/string/sepreate_the_number.py | 636 | 3.9375 | 4 | # https://www.hackerrank.com/challenges/separate-the-numbers/problem?isFullScreen=false
# Complete the separateNumbers function below.
def separateNumbers(s):
if len(s) == 1:
print("NO")
return
else:
# Half iter no need to go further
for i in range(1, len(s)//2 + 1):
new_str = s[:i]
prev_str = int(new_str)
while len(new_str) < len(s):
str1 = prev_str + 1
new_str = new_str + str(str1)
prev_str = str1
if new_str == s:
print("YES", s[:i])
return
print("NO")
|
267b7a16ad09168d324a6c235154d9343517bf8e | lakshay-saini-au8/PY_playground | /hackerrank/algorithm/string/panagrams.py | 409 | 3.9375 | 4 | # Complete the pangrams function below.
def pangrams(s):
list_check = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s",
"d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m"]
for i in s:
if i.lower() in list_check:
list_check.remove(i.lower())
if len(list_check) == 0:
return "pangram"
else:
return "not pangram"
|
6a29cb24698e9390ac9077d431d6f9001386ed84 | lakshay-saini-au8/PY_playground | /random/day26.py | 1,164 | 4.28125 | 4 |
# Write a program to find a triplet that sums to a given value with improved time complexity.
'''
Input: array = {12, 3, 4, 1, 6, 9}, sum = 24;
Output: 12, 3, 9
Explanation: There is a triplet (12, 3 and 9) present
in the array whose sum is 24.
'''
# brute force apporach
def triplet(arr, sums):
n = len(arr)
if n < 3:
return "Array length is sort"
for i in range(n-2):
for j in range(i+1, n-1):
for k in range(j+1, n):
if arr[i]+arr[j]+arr[k] == sums:
print(arr[i], arr[j], arr[k])
# triplet([12,3,4,1,6,9],24)
# triplet([1,2,3,4,5],9)
# Write a program to find a triplet such that the sum of two equals to the third element with improved time complexity
def triplet_sum(arr):
n = len(arr)
if n < 3:
return "Array length is sort"
for i in range(n-2):
for j in range(i+1, n-1):
for k in range(j+1, n):
if arr[i]+arr[j] == arr[k] or arr[j]+arr[k] == arr[i] or arr[k]+arr[i] == arr[j]:
print(arr[i], arr[j], arr[k])
triplet_sum([5, 32, 1, 7, 10, 50, 19, 21, 2])
# triplet_sum([5,32,1,7,10,50,19,21,0])
|
d988704e370a7b20970ec30934fe78bffc09ce86 | lakshay-saini-au8/PY_playground | /hackerrank/python/iteratror.py | 301 | 3.578125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import *
n = int(input())
arr = input().split()
k = int(input())
count = 0
all_combination = list(combinations(arr, k))
for i in all_combination:
if 'a' in i:
count += 1
print(count/len(all_combination))
|
bd315dc79ea21ff628a4cb3f36df0f9bacde0068 | lakshay-saini-au8/PY_playground | /hackerrank/algorithm/implementation/cat_and_a_mouse.py | 339 | 3.828125 | 4 | # https://www.hackerrank.com/challenges/cats-and-a-mouse/problem?isFullScreen=true
# Complete the catAndMouse function below.
def catAndMouse(x, y, z):
catA_dis = abs(z-x)
catB_dis = abs(z-y)
if catA_dis > catB_dis:
return "Cat B"
elif catA_dis < catB_dis:
return "Cat A"
else:
return "Mouse C"
|
a047f3b6df7cb746cb75a5dfac93b092bf4daa54 | lakshay-saini-au8/PY_playground | /leetcode/448_array.py | 663 | 3.828125 | 4 | # que https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/solution/
# solution 1
def findDisappearedNumbers(arr):
n = len(arr)
arr = list(set(arr))
for i in range(1, n+1):
if(i in arr):
arr.remove(i)
else:
arr.append(i)
return arr
print(findDisappearedNumbers([4, 3, 2, 7, 8, 2, 3, 1]))
# solution 2
def findDisappearedNumbers(arr):
n = len(arr)
set_of_nums = set(range(1, n+1))
arr = list(set(arr))
for i in arr:
if(i in set_of_nums):
set_of_nums.remove(i)
return list(set_of_nums)
print(findDisappearedNumbers([4, 3, 2, 7, 8, 2, 3, 1]))
|
e6ea83c9370f40835f317bec49f30993e520933e | lakshay-saini-au8/PY_playground | /hackerrank/ds/stack/balanced_brackets.py | 635 | 3.96875 | 4 | # https://www.hackerrank.com/challenges/balanced-brackets/problem
# Complete the isBalanced function below.
def isBalanced(s):
s1 = []
for i in range(len(s)):
if len(s1) == 0:
s1.append(s[i])
else:
check = None
if s1[-1] == "(":
check = ")"
elif s1[-1] == "{":
check = "}"
elif s1[-1] == "[":
check = "]"
if check == str(s[i]):
s1.pop()
else:
s1.append(s[i])
print(s1)
if len(s1) == 0:
return "YES"
else:
return "NO"
|
17d30a1481df46f1905e09f47d1c5cc552f22947 | rkapali/python_assignment | /set1/pywc | 216 | 3.53125 | 4 | #!/usr/bin/python
import sys, gzip
filename = str(sys.argv[1])
if filename.endswith('gz'):
f = gzip.open(filename,'r')
else:
f = open (filename,'r')
counter = 0
for line in f:
counter += 1
print counter
f.close()
|
c1e4c5da5de11fb4ba05e69e211688738c610028 | yvonneyeh/ufo-hangman | /game.py | 6,704 | 3.65625 | 4 | import re
import random
import string
from ufo import ufo
ALPHABET = set(string.ascii_uppercase) # all valid playable letters
# NOUN LIST
noun_file = open("nouns.txt", "r")
content = noun_file.read()
noun_list = content.split("\n")
noun_file.close()
# MESSAGE LIST
msg_file = open("messages.txt", "r")
content = msg_file.read()
msg_list = content.split("\n")
msg_file.close()
# GAME STATUS CATEGORIES
STATUS_WIN = "win"
STATUS_LOSE = "lose"
STATUS_PLAYING = "playing"
STATUS_CORRECT = "correct"
STATUS_INCORRECT = "incorrect"
STATUS_INVALID = "invalid"
STATUS_DUPE = "duplicate"
# DEFAULT MESSAGES
INTRO = "UFO: The Game\nInstructions: save us from alien abduction by guessing letters in the codeword."
CORRECT = "Correct! You're closer to cracking the codeword."
INCORRECT = "Incorrect! The tractor beam pulls the person in further."
ALREADY_GUESSED = "You can only guess that letter once, please try again."
INVALID_GUESS = "I cannot understand your input. Please guess a single letter."
LOSE_MSG = "You lost! The UFO abducted the person! The codeword was:"
WIN_MSG = "Correct! You saved the person and earned a medal of honor!\nThe codeword is:"
def get_word():
""" Randomly selects playable word from noun list. """
word = random.choice(noun_list)
while '-' in word or ' ' in word or word == '':
word = random.choice(noun_list)
return word.upper()
def get_message():
""" Show a random encouraging message when the user guesses an incorrect letter. """
message = random.choice(msg_list)
return message
def show_ufo(attempts):
""" Return current UFO for attempt number."""
return ufo[attempts]
class Game(object):
""" A UFO Hangman Game object. """
def __init__(self, word):
self.word_letters = set(word) # unique letters in target word
self.guessed_letters = set() # letters guessed by player
self.remaining_letters = set(word) # difference between word_letters & guessed_letters
self.attempts = 0
self.lives = 6
self.status = STATUS_PLAYING
self.word = word
def start():
""" Display the title and instructions of the game """
print(INTRO)
def play(self, word):
""" Play UFO Hangman! """
while len(self.remaining_letters) > 0 and self.lives > 0:
self.generate_gameboard(word)
guess = self.retrieve_guess()
self.process_guess(guess)
def generate_gameboard(self, word):
""" Generate the gameboard during game play. """
current_codeword = [letter if letter in self.guessed_letters else '_' for letter in word]
print(show_ufo(self.attempts))
print("Incorrect Guesses:")
print(' '.join(self.guessed_letters))
print("Codeword:")
print(' '.join(current_codeword))
def calculate_progress(self):
""" Future feature: more efficient runtime with dictionary implementation of current progress. """
# Something like:
# self.word = dict{'a': {index: [0, 2], guessed: false}}
# self.word = dict{0: {letter: a, guessed: false}}
# Rather than recalculating "current_codeword" every time, tracking differences would be easier
pass
def remove_guessed_letters(self, guess):
""" Future feature: check difference between word_letters and guessed_letters
for more efficient runtime with set implementation of letters remaining. """
# remove guessed letters from remaining set instead of word set
# set(x) == set(y)
# remaining_letters == 0 –> every letter from word was guessed
pass
def check_status(self):
""" Check current gameplay status. """
if self.status == STATUS_LOSE:
raise ValueError("You already lost!")
elif self.status == STATUS_WIN:
raise ValueError("You already won!")
# Check for win or lose
if self.lives <= 0:
self.status = STATUS_LOSE
# If all letters guessed correctly
if all([letter in self.guessed_letters for letter in self.word]):
self.status = STATUS_WIN
return self.status
def retrieve_guess(self):
""" Get user input for a guess. """
guess = input('Please enter your guess: ').upper()
return guess
def process_guess(self, guess):
""" Process a player's guess during the game. """
if type(guess) != str or len(guess) != 1 or guess not in ALPHABET:
print(INVALID_GUESS)
return STATUS_INVALID
guess = guess.upper()
if guess in self.guessed_letters:
print(ALREADY_GUESSED)
return STATUS_DUPE
# CORRECT LETTER
if guess in ALPHABET - self.guessed_letters:
self.guessed_letters.add(guess)
if guess in self.remaining_letters:
self.remaining_letters.remove(guess)
# all() function returns True if all items in an iterable are true
if all([letters in self.guessed_letters for letters in self.word_letters]):
# if self.guessed_letters == self.word_letters:
# WINNING PLAY!
self.status = STATUS_WIN
print(WIN_MSG, self.word)
return STATUS_WIN
print(CORRECT)
return STATUS_CORRECT
# INCORRECT LETTER
else:
self.lives -= 1
self.attempts += 1
# len(remaining_letters) == 0 OR lives == 0
if self.lives == 0:
# LOSING PLAY ...
self.status = STATUS_LOSE
print(show_ufo(self.attempts))
print(LOSE_MSG, self.word)
return STATUS_LOSE
print(INCORRECT)
print(get_message())
return STATUS_INCORRECT
else:
print(INVALID_GUESS)
return STATUS_INVALID
def get_status(self):
""" Get the current status of gameplay. """
return self.status
def playing():
""" Return True if the game is in session. """
return self.status == STATUS_PLAYING
def play_game():
""" Initiate gameplay. """
playing = True
while playing:
word = get_word()
UFO = Game(word)
Game.start()
Game.play(UFO, word)
keep_playing = input('Would you like to play again (Y/N)? ').upper()
while keep_playing == 'N':
playing = False
print('Goodbye!')
break
if __name__ == '__main__':
play_game()
|
65d5d74353e6bb63a1817367f631e996e9cc001a | Niraj-Suryavanshi/Python-Basic-Program | /10.chapter/13_pr_05.py | 830 | 3.78125 | 4 | class Train:
def __init__(self,name,fare,seats):
self.name=name
self.fare=fare
self.seats=seats
def getStatus(self):
print("********")
print(f"The name of the train is {self.name}")
print(f"The fare of the train is {self.fare}")
print("********")
def fareInfo(self):
print(f"The price of the ticke is Rs.{self.fare}")
def bookTicket(self):
if(self.seats>0):
print(f"Your ticket has been booked!Your seat number is {self.seats}")
self.seats=self.seats-1
else:
print("sorry this train is currently full !")
intercity=Train("Intercity train:22123",90,2)
intercity.getStatus()
intercity.bookTicket()
intercity.bookTicket()
intercity.bookTicket()
intercity.getStatus()
|
fce872e76b3da0255f503a85d718dc36fd739dd6 | Niraj-Suryavanshi/Python-Basic-Program | /7.chapter/12_pr_03.py | 224 | 4.125 | 4 | num=int(input("Enter a number: "))
prime=True
for i in range(2,num):
if(num%i==0):
prime=False
break
if prime:
print("Number is prime")
else:
print("Number is not prime")
|
674befa989acb67aefcaf986f897fe3ec8b52c60 | Niraj-Suryavanshi/Python-Basic-Program | /2.chapter/06_pr_02_remainder.py | 36 | 3.828125 | 4 | a=10
b=5
print("remainder is:",a%b)
|
3e8ad597bfff688ebb3b2bd482434ce00286fbdb | Niraj-Suryavanshi/Python-Basic-Program | /3.chapter/03_string_functions.py | 377 | 4.03125 | 4 | story='''hello ji kaise ho sare this is love babbar to chaliye shuru
krte hai'''
# print(story)
# string fuctions:
# print(len(story))
# print(story.endswith("hai"))
# print(story.count("a"))
# print(story.capitalize())
# print(story.find("love"))
# print(story.replace("love babbar","Niraj Suryavanshi"))
|
1c4cea7b464fd5f0c73acb9df338bf93edfd73a0 | Niraj-Suryavanshi/Python-Basic-Program | /7.chapter/o2_quick_quiz.py | 90 | 3.578125 | 4 | # i=1
# while i<51:
# print(i)
# i=i+1
i=0
while i<5:
print("Harry")
i=i+1 |
8d15cc01aa2db01da9ea285fc234cae188e5c0cf | Niraj-Suryavanshi/Python-Basic-Program | /3.chapter/06_pr_02.py | 210 | 4.40625 | 4 | letter='''Dear <|Name|>
you are selected
date: <|date|>'''
name=input("Enter your name:")
date=input("Enter a date:")
letter=letter.replace("<|Name|>",name)
letter=letter.replace("<|date|>",date)
print(letter) |
078b45bb79ee6d04eae262d3a75dd1b09c22c04f | Niraj-Suryavanshi/Python-Basic-Program | /4.chapter/06_pr_o1_store_fruit.py | 288 | 3.84375 | 4 | f1=input("Enter fruits name 1: ")
f2=input("Enter fruits name 2: ")
f3=input("Enter fruits name 3: ")
f4=input("Enter fruits name 4: ")
f5=input("Enter fruits name 5: ")
f6=input("Enter fruits name 6: ")
f7=input("Enter fruits name 7: ")
myfruits=[f1,f2,f3,f4,f5,f6,f7]
print(myfruits)
|
3fc8402b189c340ec3497eb455752f33a1bc5b16 | Niraj-Suryavanshi/Python-Basic-Program | /3.chapter/02_string_slicing.py | 232 | 3.953125 | 4 |
# greeting="good morning,"
# name="Niraj";
# # print(type(name))
# # Concatenating string
# c= greeting + name;
# print(c)
name="nirajisgoodperson"
# print(name[:5])
# c=name[-3:-1]
# c=name[-5:]
# print(c)
d=name[0::3]
print(d) |
d86dd844f971803b4a1a4d60efd18a8281dd21c5 | Niraj-Suryavanshi/Python-Basic-Program | /5.chapter/02_dictionary_methods.py | 519 | 3.796875 | 4 | mydict={
"harry":"coder of youtube",
"niraj":"student of SIT",
"marks":[43,3,33,3],
"anotherdictionary":{
"harry":"youtuber"
}
}
print(list(mydict.keys()))
print("\n")
print(mydict.values());print("\n")
print(mydict.items())
# print the key value for all content of value
updateDict={
"lovish":"friends",
"divya":"friends",
"harry":"rustom"
}
# print(mydict)
# mydict.update(updateDict)
# print(mydict)
print("\n")
print(mydict.get("harry2"))
print("\n")
print(mydict["harry2"]) |
cf8fc3a611222b927c9e722b62055a77ae89a005 | chanchiyakishan/challenges | /permu_and_name.py | 202 | 3.640625 | 4 | from itertools import permutations
com = input().split(" ")
li = list(permutations(com[0], int(com[1])))
for i in range(len(li)):
li[i] = "".join(li[i])
li.sort()
for x in li:
print(*x, sep="")
|
250cab70a73f6ec84677781b3b2917f99bf4882e | ALMR94/practica-2-python | /6- Pedir un numero de 1-999.py | 236 | 3.921875 | 4 | # -*- coding: cp1252 -*-
print "Dime un nmero de como mximo 3 cifras:"
a= int(raw_input())
if a<1000 and a>0:
print "El nmero",a,"es vlido."
else:
print "El nmero introducido no es vlido o no es de 3 cifras."
|
399b6519175e39f500bb34c25ac6647a1f894368 | stqc/LogisticRegression_sgd | /LogisticRegressionSGD.py | 1,727 | 3.984375 | 4 | class LogisticRegression:
'''
datax = Independent Variable
datay = Dependent Variable
alpha = Learning rate
train(iterations=10)
----------------------------------------------------
Train method takes one argument as input i.e itertions
default = 10
predict(x)
-----------------------------------------------------
predict method takes data as argument, the data has to
be enclosed either as a 2D array or 2D list
example:
obj.predict([[10]])
output: [some_value]
'''
def __init__(self,datax,datay,alpha):
self.x = np.hstack((np.array([[1 for i in range(len(datax))]]).transpose(),datax))
self.y = datay
self.alpha = alpha
self.cols = datax.shape[1]
self.theta = np.array([0 for i in range(self.cols+1)])
def update_train(self,x):
y = 0
for i in range(len(x)):
y+=(1/(1+np.exp(-np.dot(self.theta,x))))
return y
def predict(self,x):
y =[]
x = np.hstack((np.array([[1 for i in range(len(x))]]).transpose(),x))
for i in range(len(x)):
y.append(1/(1+np.exp(-np.dot(self.theta,x[i]))))
return y
def update_sgd(self,k):
sum_error =0
for i in range(len(self.x)):
error = self.update_train(self.x[i])-self.y[i]
self.theta = self.theta - self.alpha*error*self.x[i]
sum_error+=error
print(f'{k}: {sum_error**2} {error}')
def train(self, iterations=10):
for i in range(iterations):
self.update_sgd(i)
def __repr__(self):
return f'{self.theta}'
|
a6e95395b141c86ad404b5d8690c07953d2fabad | Mihir-AI/Project | /Dictionary.py | 778 | 3.671875 | 4 | import json
from difflib import get_close_matches
data=json.load(open("data.json"))
def translate(w):
w=w.lower()
if w in data:
return data[w]
elif len(get_close_matches(w,data.keys()))>0:
yn=input(f"did u mean {get_close_matches(w,data.keys())[0]} instead?Enter Y or N:")
if yn=="Y":
return data[get_close_matches(w,data.keys())[0]]
elif yn=="N":
return "we did'nt understand your entry.please check the entry"
else:
return "please check the word"
else:
return "The word doesn't exist.Please double check it"
word= input("Enter the word:")
output=translate(word)
if type(output)==list:
for item in output:
print(item)
else:
print(output) |
deb2282cae83b4fdd82cf34d6afd4911fe8a50b4 | montlebalm/Scrabbler | /scrabbler/player/wordfinder.py | 1,918 | 3.609375 | 4 | import itertools
import scrabbler.dictionary
class WordFinder():
def get_matches(self, string, constraints=[]):
"""Get all hashed that can be made from any combination of letters in
the provided string"""
real_keys = self.__get_real_keys(string)
matches = []
if real_keys:
# Find all the real hashed that match the sorted string
matches = dict((k, scrabbler.dictionary.get_words(k)) for k in real_keys)
# Apply the constraints
if constraints:
matches = self.__apply_constraints(matches, constraints)
return matches
def is_word(self, string):
return scrabbler.dictionary.is_word(string)
def get_words(self, string):
output = []
for words in self.__get_word_groups(string):
output += [w for w in words]
return output
def __get_real_keys(self, string):
# Get unique combinations of all the letters
combos = self.__get_combinations(sorted(string))
# Find all the hashed whose letters are in a combo
real_keys = [x for x in combos if scrabbler.dictionary.is_key(x)]
return real_keys
def __apply_constraints(self, matches, constraints):
"""Return the matches that comply with the specified constraints"""
complying_words = dict()
for k, v in matches.iteritems():
complies = [x for x in v if self.__meets_constraints(x, constraints)]
if complies:
complying_words[k] = complies
return complying_words
def __meets_constraints(self, word, constraints):
for con in constraints:
if not con.satisfied_by(word):
return False
return True
def __get_combinations(self, letters, min_len=2):
"""Get all unique combinations of the provided list of letters"""
combos = []
# Only look at letters equal to or greater than the min_len
for i in xrange(min_len, len(letters) + 1):
# Get unique combinations of letters and join into a string
combos += [''.join(x) for x in itertools.combinations(letters, i)]
return combos |
98358a5dd94f1a18198c4935c554420bc3ba10dc | ramya-creator/InnovationPython_Ramya | /Task7.py | 3,794 | 4 | 4 | """1. Write a program that calculates and prints the value according to the given formula:
Q= Square root of [(2*C*D)/H]
Following are the fixed values of C and H:
C is 50.
H is 30.
D is a variable whose values should be input to your program in a comma-separated sequence.
"""
import math
C = 50
H = 30
result = []
D = input("enter numbers seperated by ',': ")
Ds = D.split(',')
Ds = [int(a) for a in Ds]
for i in Ds:
Q=math.sqrt((2*C*i)/H)
result.append(Q)
print(result)
"""2. Define a class named Shape and its subclass Square. The Square class has an init function which
takes length as argument. Both classes have an area function which can print the area of the shape
where Shape’s area is 0 by default."""
class shape():
def __init__(self):
pass
def area(self):
print(0)
class square():
def __init__(self, length):
self.length = length
def area(self):
a = (self.length * self.length)
print("Area of square:", a)
s = square(2)
print(s.area())
print(shape().area())
#3. Create a class to find three elements that sum to zero from a set of n real numbers
arr = [-25,-10,-7,-3,2,4,8,10]
n = len(arr)
def findTriplets(arr, n):
f = True
for i in range(0, n-2):
for j in range(i+1, n-1):
for k in range(j+1, n):
if (arr[i] + arr[j] + arr[k] == 0):
print(arr[i], arr[j], arr[k])
f = True
if (f == False):
print(" not exist ")
findTriplets(arr, n)
"""4. Create a Time class and initialize it with hours and minutes.
Create a method addTime which should take two Time objects and add them.
Create another method displayTime which should print the time.
Also create a method displayMinute which should display the total minutes in the Time.
"""
class Time:
def __init__(self,hours,minutes):
self.hours = hours
self.minutes = minutes
def addTime(t1,t2):
t3 = Time(0,0)
t3.hours = t1.hours + t2.hours
t3.minutes = t1.minutes + t2.minutes
while t3.minutes >= 60:
t3.hours += 1
t3.minutes -= 60
return t3
def displayTime(self):
print("Time is %d hours and %d minutes" %(self.hours, self.minutes))
def displayMinute(self):
print((self.hours*60) + self.minutes, "minutes")
a = Time(2,50)
b = Time(1,20)
c = Time.addTime(a,b)
c.displayTime()
c.displayMinute()
"""#5. Write a Person class with an instance variable “age” and a constructor that takes an integer as a
parameter. The constructor must assign the integer value to the age variable after confirming the
argument passed is not negative; if a negative argument is passed then the constructor should set
age to 0 and print “Age is not valid, setting age to 0”. In addition, you must write the following instance
methods:
yearPasses() should increase age by the integer value that you are passing inside the function.
amIOld() should perform the following conditional actions:I
f age is between 0 and <13, print “You are young”.
If age is >=13 and <=19 , print “You are a teenager”.
Otherwise, print “You are old”."""
class Person:
def __init__(self,age):
if age<0:
print("Age is not valid, setting age to 0")
self.age=0
else:
self.age=age
def yearPasses(self,increase):
self.age += increase
return self.age
def amIOld(self):
if self.age>=0 and self.age<13:
print("You are young")
elif self.age>=13 and self.age<=19:
print("You are a teenager")
else:
print("You are old")
age=[-1,4,10,16,18,64,38]
for i in age:
a=Person(i)
a.amIOld()
a=Person(38)
print(a.yearPasses(4))
|
f208db323af29ccf0111a0d5a54ecc60177c0676 | ramya-creator/InnovationPython_Ramya | /Task2_Operators_DecisionMaking_py_files/4_question.py | 170 | 3.9375 | 4 | #4_question
while 1:
i = int(input("Enter an integer: "))
if i < 0:
print("Its Over")
break
else:
print("Going good")
continue |
7330dc0f3f50ec43849ca879fe2e9e8907ecafb1 | jiwoooooo/ibk | /mycode/first.py | 398 | 3.609375 | 4 | def add(n1,n2):
#pass
return n1+n2
print(add(10,20))
#실행 단축키 ctrl shift f10
add2 = lambda n1,n2 : n1+n2
print(type(add2))
print(add2(100,200))
class USer:
#생성자 선언
def __init__(self, name):
self.name = name
#toString()
def __str__(self):
return self.name
#객체 생성
user = User("파이썬")
print(user)
"""
block comment
"""
|
91c554b28d22ec7518eb34b46a7f2fa53cc559b6 | jimbrayrcp/turtler | /turtler/car_manager.py | 1,912 | 3.859375 | 4 | # ################################
# Copyright (c) 2021 Jim Bray
# All Rights Reserved
# ################################
from turtle import Turtle
import random
COLORS = ["red", "orange", "khaki3", "green", "blue", "purple", "LightBlue3"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
class CarManager:
def __init__(self):
self.car_group = []
self.car_speed = STARTING_MOVE_DISTANCE
def create_car(self):
random_chance_car = random.randint(1, 6)
borders = (211, 0, 255)
if random_chance_car == 6:
new_car = Turtle("square")
new_car.fillcolor(random.choice(COLORS))
new_car.penup()
new_car.pencolor(borders)
new_car.width(20)
new_car.pensize(10)
new_car.shapesize(1, 2, 1)
range_y = random.randrange(-240, 250, 40)
new_car.setposition(290, range_y)
for car in self.car_group:
if new_car.distance(car) <= 50:
new_car.setposition(320, range_y)
self.car_group.append(new_car)
def car_automate(self):
for car in self.car_group:
car.backward(self.car_speed)
def new_level(self):
self.car_speed += MOVE_INCREMENT
def reset_level(self):
self.car_speed = STARTING_MOVE_DISTANCE
if __name__ == "__main__":
from turtle import Screen
from time import sleep
screen = Screen()
screen.colormode(255)
screen.setup(width=600, height=600)
screen.tracer(0)
cars = CarManager()
counts = 0
check_val = 75
game_is_on = True
while game_is_on:
counts += 1
sleep(0.1)
screen.update()
cars.create_car()
cars.car_automate()
if counts > check_val:
cars.new_level()
check_val += 75
print(f"VALUE: {counts} LOOKING FOR: {check_val}")
|
953ed440d979b8d630b868bcbd004315bb14e26e | merrittd42/HackerRankCode | /PythonTut/Intro/ex6.py | 65 | 3.609375 | 4 | N = int(input())
x = 0
while(x<N):
print(x*x)
x = x + 1
|
d72a4781665603d1046ce3d833fd57c18a816862 | rahulk007/war | /war.py | 3,478 | 3.703125 | 4 |
suits=['hearts','diamonds','spades','clubs']
ranks=['two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen']
values={'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9,'ten':10,'eleven':11,'twelve':12,'thirteen':13,'fourteen':14}
# each car is described by suit and rank
class Card:
def __init__(self,suit,rank):
self.suit=suit
self.rank=rank
self.value=values[rank]
def __str__(self):
return f'{self.rank} of {self.suit}'
import random
class Deck:
def __init__(self):
self.all_cards=[]
for suit in suits:
for rank in ranks:
created_card=Card(suit,rank)
self.all_cards.append(created_card)
def shuffle(self):
random.shuffle(self.all_cards)
def deal_one(self):
return self.all_cards.pop()
class Player:
def __init__(self,name):
self.name=name
self.player_cards=[]
def add_card(self,new_card):
if type(new_card)== type([]):
self.player_cards.extend(new_card)
else:
self.player_cards.append(new_card)
def remove_card(self):
return self.player_cards.pop(0)
def __str__(self):
return f'Player {self.name} has {len(self.player_cards)} cards'
## Game setup
#creat a deck of 52 cards
new_deck=Deck()
#create a player1 and player2
player_one=Player('one')
player_two=Player('two')
#shuffle the deck of cards
new_deck.shuffle()
#deal the shuffled cards between the two player
for i in range(26):
player_one.add_card(new_deck.deal_one())
player_two.add_card(new_deck.deal_one())
# drawing the top cards from the deck for each player to play
game_on= True
count=0
while game_on:
count+=1
print(f'round{count}!')
if len(player_one.player_cards)==0:
print('player_one do not have enough cards!')
print('player_two Wins!!')
game_on=False
break
if len(player_two.player_cards)==0:
print('player_two does not have enough cards!')
print('player_one Wins!!')
game_on=False
break
# drawing cards from each player deck
player_one_draw=[]
player_two_draw=[]
player_one_draw.append(player_one.remove_card())
player_two_draw.append(player_two.remove_card())
at_war=True
while at_war:
if player_one_draw[-1].value > player_two_draw[-1].value:
player_one.add_card(player_one_draw)
player_one.add_card(player_two_draw)
at_war=False
elif player_one_draw[-1].value < player_two_draw[-1].value:
player_two.add_card(player_one_draw)
player_two.add_card(player_two_draw)
at_war=False
else:
print('war!')
if len(player_one.player_cards)<5:
print('player_one unable to declare war,dont have enough cards!')
print('player_two Wins!!')
game_on=False
break
elif len(player_two.player_cards)<5:
print('player_two unable to declare war,dont have enough cards!')
print('player_one Wins!!')
game_on=False
break
else:
for i in range(5):
player_one_draw.append(player_one.remove_card())
player_two_draw.append(player_two.remove_card())
|
a8e4037f1cd7ccef00eba8602f996fc64f08caa0 | tjuva3/Prepoznava-stevil | /main.py | 2,288 | 3.625 | 4 | from keras.models import Sequential #Archytecture for our network
from keras.layers import Flatten, Dense #Layers for our neural network
from keras.datasets import mnist #handwritten images 28x28px
from keras.utils import normalize
import numpy as np
(xTrain, yTrain), (xTest, yTest) = mnist.load_data() #28*28 images of hand-written digits 0-9
xTrain = normalize(xTrain, axis=1) #normalize; values are scalled between 0 and 1
xTest = normalize(xTest, axis=1)
model = Sequential() #archytecture of the model
model.add(Flatten()) #Flatten is a layer that is build in keras; it flattens data
model.add(Dense(128, activation="relu")) #128 neurons
model.add(Dense(128, activation="relu"))
model.add(Dense(10, activation="softmax")) #output layer; softmax for probability distribution
#compiling
model.compile(optimizer="adam", #there are around 10 optimizers in keras; adam is the most basic one
loss="sparse_categorical_crossentropy", #loss = degree of how much you got wrong; neural network doesnt try to optimise for acuraccy but it is always trying to minimize loss
metrics=["accuracy"]) #tracks accuracy
#training
model.fit(xTrain, yTrain,
validation_data=(xTest, yTest),
epochs=10,
batch_size=100)
#show predictions for the first 20 images in the test set
predictions = model.predict(xTest[:20])
print(np.argmax(predictions, axis=1))
print(yTest[:20]) #show actual results for the first 20 images in the test set
|
12b3ce649326dd58dfc08086f8cc5ef644f3453d | rpathak38/OpenCV-Tutorial | /image_gradients_and_canny_edge_detection.py | 1,431 | 3.6875 | 4 | import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread("sudoku.png", cv2.IMREAD_GRAYSCALE)
img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 101, 2)
# whenever we encounter an edge in a picture, there is a great change in the intensity. For example, consider a
# marshmellow in a dark room. When we look at the edge of the marshmellow, we are able to identify it by noting the
# blackness on the outside of the marshmellow, This point, where the white pixels change to black produces a huge
# drop in intensity, or in otherwords a place where the rate of intensity change is at a maximum or minimum. Using
# this idea we develop the Laplacian and Sobel functions. These functions allow us to find the places where intensity
# changes.
lap = cv2.Laplacian(img, -1, ksize=1)
#The lower the kernel, the stronger the edge must be (larger change in intensity, as we are comparing directly to the next pixel)
#Use cv2.CV_64F as the values of the Laplacian can be pretty large or small
sobel = cv2.Sobel(img, -1, 1, 1, ksize=1)
#Uses a sobel derivative (directional derivative)
canny = cv2.Canny(img, 100, 200)
images = [img, lap, sobel, canny]
titles = ["Image","Laplacian", "sobel", "Canny"]
for (num, image) in enumerate(images):
plt.subplot(2, 2, num+1)
plt.imshow(image, "gray")
plt.title(titles[num])
plt.xticks([]), plt.yticks([])
plt.show() |
0f36de4072a59c3d1ce392a3198c9ddaef3e28c2 | Flor246/PYTHONEF | /MODULO1/prob2.py | 373 | 3.796875 | 4 | #2 problema de cuenta de ahorros
dinero=float(input('Ingrese la cantidad de dinero: '))
interes=0.04
año1=round(dinero*(1+interes),2)
año2=round(año1*(1+interes),2)
año3=round(año2*(1+interes),2)
print('Ahorro del primer año es: {}'.format(año1))
print('Ahorro del segundo año es: {}'.format(año2))
print('Ahorro del stercer año es: {}'.format(año3))
|
aa8aaf2c9b9c8b82b4e4fb2a124554586de37a00 | aasthahooda811/python-basics | /Assignment24.py | 209 | 3.875 | 4 | '''
Created on 26-Jan-2018
@author: Vijay
'''
string1 = input("Enter a string")
count = 0;
c = ''
for x in string1:
if(x.isupper()):
count += 1
c = c + x
print(count)
print(c) |
c383ed3dddec3b4adca2f2e176b3c2db9dea6ae3 | Jennycbx/Making_tests_homework | /start_code/tests/compare_test.py | 925 | 3.796875 | 4 | import unittest
from src.compare import *
# from src.compare import colour_of_apple
class TestCompare(unittest.TestCase):
def setup (self):
self.twin_1 = ("Jenny", 30, 5.5)
self.twin_2 = ("Claire", 30, 5.6)
def test_compare_3_1_returns_3_is_greater_than_1(self):
self.assertEqual("3 is greater than 1", compare_numbers(3, 1))
# def test_compare_height(self):
# self.assertEqual("Claire is taller than Jenny", self.compare_height(self.twin_1, self.twin_2))
def test_colour_of_apple(self):
self.assertEqual("The apple is red", colour_of_apple("red"))
def test_distance_travelled(self):
self.assertEqual("Andrew travelled further than John", distance_travelled("Andrew", "John"))
# def test_add_grapes_to_list(self):
# shopping_list = shopping_list[]
# self.assertEqual(shopping_list["grapes"], add_grapes_to_list("grapes")) |
52315cfb7ebbe5f6d9d03e0b1f70c9a681305e08 | kcam100/DataVisualization | /titanic_cleaning.py | 1,900 | 3.671875 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
# Read in titanic csv
titanic = pd.read_csv('titanic-data.csv')
# View first 5 rows of dataframe
titanic.head()
# Delete all unnecessary columns
titanic_clean = titanic.drop(['PassengerId','Name','Ticket','Cabin',
'Fare','Embarked', 'Parch', 'SibSp'], axis=1)
# View first 5 rows of new dataframe
titanic_clean.head()
# View missing value count of titanic_clean
titanic_clean.isnull().sum()
# Replace titanic_clean['Age'] 'NaN' values to median age value
age_median = titanic_clean['Age'].dropna().median()
if len(titanic_clean.Age[titanic_clean.Age.isnull()]) > 0:
titanic_clean.loc[(titanic_clean.Age.isnull()), 'Age'] = age_median
# Audit dataframe to make sure code executed properly
titanic_clean.describe(include="all")
# Create Age categories
titanic_clean['Age_categories'] = pd.cut(titanic_clean['Age'],
bins=[0,18,49,90], labels=["Child","Adult","Senior"])
# Drop 'Age' column
titanic_clean = titanic_clean.drop(['Age'], axis=1)
# View Survival Rate Based on Class and Gender
class_sex_survived = titanic_clean.groupby(['Pclass' , 'Sex'])[['Survived']].mean()
print class_sex_survived
# Create new dataframe with survival rates for gender/socioeconomic status
survival_rate_columns = ['Class', 'Sex', 'Survival Rate']
survival_rate_data = [('Upper', 'Female', 0.97),
('Upper', 'Male', 0.37),
('Middle', 'Female', 0.92),
('Middle', 'Male', 0.16),
('Lower', 'Female', 0.5),
('Lower', 'Male', 0.14)]
survival_rates = pd.DataFrame.from_records(survival_rate_data, columns=survival_rate_columns)
# View New Dataframe
survival_rates.head()
# Export survival_rates DataFrame to .csv
survival_rates.to_csv('titanic_survival_rates2.csv')
|
0da4f9a8d4ff1332d1039ab95d595b2172b05213 | Chofito/ejercicios-1-2 | /Solutions.py | 1,458 | 3.53125 | 4 | def task_1(a_sacar):
pass # Creo que era mas sencillo el del archivo de texto triangle.txt xD
def calcular_5(cantidad):
return ["5C" for i in range(int(cantidad * 20))]
def calcular_10(cantidad):
cantidad_10 = ["10C" for i in range(int(cantidad * 10))]
sobrante = cantidad % 0.1
return [cantidad, sobrante]
def calcular_25():
cantidad_25 = ["25C" for i in range(int(cantidad * 4))]
sobrante = cantidad % 0.25
return [cantidad_25, sobrante]
def calcular_50():
cantidad_50 = ["50C" for i in range(int(cantidad * 2))]
sobrante = cantidad % 0.5
return [cantidad_50, sobrante]
# 1 Quetzal
def calcular_100():
cantidad_100 = ["100" for i in range(int(cantidad))]
sobrante = cantidad % 1
return [cantidad_100, sobrante]
def task_2():
lista_machete = []
for i in range(10000):
num = i
reversed_num = str(i)[::-1]
for j in range(51):
result = num + int(reversed_num)
txt = str(result)
n = len(txt)
count = 0
for x in range(0,n-1):
if txt[x] == txt[n-x-1]:
count += 1
if count == n:
break
else:
num = result
reversed_num = str(result)[::-1]
else:
lista_machete.append(i)
return lista_machete
if __name__ == '__main__':
print(task_2())
print(calcular_5(100))
|
83838f103161cfc3f71bbb1865a9052bef65036b | caketi/cake | /heap_sort_objects.py | 973 | 4 | 4 | from heapq import heappop, heappush
class Movie:
def __init__(self, title, year):
self.title = title
self.year = year
def __str__(self):
return str.format("Title: {}, Year: {}", self.title, self.year)
def __lt__(self, other):
return self.year < other.year
def __gt__(self, other):
return other.__lt__(self)
def __eq__(self, other):
return self.year == other.year
def __ne__(self, other):
return not self.__eq__(other)
def heap_sort(array):
heap = []
for element in array:
heappush(heap, element)
ordered = []
while heap:
ordered.append(heappop(heap))
return ordered
movie1 = Movie("Citizen Kane", 1941)
movie2 = Movie("Back to the Future", 1985)
movie3 = Movie("Forrest Gump", 1994)
movie4 = Movie("The Silence of the Lambs", 1991);
movie5 = Movie("Gia", 1998)
array = [movie1, movie2, movie3, movie4, movie5]
for movie in heap_sort(array):
print(movie) |
08703d48dac44c29429f1dc5af0ac7de2d41bf2d | huegli/PythonWorkOut | /chap03/mysum.py | 184 | 3.609375 | 4 | def mysum(*items):
output = ()
if not items:
return ()
else:
output = items[0]
for item in items[1:]:
output += item
return output
|
af020fb179051849f8489361c2d2aa0d0b2b0d3b | huegli/PythonWorkOut | /chap01/guess.py | 430 | 4.09375 | 4 | import random
number = random.randint(0, 100)
while guess := input("Enter a number guess: "):
if not guess.isdecimal():
print("Please enter a number from 0 - 100")
else:
guess = int(guess)
if guess < number:
print(f"{guess} is too low")
elif guess > number:
print(f"{guess} is too high")
else:
print(f"{guess} is correct!")
exit(0)
|
729817cb29e8b7f6cbe1a7e39adfb394ac593bbd | huegli/PythonWorkOut | /chap01/hexadecimal.py | 410 | 3.53125 | 4 | def hex_output(hexnum):
decnum = 0
for power, num in enumerate(reversed(hexnum)):
try:
decnum += 16**power*int(num, 16)
except ValueError:
return -1
return decnum
if __name__ == "__main__":
print(f"0x50 is {hex_output('50')}")
print(f"0x20 is {hex_output('20')}")
print(f"0xAA is {hex_output('AA')}")
print(f"0xxx is {hex_output('xx')}")
|
2686affb610a772f54c93b3730ce22d11655d317 | JoyDajunSpaceCraft/leetcode_job | /hash/549-最长和谐子串.py | 1,255 | 3.5 | 4 | # 594. 最长和谐子序列
# 和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。
# 现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。
# 示例 1:
# 输入: [1,3,2,2,5,2,3,7]
# 输出: 5
# 原因: 最长的和谐数组是:[3,2,2,2,3].
class Solution:
def findLHS(self, nums: List[int]) -> int:
res = 0
num = len(nums)
for i in range(num):
count = 0
flag = False
for j in range(num):
if nums[i] == nums[j]:
count +=1
elif nums[j]==nums[i]+1:
count += 1
flag = True
if flag:
res = max(res, count)
return res
class Solution:
def findLHS(self, nums: List[int]) -> int:
res = 0
dict_num = {}
for i in range(len(nums)):
num = nums[i]
if num not in dict_num:
dict_num[num] = 1
else:
dict_num[num]+=1
for key in dict_num:
if key+1 in dict_num:
res = max(res, dict_num[key]+ dict_num[key+1])
return res |
ecf9a867a183ad98ccb14b147e458a338a9ff33c | JoyDajunSpaceCraft/leetcode_job | /tree/1382. 将二叉搜索树变平衡.py | 1,496 | 3.78125 | 4 | # 1382. 将二叉搜索树变平衡
# 给你一棵二叉搜索树,请你返回一棵 平衡后 的二叉搜索树,新生成的树应该与原来的树有着相同的节点值。
# 如果一棵二叉搜索树中,每个节点的两棵子树高度差不超过 1 ,我们就称这棵二叉搜索树是 平衡的 。
# 如果有多种构造方法,请你返回任意一种。
# 示例:
# 输入:root = [1,null,2,null,3,null,4,null,null]
# 输出:[2,1,3,null,null,null,4]
# 解释:这不是唯一的正确答案,[3,1,4,null,2,null,null] 也是一个可行的构造方案。
# 提示:
# 树节点的数目在 1 到 10^4 之间。
# 树节点的值互不相同,且在 1 到 10^5 之间。
# 将二叉树 读入列表 列表中元素 按照排列
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
def inorder(node):
if not node:
return []
return inorder(node.left) + [node.val] + inorder(node.right)
l = inorder(root)
def generator(l):
if not l:
return None
mid = len(l) // 2 # 地板除获得整数
root = TreeNode(l[mid])
root.left = generator(l[:mid])
root.right = generator(l[mid + 1:])
return root
return generator(l)
|
af5f80868ba24a2e59bf79f9977ac3f2635450dd | JoyDajunSpaceCraft/leetcode_job | /array/1038. 从二叉搜索树到更大和树.py | 1,243 | 3.609375 | 4 | # 1038. 从二叉搜索树到更大和树
# 给出二叉 搜索 树的根节点,该二叉树的节点值各不相同,修改二叉树,使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。
# 提醒一下,二叉搜索树满足下列约束条件:
# 节点的左子树仅包含键 小于 节点键的节点。
# 节点的右子树仅包含键 大于 节点键的节点。
# 左右子树也必须是二叉搜索树。
# 示例:
# 输入:[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
# 输出:[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
# 提示:
# 树中的节点数介于 1 和 100 之间。
# 每个节点的值介于 0 和 100 之间。
# 给定的树为二叉搜索树。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
self.sums = 0
self.inOrder(root)
return root
def inOrder(self, root):
if not root:
return
self.inOrder(root.right)
self.sums += root.val
root.val = self.sums
self.inOrder(root.left) |
952075fc18f7754d30a41695e41f630c70141168 | jdalzatec/EulerProject | /Problem_34/main.py | 449 | 3.6875 | 4 | import math
def main():
limit = 10**5 #This number is a guess
total_sum = 0
for i in range(1,limit+1):
num = str(i)
suma = 0
for j in range(len(num)):
factorial = math.factorial(int(num[j]))
suma += factorial
if suma == i:
print(i, True)
total_sum += i
print(total_sum - 3) #As 1 and 2 are not included in the sum
if __name__ == '__main__':
main() |
e0239d0f067404e6d177a30341328d2ecd00c0c1 | jdalzatec/EulerProject | /Problem_20/main.py | 225 | 3.625 | 4 | from functools import reduce
from math import factorial
def main():
num = 100
value = factorial(num)
suma = reduce(lambda x, y: int(x) + int(y), str(value))
print(suma)
if __name__ == '__main__':
main() |
c76e5f3aa5fbca04d7a4844a48b3303bb9999156 | jdalzatec/EulerProject | /Problem_8/main.py | 523 | 3.6875 | 4 | import numpy
def function(number, i, len_adjacent):
result = 1
for j in range(len_adjacent):
if j + i < len(number):
result *= int(number[j + i])
else:
return 0
return result
def main():
number = open("data.dat", mode = "r")
number = number.read()
adjacent_numbers = 13
products = []
for i in range(len(number)):
products.append(function(number, i, adjacent_numbers))
print(max(products))
if __name__ == '__main__':
main() |
4e5e21db55e6653b725c93f9a80ebfa607952ec0 | faraaz-ahmed/Competitive-Coding | /DBS/minimum_sum.py | 643 | 3.546875 | 4 | def round(num):
if num % 2 == 1:
return int((num + 1)/2)
else:
return int(num/2)
def brute_minSum(arr, k):
sum_ = sum(arr)
for i in range(0, k):
sum_ -= round(max(arr))
arr[arr.index(max(arr))] = round(arr[arr.index(max(arr))])
print(arr)
return sum(arr)
# def minSum(arr, k):
# x = list(arr).sort(reverse = True)
# my_dict = {}
# for i in range(0, len(arr)):
# my_dict[i] = arr[i]
# max_1 = x[0]
# max_2 = x[1]
# for i in range(0, len(arr)):
# test cases
print(brute_minSum([10, 20, 7], 4))
print(brute_minSum([2],1))
print(brute_minSum([2, 3], 1))
|
5526dcd35ecf66533f5414ab4604752ce258adcd | rwwinfree/udemy_deep_learning_A-Z | /Deep_Learning_A_Z/Volume_1-Supervised_Deep_Learning/Part 1 - Artificial Neural Networks (ANN)/Section 4 - Building an ANN/Artificial_Neural_Networks/ann-rw.py | 5,372 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 25 13:26:26 2018
@author: ryanwinfree
"""
# Artificial Neural Network
# Installing Theano
# pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
# Installing Tensorflow
# pip install tensorflow
# Installing Keras
# pip install --upgrade keras
###### Part 1 - Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Churn_Modelling.csv')
X = dataset.iloc[:, 3:13].values
y = dataset.iloc[:, 13].values
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
# Start with encoding the countries
labelencoder_X_1 = LabelEncoder()
X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])
# Next encode the genders (index 2)
labelencoder_X_2 = LabelEncoder()
X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])
#Now create dummy variables to separate the encoded countries
#this will keep the NN from thinking there is a relation between the countries
#i.e. Spain = 2 and France = 0 but 2 is not > 0 in this case...they are unrelated
onehotencoder = OneHotEncoder(categorical_features = [1])
X = onehotencoder.fit_transform(X).toarray()
#Remove a dummy variable to avoid falling into the "dummy variable trap"
#See http://www.algosome.com/articles/dummy-variable-trap-regression.html as a ref
X = X[:, 1:]
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
# Feature Scaling This is Necessary!!!!
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
###### Part 2 - Now let's make the ANN!
# Importing the Keras libraries and packages
import keras
from keras.models import Sequential
from keras.layers import Dense
# Initialising the ANN
## This is a classifier ANN
classifier = Sequential()
# Adding the input layer and the first hidden layer
## Step 1: Randomly initialize the weights to a value close to 0 but not 0
classifier.add(Dense(units = 6, kernel_initializer='uniform', activation='relu'))
# Add the second idden layer
classifier.add(Dense(units = 6, kernel_initializer='uniform', activation='relu'))
# Adding the output layer
# if more than 1 dependent variable use activation = 'softmax'
classifier.add(Dense(units = 1, kernel_initializer='uniform', activation='sigmoid'))
# Compiling the ANN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Fitting the ANN to the Training Set
classifier.fit(X_train, y_train, batch_size = 10, epochs = 100)
# Part 3 - Making the predictions and evaluating the model
# Predicting the Test set results
y_pred = classifier.predict(X_test)
y_pred = (y_pred > 0.5) #returns true or false based on criteria
#This is removing the probablity value and instead setting the y_prediction
#results to say if > 50% probability then say they will leave. If less then
#return that they stay
""" Homework Assignment Answer:
Predict if the customer with the following information will leave the bank:
Geography: France
Credit Score: 600
Gender: Male
Age: 40 years old
Tenure: 3 years
Balance: $60000
Number of Products: 2
Does this customer have a credit card ? Yes
Is this customer an Active Member: Yes
Estimated Salary: $50000
"""
# Adding the customer information as a 2d array and adding it already encoded
##new_prediction = classifier.predict(np.array([[0, 0, 600, 1, 40, 3, 60000, 2, 1, 1, 50000]]))
# Now we have to scale our data
new_prediction = classifier.predict(sc.transform(np.array([[0.0, 0, 600, 1, 40, 3, 60000, 2, 1, 1, 50000]])))
new_prediction = (new_prediction > 0.5) #returns true or false based on criteria
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
"""
#### Homework Assignment: Ryan W. Attempt...all wrong :(
# Importing the dataset
dataset = pd.read_csv('test-data.csv')
x_example = dataset.iloc[:, 3:13].values
y_example = dataset.iloc[:, 13].values
# Encoding categorical data
# Start with encoding the countries
labelencoder_x_example_1 = LabelEncoder()
x_example[:, 1] = labelencoder_x_example_1.fit_transform(x_example[:, 1])
# Next encode the genders (index 2)
labelencoder_x_example_2 = LabelEncoder()
x_example[:, 2] = labelencoder_x_example_2.fit_transform(x_example[:, 2])
#Now create dummy variables to separate the encoded countries
#this will keep the NN from thinking there is a relation between the countries
#i.e. Spain = 2 and France = 0 but 2 is not > 0 in this case...they are unrelated
onehotencoder = OneHotEncoder(categorical_features = [1])
x_example = onehotencoder.fit_transform(x_example).toarray()
#Remove a dummy variable to avoid falling into the "dummy variable trap"
#See http://www.algosome.com/articles/dummy-variable-trap-regression.html as a ref
x_example = x_example[:, 1:]
"""
### Part 4 - Evaluating, Improving and Tuning the ANN
# Evaluating the ANN
##Need to combine keras and scikit together for this part
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score
# Improving the ANN
# Tuning the ANN
|
cc70946e288aef2c09fe0a9b56bc4f38b88a2069 | jeremie1207/coffee_machine_python_procedural | /main.py | 5,291 | 4.15625 | 4 | MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"Money": 0,
}
# TO DO: 1 Prompt user by asking
coffee = True
while coffee:
order = input('What would you like? (espresso/latte/cappuccino): ')
# TO DO: 4 Check resources sufficient
if order in MENU.keys():
coffee = MENU[order]
if coffee['ingredients']['water'] > resources['water']:
print('Sorry there is not enough water.')
if order != 'espresso':
if coffee['ingredients']['milk'] > resources['milk']:
print('Sorry there is not enough milk.')
if coffee['ingredients']['coffee'] > resources['coffee']:
print('Sorry there is not enough coffee.')
if order == 'espresso':
if resources['water'] >= MENU[order]['ingredients']['water'] and resources["coffee"] >= MENU[order]['ingredients']['coffee']:
print('Please insert coins : ')
penny = int(input('penny : '))
nickel = int(input('nickel : '))
dime = int(input('dime : '))
quarter = int(input('quarter : '))
clientMoney = round(((penny * 0.01) + (dime * 0.10) + (nickel * 0.05) + (quarter * 0.25)), 2)
if clientMoney < MENU[order]['cost']:
print("Sorry that's not enough money. Money refunded.")
else:
if clientMoney == MENU[order]['cost']:
pass
else:
print("Here is {:.2} dollars in change".format(clientMoney - MENU[order]['cost']))
clientMoney = MENU[order]['cost']
resources['Money'] += clientMoney
resources['water'] -= MENU[order]['ingredients']['water']
resources["coffee"] -= MENU[order]['ingredients']['coffee']
print('Here is your espresso. Enjoy!')
elif order == 'latte':
if resources['water'] >= MENU[order]['ingredients']['water'] and resources["milk"] >= MENU[order]['ingredients']['milk'] and resources["coffee"] >= MENU[order]['ingredients']['coffee']:
print('Please insert coins : ')
penny = int(input('penny : '))
nickel = int(input('nickel : '))
dime = int(input('dime : '))
quarter = int(input('quarter : '))
clientMoney = round(((penny * 0.01) + (dime * 0.10) + (nickel * 0.05) + (quarter * 0.25)), 2)
if clientMoney < MENU[order]['cost']:
print("Sorry that's not enough money. Money refunded.")
else:
if clientMoney == MENU[order]['cost']:
pass
else:
print("Here is {:.2} dollars in change".format(clientMoney - MENU[order]['cost']))
clientMoney = MENU[order]['cost']
resources['Money'] += clientMoney
resources['water'] -= MENU[order]['ingredients']['water']
resources["milk"] -= MENU[order]['ingredients']['milk']
resources["coffee"] -= MENU[order]['ingredients']['coffee']
print('“Here is your latte. Enjoy!')
elif order == 'cappuccino':
if resources['water'] >= MENU[order]['ingredients']['water'] and resources["milk"] >= MENU[order]['ingredients']['milk'] and resources["coffee"] >= MENU[order]['ingredients']['coffee']:
print('Please insert coins : ')
penny = int(input('penny : '))
nickel = int(input('nickel : '))
dime = int(input('dime : '))
quarter = int(input('quarter : '))
clientMoney = round(((penny * 0.01) + (dime * 0.10) + (nickel * 0.05) + (quarter * 0.25)), 2)
if clientMoney < MENU[order]['cost']:
print("Sorry that's not enough money. Money refunded.")
else:
if clientMoney == MENU[order]['cost']:
pass
else:
print("Here is {:.2} dollars in change".format(clientMoney - MENU[order]['cost']))
clientMoney = MENU[order]['cost']
resources['Money'] += clientMoney
resources['water'] -= MENU[order]['ingredients']['water']
resources["milk"] -= MENU[order]['ingredients']['milk']
resources["coffee"] -= MENU[order]['ingredients']['coffee']
print('“Here is your cappuccino. Enjoy!')
# TO DO: 2 Turn off
elif order == 'off':
print('machine is turning off')
coffee = False
# TO DO: 3 Print report
elif order == 'report':
for (key, value) in resources.items():
print(key + ' : ' + str(value))
|
f9d978e5e18f5dada8acdce5f2d46650dc843c3c | flerdacodeu/CodeU-2018-Group8 | /aliiae/assignment3/tests_trie.py | 1,088 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from trie import Trie
class TestTrie(unittest.TestCase):
def setUp(self):
self.word_list = 'CAR, CARD, CART, CAT'.lower().split(', ')
self.dictionary = Trie(self.word_list)
def test_trie_empty_word(self):
self.assertFalse(self.dictionary.is_word([]))
def test_trie_node_is_word(self):
for word in self.word_list:
self.assertTrue(self.dictionary.is_word(word))
def test_trie_node_is_not_word(self):
for non_word in ['c', 'ca', 'cards']:
self.assertFalse(self.dictionary.is_word(non_word))
def test_trie_prefix_is_prefix(self):
for prefix in 'C, CA, CAR, CARD, CART, CAT'.lower().split(', '):
self.assertTrue(self.dictionary.is_prefix(prefix))
def test_trie_word_is_prefix(self):
for word in self.word_list:
self.assertTrue(self.dictionary.is_prefix(word))
def test_trie_print(self):
self.assertEqual('c', str(self.dictionary))
if __name__ == '__main__':
unittest.main()
|
3e12235cd20dfbfbc25f8f5505c87793a71f51af | flerdacodeu/CodeU-2018-Group8 | /ibalazevic/assignment3/q1.py | 6,395 | 4.25 | 4 | from collections import defaultdict
import unittest
def find_valid_words(grid, prefix_dict):
"""
A method that finds all the valid words from a
dictionary in a grid of letters. The assumption
is that all the letters in the grid are lowercase.
- grid - list of lists, a 2D grid of characters
- prefix_dict - dict, tree-like dictionary in
which the keys are the prefixes
and values the following letters
for each of the prefix in its
corresponding valid word
Returns: a set of all the valid words found in
the grid.
"""
valid_words = set()
shifts = ((1, 1), (0, 1), (1, 0), (-1, -1),
(-1, 0), (0, -1), (1, -1), (-1, 1))
for posx in range(len(grid)):
for posy in range(len(grid[0])):
visited_positions = set()
word_list = []
curr_word = ""
pos = (posx, posy)
_search_words(grid, prefix_dict, pos, shifts, curr_word,
valid_words, visited_positions, word_list)
return valid_words
def _search_words(grid, prefix_dict, pos, shifts, curr_word,
valid_words, visited_positions, word_list):
"""
A recursive helper method to find all the valid words
from a dictionary in a grid of letters.
- grid - list of lists, a 2D grid of characters
- prefix_dict - dict, tree-like dictionary in
which the keys are the prefixes
and values the following letters
for each of the prefix in its
corresponding valid word
- pos - tuple of ints, current position in the grid
- shifts - list of tuples, the 8 possible moves moves
from the current position
- curr_word - str, current string of letters that has
been formed by moving through the grid
- valid_words - list, the list of valid words that have
been found in the grid so far
- visited_positions - set of tuples, keeps track of all
the positions we"ve visited so far
so we don"t end up in the same twice
- word_list - list, keeps track of all the prefixes in the
current recursive call for a given word.
"""
if len(grid) > pos[0] >= 0 and len(grid[0]) > pos[1] >= 0:
curr_word += grid[pos[0]][pos[1]]
if is_prefix(curr_word, prefix_dict):
word_list.append(curr_word)
if pos not in visited_positions:
if is_word(curr_word, prefix_dict):
valid_words.add(curr_word)
visited_positions.add(pos)
for shift in shifts:
_search_words(grid, prefix_dict, (pos[0]+shift[0], pos[1]+shift[1]),
shifts, curr_word, valid_words, visited_positions, word_list)
visited_positions.remove(pos)
if prefix_dict[curr_word] == set([]) or prefix_dict[curr_word] == set(["END"]):
del prefix_dict[curr_word]
prefix_dict[curr_word[:-1]].remove(curr_word[-1])
word_list.pop()
def is_word(word, prefix_dict):
"""
A method that checks whether a given string
is present in the dictionary of words.
- word - str, current string of letters
- prefix_dict - dict, tree-like dictionary in
which the keys are the prefixes
and values the following letters
for each of the prefix in its
corresponding valid word
Returns: True if a word is valid, False otherwise.
"""
return word in prefix_dict and "END" in prefix_dict[word]
def is_prefix(prefix, prefix_dict):
"""
A method that checks whether a given string
is a valid prefix for any of the words.
- prefix - str, current string of letters
- prefix_dict - dict, tree-like dictionary in
which the keys are the prefixes
and values the following letters
for each of the prefix in its
corresponding valid word
Returns: True if a prefix is valid, False otherwise.
"""
return prefix in prefix_dict
def get_prefix_tree(word_dict):
"""
A method that creates the prefix tree for all the
words in the word_dict.
- word_dict - set, contains all the valid words
Returns: dict, tree-like dictionary in
which the keys are the prefixes
and values the following letters
for each of the prefix in its
corresponding valid word
"""
prefix_dict = defaultdict(set)
for word in word_dict:
for cidx in range(len(word)):
prefix_dict[word[:cidx]].add(word[cidx])
prefix_dict[word].add("END")
return prefix_dict
class WordSearchTest(unittest.TestCase):
def test_base(self):
word_dict = set(["car", "card", "cart", "cat", "cat"])
grid = [["a", "a", "r"], ["t", "c", "d"]]
prefix_dict = get_prefix_tree(word_dict)
self.assertEqual(find_valid_words(grid, prefix_dict),
set(["car", "card", "cat"]))
def test_empty(self):
word_dict = set([])
grid = [[]]
prefix_dict = get_prefix_tree(word_dict)
self.assertEqual(find_valid_words(grid, prefix_dict), set([]))
def test_1D(self):
word_dict = set(["c", "af", "bc", "b"])
grid = [["c", "b", "b", "b", "b", "b", "b", "b", "b", "b", "a", "f"]]
prefix_dict = get_prefix_tree(word_dict)
self.assertEqual(find_valid_words(grid, prefix_dict),
set(["c", "bc", "b", "af"]))
def test_same_cell_twice(self):
word_dict = set(["car", "card", "cart", "cat", "catc"])
grid = [["a", "a", "r"], ["t", "c", "d"]]
prefix_dict = get_prefix_tree(word_dict)
self.assertEqual(find_valid_words(grid, prefix_dict),
set(["car", "card", "cat"]))
if __name__ == "__main__":
unittest.main()
|
d8931aab5a51da776af9af705b12e6f3d90c175a | flerdacodeu/CodeU-2018-Group8 | /group/assignment6/parking_lot.py | 7,807 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""Computes a sequence of moves from the start state to the target state.
Uses:
- Data structure which represents the start and target states which
support validation and swapping functionality (see class ParkingState);
- Representation of the sequence of moves (List[MoveType]).
Computes:
1) Given target state, computes the shortest sequence of moves to obtain it.
2) Given target state and set of constraints, computes a sequence of moves
which are inline with the given constraints.
3) Given target state, computes all the possible sequence of moves that lead
from the start to the target state, without ever repeating the same
configuration more than once.
"""
import copy
from typing import List, Set, Dict
from parking_state import ParkingState, CarType, MoveType
class ParkingLot:
"""Implements a ParkingLot of N slots and N-1 cars in it.
Each instance stores the current state (see class ParkingState)
as well as a set of constraints, where a constraint is indicating
that a certain parking place is reserved only for certain cars.
Attributes:
start: Ordered list of cars/empty slot.
empty: Object representing the empty slot, used in start.
constraints: A map of <position, allowed cars for the position>.
Raises:
TypeError, ValueError: See input validation in the ParkingState class.
"""
def __init__(self, start: List[CarType], empty: CarType = 0,
constraints: Dict[int, Set[CarType]] = None):
self.state = ParkingState(start, empty)
if constraints is not None:
self._validate_constraints(constraints)
self.constraints = constraints
self._seen_states = set()
def __len__(self):
return len(self.state)
def get_moves(self, target_state: List[CarType],
retain_state: bool = False) -> List[MoveType]:
"""Computes a sequence of moves from the start state to the target one.
Unless deselected, self.state is updated as the moves are generated,
and finally set to target_state.
Args:
target_state: Targeted state (arrangement of cars).
retain_state: Retains self.state unchanged if True,
updates it as moves are generated if False.
Returns:
List of car moves (car, position) where car is any CarType object,
and the latter is the position to which car should be moved.
"""
state, target_state = self._prepare_states(retain_state, target_state)
return next(state.generate_all_paths([], target_state,
self._find_diff(target_state),
self._seen_states,
self.constraints),
None)
def _prepare_states(self, retain_state, target_state):
"""Creates and validates the current and target ParkingState objects."""
target_state = ParkingState(target_state, self.state.symbol_empty)
self._validate_two_states(target_state)
self._validate_feasibility(target_state)
state = self.state if not retain_state else copy.deepcopy(self.state)
return state, target_state
def get_all_paths(self, target_state, retain_state=False):
"""Computes all possible paths leading from the state to the target state.
It does not have a single sequence that has the same parking lot
configuration (positions of cars in the parking lot) more than once,
however, different paths can share the same state.
Args:
target_state: Targeted state (arrangement of cars).
retain_state: Retains self.state unchanged if True,
updates it as moves are generated if False.
Returns:
A list of all possible paths leading from the start state to the
target state, sorted by length (shortest first).
"""
state, target_state = self._prepare_states(retain_state, target_state)
return sorted(
state.generate_all_paths([], target_state,
self._find_diff(target_state),
self._seen_states, self.constraints),
key=lambda path: len(path))
def _validate_constraints(self, constraints: Dict[int, Set[CarType]]):
"""Validates if constraints are applicable to the input.
The given conditions:
1) must be dictionary of < int, set > pairs;
2) each key must be in [0, N); and
3) each element in the set must be element of self.cars.
Note: "Position not in constraints", implies any car can park at it.
As any parking slot can be free, it adds the empty slot to the set.
Raises:
TypeError: Property 1 violated.
ValueError: Property 2 or 3 violated.
"""
if not isinstance(constraints, dict):
raise TypeError(f"Unsupported type: {type(constraints)}. "
f"Expected dictionary.")
for position, cars in constraints.items():
if not isinstance(position, int):
raise TypeError(f"Unsupported position type: {type(position)}. "
f"Expected int.")
if not isinstance(cars, set):
raise TypeError(f"Unsupported cars type: {type(cars)}. "
f"Expected set.")
if not 0 <= position <= len(self):
raise ValueError(
f"Out of bounds. {position} not in [0, {len(self)}]")
if len(cars & set(self.state.cars)) != len(cars):
raise ValueError("Unrecognized vehicle(s).")
constraints[position].add(self.state.symbol_empty)
def _validate_two_states(self, state: "ParkingState"):
"""Validates if the current state can be led to the target state."""
if len(self.state.cars) != len(state):
raise ValueError(
f"States' lengths mismatch, {len(self.state)} != {len(state)}")
if self.state.symbol_empty != state.symbol_empty:
raise ValueError(
f"The two states have different empty slot symbols: "
f"{self.state.symbol_empty} & {state.symbol_empty}.")
if set(self.state.cars) != set(state.cars):
raise ValueError(
"The two sets of cars are different. Cannot find moves.")
def _validate_feasibility(self, target_state: ParkingState):
"""Checks for contradiction between constraints and the target state.
Args:
target_state: A ParkingState instance.
Raises:
ValueError: If there is a contradiction between constraints
and target state.
"""
if self.constraints is None:
return
for pos, car in enumerate(target_state.cars):
if pos in self.constraints and car not in self.constraints[pos]:
raise ValueError(
"Found contradiction between constraints and target state.")
def _find_diff(self, state: "ParkingState") -> Set[CarType]:
"""Returns elements of current state that differ from those of state."""
self._validate_two_states(state)
return {car for car, end_car in zip(self.state.cars, state.cars)
if car != end_car and car != self.state.symbol_empty}
def update_constraints(self, constraints: Dict[int, Set[CarType]]):
"""Adds/updates constraints to the current parking state."""
if constraints is not None:
self._validate_constraints(constraints)
self.constraints = constraints
|
69f491abbf9b757d6dc5b7fe6d5e7cd925785389 | flerdacodeu/CodeU-2018-Group8 | /cliodhnaharrison/assignment1/question1.py | 896 | 4.25 | 4 | #Using Python 3
import string
#Input through command line
string_one = input()
string_two = input()
def anagram_finder(string_one, string_two, case_sensitive=False):
anagram = True
if len(string_one) != len(string_two):
return False
#Gets a list of ascii characters
alphabet = list(string.printable)
if not case_sensitive:
#Case Insensitive so making sure only lowercase letters in strings
string_one = string_one.lower()
string_two = string_two.lower()
for char in alphabet:
if anagram:
#Counts occurences of a character in both strings
#If there is a difference it returns False
if string_one.count(char) != string_two.count(char):
anagram = False
else:
return anagram
return anagram
#My Testing
#print (anagram_finder(string_one, string_two))
|
c425fd70a75756fa84add2f21f7593b8e91b1203 | flerdacodeu/CodeU-2018-Group8 | /aliiae/assignment3/trie.py | 2,519 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Optional follow-up:
Implement a dictionary class that can be constructed from a list of words.
A dictionary class with these two methods:
* isWord(string): Returns whether the given string is a valid word.
* isPrefix(string): Returns whether the given string is a prefix of at least one
word in the dictionary.
Assumptions:
The dictionary is a trie implemented as node objects with children stored in
a hashmap.
"""
from collections import defaultdict
class Trie:
def __init__(self, words=None):
"""
Implement a trie node that has trie children and bool if it ends a word.
Args:
words: A list of words that can be inserted into the trie.
"""
self.children = defaultdict(Trie)
self._is_word_end = False
if words:
self.insert_words(words)
def __str__(self):
return ' '.join(self.children)
def insert_words(self, words):
"""
Insert a list of words into the trie.
Args:
words: A list of words to be inserted into the trie.
Returns: None
"""
for word in words:
self.insert_word(word)
def insert_word(self, word):
"""
Insert a word into the trie.
Args:
word: A word to be inserted into the trie.
Returns: None
"""
current = self
for letter in word:
current = current.children[letter]
current._is_word_end = True
def is_word(self, word):
"""
Return whether the given string is a valid word.
Args:
word: The word to look for.
Returns: True if the word is found, else False.
"""
current = self
for letter in word:
if letter in current.children:
current = current.children[letter]
else:
return False
else:
return current._is_word_end
def is_prefix(self, prefix):
"""
Return whether the given string is a prefix of at least one word.
Args:
prefix: Prefix to search for in the trie.
Returns: True if the string is a prefix of a word, else False.
"""
current = self
for letter in prefix:
if letter in current.children:
current = current.children[letter]
else:
return False
else:
return True
|
ea2263a284564b3074b19aca5ce03c36909f1fda | flerdacodeu/CodeU-2018-Group8 | /TatjanaCh/assignment4/utils.py | 3,632 | 4.15625 | 4 | class DisjointSet:
"""
Implements a class DisjointSet, which represents a set of disjoint sets.
Two sets are disjoint if they have no elements in common.
It uses dict to speed up finding an element of the subsets.
Attributes:
disjointSets List of the disjoint sets.
element_set_mapping Dictionary of <element, index of subset> pairs.
"""
def __init__(self, elements):
"""
Initially create separate set for each element.
The dict 'element_set_mapping' will allow for speeding up find.
:param elements: [list of int]
:return: None
"""
self.disjointSets = []
self.element_set_mapping = {}
for ind, e in enumerate(elements):
self.disjointSets.append(self.make_set(e))
self.element_set_mapping[e] = ind
@staticmethod
def make_set(x):
"""
Create a new set with x (the representative of the set is x)
:param x: [int]
:return: [set]
"""
return set([x])
def find(self, e):
"""
Find the index of the set which contains the element x.
:param e: [int] the element to be found in any subset
:return: [int] the index of the set within the attribute disjointSets [list]
"""
return self.element_set_mapping[e] if e in self.element_set_mapping else None
def union(self, x, y):
"""
Merge the set to which x and y belong
:param x: [int] element
:param y: [int] element
:return: None
"""
x_set = self.find(x)
y_set = self.find(y)
if x_set is not None and y_set is not None and x_set != y_set:
# update element_set_mapping
for e in self.disjointSets[y_set]:
self.element_set_mapping[e] = x_set
# extend x_set
self.disjointSets[x_set].update(self.disjointSets[y_set])
# delete y_set
self.disjointSets[y_set] = None
def filter(self):
"""
Remove None elements and update element_set_mapping accordingly.
:return: None
"""
decrement, to_del = 0, []
for i, s in enumerate(self.disjointSets):
if s is None:
decrement += 1
to_del.append(i)
elif decrement > 0:
for e in s:
self.element_set_mapping[e] -= decrement
for index in sorted(to_del, reverse=True):
self.disjointSets.pop(index)
def __len__(self):
return sum([1 if s is not None else 0 for s in self.disjointSets])
def get(self):
return self.disjointSets
def neighbors(x, y, width, height):
"""
Checks if x and y are neighbors in a grid of given width.
Two positions x and y are neighbors if they are adjacent horizontally or
vertically, but not diagonally. Assumes given position is not neighbor to itself.
Returns False if x or y are out of the bounds of the grid.
:param x: [int] position identifier
:param y: [int] position identifier
:param width: [int] width of the grid
:param height: [int] height of the grid (used for checking the arg values)
:return: [bool] True iff x and y are neighbours, False otherwise
"""
if width <= 0 or height <= 0:
raise ValueError
if not 0 <= x < width * height or not 0 <= y < width * height:
return False
if (x % width == y % width and abs(x - y) == width) or \
(x // width == y // width and abs(x - y) == 1):
return True
else:
return False
|
6ddf930b444a33d37a4cc79308577c45cf45af96 | Saraabd7/Python-Eng-54 | /For_loops_107.py | 1,117 | 4.21875 | 4 | # For loops
# Syntax
# for item in iterable: mean something you can go over for e.g: list
# block of code:
import time
cool_cars = ['Skoda felicia fun', 'Fiat abarth the old one', 'toyota corola, Fiat panda 4x4', 'Fiat Multipla']
for car in cool_cars:
print(car)
for lunch_time in cool_cars:
print(car)
time.sleep(1)
print('1 -', cool_cars[0])
Count = 0 # first number being used ( to do the count for points.
for car in cool_cars:
print(Count + 1, '-', car)
Count += 1
# For Loop for dictionaries:
boris_dict = {
'name': 'boris',
'l_name': 'Johnson',
'phone': '0784171157',
'address': '10 downing street'}
for item in boris_dict:
print(item)
# this item is the key so we change it to key:
for key in boris_dict:
print(key)
# I want each individual values
# for this i need, dictionary + key
print(boris_dict[key])
print(boris_dict['phone'])
# for key in boris_dict:
# print(boris_dict['phone'])
# print(boris_dict['name'])
for value in boris_dict.values():
print(value)
print('Name:', 'Boris Johnson')
print('phone:', '0784171157') |
5cd8799dc1b3ca6b5458338a02a4b118e959ec85 | Saraabd7/Python-Eng-54 | /103_integers.py | 416 | 3.984375 | 4 | # Numerical Types
# Integers and Float, Complex, Numbers , big ints
# Integers
# Full Numbers
print(10)
print(type(10))
print(type('10'))
#Float
#decimal numbers
print(10.0)
print(type(10.0))
#They can be used together
print(10/3)
print(10 * 10))
#Add
print(3 + 4)
# Subtract
print (3 - 4)
#divide
print (10/2)
#Multiple
print(10*2)
Something with the thing % (Module)
They give us the reminder
print (10%3) |
2aabcb1ef493e647d36f9ee49d7ea3785fafcedb | NaveedShaikh78/system-equip | /treadexample.py | 315 | 3.9375 | 4 | import thread
import time
# Define a function for the thread
def print_time():
time.sleep(5)
print "%s: %s" % ( time.ctime(time.time()) )
i=0;
while i < 3:
# Create two threads as follows
try:
thread.start_new_thread( print_time )
print "end thread"
except:
print "Error: unable to start thread"
i=i+1 |
000bb0f9ab4b34e8278d5df3c797d2723028066b | nifemiojo/Algorithms | /Arrays/NewYearChaos/src/test.py | 941 | 3.65625 | 4 | import unittest
from .solution_inefficient import minimumBribes
class TestMinimumBribes(unittest.TestCase):
def test_one_bribe(self):
q = [1, 2, 4, 3]
number_of_bribes = minimumBribes(q)
self.assertEqual(number_of_bribes, 1)
def test_two_single_bribes(self):
q = [1, 2, 4, 3, 6, 5]
number_of_bribes = minimumBribes(q)
self.assertEqual(number_of_bribes, 2)
def test_bribed_bribes(self):
q = [1, 4, 3, 2]
number_of_bribes = minimumBribes(q)
self.assertEqual(number_of_bribes, 3)
def test_bribed_bribes_with_other_bribes(self):
q = [1, 4, 3, 5, 2]
number_of_bribes = minimumBribes(q)
self.assertEqual(number_of_bribes, 4)
def test_chaotic(self):
q = [4, 1, 2, 3]
number_of_bribes = minimumBribes(q)
self.assertEqual(number_of_bribes, "Too chaotic")
if __name__ == "__main__":
unittest.main()
|
85033f9d0938a1a5af4ae5c241fdf9b530565471 | nifemiojo/Algorithms | /dismath/recursion/coin_problem/change.py | 436 | 3.734375 | 4 | def change(amount):
assert (1000 >= amount >= 24)
if amount == 24:
return [5, 5, 7, 7]
elif amount == 25:
return [5, 5, 5, 5, 5]
elif amount == 26:
return [7, 7, 7, 5]
elif amount == 27:
return [5, 5, 5, 5, 7]
elif amount == 28:
return [7, 7, 7, 7]
coins = change(amount - 5)
coins.append(5)
return coins
for n in range(24, 1001):
print(sum(change(n))) |
949e1de8aaf4bc99fc04ac991c936d9455640730 | monlie/LeetCode | /263.py | 354 | 3.546875 | 4 | class Solution:
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
d = [2, 3, 5]
while 1:
f = num
for i in d:
if num % i == 0:
num = num//i
if f == num:
break
return num == 1
|
3eaaaad898909b745a4e4d1c986e6ba5c4fbe049 | monlie/LeetCode | /58.py | 324 | 3.53125 | 4 | class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
length = 0
for char in s[::-1]:
if char == ' ' and length:
break
if char != ' ':
length += 1
return length
|
c5c272c639aef7f306df597af4a1d405d4464108 | monlie/LeetCode | /43.py | 328 | 3.53125 | 4 | class Solution:
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
s = 0
for n, i in enumerate(num1[::-1]):
for m, j in enumerate(num2[::-1]):
s += int(i)*10**n * int(j)*10**m
return str(s)
|
3e3961e8cadc01e0b73ed1e5d1846538d4a9ef36 | monlie/LeetCode | /46.py | 622 | 3.71875 | 4 | from copy import deepcopy
class Solution:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def permute_iter(n):
if n:
last = permute_iter(n-1)
p = nums[n]
new = []
for item in last:
for i in range(n+1):
d = deepcopy(item)
d.insert(i, p)
new.append(d)
return new
return [[nums[0]]]
return permute_iter(len(nums)-1) |
2d56e3b4cd768ff456a090bd782bd4989c2e3c86 | techacademybd/python-automate-sc | /11.py | 1,673 | 3.5 | 4 | import imaplib
import email
from collections import defaultdict
'''Read the last few emails and display the message content'''
src = "techacademy1234@gmail.com"
password = "t3chn0tt@b0t5"
count = 2
book = {}
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(src, password)
mail.list()
mail.select("inbox")
# convert raw message block to READABLE text
def get_first_text_block(email_message_instance):
maintype = email_message_instance.get_content_maintype()
if maintype == 'multipart':
for part in email_message_instance.get_payload():
if part.get_content_maintype() == 'text':
return part.get_payload()
elif maintype == 'text':
return email_message_instance.get_payload()
# read emails from inbox
def get_email(counter): # counter: read how many emails?
result, data = mail.search(None, "ALL")
# data is a list
ids = data[0]
# ids is a space separated string
id_list = ids.split()
# get the latest email in the inbox stack
counter = -counter
latest_email_id = id_list[counter]
# get raw email
_, data = mail.fetch(latest_email_id, "(RFC822)")
raw_email = data[0][1]
decoded_raw_email = raw_email.decode()
email_message = email.message_from_string(decoded_raw_email)
# convert raw email to text
message = get_first_text_block(email_message)
# print(str(email.utils.parseaddr(email_message['From'])[0]))
name = str(email.utils.parseaddr(email_message['From'])[0])
return name, message
for i in range(count):
i+=1
name, msg = get_email(i)
book[name] = msg
for name, message in book.items():
print(name, message)
print("Done!")
|
f34afbf2104adb8622f09489a8b4bc9b4c9a6d77 | dmonzonis/advent-of-code-2017 | /day7/day7.py | 2,246 | 3.84375 | 4 | from collections import Counter
def find_root_node(parent_tree):
node = list(parent_tree.keys())[0] # Get a starting node
# Go backwards until we find the root
while node in parent_tree:
node = parent_tree[node]
return node
def generate_trees(inp):
"""
Generates a bottom-up parent tree for quickly finding the root of the graph, and a
regular top-down tree with weights
"""
parent_tree = {} # Keeps track of node's parent if it has any
tree = {}
for line in inp.splitlines():
node = line.split()[0]
weight = line.split()[1].strip('()')
tree[node] = {'weight': int(weight)}
if '->' in line:
children = [s.strip() for s in line.split('->')[1].split(',')]
tree[node].update({'children': children})
for child in children:
parent_tree[child] = node
return tree, parent_tree
def find_weight_unbalance(tree, node):
"""
Given a node and the graph tree, recursively finds an unbalance in its sublevels and returns the
unbalance and True if the unbalance was found (assumes there's only one node with an unbalanced
weight), or the total weight of the node and all of its subnodes and False if no unbalance was
found
"""
if 'children' not in tree[node]:
return tree[node]['weight'], False
weights = []
for child in tree[node]['children']:
weight, found = find_weight_unbalance(tree, child)
if found:
return weight, found
weights.append(weight)
# Check if there's an unbalance
count = Counter(weights).most_common()
if len(count) > 1:
# Unbalance found
diff = count[0][0] - count[1][0]
unbalanced = tree[node]['children'][weights.index(count[1][0])]
return tree[unbalanced]['weight'] + diff, True # Set found flag to True
return sum(weights) + tree[node]['weight'], False
def main():
with open("input") as f:
inp = f.read()
tree, parent_tree = generate_trees(inp)
root = find_root_node(parent_tree)
print("Part 1:", root)
unbalance, _ = find_weight_unbalance(tree, root)
print("Part 2:", unbalance)
if __name__ == "__main__":
main()
|
933c9d74c3dee9ac64fefe649af9aba3dcffce02 | dmonzonis/advent-of-code-2017 | /day24/day24.py | 2,809 | 4.34375 | 4 | class Bridge:
"""Represents a bridge of magnetic pieces.
Holds information about available pieces to construct the bridge, current pieces used
in the bridge and the available port of the last piece in the bridge."""
def __init__(self, available, bridge=[], port=0):
"""Initialize bridge variables."""
self.available = available
self.bridge = bridge
self.port = port
def strength(self):
"""Return the strength of the current bridge."""
return sum([sum([port for port in piece]) for piece in self.bridge])
def fitting_pieces(self):
"""Return a list of pieces that can be used to extend the current bridge."""
return [piece for piece in self.available if self.port in piece]
def add_piece(self, piece):
"""Return a new bridge with the piece added to it and removed from the available list."""
new_bridge = self.bridge + [piece]
# The new port is the unmatched port in the added piece
new_port = piece[0] if piece[1] == self.port else piece[1]
new_available = self.available[:]
new_available.remove(piece)
return Bridge(new_available, new_bridge, new_port)
def find_strongest(pieces):
"""Find strongest bridge constructable with a given list of pieces."""
max_strength = 0
queue = [Bridge(pieces)]
while queue:
bridge = queue.pop(0)
fitting = bridge.fitting_pieces()
if not fitting:
strength = bridge.strength()
if strength > max_strength:
max_strength = strength
continue
for piece in fitting:
queue.append(bridge.add_piece(piece))
return max_strength
def find_strongest_longest(pieces):
"""Find strongest bridge from the longest bridges constructable with a list of pieces."""
max_strength = max_length = 0
queue = [Bridge(pieces)]
while queue:
bridge = queue.pop(0)
fitting = bridge.fitting_pieces()
if not fitting:
length = len(bridge.bridge)
if length > max_length:
max_length = length
max_strength = bridge.strength()
elif length == max_length:
strength = bridge.strength()
if strength > max_strength:
max_strength = strength
max_length = length
continue
for piece in fitting:
queue.append(bridge.add_piece(piece))
return max_strength
def main():
with open("input") as f:
pieces = [[int(x), int(y)] for x, y in [p.split('/') for p in f.read().splitlines()]]
# print("Part 1:", find_strongest(pieces))
print("Part 2:", find_strongest_longest(pieces))
if __name__ == "__main__":
main()
|
a68e2b0be94ba93bb4e9d123c55af80297ddc5d6 | dmonzonis/advent-of-code-2017 | /day19/day19.py | 1,866 | 4.34375 | 4 | def step(pos, direction):
"""Take a step in a given direction and return the new position."""
return [sum(x) for x in zip(pos, direction)]
def turn_left(direction):
"""Return a new direction resulting from turning 90 degrees left."""
return (direction[1], -direction[0])
def turn_right(direction):
"""Return a new direction resulting from turning 90 degrees right."""
return (-direction[1], direction[0])
def get_tile(roadmap, pos):
"""With a position in the form (x, y), return the tile in the roadmap corresponding to it."""
x, y = pos
return roadmap[y][x]
def follow_roadmap(roadmap):
"""Follow the roadmap and return the list of characters encountered and steps taken."""
direction = (0, 1) # Start going down
valid_tiles = ['-', '|', '+'] # Valid road tiles
collected = []
steps = 1
pos = (roadmap[0].index('|'), 0) # Initial position in the form (x, y)
while True:
new_pos = step(pos, direction)
tile = get_tile(roadmap, new_pos)
if tile == ' ':
# Look for a new direction left or right
if get_tile(roadmap, step(pos, turn_left(direction))) != ' ':
direction = turn_left(direction)
continue
elif get_tile(roadmap, step(pos, turn_right(direction))) != ' ':
direction = turn_right(direction)
continue
else:
# We got to the end of the road
return collected, steps
elif tile not in valid_tiles:
collected.append(tile)
pos = new_pos
steps += 1
def main():
with open("input") as f:
roadmap = f.read().split('\n')
collected, steps = follow_roadmap(roadmap)
print("Part 1:", ''.join(collected))
print("Part 2:", steps)
if __name__ == "__main__":
main()
|
00ad262b85b87c8740f09b5e71575ef496f03e49 | mahidhar93988/python-basics-nd-self | /bulb.py | 581 | 3.703125 | 4 | n = int(input())
list1 = []
for i in range(n):
element = input()
list1.append(element)
bulb = "OFF"
Count = 0
for i in range(n):
if(list1[i] == "ON"):
if(bulb == "OFF"):
bulb = "ON"
Count += 1
else:
continue
elif(list1[i] == "OFF"):
if(bulb == "ON"):
bulb = "OFF"
else:
continue
# toggle condition
else:
if(bulb == "OFF"):
bulb = "ON"
Count += 1
else:
bulb = "OFF"
print(Count)
|
34d60c5614f9f11d5b8d7970c33651040ee8ac7b | mahidhar93988/python-basics-nd-self | /implement_quick_sort.py | 1,709 | 3.96875 | 4 | # implement Quick Sort
class QuickSort:
arr = []
def __init__(self, arr):
self.arr = arr
# swap
def swap(self, i, j):
temp = self.arr[i]
self.arr[i] = self.arr[j]
self.arr[j] = temp
# partition
def partition(self, l, h):
pivot = self.arr[l]
i = l
j = h
while i < j:
# [60, 20, 5, 40]
# increment i until we get element greater than pivot
while self.arr[i] <= pivot and l < h:
i = i+1 # 4
# decrement j until we get element less than pivot
while self.arr[j] > pivot and j > l:
j = j - 1
if i < j:
self.swap(i, j)
return j # return the expected position of pivot
# quickSort -> divide and conquer
def quickSort(self, l, h): # 0, 2
if l < h:
p = self.partition(l, h) # 2
self.swap(l, p)
self.quickSort(p+1, h) # quick sort on right sub array
self.quickSort(l, p-1) # quick sort on left sub array
def sort(self, reverse=False):
self.quickSort(0, len(self.arr)-1)
if reverse:
self.arr = self.arr[::-1]
# q = QuickSort([30, 15, 55, 25, 60, 80, 20])
# print(q.arr)
# q.sort()
# print(q.arr)
# 3
# 1 3 -5
# -2 4 1
# n = int(input())
# arr1 = []
# for i in range(n):
# arr1.append(int(input()))
# arr2 = []
# for i in range(n):
# arr2.append(int(input()))
# # ascending Order
# q = QuickSort(arr1)
# q.sort()
# arr1 = q.arr
# print(arr1)
# descending order
q = QuickSort([-2, 4, 1])
q.sort()
arr2 = q.arr
print(arr2)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.