blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0e98f845ba6130c720987557db74c04b639ea339 | ellenne/NaturalProcessesSimulation | /Code/piles.py | 1,530 | 4.09375 | 4 | '''
Suppose you have 10 piles of 10 coins each.
Say now that you are playing the following game. At each turn you pick a coin from each pile and move it in
a randomly selected pile (it can be any of the piles). You can repeat the process an arbitrary amount of times.
If a pile becomes empty, you cannot move a coin back to it. Therefore if there is only one pile left
the game is over.
Can you guess the number of piles that will remain if you are allowed to play an infinite amount of turns?
If not, the program attached "piles.py" is an implementation of this game. You can change the parameter
maxIter which changes the maximal number of turns to get a better understanding of what is actually
happening with the number of piles.
'''
import numpy as np
import random
numberOfPiles = 10
maxIter = 10000000
piles = np.empty(numberOfPiles)
piles.fill(numberOfPiles)
totPiles = np.sum(piles)
numPiles = numberOfPiles
x = 0;
while (x < maxIter and piles.size > 1):
# the function np.nonzero returns the position of the
# elements that are nonzero in an array
# therefore using as argument of a list it gives you only
# those piles that are not empty
piles = piles[np.nonzero(piles)]
for i in np.arange(piles.size):
# takes a token from the first pile available and reassign it randomly to another pile
piles[i] -= 1
num = np.random.randint(piles.size)
piles[num] += 1
numPiles = piles.size
x += 1
print("The number of piles remaining are: ", numPiles) |
fae62ae46755e7aa675c4518aa7f88cf2c46e202 | jacquerie/leetcode | /leetcode/0415_add_strings.py | 674 | 3.734375 | 4 | # -*- coding: utf-8 -*-
import itertools
class Solution:
def addStrings(self, num1, num2):
def toInt(c):
if c is None:
return 0
return int(c)
result = []
carry = 0
for d1, d2 in itertools.zip_longest(reversed(num1), reversed(num2)):
carry, digit = divmod(toInt(d1) + toInt(d2) + carry, 10)
result.append(str(digit))
if carry:
result.append(str(carry))
return "".join(reversed(result))
if __name__ == "__main__":
solution = Solution()
assert "18" == solution.addStrings("9", "9")
assert "28" == solution.addStrings("9", "19")
|
447c6111bbd32af813f75967e86d88ece1e91d71 | gomtinQQ/algorithm-python | /codeUp/codeUpBasic/1559.py | 325 | 3.53125 | 4 | '''
1559 : [기초-함수작성] 함수로 두 정수의 합 리턴하기
int 형 정수 두 개를 입력 받아
두 수를 합한 결과를 출력하시오.
단, 함수형 문제이므로 함수 f()만 작성하여 제출하시오.
'''
def f(x,y):
return x+y
x, y = input().split()
x = int(x)
y = int(y)
print(f(x,y)) |
60ee7c922021ad82392c650099eaa7ed55f54221 | GetulioCastro/codigo_livro_aprenda_python_basico | /13-programacao-orientada-a-objetos/13-programacao-orientada-a-objetos.py | 2,080 | 4.71875 | 5 | # Código utilizado no livro Aprenda Python Básico - Rápido e Fácil de entender, de Felipe Galvão
# Mais informações sobre o livro: http://felipegalvao.com.br/livros
# Capítulo 13: Programação Orientada a Objetos
# Definindo nossa primeira classe
class Usuario:
contador = 0
def __init__(self, nome, email):
self.nome = nome
self.email = email
Usuario.contador += 1
def diga_ola(self):
print("Olá, meu nome é %s e meu email é %s" % (self.nome, self.email))
# Criando o primeiro objeto da classe
usuario1 = Usuario(nome="Felipe", email="contato@felipegalvao.com.br")
usuario1.diga_ola()
print(usuario1.nome)
# Alterando propriedade do objeto
usuario1.nome = "Felipe Galvão"
print(usuario1.nome)
# Funções para alterar, recuperar e deletar uma propriedade
print(hasattr(usuario1, "nome"))
print(hasattr(usuario1, "idade"))
print(getattr(usuario1, "email"))
setattr(usuario1, "nome", "Felipe G.")
setattr(usuario1, "idade", 30)
print(getattr(usuario1, "nome"))
print(getattr(usuario1, "idade"))
delattr(usuario1, "idade")
# print(getattr(usuario1, "idade"))
# Variável de classe - contador
usuario2 = Usuario(nome="Jurema", email="jurema@jurema.com")
print(Usuario.contador)
# Herança - Definição de uma classe estendida a partir de outra classe
class Administrador(Usuario):
def __init__(self, nome, email, chave_de_administrador):
Usuario.__init__(self, nome, email)
self.chave_de_administrador = chave_de_administrador
def poder_administrativo(self):
print("Eu tenho o poder! Minha chave é %s" % self.chave_de_administrador)
usuario_adm = Administrador(nome="Admin", email="admin@admin.com", chave_de_administrador="123456")
usuario_adm.diga_ola()
usuario_adm.poder_administrativo()
# Nova classe, sobrescrevendo o método diga_ola da classe original
class MembroStaff(Usuario):
def __init__(self, nome, email):
Usuario.__init__(self, nome, email)
def diga_ola(self):
print("Olá, meu nome é %s e eu sou membro do Staff. Em que posso ajudar?" % (self.nome))
membro_staff_1 = MembroStaff(nome="Mariazinha", email="maria@zinha.com.br")
membro_staff_1.diga_ola() |
9d873abe33a4701e57ba5c2fb4637546fd9a6d60 | liseyko/CtCI | /leetcode/p0258 - Add Digits.py | 725 | 3.703125 | 4 | class Solution:
# If an integer is like 100a+10b+c, then (100a+10b+c)%9=(a+99a+b+9b+c)%9=(a+b+c)%9
def addDigits(self, num):
if not num: return 0
return num % 9 or 9
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
if num > 9:
return self.addDigits(sum([int(i) for i in str(num)]))
return num
def addDigits(self, num):
while num > 9:
num = sum([int(i) for i in str(num)])
return num
def addDigits(self, num):
while num > 9:
tmp = 0
while num:
tmp += num % 10
num //= 10
num = tmp
return num |
391ea1540ed0bd71e1edfd4c0858c9110c1a796d | jastination/software-engineering-excercise-repository | /seer_python/dp/MaxArithmeticProgression.py | 442 | 3.703125 | 4 | '''
Created on May 20, 2012
@author: Jason Huang
'''
#Given an array of integers A, give an algorithm to find the longest Arithmetic progression in it, i.e find a sequence i1 < i2 < < ik, such that
#A[i1], A[i2], , A[ik] forms an arithmetic progression, and k is the largest possible.
#The sequence S1, S2, , Sk is called an arithmetic progression if
#Sj+1 C Sj is a constant
if __name__ == '__main__':
pass |
eab16b6733c4ae405703473bde9d41672d4b521d | Matt-Robinson-byte/DigitalCrafts-classes | /python102/leetspeak.py | 408 | 3.5625 | 4 | def leetspeak():
phrase = (input("Input to translate: ").upper())
new_phrase = ""
letter = [""]
i = 0
j = 0
while i < len(phrase):
while j < len(letter):
if phrase[i] == letter[j]:
new_phrase.append(number[j])
else:
new_phrase[i] = phrase[i]
j += 1
i += 1
return new_phrase
print(leetspeak()) |
ace985e211c588092e87107c78d376aa9f514b2c | henrany/BCC | /programming languages/EX5/05.py | 1,809 | 4.03125 | 4 | class Animal:
atrb_animal = 0
def __init__(self , nome):
self.nome = nome
def __str__(self):
return self.nome + " eh um animal"
def comer(self):
print(self.nome + ", que eh um animal , esta comendo.")
class Mamifero(Animal):
def __str__(self):
return(self.nome + " eh um mamifero")
def beber_leite(self):
print(self.nome + ", que eh um mamifero , esta bebendoleite.")
class Cao(Mamifero):
def __str__(self):
return self.nome + " eh um cachorro"
def latir(self):
print(self.nome + " esta latindo bem auto.")
def comer(self):
print(self.nome + " late quando come.")
self.latir()
def test():
a1 = Animal("Tigrinho")
a2 = Mamifero("Oncinha")
a3 = Cao("Mameluco")
print(a1) # 1 Algo sera impresso. "Tigrinho eh um animal"
print(a2) # 2 Algo sera impresso. "Oncinha eh um mamifero"
print(a3) # 3 Algo sera impresso. "Mameluco eh um cachorro"
a1.comer () # 4 Algo sera impresso. "Tigrinho, que eh um animal , esta comendo."
a2.beber_leite () # 5 Algo sera impresso. "Oncinha, que eh um mamifero , esta bebendoleite."
a2.comer () # 6 Algo sera impresso. "Oncinha, que eh um animal , esta comendo."
a3.latir () # 7 Algo sera impresso."Mameluco esta latindo bem auto."
a3.beber_leite () # 8 Algo sera impresso. "Mameluco, que eh um mamifero , esta bebendoleite."
a3.comer () # 9 Algo sera impresso. "Mameluco late quando come." e "Mameluco esta latindo bem auto."
# a1.beber_leite () # 10 um erro sera produzido no em temp de execucao
a1 = a3
a1.latir () # 11 Algo sera impresso. "Mameluco esta latindo bem auto." |
95815e138b1b86084e242d9499baef5767a0c655 | CUGshadow/Python-Programming-and-Data-Structures | /Chapter 01/Exercise01_17.py | 364 | 4.125 | 4 | """
(Turtle: draw a line)
Write a program that draws a red line connecting two points (−39, 48)
and (50, −50) and displays the coordinates of the two points
"""
import turtle
turtle.penup()
turtle.goto(-39, 48)
turtle.write('(-39, 48)')
turtle.pendown()
turtle.color('red')
turtle.goto(50, -50)
turtle.color('black')
turtle.write('(50, -50)')
turtle.done()
|
989796f90b0e9c18b7b65b0f5912ec7c3606aa28 | theeric80/LeetCode | /medium/surrounded_regions.py | 2,319 | 3.5625 | 4 |
class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if not board: return
m, n = len(board), len(board[0])
for i in xrange(m):
if board[i][0] == 'O':
self.bfs(board, i, 0)
if board[i][n-1] == 'O':
self.bfs(board, i, n-1)
for j in xrange(n):
if board[0][j] == 'O':
self.bfs(board, 0, j)
if board[m-1][j] == 'O':
self.bfs(board, m-1, j)
for i in xrange(m):
for j in xrange(n):
if board[i][j] == 'O':
board[i][j] = 'X'
if board[i][j] == '1':
board[i][j] = 'O'
def bfs(self, board, i, j):
m, n = len(board), len(board[0])
q = [(i, j)]
board[i][j] = '1'
while q:
i, j = q.pop(0)
adjs = [(i, j-1), (i, j+1), (i-1, j), (i+1, j)]
for x, y in adjs:
if x < 0 or x >= m or y < 0 or y >= n: continue
if board[x][y] == 'O':
board[x][y] = '1'
q.append((x, y))
def main():
board = [
['X', 'X', 'X', 'X'],
['X', 'O', 'O', 'X'],
['X', 'X', 'O', 'X'],
['X', 'O', 'X', 'X']]
Solution().solve(board)
for r in board:
print r
board0 = [
'XOOOOOOOOOOOOOOOOOOO',
'OXOOOOXOOOOOOOOOOOXX',
'OOOOOOOOXOOOOOOOOOOX',
'OOXOOOOOOOOOOOOOOOXO',
'OOOOOXOOOOXOOOOOXOOX',
'XOOOXOOOOOXOXOXOXOXO',
'OOOOXOOXOOOOOXOOXOOO',
'XOOOXXXOXOOOOXXOXOOO',
'OOOOOXXXXOOOOXOOXOOO',
'XOOOOXOOOOOOXXOOXOOX',
'OOOOOOOOOOXOOXOOOXOX',
'OOOOXOXOOXXOOOOOXOOO',
'XXOOOOOXOOOOOOOOOOOO',
'OXOXOOOXOXOOOXOXOXOO',
'OOXOOOOOOOXOOOOOXOXO',
'XXOOOOOOOOXOXXOOOXOO',
'OOXOOOOOOOXOOXOXOXOO',
'OOOXOOOOOXXXOOXOOOXO',
'OOOOOOOOOOOOOOOOOOOO',
'XOOOOXOOOXXOOXOXOXOO']
board = [list(row) for row in board0]
for r in board:
print r
Solution().solve(board)
for r in board:
print r
if __name__ == '__main__':
main()
|
12ea8621138a409842f1418a1535de76e9c66084 | wjsc/python-flask-api-example | /my_math.py | 117 | 3.625 | 4 | sum = lambda x, y: x + y
minus = lambda x, y: x - y
def mult(x, y):
return x*y
def divide(x, y):
return x/y |
55619dd38c49bba77442742f2e83aaca58a8a1de | DhivyaKavidasan/python | /problemset_3/q9.py | 337 | 4.0625 | 4 | '''
function called is_sorted that takes a list as a parameter and returns True if the list is sorted in ascending order and False otherwise
submitted by : dhivya.kavidasan
date: 05/12/2017
'''
def is_sorted(s):
j=0
for i in s:
if s[j+1] >= s[j]:
return True
else:
return False
s = '122'
print is_sorted(s)
|
32503914dd6ad35fe5812d09ddadab0349833f29 | santhoshkalisamy/daily_coding_problem_java_solutions | /Python/src/Test.py | 312 | 3.515625 | 4 | def pair(a,b):
def pair(calc):
return calc(a,b)
return pair
def add(pair):
def calc(a,b):
return a+b;
return pair(calc)
def mul(pair):
def calc(a,b):
return a*b;
return pair(calc)
if __name__ == '__main__':
print(mul(pair(5,10)))
print(add(pair(5,10)))
|
0558835ce983d908544082481ba794108eca2894 | csitedexperts/DSML_MadeEasy | /Clustering K-Means/00Develope and Verify a K-Means++ Clustering Model with a Randomly Generated Dataset in Python.py | 2,254 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 24 08:51:47 2019
@author: mhossa12
"""
## https://www.kaggle.com/andyxie/k-means-clustering-implementation-in-python
# Import necessary libraries
from copy import deepcopy
import numpy as np # linear algebra
from matplotlib import pyplot as plt
# Set three centers, the model should predict similar results
center_1 = np.array([1,1])
center_2 = np.array([5,5])
center_3 = np.array([8,1])
# Generate random data and center it to the three centers
data_1 = np.random.randn(200, 2) + center_1
data_2 = np.random.randn(200,2) + center_2
data_3 = np.random.randn(200,2) + center_3
data = np.concatenate((data_1, data_2, data_3), axis = 0)
plt.scatter(data[:,0], data[:,1], s=7)
plt.grid()
plt.show()
# Number of clusters
k = 3
# Number of training data
n = data.shape[0]
# Number of features in the data
c = data.shape[1]
# Generate random centers, here we use sigma and mean to ensure it represent the whole data
mean = np.mean(data, axis = 0)
std = np.std(data, axis = 0)
centers = np.random.randn(k,c)*std + mean
# Plot the data and the centers generated as random
plt.scatter(data[:,0], data[:,1], s=7)
plt.scatter(centers[:,0], centers[:,1], marker='*', c='g', s=150)
plt.grid()
plt.show()
centers_old = np.zeros(centers.shape) # to store old centers
centers_new = deepcopy(centers) # Store new centers
data.shape
clusters = np.zeros(n)
distances = np.zeros((n,k))
error = np.linalg.norm(centers_new - centers_old)
# When, after an update, the estimate of that center stays the same, exit loop
while error != 0:
# Measure the distance to every center
for i in range(k):
distances[:,i] = np.linalg.norm(data - centers[i], axis=1)
# Assign all training data to closest center
clusters = np.argmin(distances, axis = 1)
centers_old = deepcopy(centers_new)
# Calculate mean for every cluster and update the center
for i in range(k):
centers_new[i] = np.mean(data[clusters == i], axis=0)
error = np.linalg.norm(centers_new - centers_old)
centers_new
# Plot the data and the centers generated as random
plt.scatter(data[:,0], data[:,1], s=7)
plt.scatter(centers_new[:,0], centers_new[:,1], marker='*', c='g', s=150)
plt.grid()
plt.show()
|
b64c6edf2ad59fb6801fabaf29f452d76040ab40 | hyu-likelion/Y1K3 | /week1/sunwoong/hard_problem3.py | 365 | 3.703125 | 4 | word = list(input().lower())
words = [0 for i in range(26)]
largestNum = 0
largestChar = ''
for i in range(0, len(word)):
index = ord(word[i])-97
words[index] += 1
if words[index] > largestNum:
largestNum = words[index]
largestChar = word[i]
elif words[index] == largestNum:
largestChar = '?'
print(largestChar.upper()) |
025306072a39c2cd9175e6542a616c5a8f986e60 | mancuzzo-x2/Guess-The-Number | /GuessTheNumber.py | 1,873 | 3.734375 | 4 | import random
class GTNum:
def __init__(self, range = 20, guess = 0):
self.range = range
self.guess = guess
def Set_range(self):
self.range = input("Insert an integer >= 0: ")
def Set_guess(self):
self.guess = input("\nGuess a number between 0 and " + str(self.range) + ": ")
def Get_guess(self):
return self.guess
def Get_range(self):
return self.range
def GTC(self):
rn = random.randrange(0, self.range)
if self.guess == rn:
return 0
elif self.guess < rn:
return -1
else:
return 1
def GTN(self):
print("Define a range from 0 to N.")
self.Set_range()
self.Set_guess()
range = self.Get_range()
guess = self.Get_guess()
while True:
compare = self.GTC()
if compare == 0:
print("\nYou hit the right answer!\n")
ans = raw_input("\nDo you want to retry?\nPress Y for yes or N for no: ")
if ans == "Y" or ans == "y":
guess = self.Set_guess()
continue
else:
break
elif compare == -1:
print("\nYour guess was too low...")
ans = raw_input("\nDo you want to retry?\nPress Y for yes or N for no: ")
if ans == "Y" or ans == "y":
guess = self.Set_guess()
continue
else:
break
else:
print("\nYour guess was too high...")
ans = raw_input("\nDo you want to retry?\nPress Y for yes or N for no: ")
if ans == "Y" or ans == "y":
guess = self.Set_guess()
continue
else:
break
return;
x = GTNum()
x.GTN()
|
cecd81f2b82daf735997e2c0b3027754c23e81ce | pgenkin/geekbrains | /task5_2.py | 250 | 3.765625 | 4 | my_file = open('file5_2.txt', 'r')
for line in my_file:
print("There are", line.count(' ') + 1, "words in the line.")
my_file.seek(0)
total_lines = len(my_file.readlines())
print("There are", total_lines, "lines in the file.")
my_file.close()
|
4950810e0244711c1d687601f7aa7a7eacb2e555 | seongkyun/DRFBNet300 | /lib/functions.py | 3,087 | 3.5625 | 4 | def th_selector(over_area, altitude):
if altitude <= 10:
th_x = over_area // 2 # 40
th_y = over_area // 4 # 20
return th_x, th_y
elif altitude <=20:
th_x = over_area // 8
th_y = over_area // 20
return th_x, th_y
else:
th_x = over_area // 20
th_y = over_area // 40
return th_x, th_y
def is_overlap_area(gt, box):
#order: [start x, start y, end x, end y]
if(gt[0]<=int(box[0]) and int(box[2])<=gt[2])\
or (gt[0]<=int(box[2]) and int(box[2])<=gt[2])\
or (gt[0]<=int(box[0]) and int(box[0])<=gt[2])\
or (int(box[0])<=gt[0] and gt[2]<=int(box[2])):
return True
else:
return False
def lable_selector(box_a, box_b):
#order: [start x, start y, end x, end y, lable, score]
if box_a[5] > box_b[5]:
return box_a[4], box_a[5]
else:
return box_b[4], box_b[5]
def bigger_box(box_a, box_b):
#order: [start x, start y, end x, end y, lable, score]
lable, score = lable_selector(box_a, box_b)
bigger_box = [min(box_a[0], box_b[0]), min(box_a[1], box_b[1])
, max(box_a[2], box_b[2]), max(box_a[3], box_b[3])
, lable, score]
return bigger_box
def is_same_obj(box, r_box, over_area, th_x, th_y):
#order: [start x, start y, end x, end y]
r_x_dist = (r_box[2] - r_box[0])
l_x_dist = (box[2] - box[0])
small_th = over_area // 3
r_mx = (r_box[0] + r_box[2]) // 2
sy_dist = abs(r_box[1] - box[1])
ey_dist = abs(r_box[3] - box[3])
l_mx = (box[0] + box[2]) // 2
# is y distance close?
if sy_dist<th_y and ey_dist<th_y:
# is x center distance close?
if abs(l_mx - r_mx) < th_x:
return True
else:
# is object too small?
if l_x_dist < small_th and r_x_dist < small_th:
#return True
return False
box_size = (box[2] - box[0]) * (box[3] - box[1])
r_box_size = (r_box[2] - r_box[0]) * (r_box[3] - r_box[1])
th_size = over_area * over_area * 4
th_th = int(over_area*0.2)
#if (box_size >= th_size) and (r_box_size >= th_size):
# return True
#
if (box_size >= th_size) and (r_box_size >= th_size)\
and (abs(box[2] - over_area*9)<th_th)\
and (abs(r_box[0] - over_area*7)<th_th)\
and r_box[0] < box[2]:
return True
return False
else:
return False
def get_close_obj(boxes, r_box, over_area, th_x, th_y):
#order: [start x, start y, end x, end y, lable, score]
# make the same object map
obj_map = []
new_obj = 0
for j in range(len(boxes)):
obj_map.append(is_same_obj(boxes[j], r_box, over_area, th_x, th_y))
# change the existing object
for j in range(len(obj_map)):
new_obj += int(obj_map[j])
if obj_map[j]:
boxes[j] = bigger_box(r_box, boxes[j])
break
# add the none existing obj
if new_obj == 0:
boxes.append(r_box)
return None |
f65ac732674787e00f845dae8de9c4ce1e9a0ab8 | adriangalende/ejerciciosPython | /findTheVowels.py | 410 | 3.734375 | 4 |
#vowels = a e i o u y
def vowel_indices(word):
word = word.lower()
position = []
index = 1
vowels = 'aeiouy'
for letter in word:
if letter in vowels:
position.append(index)
index += 1
return position
#casos Test
print(vowel_indices('YoMama'))
#vowel_indices('Super') ==> [2,4]
#vowel_indices('Apple') ==> [1,5]
#vowel_indices('YoMama') ==> [1,2,4,6]
|
39c7e9b34f702ea2d90b980750919d94da86557e | mikekulinski/DailyCodingProblem | /day24.py | 2,351 | 3.90625 | 4 | class BinaryTreeNode():
def __init__(self, name, left = None, right = None):
self.name = name
self.locked = False
self.parent = None
self.set_left(left)
self.set_right(right)
def __str__(self):
return "<Name: " + self.name + ", Locked: " + str(self.locked) + ">"
def set_left(self, other):
if type(other) == BinaryTreeNode:
self.left = other
other.parent = self
else:
self.left = None
def set_right(self, other):
if type(other) == BinaryTreeNode:
self.right = other
other.parent = self
else:
self.right = None
def is_locked(self):
return self.locked
def check_anscestors(self):
if self.parent == None:
return self.is_locked()
else:
return self.is_locked() or self.parent.check_anscestors()
def check_descendents(self):
if not self.left and not self.right:
return self.is_locked()
elif self.left:
return self.is_locked() or self.left.check_descendents()
elif self.right:
return self.is_locked() or self.right.check_descendents()
else:
return self.is_locked() or self.left.check_descendents() \
or self.right.check_descendents()
def lock(self):
if not self.check_anscestors() and not self.check_descendents():
self.locked = True
return True
else:
return False
def unlock(self):
if self.check_anscestors() and self.check_descendents():
self.locked = False
return True
else:
return False
if __name__ == "__main__":
tree = BinaryTreeNode("A",
BinaryTreeNode("B",
BinaryTreeNode("D"),
BinaryTreeNode("E")),
BinaryTreeNode("C",
None,
BinaryTreeNode("F",
None,
BinaryTreeNode('G'))))
print(tree.lock())
print(tree)
print(tree.left.left.lock())
print(tree.left.left)
print(tree.lock())
print(tree)
print(tree.unlock())
print(tree)
print(tree.left.right.lock())
print(tree.left.right)
|
f5e001e6e7deead6c95f89a12bcfc357f9724b79 | oqolarte/python-noob-filez | /add_remove_dots.py | 876 | 4.25 | 4 | # Adding and removing dots
# Write a function named add_dots that takes a string and adds "." in between each letter.
# For example, calling add_dots("test") should return the string "t.e.s.t".
# Then, below the add_dots function, write another function named remove_dots that removes all dots from a string.
# For example, calling remove_dots("t.e.s.t") should return "test".
#
# If both functions are correct, calling remove_dots(add_dots(string)) should return back the original string for any string.
#
# (You may assume that the input to add_dots does not itself contain any dots.)
def add_dots(text):
dots = '.'.join(text)
print(dots)
return dots
def remove_dots(text):
dots = ''.join(text.split('.'))
print(dots)
return dots
add_dots('hello')
remove_dots('m.a.s.s.a.g.e')
remove_dots(add_dots('i adore you'))
add_dots(remove_dots('edgar the cat'))
|
d046ca56efde7a13fa3b7ccd375abba66a9ee23f | MotownMystery/Exercises-for-Programmers-57-Challenges-Python | /ee44.py | 657 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 18 09:00:32 2017
@author: christophernovitsky
"""
Data = [{"name" : "widget", "price" : 2, "quantity" : 5},
{"name" : "thing", "price" : 15, "quantity" : 5},
{"name" : "doodad", "price" : 5, "quantity" : 10}]
X = [d["name"] for d in Data]
while True:
try:
name = input("What is the name of the product? ").lower()
break
except ValueError:
print("error")
pass
id = X.index(name)
Price = Data[id]["price"]
Quantity = Data[id]["quantity"]
print("\n")
print("Name: ",name)
print("Price: ",Price)
print("Quantity: ",Quantity) |
79ed6b508574bedd4830e0ccfa6602f64d5046cb | Btrenary/Module6 | /more_functions/function_parameter_assignment.py | 268 | 4 | 4 | """
Author: Brady Trenary
function takes in a string and a number, then multiplies the string by the number
"""
def multiply_string(message, n):
result = message * n
print(result)
return result
if __name__ == '__main__':
multiply_string('Chemistry', 5)
|
0a9aa6be8f756cbd3de3d293d53361e96e8712fc | sivarre/PythonPractise | /PythonScriptPractise/For_Loop.py | 210 | 3.953125 | 4 | print(list(range(5)))
for i in range(5):
print("Hello World",i)
mylist = [10,100,1000]
for jj in mylist:
print("jj value is :",jj)
#2*1=2
a=2
for i in range(10):
b=a*i
print(a," * ",i,"=",b)
|
8328a32129a2a9cbb7e2ab1a943a531f4808f36c | BeijiYang/algorithmExercise | /binaryTreeLeafsSum.py | 503 | 3.828125 | 4 | class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
node3 = TreeNode(3)
node1 = TreeNode(1)
node6 = TreeNode(6)
node4 = TreeNode(4)
node3.left = node1
node3.right = node6
node6.left = node4
def getTreeLeafsSum(node):
if node is None:
return 0
if node.left is None and node.right is None:
return node.value
return getTreeLeafsSum(node.left) + getTreeLeafsSum(node.right)
print getTreeLeafsSum(node3) |
d20d9f091a3b4799ed8b7d48e994be2a5c32b66a | monteua/Python | /List/14.py | 153 | 3.921875 | 4 | '''
Write a Python program to shuffle and print a specified list.
'''
import random
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
random.shuffle(lst)
print (lst)
|
934245c0e0a0c8e8c2898e2f0341b6416e6a89e3 | anshu-gautam/python_learning | /pattern_printing.py | 224 | 3.921875 | 4 | # # for i in range(1, 9):
# # print(i*"*")
#print this pattern horizontally
# *
# **
# ***
# ****
# *****
# ******
# *******
# ********
max = 9
for x in range (1 , 10):
print ((max - 1)* " " , x * "*")
max = max - 1 |
cf0b924d58ae073f52922cdaa91df60550f38349 | ashlin-k/MIT-CompBio | /Projects/M1/exact_matching.py | 2,268 | 3.65625 | 4 |
# This program will find an exact number of matches of an M-length
# pattern, P, in a N-length string, T, in linear time, O(N) using the
# Z algorithm, Boyer-Moore and Knuth-Morris-Pratt (KMP)
# Based of of Lecture 3 in the MIT CompBio lecture series
# https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-047-computational-biology-fall-2015/lectures_slides/MIT6_047F15_Lecture03.pdf
# ZString:
# A string that can be preprocessed to store a Z array.
# Z[i] = length of longest substirng starting from Z[i],
# which is also a prefix of the string
# (meaning the first char of the substring must be str[0])
class ZString:
def __init__(self, str):
self.string = str # the string
self.N = len(self.string) # size of the string
self.Z = [0 for i in range(self.N)] # Z values, redundancy structure, init to 0
self.ZisInit = False
def size(self):
return self.N
def getString(self):
return self.string
def getZ(self):
return self.Z
# code borrowed from GeeksForGeeks
# https://www.geeksforgeeks.org/z-algorithm-linear-time-pattern-searching-algorithm/
def preprocessZ(self):
l, r, k = 0, 0, 0
for i in range(1, self.N):
if i > r:
l, r = i, i
while r < self.N and self.string[r - l] == self.string[r]:
r += 1
self.Z[i] = r - l
r -= 1
else:
k = i - l
if self.Z[k] < r - i + 1:
self.Z[i] = self.Z[k]
else:
l = i
while r < self.N and self.string[r - l] == self.string[r]:
r += 1
self.Z[i] = r - l
r -= 1
self.ZisInit = True
return self.Z
if __name__ == '__main__':
# the pattern, P, and the text, T
P = "ACA" # the pattern string, size M
T = "TAACAGACACAGG" # the text string, size N
# preprocess concatenated P-T string, O((M+N)^2)
concatenatedPT = P + "$" + T
PT = ZString(concatenatedPT)
z = PT.preprocessZ()
# find P in T, O(M+N)
M = len(P)
indicatorString = ""
arrowString = "^" * M
startArrow = M-3
for i in range(M+1, PT.size()):
if z[i] == M:
indicatorString += arrowString
startArrow = i
else:
if i > startArrow + 2:
indicatorString += " "
print "P = ", P
print "T = ", T
print " " * len("T = "), indicatorString
|
6f61d70d2b8dd7424022afe61234b0d7bd20689b | ggibson5972/Kattis | /sibice.py | 390 | 3.921875 | 4 | #read in the number of matches and the dimensions of the box
N, W, H = map(int, raw_input().split(" "))
#calculate diagonal of box (pythagorean theorem)
d = int((W ** 2 + H ** 2) ** 0.5)
while N > 0:
#read in length of each match
L = input()
#check if match is smaller than the longest part of box
if int(L) <= d:
print "DA"
else:
print "NE"
N -= 1
|
6870e1333b4d201161560e8629787e4064882b2c | MaksymSkorupskyi/HackerRank_Challenges | /Strings/Find a string.py | 705 | 4.15625 | 4 | """Find a string
https://www.hackerrank.com/challenges/find-a-string/problem
In this challenge, the user enters a string and a substring.
You have to print the number of times that the substring occurs in the given string.
String traversal will take place from left to right, not from right to left.
NOTE: String letters are case-sensitive.
Input Format
The first line of input contains the original string. The next line contains the substring.
"""
import re
def count_substring(string, sub_string):
return len(re.findall('(?=' + sub_string + ')', string))
if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()
print(count_substring(string, sub_string)) |
8d29852ae236a60eedb362ede030781b53b46c4a | Surgeon-76/KaPythoshka | /Stepik/13_function/is_valid_triangle/my.py | 381 | 4.03125 | 4 | # объявление функции
def is_valid_triangle(side1, side2, side3):
if (side1 < (side2 + side3)) and (side2 < (side1 + side3)) and (side3 < (side1 + side2)):
return True
else:
return False
# считываем данные
a, b, c = int(input()), int(input()), int(input())
# вызываем функцию
print(is_valid_triangle(a, b, c)) |
ec07b68f138db4ba0a2722cb569ba1086d1c0076 | jeffrey-hong/interview-prep | /Daily Coding Problem/Problem21.py | 980 | 3.859375 | 4 | def lecture_rooms(intervals):
# Given an array of time intervals (start, end) for classroom lectures (possibly overlapping),
# find the minimum number of rooms required.
# For example, given [(30, 75), (0, 50), (60, 150)], you should return 2.
start = sorted(start for start, end in intervals)
end = sorted(end for start, end in intervals)
current_overlap = 0
current_max = 0
i = 0
j = 0
while i < len(intervals) and j < len(intervals):
if start[i] < end[j]:
print(current_overlap)
current_overlap += 1
current_max = max(current_max, current_overlap)
i += 1
else:
current_overlap -= 1
j += 1
return current_max
# Tests
# Given, should return 2
intervals = [(30, 75), (0, 50), (60, 150)]
print(lecture_rooms(intervals))
# All overlapping, should return 2
# intervals = [(30, 75), (25, 35), (60, 100)]
print(lecture_rooms(intervals))
# No overlapping, should return 1
intervals = [(10, 20), (30, 40), (40, 50)]
print(lecture_rooms(intervals)) |
4d3e36d51bbbf6e860bada70f1b831ef3dd53c7b | jaeyun95/Baekjoon | /code/2750.py | 3,107 | 3.6875 | 4 | #(2750) 수 정렬하기
number = int(input())
input_list = []
for _ in range(number):
input_list.append(int(input()))
## using python function
#input_list = sorted(input_list)
## bubble sort
'''
for i in range(len(input_list)-1):
for j in range(len(input_list)-i-1):
if input_list[j] > input_list[j+1]:
input_list[j], input_list[j+1] = input_list[j+1], input_list[j]
'''
## selection sort
'''
for i in range(len(input_list)):
index = i
for j in range(i+1,len(input_list)):
if input_list[index] > input_list[j]:
index = j
input_list[i], input_list[index] = input_list[index], input_list[i]
'''
## insertion sort
'''
for i in range(1,len(input_list)):
for j in range(i,0,-1):
if input_list[j] < input_list[j-1]:
input_list[j], input_list[j-1] = input_list[j-1], input_list[j]
'''
## merge sort
'''
def merge_sort(lst):
if len(lst) <= 1:
return lst
mid = len(lst)//2
left_list = merge_sort(lst[:mid])
right_list = merge_sort(lst[mid:])
return merge(left_list,right_list)
def merge(left_list, right_list):
sorted_list = []
li = 0
ri = 0
while (li < len(left_list) and ri < len(right_list)):
if left_list[li] < right_list[ri]:
sorted_list.append(left_list[li])
li += 1
else:
sorted_list.append(right_list[ri])
ri += 1
while(li < len(left_list)):
sorted_list.append(left_list[li])
li += 1
while (ri < len(right_list)):
sorted_list.append(right_list[ri])
ri += 1
return sorted_list
input_list = merge_sort(input_list)
'''
## heap sort
'''
def heapify(lst, index, size):
parent = index
child = 2 * index + 1
if child < size and lst[child] > lst[parent]:
parent = child
if (child + 1) < size and lst[(child + 1)] > lst[parent]:
parent = (child + 1)
if parent != index:
lst[parent], lst[index] = lst[index], lst[parent]
heapify(lst, parent, size)
def heap_sort(lst):
for i in range(len(lst)//2-1,-1,-1):
heapify(lst, i, len(lst))
for i in range(len(lst) - 1, 0, -1):
lst[0], lst[i] = lst[i], lst[0]
heapify(lst, 0, i)
return lst
input_list = heap_sort(input_list)
'''
## quick sort
'''
def quick_sort(lst):
if len(lst) <= 1:
return lst
pivot = lst[0]
left, right = [], []
for item in lst[1:]:
if item < pivot: left.append(item)
else: right.append(item)
return quick_sort(left) + [pivot] + quick_sort(right)
input_list = quick_sort(input_list)
'''
## counting sort
'''
def counting_sort(lst, K):
count_lst = [0] * K
sorted_lst = [0] * len(lst)
for item in lst:
count_lst[item] += 1
for count in range(1,K):
count_lst[count] += count_lst[count-1]
for index in range(len(lst)):
sorted_lst[count_lst[lst[index]]-1] = lst[index]
count_lst[lst[index]] -= 1
return sorted_lst
input_list = counting_sort(input_list,max(input_list)+1)
'''
for item in input_list:
print(item)
|
78d37228503a9e325ba70c204c471bfbb66ee468 | KarAbhishek/MSBIC | /Practice/quick_select.py | 929 | 3.609375 | 4 | from random import random
def partition1(arr, left, right, pivotIndex):
arr[right], arr[pivotIndex] = arr[pivotIndex], arr[right]
pivot = arr[right]
swapIndex = left
for i in range(left, right):
if arr[i] < pivot:
arr[i], arr[swapIndex] = arr[swapIndex], arr[i]
swapIndex += 1
arr[right], arr[swapIndex] = arr[swapIndex], arr[right]
return swapIndex
def kthLargest1(arr, left, right, k):
if not 1 <= k <= len(arr):
return
if left == right:
return arr[left]
while True:
pivotIndex = random.randint(left, right)
pivotIndex = partition1(arr, left, right, pivotIndex)
rank = pivotIndex - left + 1
if rank == k:
return arr[pivotIndex]
elif k < rank:
return kthLargest1(arr, left, pivotIndex - 1, k)
else:
return kthLargest1(arr, pivotIndex + 1, right, k - rank) |
a16f5a8aa07f425e0ef7746472fbe1a6f8865b8b | bersavosh/P4J | /P4J/math.py | 1,883 | 3.65625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
"""
Computes a given quantile of the data considering
that each sample has a weight.
x is a N float array
weights is a N float array, it expects sum w_i = 1
quantile is a float in [0.0, 1.0]
"""
def weighted_quantile(x, weights, quantile):
I = np.argsort(x)
sort_x = x[I]
sort_w = weights[I]
acum_w = np.add.accumulate(sort_w)
norm_w = (acum_w - 0.5*sort_w)/acum_w[-1]
interpq = np.searchsorted(norm_w, [quantile])[0]
if interpq == 0:
return sort_x[0]
elif interpq == len(x):
return sort_x[-1]
else:
tmp1 = (norm_w[interpq] - quantile)/(norm_w[interpq] - norm_w[interpq-1])
tmp2 = (quantile - norm_w[interpq-1])/(norm_w[interpq] - norm_w[interpq-1])
assert tmp1>=0 and tmp2>=0 and tmp1<=1 and tmp2<=1
return sort_x[interpq-1]*tmp1 + sort_x[interpq]*tmp2
"""
Computes the weighted interquartile range (IQR) of x.
x is a N float array
weights is a N float array, it expects sum w_i = 1
"""
def wIQR(x, weights):
return weighted_quantile(x, weights, 0.75) - weighted_quantile(x, weights, 0.25)
"""
Computes the weighted standard deviation of x.
x is a N float array
weights is a N float array, it expects sum w_i = 1
"""
def wSTD(x, weights):
wmean = np.average(x, weights=weights)
return np.sqrt(np.average((x - wmean)**2, weights=weights))
"""
Computes a robust measure of scale by comparing the weighted versions of the
standard deviation and the interquartile range of x.
x is a N float array
weights is a N float array, it expects sum w_i = 1
"""
def robust_scale(x, weights):
return np.amin([wSTD(x, weights), wIQR(x, weights)/1.349])
def robust_loc(x, weights):
return weighted_quantile(x, weights, 0.5)
|
568fff18a0dba36d574ed7366aa60be03b9d4e67 | dariusciupe/adventofcode | /2016/Day2/day1.py | 667 | 3.90625 | 4 | def get_digit(cmd, start):
digit = start
for c in cmd:
if c == 'U':
digit = digit - 3 if digit - 3 > 0 else digit
elif c == 'D':
digit = digit + 3 if digit + 3 < 10 else digit
elif c == 'L':
digit = digit - 1 if (digit - 1) % 3 != 0 else digit
elif c == 'R':
digit = digit + 1 if digit % 3 != 0 else digit
return digit
def main():
code = ''
start = 5
with open('input.txt') as file:
input = file.readlines()
for cmd in input:
start = get_digit(cmd.strip(), start)
code = code + str(start)
print('Bathroom code: ', code)
main()
|
e3312cc8039fc82d9d8618559483340c20fd33a3 | eggypesela/freecodecamp-exercise-scientific-computing | /Exercise Files/boilerplate-time-calculator/time_calculator.py | 2,697 | 3.96875 | 4 | #!/usr/bin/env python3
#created by Regina Citra Pesela (reginapasela@gmail.com)
def add_time(start, duration, currentDay = ""):
#clean start time data into variables
startHour, startMinute, startAMPM = int(start.split(":")[0]), int(start.split(":")[1][:2]), start.split(" ")[1]
#clean duration time data into variables
addHour, addMinute = int(duration.split(":")[0]), int(duration.split(":")[1][:2])
if startAMPM == "AM":
dictAMPM = {0: startAMPM, 1: "PM"}
else:
dictAMPM = {0: startAMPM, 1: "AM"}
tupDays = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
if currentDay != "":
currentDay = currentDay.title()
dayIndex = (tupDays.index(currentDay))
else:
dayIndex = ""
#calculate the time
#calculate start minute plus duration minute
resultMinute = startMinute + addMinute
#if result minute bigger than 60 we should divide it and then add to result hour
moreHour = 0
if resultMinute > 60:
moreHour = round(resultMinute/60)
resultMinute = resultMinute % 60
#fix minute < 10 to be 2 digits (02-09)
if resultMinute < 10:
resultMinute = "0" + str(resultMinute)
#calculate start hour plus duration hour
resultHour = startHour + addHour + moreHour
#if result hour is bigger than 24 we should divide it and then add to result day
if resultHour > 24:
moreDay = round(resultHour / 24)
elif startAMPM == "PM" and resultHour > 12:
moreDay = 1
else:
moreDay = 0
#determine AM or PM
countAMPM = 0
while resultHour >= 12:
resultHour -= 12
countAMPM += 1
if countAMPM > 1:
countAMPM = countAMPM % 2
#IF function to check how many days passed, if there is > 0 put some text
if moreDay == 0:
resultDay = ""
elif moreDay == 1:
resultDay = " (next day)"
else:
resultDay = " (" + str(moreDay) + " days later)"
if dayIndex != "":
dayIndex += (moreDay % 7)
dayIndex = dayIndex % 7
print(dayIndex, moreDay)
#change 24 hour format to AMPM format
if resultHour > 12:
resultHour = resultHour % 12
elif resultHour == 0:
resultHour = 12
#return the result into new_time variable
if dayIndex == "":
new_time = str(resultHour) + ":" + str(resultMinute) + " " + str(dictAMPM[countAMPM]) + str(resultDay)
else:
new_time = str(resultHour) + ":" + str(resultMinute) + " " + str(dictAMPM[countAMPM]) + ", " + str(tupDays[int(dayIndex)]) + str(resultDay)
return new_time |
f260d0c7c4897f90526a281e9ad0c36bb2972094 | KevinVuongly/ProgrAmsterdam | /src/classes/Heuristics.py | 2,604 | 3.984375 | 4 | from classes.Board import Board
class Heuristic:
""" A class that has all the heuristics made for the rush hour game"""
def __init__(self, board):
""" Takes all information of the board with it's state as the beginning of the game.
Args:
board (class): Containing all information of the game.
"""
self.board = board
def blockingRedCar(self, stateChangeable):
""" Checks how many cars are blocking the way of the red car.
Initalization:
blocks (int): Amount of blocks is 0 initially.
redCarSize (int): The carsize of the red car. The size is typically 2.
posToCheck (int): The maximum amount of cars that might be
blocking the way of the red car.
Args:
stateChangeable (list): The current state of the game.
Return:
blocks (int): The real amount of cars blocking the way of the red car.
"""
blocks = 0
redCarSize = self.board.length[0]
posToCheck = self.board.gridSize - stateChangeable[0] - redCarSize
for i in range(1, self.board.nrOfCars):
if self.board.direction[i] == "v":
for j in range(posToCheck):
for k in range(self.board.length[i]):
if stateChangeable[i] == self.board.fixed[0] - k and self.board.fixed[i] == redCarSize + stateChangeable[0] + j:
blocks += 1
break
return blocks
def positionScore(self, stateChangeable, stateSolution, astar=False):
""" Calculates the score of the given board compared to the solution board.
For every distance difference of a car compared to it's position in
the solution adds a penalty of 1.
If the algorithm used is an A*, the penalty is 1 regardless how far
the car is from it's end position.
Args:
stateChangeable (list): The current state of the game.
stateSolution (list): The solution state of the game.
Return:
score (int): The score of the given board according to the heuristic.
"""
score = 0
if astar == False:
for i in range(self.board.nrOfCars):
score += abs(stateSolution[i] - stateChangeable[i])
else:
for i in range(self.board.nrOfCars):
toMove = abs(stateSolution[i] - stateChangeable[i])
if toMove > 0:
score += 1
return score
|
be0542fec6087ba04f673b7eaebd7bdfa1a598fd | Fullstack-Datascientist-BootCamp/ipdb | /step.py | 478 | 3.5625 | 4 | def subroutine(x, y):
return x*y
def wrapper(x):
# now you are here. press c
return x
if __name__ == "__main__":
a = 3
b = 5
# put break point on line 14 and 16
# press "s"
import ipdb; ipdb.set_trace() # BREAKPOINT
subroutine(wrapper(a), b)
import ipdb; ipdb.set_trace() # BREAKPOINT
# press s then n
subroutine(
a,b
)
# You did not step in! press q to quit. Next time press s and s
subroutine(a,b)
|
776464e4b021493ef41d644da3eb3ab5728b1913 | cybersp/TensorBase | /tensorbase/base.py | 39,318 | 3.71875 | 4 | #!/usr/bin/env python
"""
@author: Dan Salo, Nov 2016
Purpose: To facilitate data I/O, and model training in TensorFlow
Classes:
Data
Model
"""
import tensorflow as tf
import numpy as np
import logging
import math
import os
from tensorflow.python import pywrap_tensorflow
import sys
class Data:
"""
A Class to handle data I/O and batching in TensorFlow.
Use class methods for datasets:
- That can be loaded into memory all at once.
- That use the placeholder function in TensorFlow
Use batch_inputs method et al for datasets:
- That can't be loaded into memory all at once.
- That use queueing and threading fuctions in TesnorFlow
"""
def __init__(self, flags, valid_percent=0.2, test_percent=0.15):
self.flags = flags
train_images, train_labels, self.test_images, self.test_labels = self.load_data(test_percent)
self._num_test_images = len(self.test_labels)
self._num_train_images = math.floor(len(train_labels) * (1 - valid_percent))
self._num_valid_images = len(train_labels) - self._num_train_images
self.train_images, self.train_labels, self.valid_images, self.valid_labels = \
self.split_data(train_images, train_labels)
self.train_epochs_completed = 0
self.index_in_train_epoch = 0
self.index_in_valid_epoch = 0
self.index_in_test_epoch = 0
def load_data(self, test_percent=0.15):
"""Load the dataset into memory. If data is not divided into train/test, use test_percent to divide the data"""
train_images = list()
train_labels = list()
test_images = list()
test_labels = list()
return train_images, train_labels, test_images, test_labels
def split_data(self, train_images, train_labels):
"""
:param train_images: numpy array (image_dim, image_dim, num_images)
:param train_labels: numpy array (labels)
:return: train_images, train_labels, valid_images, valid_labels
"""
valid_images = train_images[:self.num_valid_images]
valid_labels = train_labels[:self.num_valid_images]
train_images = train_images[self.num_valid_images:]
train_labels = train_labels[self.num_valid_images:]
return train_images, train_labels, valid_images, valid_labels
def next_train_batch(self, batch_size):
"""
Return the next batch of examples from train data set
:param batch_size: int, size of image batch returned
:return train_labels: list, of labels
:return images: list, of images
"""
start = self.index_in_train_epoch
self.index_in_train_epoch += batch_size
if self.index_in_train_epoch > self.num_train_images:
# Finished epoch
self.train_epochs_completed += 1
# Shuffle the data
perm = np.arange(self.num_train_images)
np.random.shuffle(perm)
self.train_images = self.train_images[perm]
self.train_labels = self.train_labels[perm]
# Start next epoch
start = 0
self.index_in_train_epoch = batch_size
assert batch_size <= self.num_train_images
end = self.index_in_train_epoch
return self.train_labels[start:end], self.img_norm(self.train_images[start:end])
def next_valid_batch(self, batch_size):
"""
Return the next batch of examples from validiation data set
:param batch_size: int, size of image batch returned
:return train_labels: list, of labels
:return images: list, of images
"""
start = self.index_in_valid_epoch
if self.index_in_valid_epoch + batch_size > self.num_valid_images:
batch_size = 1
self.index_in_valid_epoch += batch_size
end = self.index_in_valid_epoch
return self.valid_labels[start:end], self.img_norm(self.valid_images[start:end]), end, batch_size
def next_test_batch(self, batch_size):
"""
Return the next batch of examples from test data set
:param batch_size: int, size of image batch returned
:return train_labels: list, of labels
:return images: list, of images
"""
start = self.index_in_test_epoch
print(start)
if self.index_in_test_epoch + batch_size > self.num_test_images:
batch_size = 1
self.index_in_test_epoch += batch_size
end = self.index_in_test_epoch
return self.test_labels[start:end], self.img_norm(self.test_images[start:end]), end, batch_size
@property
def num_train_images(self):
return self._num_train_images
@property
def num_test_images(self):
return self._num_test_images
@property
def num_valid_images(self):
return self._num_valid_images
@staticmethod
def img_norm(x, max_val=255):
"""
Normalizes stack of images
:param x: input feature map stack, assume uint8
:param max_val: int, maximum value of input tensor
:return: output feature map stack
"""
return (x * (1 / max_val) - 0.5) * 2 # returns scaled input ranging from [-1, 1]
@classmethod
def batch_inputs(cls, read_and_decode_fn, tf_file, batch_size, mode="train", num_readers=4, num_threads=4,
min_examples=1000):
with tf.name_scope('batch_processing'):
example_serialized = cls.queue_setup(tf_file, mode, batch_size, num_readers, min_examples)
decoded_data = cls.thread_setup(read_and_decode_fn, example_serialized, num_threads)
return tf.train.batch_join(decoded_data, batch_size=batch_size)
@staticmethod
def queue_setup(filename, mode, batch_size, num_readers, min_examples):
""" Sets up the queue runners for data input """
filename_queue = tf.train.string_input_producer([filename], shuffle=True, capacity=16)
if mode == "train":
examples_queue = tf.RandomShuffleQueue(capacity=min_examples + 3 * batch_size,
min_after_dequeue=min_examples, dtypes=[tf.string])
else:
examples_queue = tf.FIFOQueue(capacity=min_examples + 3 * batch_size, dtypes=[tf.string])
enqueue_ops = list()
for _ in range(num_readers):
reader = tf.TFRecordReader()
_, value = reader.read(filename_queue)
enqueue_ops.append(examples_queue.enqueue([value]))
tf.train.queue_runner.add_queue_runner(tf.train.queue_runner.QueueRunner(examples_queue, enqueue_ops))
example_serialized = examples_queue.dequeue()
return example_serialized
@staticmethod
def thread_setup(read_and_decode_fn, example_serialized, num_threads):
""" Sets up the threads within each reader """
decoded_data = list()
for _ in range(num_threads):
decoded_data.append(read_and_decode_fn(example_serialized))
return decoded_data
@staticmethod
def init_threads(tf_session):
""" Starts threads running """
coord = tf.train.Coordinator()
threads = list()
for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS):
threads.extend(qr.create_threads(tf_session, coord=coord, daemon=True, start=True))
return threads, coord
@staticmethod
def exit_threads(threads, coord):
""" Closes out all threads """
coord.request_stop()
coord.join(threads, stop_grace_period_secs=10)
class Model:
"""
A Class for easy Model Training.
Methods:
See list in __init__() function
"""
def __init__(self, flags, config_dict=None):
config_yaml_flags_dict = self.load_config_yaml(flags, config_dict)
config_yaml_flags_dict_none = self.check_dict_keys(config_yaml_flags_dict)
# Define constants
self.step = 1
self.flags = config_yaml_flags_dict_none
# Run initialization functions
self._check_file_io()
self._data()
self._set_seed()
self._network()
self._optimizer()
self._summaries()
self.merged, self.saver, self.sess, self.writer = self._set_tf_functions()
self._initialize_model()
def load_config_yaml(self, flags, config_dict):
""" Load config dict and yaml dict and then override both with flags dict. """
if config_dict is None:
print('Config File not specified. Using only input flags.')
return flags
try:
config_yaml_dict = self.cfg_from_file(flags['YAML_FILE'], config_dict)
except KeyError:
print('Yaml File not specified. Using only input flags and config file.')
return config_dict
print('Using input flags, config file, and yaml file.')
config_yaml_flags_dict = self._merge_a_into_b_simple(flags, config_yaml_dict)
return config_yaml_flags_dict
def check_dict_keys(self, config_yaml_flags_dict):
""" Fill in all optional keys with None. Exit in a crucial key is not defined. """
crucial_keys = ['MODEL_DIRECTORY', 'SAVE_DIRECTORY']
for key in crucial_keys:
if key not in config_yaml_flags_dict:
print('You must define %s. Now exiting...' % key)
exit()
optional_keys = ['RESTORE_SLIM_FILE', 'RESTORE_META', 'RESTORE_SLIM', 'SEED', 'GPU']
for key in optional_keys:
if key not in config_yaml_flags_dict:
config_yaml_flags_dict[key] = None
print('%s in flags, yaml or config dictionary was not found.' % key)
if 'RUN_NUM' not in config_yaml_flags_dict:
config_yaml_flags_dict['RUN_NUM'] = 0
if 'NUM_EPOCHS' not in config_yaml_flags_dict:
config_yaml_flags_dict['NUM_EPOCHS'] = 1
return config_yaml_flags_dict
def _check_file_io(self):
""" Create and define logging directory """
folder = 'Model' + str(self.flags['RUN_NUM']) + '/'
folder_restore = 'Model' + str(self.flags['MODEL_RESTORE']) + '/'
self.flags['RESTORE_DIRECTORY'] = self.flags['SAVE_DIRECTORY'] + self.flags[
'MODEL_DIRECTORY'] + folder_restore
self.flags['LOGGING_DIRECTORY'] = self.flags['SAVE_DIRECTORY'] + self.flags[
'MODEL_DIRECTORY'] + folder
self.make_directory(self.flags['LOGGING_DIRECTORY'])
sys.stdout = Logger(self.flags['LOGGING_DIRECTORY'] + 'ModelInformation.log')
print(self.flags)
def _set_tf_functions(self):
""" Sets up summary writer, saver, and session, with configurable gpu visibility """
merged = tf.summary.merge_all()
saver = tf.train.Saver()
if type(self.flags['GPU']) is int:
os.environ["CUDA_VISIBLE_DEVICES"] = str(self.flags['GPU'])
print('Using GPU %d' % self.flags['GPU'])
gpu_options = tf.GPUOptions(allow_growth=True)
config = tf.ConfigProto(log_device_placement=False, gpu_options=gpu_options)
sess = tf.Session(config=config)
writer = tf.summary.FileWriter(self.flags['LOGGING_DIRECTORY'], sess.graph)
return merged, saver, sess, writer
def _get_restore_meta_file(self):
return 'part_' + str(self.flags['FILE_EPOCH']) + '.ckpt.meta'
def _restore_meta(self):
""" Restore from meta file. 'RESTORE_META_FILE' is expected to have .meta at the end. """
restore_meta_file = self._get_restore_meta_file()
filename = self.flags['RESTORE_DIRECTORY'] + self._get_restore_meta_file()
new_saver = tf.train.import_meta_graph(filename)
new_saver.restore(self.sess, filename[:-5])
print("Model restored from %s" % restore_meta_file)
def _restore_slim(self, variables):
""" Restore from tf-slim file (usually a ImageNet pre-trained model). """
variables_to_restore = self.get_variables_in_checkpoint_file(self.flags['RESTORE_SLIM_FILE'])
variables_to_restore = {self.name_in_checkpoint(v): v for v in variables if (self.name_in_checkpoint(v) in variables_to_restore)}
if variables_to_restore is []:
print('Check the SLIM checkpoint filename. No model variables matched the checkpoint variables.')
exit()
saver = tf.train.Saver(variables_to_restore)
saver.restore(self.sess, self.flags['RESTORE_SLIM_FILE'])
print("Model restored from %s" % self.flags['RESTORE_SLIM_FILE'])
def _initialize_model(self):
""" Initialize the defined network and restore from files is so specified. """
# Initialize all variables first
self.sess.run(tf.local_variables_initializer())
self.sess.run(tf.global_variables_initializer())
if self.flags['RESTORE_META'] == 1:
print('Restoring from .meta file')
self._restore_meta()
elif self.flags['RESTORE_SLIM'] == 1:
print('Restoring TF-Slim Model.')
all_model_variables = tf.global_variables()
self._restore_slim(all_model_variables)
else:
print("Model training from scratch.")
def _init_uninit_vars(self):
""" Initialize all other trainable variables, i.e. those which are uninitialized """
uninit_vars = self.sess.run(tf.report_uninitialized_variables())
vars_list = list()
for v in uninit_vars:
var = v.decode("utf-8")
vars_list.append(var)
uninit_vars_tf = [v for v in tf.global_variables() if v.name.split(':')[0] in vars_list]
self.sess.run(tf.variables_initializer(var_list=uninit_vars_tf))
def _save_model(self, section):
""" Save model in the logging directory """
checkpoint_name = self.flags['LOGGING_DIRECTORY'] + 'part_%d' % section + '.ckpt'
save_path = self.saver.save(self.sess, checkpoint_name)
print("Model saved in file: %s" % save_path)
def _record_training_step(self, summary):
""" Adds summary to writer and increments the step. """
self.writer.add_summary(summary=summary, global_step=self.step)
self.step += 1
def _set_seed(self):
""" Set random seed for numpy and tensorflow packages """
if self.flags['SEED'] is not None:
tf.set_random_seed(self.flags['SEED'])
np.random.seed(self.flags['SEED'])
def _summaries(self):
""" Print out summaries for every variable. Can be overriden in main function. """
for var in tf.trainable_variables():
tf.summary.histogram(var.name, var)
print(var.name)
def _data(self):
"""Define data"""
raise NotImplementedError
def _network(self):
"""Define network"""
raise NotImplementedError
def _optimizer(self):
"""Define optimizer"""
raise NotImplementedError
def get_flags(self):
return self.flags
@staticmethod
def make_directory(folder_path):
""" Make directory at folder_path if it does not exist """
if not os.path.exists(folder_path):
os.makedirs(folder_path)
@staticmethod
def print_log(message):
""" Print message to terminal and to logging document if applicable """
print(message)
logging.info(message)
@staticmethod
def check_str(obj):
""" Returns a string for various input types """
if isinstance(obj, str):
return obj
if isinstance(obj, float):
return str(int(obj))
else:
return str(obj)
@staticmethod
def name_in_checkpoint(var):
""" Removes 'model' scoping if it is present in order to properly restore weights. """
if var.op.name.startswith('model/'):
return var.op.name[len('model/'):]
@staticmethod
def get_variables_in_checkpoint_file(filename):
try:
reader = pywrap_tensorflow.NewCheckpointReader(filename)
var_to_shape_map = reader.get_variable_to_shape_map()
return var_to_shape_map
except Exception as e: # pylint: disable=broad-except
print(str(e))
if "corrupted compressed block contents" in str(e):
print("It's likely that your checkpoint file has been compressed "
"with SNAPPY.")
def _merge_a_into_b(self, a, b):
"""Merge config dictionary a into config dictionary b, clobbering the
options in b whenever they are also specified in a.
"""
from easydict import EasyDict as edict
if type(a) is not edict:
return
for k, v in a.items():
# a must specify keys that are in b
if k not in b:
raise KeyError('{} is not a valid config key'.format(k))
# the types must match, too
old_type = type(b[k])
if old_type is not type(v):
if isinstance(b[k], np.ndarray):
v = np.array(v, dtype=b[k].dtype)
else:
raise ValueError(('Type mismatch ({} vs. {}) '
'for config key: {}').format(type(b[k]),
type(v), k))
# recursively merge dicts
if type(v) is edict:
try:
self._merge_a_into_b(a[k], b[k])
except:
print('Error under config key: {}'.format(k))
raise
else:
b[k] = v
return b
def _merge_a_into_b_simple(self, a, b):
"""Merge config dictionary a into config dictionary b, clobbering the
options in b whenever they are also specified in a. Do not do any checking.
"""
for k, v in a.items():
b[k] = v
return b
def cfg_from_file(self, yaml_filename, config_dict):
"""Load a config file and merge it into the default options."""
import yaml
from easydict import EasyDict as edict
with open(yaml_filename, 'r') as f:
yaml_cfg = edict(yaml.load(f))
return self._merge_a_into_b(yaml_cfg, config_dict)
class Logger(object):
def __init__(self, filename):
self.terminal = sys.stdout
self.log = open(filename, "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
#this flush method is needed for python 3 compatibility.
#this handles the flush command by doing nothing.
#you might want to specify some extra behavior here.
pass
class Layers:
"""
A Class to facilitate network creation in TensorFlow.
Methods: conv2d, deconv2d, cflatten, maxpool, avgpool, res_layer, noisy_and, batch_norm
"""
def __init__(self, x):
"""
Initialize model Layers.
.input = numpy array
.count = dictionary to keep count of number of certain types of layers for naming purposes
"""
self.input = x # initialize input tensor
self.count = {'conv': 0, 'deconv': 0, 'fc': 0, 'flat': 0, 'mp': 0, 'up': 0, 'ap': 0, 'rn': 0}
def conv2d(self, filter_size, output_channels, stride=1, padding='SAME', bn=True, activation_fn=tf.nn.relu,
b_value=0.0, s_value=1.0, trainable=True):
"""
2D Convolutional Layer.
:param filter_size: int. assumes square filter
:param output_channels: int
:param stride: int
:param padding: 'VALID' or 'SAME'
:param activation_fn: tf.nn function
:param b_value: float
:param s_value: float
"""
self.count['conv'] += 1
scope = 'conv_' + str(self.count['conv'])
with tf.variable_scope(scope):
# Conv function
input_channels = self.input.get_shape()[3]
if filter_size == 0: # outputs a 1x1 feature map; used for FCN
filter_size = self.input.get_shape()[2]
padding = 'VALID'
output_shape = [filter_size, filter_size, input_channels, output_channels]
w = self.weight_variable(name='weights', shape=output_shape, trainable=trainable)
self.input = tf.nn.conv2d(self.input, w, strides=[1, stride, stride, 1], padding=padding)
if bn is True: # batch normalization
self.input = self.batch_norm(self.input)
if b_value is not None: # bias value
b = self.const_variable(name='bias', shape=[output_channels], value=b_value, trainable=trainable)
self.input = tf.add(self.input, b)
if s_value is not None: # scale value
s = self.const_variable(name='scale', shape=[output_channels], value=s_value, trainable=trainable)
self.input = tf.multiply(self.input, s)
if activation_fn is not None: # activation function
self.input = activation_fn(self.input)
print(scope + ' output: ' + str(self.input.get_shape()))
def convnet(self, filter_size, output_channels, stride=None, padding=None, activation_fn=None, b_value=None,
s_value=None, bn=None, trainable=True):
'''
Shortcut for creating a 2D Convolutional Neural Network in one line
Stacks multiple conv2d layers, with arguments for each layer defined in a list.
If an argument is left as None, then the conv2d defaults are kept
:param filter_sizes: int. assumes square filter
:param output_channels: int
:param stride: int
:param padding: 'VALID' or 'SAME'
:param activation_fn: tf.nn function
:param b_value: float
:param s_value: float
'''
# Number of layers to stack
depth = len(filter_size)
# Default arguments where None was passed in
if stride is None:
stride = np.ones(depth)
if padding is None:
padding = ['SAME'] * depth
if activation_fn is None:
activation_fn = [tf.nn.relu] * depth
if b_value is None:
b_value = np.zeros(depth)
if s_value is None:
s_value = np.ones(depth)
if bn is None:
bn = [True] * depth
# Make sure that number of layers is consistent
assert len(output_channels) == depth
assert len(stride) == depth
assert len(padding) == depth
assert len(activation_fn) == depth
assert len(b_value) == depth
assert len(s_value) == depth
assert len(bn) == depth
# Stack convolutional layers
for l in range(depth):
self.conv2d(filter_size=filter_size[l],
output_channels=output_channels[l],
stride=stride[l],
padding=padding[l],
activation_fn=activation_fn[l],
b_value=b_value[l],
s_value=s_value[l],
bn=bn[l], trainable=trainable)
def deconv2d(self, filter_size, output_channels, stride=1, padding='SAME', activation_fn=tf.nn.relu, b_value=0.0,
s_value=1.0, bn=True, trainable=True):
"""
2D Deconvolutional Layer
:param filter_size: int. assumes square filter
:param output_channels: int
:param stride: int
:param padding: 'VALID' or 'SAME'
:param activation_fn: tf.nn function
:param b_value: float
:param s_value: float
"""
self.count['deconv'] += 1
scope = 'deconv_' + str(self.count['deconv'])
with tf.variable_scope(scope):
# Calculate the dimensions for deconv function
batch_size = tf.shape(self.input)[0]
input_height = tf.shape(self.input)[1]
input_width = tf.shape(self.input)[2]
if padding == "VALID":
out_rows = (input_height - 1) * stride + filter_size
out_cols = (input_width - 1) * stride + filter_size
else: # padding == "SAME":
out_rows = input_height * stride
out_cols = input_width * stride
# Deconv function
input_channels = self.input.get_shape()[3]
output_shape = [filter_size, filter_size, output_channels, input_channels]
w = self.weight_variable(name='weights', shape=output_shape, trainable=trainable)
deconv_out_shape = tf.stack([batch_size, out_rows, out_cols, output_channels])
self.input = tf.nn.conv2d_transpose(self.input, w, deconv_out_shape, [1, stride, stride, 1], padding)
if bn is True: # batch normalization
self.input = self.batch_norm(self.input)
if b_value is not None: # bias value
b = self.const_variable(name='bias', shape=[output_channels], value=b_value, trainable=trainable)
self.input = tf.add(self.input, b)
if s_value is not None: # scale value
s = self.const_variable(name='scale', shape=[output_channels], value=s_value, trainable=trainable)
self.input = tf.multiply(self.input, s)
if activation_fn is not None: # non-linear activation function
self.input = activation_fn(self.input)
print(scope + ' output: ' + str(self.input.get_shape())) # print shape of output
def deconvnet(self, filter_sizes, output_channels, strides=None, padding=None, activation_fn=None, b_value=None,
s_value=None, bn=None, trainable=True):
'''
Shortcut for creating a 2D Deconvolutional Neural Network in one line
Stacks multiple deconv2d layers, with arguments for each layer defined in a list.
If an argument is left as None, then the conv2d defaults are kept
:param filter_sizes: int. assumes square filter
:param output_channels: int
:param stride: int
:param padding: 'VALID' or 'SAME'
:param activation_fn: tf.nn function
:param b_value: float
:param s_value: float
'''
# Number of layers to stack
depth = len(filter_sizes)
# Default arguments where None was passed in
if strides is None:
strides = np.ones(depth)
if padding is None:
padding = ['SAME'] * depth
if activation_fn is None:
activation_fn = [tf.nn.relu] * depth
if b_value is None:
b_value = np.zeros(depth)
if s_value is None:
s_value = np.ones(depth)
if bn is None:
bn = [True] * depth
# Make sure that number of layers is consistent
assert len(output_channels) == depth
assert len(strides) == depth
assert len(padding) == depth
assert len(activation_fn) == depth
assert len(b_value) == depth
assert len(s_value) == depth
assert len(bn) == depth
# Stack convolutional layers
for l in range(depth):
self.deconv2d(filter_size=filter_sizes[l], output_channels=output_channels[l], stride=strides[l],
padding=padding[l], activation_fn=activation_fn[l], b_value=b_value[l], s_value=s_value[l],
bn=bn[l], trainable=trainable)
def flatten(self, keep_prob=1):
"""
Flattens 4D Tensor (from Conv Layer) into 2D Tensor (to FC Layer)
:param keep_prob: int. set to 1 for no dropout
"""
self.count['flat'] += 1
scope = 'flat_' + str(self.count['flat'])
with tf.variable_scope(scope):
# Reshape function
input_nodes = tf.Dimension(
self.input.get_shape()[1] * self.input.get_shape()[2] * self.input.get_shape()[3])
output_shape = tf.stack([-1, input_nodes])
self.input = tf.reshape(self.input, output_shape)
# Dropout function
if keep_prob != 1:
self.input = tf.nn.dropout(self.input, keep_prob=keep_prob)
print(scope + ' output: ' + str(self.input.get_shape()))
def fc(self, output_nodes, keep_prob=1, activation_fn=tf.nn.relu, b_value=0.0, s_value=1.0, bn=True,
trainable=True):
"""
Fully Connected Layer
:param output_nodes: int
:param keep_prob: int. set to 1 for no dropout
:param activation_fn: tf.nn function
:param b_value: float or None
:param s_value: float or None
:param bn: bool
"""
self.count['fc'] += 1
scope = 'fc_' + str(self.count['fc'])
with tf.variable_scope(scope):
# Flatten if necessary
if len(self.input.get_shape()) == 4:
input_nodes = tf.Dimension(
self.input.get_shape()[1] * self.input.get_shape()[2] * self.input.get_shape()[3])
output_shape = tf.stack([-1, input_nodes])
self.input = tf.reshape(self.input, output_shape)
# Matrix Multiplication Function
input_nodes = self.input.get_shape()[1]
output_shape = [input_nodes, output_nodes]
w = self.weight_variable(name='weights', shape=output_shape, trainable=trainable)
self.input = tf.matmul(self.input, w)
if bn is True: # batch normalization
self.input = self.batch_norm(self.input, 'fc')
if b_value is not None: # bias value
b = self.const_variable(name='bias', shape=[output_nodes], value=b_value, trainable=trainable)
self.input = tf.add(self.input, b)
if s_value is not None: # scale value
s = self.const_variable(name='scale', shape=[output_nodes], value=s_value, trainable=trainable)
self.input = tf.multiply(self.input, s)
if activation_fn is not None: # activation function
self.input = activation_fn(self.input)
if keep_prob != 1: # dropout function
self.input = tf.nn.dropout(self.input, keep_prob=keep_prob)
print(scope + ' output: ' + str(self.input.get_shape()))
def maxpool(self, k=2, s=None, globe=False):
"""
Takes max value over a k x k area in each input map, or over the entire map (global = True)
:param k: int
:param globe: int, whether to pool over each feature map in its entirety
"""
self.count['mp'] += 1
scope = 'maxpool_' + str(self.count['mp'])
with tf.variable_scope(scope):
if globe is True: # Global Pool Parameters
k1 = self.input.get_shape()[1]
k2 = self.input.get_shape()[2]
s1 = 1
s2 = 1
padding = 'VALID'
else:
k1 = k
k2 = k
if s is None:
s1 = k
s2 = k
else:
s1 = s
s2 = s
padding = 'SAME'
# Max Pool Function
self.input = tf.nn.max_pool(self.input, ksize=[1, k1, k2, 1], strides=[1, s1, s2, 1], padding=padding)
print(scope + ' output: ' + str(self.input.get_shape()))
def avgpool(self, k=2, s=None, globe=False):
"""
Averages the values over a k x k area in each input map, or over the entire map (global = True)
:param k: int
:param globe: int, whether to pool over each feature map in its entirety
"""
self.count['ap'] += 1
scope = 'avgpool_' + str(self.count['mp'])
with tf.variable_scope(scope):
if globe is True: # Global Pool Parameters
k1 = self.input.get_shape()[1]
k2 = self.input.get_shape()[2]
s1 = 1
s2 = 1
padding = 'VALID'
else:
k1 = k
k2 = k
if s is None:
s1 = k
s2 = k
else:
s1 = s
s2 = s
padding = 'SAME'
# Average Pool Function
self.input = tf.nn.avg_pool(self.input, ksize=[1, k1, k2, 1], strides=[1, s1, s2, 1], padding=padding)
print(scope + ' output: ' + str(self.input.get_shape()))
def res_layer(self, output_channels, filter_size=3, stride=1, activation_fn=tf.nn.relu, bottle=False,
trainable=True):
"""
Residual Layer: Input -> BN, Act_fn, Conv1, BN, Act_fn, Conv 2 -> Output. Return: Input + Output
If stride > 1 or number of filters changes, decrease dims of Input by passing through a 1 x 1 Conv Layer
The bottle option changes the Residual layer blocks to the bottleneck structure
:param output_channels: int
:param filter_size: int. assumes square filter
:param stride: int
:param activation_fn: tf.nn function
:param bottle: boolean
"""
self.count['rn'] += 1
scope = 'resnet_' + str(self.count['rn'])
input_channels = self.input.get_shape()[3]
with tf.variable_scope(scope):
# Determine Additive Output if dimensions change
# Decrease Input dimension with 1 x 1 Conv Layer with stride > 1
if (stride != 1) or (input_channels != output_channels):
with tf.variable_scope('conv0'):
output_shape = [1, 1, input_channels, output_channels]
w = self.weight_variable(name='weights', shape=output_shape, trainable=trainable)
additive_output = tf.nn.conv2d(self.input, w, strides=[1, stride, stride, 1], padding='SAME')
b = self.const_variable(name='bias', shape=[output_channels], value=0.0)
additive_output = tf.add(additive_output, b)
else:
additive_output = self.input
# First Conv Layer. Implement stride in this layer if desired.
with tf.variable_scope('conv1'):
fs = 1 if bottle else filter_size
oc = output_channels // 4 if bottle else output_channels
output_shape = [fs, fs, input_channels, oc]
w = self.weight_variable(name='weights', shape=output_shape, trainable=trainable)
self.input = self.batch_norm(self.input)
self.input = activation_fn(self.input)
self.input = tf.nn.conv2d(self.input, w, strides=[1, stride, stride, 1], padding='SAME')
b = self.const_variable(name='bias', shape=[oc], value=0.0)
self.input = tf.add(self.input, b)
# Second Conv Layer
with tf.variable_scope('conv2'):
input_channels = self.input.get_shape()[3]
oc = output_channels // 4 if bottle else output_channels
output_shape = [filter_size, filter_size, input_channels, oc]
w = self.weight_variable(name='weights', shape=output_shape, trainable=trainable)
self.input = self.batch_norm(self.input)
self.input = activation_fn(self.input)
self.input = tf.nn.conv2d(self.input, w, strides=[1, 1, 1, 1], padding='SAME')
b = self.const_variable(name='bias', shape=[oc], value=0.0)
self.input = tf.add(self.input, b)
if bottle:
# Third Conv Layer
with tf.variable_scope('conv3'):
input_channels = self.input.get_shape()[3]
output_shape = [1, 1, input_channels, output_channels]
w = self.weight_variable(name='weights', shape=output_shape, trainable=trainable)
self.input = self.batch_norm(self.input)
self.input = activation_fn(self.input)
self.input = tf.nn.conv2d(self.input, w, strides=[1, 1, 1, 1], padding='SAME')
b = self.const_variable(name='bias', shape=[output_channels], value=0.0)
self.input = tf.add(self.input, b)
# Add input and output for final return
self.input = self.input + additive_output
print(scope + ' output: ' + str(self.input.get_shape()))
def noisy_and(self, num_classes, trainable=True):
""" Multiple Instance Learning (MIL), flexible pooling function
:param num_classes: int, determine number of output maps
"""
assert self.input.get_shape()[3] == num_classes # input tensor should have map depth equal to # of classes
scope = 'noisyAND'
with tf.variable_scope(scope):
a = self.const_variable(name='a', shape=[1], value=1.0, trainable=trainable)
b = self.const_variable(name='b', shape=[1, num_classes], value=0.0, trainable=trainable)
mean = tf.reduce_mean(self.input, axis=[1, 2])
self.input = (tf.nn.sigmoid(a * (mean - b)) - tf.nn.sigmoid(-a * b)) / (
tf.sigmoid(a * (1 - b)) - tf.sigmoid(-a * b))
print(scope + ' output: ' + str(self.input.get_shape()))
def get_output(self):
"""
:return tf.Tensor, output of network
"""
return self.input
def batch_norm(self, x, type='conv', epsilon=1e-3):
"""
Batch Normalization: Apply mean subtraction and variance scaling
:param x: input feature map stack
:param type: string, either 'conv' or 'fc'
:param epsilon: float
:return: output feature map stack
"""
# Determine indices over which to calculate moments, based on layer type
if type == 'conv':
size = [0, 1, 2]
else: # type == 'fc'
size = [0]
# Calculate batch mean and variance
batch_mean1, batch_var1 = tf.nn.moments(x, size, keep_dims=True)
# Apply the initial batch normalizing transform
z1_hat = (x - batch_mean1) / tf.sqrt(batch_var1 + epsilon)
return z1_hat
@staticmethod
def print_log(message):
""" Writes a message to terminal screen and logging file, if applicable"""
print(message)
logging.info(message)
@staticmethod
def weight_variable(name, shape, trainable):
"""
:param name: string
:param shape: 4D array
:return: tf variable
"""
w = tf.get_variable(name=name, shape=shape, initializer=tf.contrib.layers.variance_scaling_initializer(),
trainable=trainable)
weights_norm = tf.reduce_sum(tf.nn.l2_loss(w),
name=name + '_norm') # Should user want to optimize weight decay
tf.add_to_collection('weight_losses', weights_norm)
return w
@staticmethod
def const_variable(name, shape, value, trainable):
"""
:param name: string
:param shape: 1D array
:param value: float
:return: tf variable
"""
return tf.get_variable(name, shape, initializer=tf.constant_initializer(value), trainable=trainable)
|
b819d9d113e99285b7340e18e712e4c90745804f | georgelzh/Cracking-the-Code-Interview-Solutions | /recursionAndDynamicProgramming/recursiveMultiply.py | 2,225 | 4.09375 | 4 | """
Recursive Multiply: Write a recursive function to multiply two positive integers without using the
*operator.You can use addition, subtraction, and bit shifting, but you should minimize the number
of those operations
Hints: #166, #203, #227, #234, #246, #280
"""
"""
# solution 1
def minProduct(a, b):
print(a, b)
bigger = a if a >= b else b
smaller = a if a < b else b
return minProductHelper(smaller, bigger)
def minProductHelper(smaller, bigger):
if smaller == 0:
return 0
if smaller == 1:
return bigger
# compute half. if uneven, compute other half. if even double it
s = smaller >> 1 # divide by 2
side1 = minProduct(s, bigger)
side2 = side1
if smaller % 2 == 1:
side2 = minProductHelper(smaller - s, bigger)
return side1 + side2
# solution 2
# deduce repeated work with cache, we know bigger number is always the same
# in our algorithms so we just need to keep track of the smaller in cache
def minProduct(a, b):
print(a, b)
bigger = a if a >= b else b
smaller = a if a < b else b
cache = {}
return minProductHelper(smaller, bigger, cache)
def minProductHelper(smaller, bigger, cache):
if smaller == 0:
return 0
if smaller == 1:
return bigger
if smaller in cache and cache[smaller] > 0:
return cache[smaller]
# compute half. if uneven, compute other half. if even double it
s = smaller >> 1 # divide by 2
side1 = minProduct(s, bigger)
side2 = side1
if smaller % 2 == 1:
side2 = minProductHelper(smaller - s, bigger, cache)
cache[smaller] = side1 + side2
return cache[smaller]
"""
def minProduct(a, b):
print(a, b)
bigger = a if a >= b else b
smaller = a if a < b else b
return minProductHelper(smaller, bigger)
def minProductHelper(smaller, bigger):
if smaller == 0:
return 0
if smaller == 1:
return bigger
# compute half. if uneven, compute other half. if even double it
s = smaller >> 1 # divide by 2
halfprod = minProduct(s, bigger)
if smaller % 2 == 0:
return halfprod + halfprod
else:
return halfprod + halfprod + bigger
a = minProduct(2, 5)
print(a) |
104de4a5244ef809fe899336f0f5ad62c5eadbed | turing-20/python-cte | /runner up score.py | 634 | 4.21875 | 4 | """Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given scores. Store them in a list and find the score of the runner-up.
Input Format
The first line contains . The second line contains an array of integers each separated by a space.
Constraints
Output Format
Print the runner-up score.
Sample Input 0
5
2 3 6 6 5
Sample Output 0
5
Explanation 0
Given list is . The maximum score is , second maximum is . Hence, we print as the runner-up score."""
n=int(input())
arr=set(map(int,input().split()))
arr=list(arr)
print(arr)
print(arr[len(arr)-2]) |
0a12025c334eeb34cdf57b20b14f544476bd7f3a | akomawar/Python-codes | /Practise_Assignments/function.py | 289 | 4.03125 | 4 | def addition():
n1=int(input("Enter 1st no.: "))
n2=int(input("Enter 2nd no.: "))
print("Addition of 1st and 2nd is: ", n1+n2)
def subtraction():
n1=int(input("Enter 1st no.: "))
n2=int(input("Enter 2nd no.: "))
print("Subtraction of 1st and 2nd is: ",n1-n2)
|
928b161b7ade43d615f1020cb6afa7d50a50f5b7 | markogolub/LP | /ColoringAreaAbove.py | 1,033 | 3.5625 | 4 | import pylab as plt
import numpy as np
# Format of (in)equation is 'y (<, >)= ax + b'.
# Will be added later for the user to enter the (in)equations.
# Linear problem:
# 1) X + 2Y >= 16
# 2) -5X + 3Y >= 45
# X,Y >=0
# Express (in)equations to this format:
# 1) Y >= -1/2X + 8
# 2) Y >= 5/3X + 15
# Range of points for which is drawn plot.
x = np.linspace(0,20)
plt.xlim(0,20)
plt.ylim(0,20)
a1, b1 = -1/2, 8
a2, b2 = -5/3, 15
y1 = a1*np.power(x, 1)+b1
y2 = a2*np.power(x,1)+b2
plt.plot(x, y1, 'black', label="Y = -1/2X + 8")
plt.plot(x, y2, 'red', label="Y = -5/3X + 15")
y3 = np.maximum(y1, y2)
xi = (b1-b2) / (a2-a1)
yi = a1 * xi + b1
intersection = (xi, yi)
plt.title('Finding area above', fontsize=10)
plt.scatter(xi,yi, color='blue')
plt.legend(loc="upper right")
# Infinity represented with 1000.
plt.fill_between(x, y3, 1000, color='grey', alpha=.3)
# Saving plot to .png format file.
# Warning: may overwrite exitsting file with same name.
# plt.savefig("above.png", bbox_inches='tight')
plt.show() |
3ccf57f03283f69117e6b4b689aeeec1ddcceac7 | kapoor-rakshit/Miscellaneous | /py_deque.py | 1,143 | 4.09375 | 4 |
# REFERENCE : https://www.hackerrank.com/challenges/py-collections-deque/problem
# collections.deque()
# A deque is a double-ended queue.
# It can be used to add or remove elements from both ends.
# Deque support thread safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.
from collections import deque
d = deque() # initialize deque()
d.append(1) # deque([1])
d.appendleft(2) # deque([2, 1])
d.clear() # deque([])
d.extend('1') # deque(['1'])
d.extendleft('234') # deque(['4', '3', '2', '1'])
d.count('1') # 1
d.pop() # deque(['4', '3', '2'])
d.popleft() # deque(['3', '2'])
d.extend('7896')
d.remove('2') # deque(['3', '7', '8', '9', '6'])
d.reverse() # deque(['6', '9', '8', '7', '3'])
|
fe9f050ee46c21860ed7e6da785cd3f6880a844b | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/wwhite/Lesson01/spotify_danceability.py | 816 | 3.609375 | 4 | #!/usr/bin/env python
"""
Get artists and song names for for tracks with danceability scores over 0.8 and loudness scores below -5.0.
In other words, quiet yet danceable tracks.
Also, these tracks should be sorted in descending order by danceability so that the most danceable tracks are up top.
"""
import pandas as pd
music = pd.read_csv("featuresdf.csv")
# Songs with danceability scores over 0.8
danceable = [x for x in music.danceability if x > 0.8]
# Get the artist and song name from 'music' where danceability > 0.8 and loudness < -5.0
results = sorted([(a, b, c, d) for a, b, c, d in zip(music.name, music.artists, music.danceability, music.loudness) if
c > 0.8 and d < -5], key=lambda tup: tup[2], reverse=True)
final_results = [(a[0], a[1]) for a in results]
print(final_results)
|
68031570a218601818104ad6debc3697b270ab17 | krstoilo/SoftUni-Basics | /Python-Basics/conditional_statements/toy_store.py | 684 | 3.640625 | 4 | trip_price = float(input())
puzzles = int(input())
dolls = int(input())
teddy_bears = int(input())
minions = int(input())
trucks = int(input())
puzzles_sum = puzzles * 2.60
dolls_sum = dolls * 3
teddy_bears_sum = teddy_bears * 4.10
minions_sum = minions * 8.20
trucks_sum = trucks * 2
total = puzzles_sum + dolls_sum + teddy_bears_sum + minions_sum + trucks_sum
toys_number = puzzles + dolls + teddy_bears + minions + trucks
if toys_number >= 50:
total = total * 0.75
rent_deducted = total * 0.9
if rent_deducted >= trip_price:
print(f'Yes! {(rent_deducted - trip_price):.2f} lv left.')
else:
print(f'Not enough money! {(trip_price - rent_deducted):.2f} lv needed.')
|
97c3cf09375237db11e94f10fbca8e32025386db | longyueying/LeetCode | /113.py | 783 | 3.515625 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
self.res = []
nums = []
self.solver(root, nums, 0, sum)
return self.res
def solver(self, root, nums, v, sum):
if root==None:
return
nums.append[root.val]
v = v + root.val
if root.left==None and root.right==None:
if v== sum:
self.res.append(nums[:])
nums.pop()
return
self.solver(root.left, nums, v, sum)
self.solver(root.right, nums, v, sum)
nums.pop() |
ad3de89487692604ac6616381c3e6f9f4d2b82e1 | nomad-vino/open-tamil | /solthiruthi/datastore.py | 4,772 | 3.53125 | 4 | ## -*- coding: utf-8 -*-
## (C) 2015 Muthiah Annamalai,
##
from __future__ import print_function
import abc
import sys
import codecs
import argparse
from tamil import utf8
from pprint import pprint
PYTHON3 = (sys.version[0] == '3')
class Trie:
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def add(self,word):
return
@abc.abstractmethod
def isWord(self,word):
return
@abc.abstractmethod
def getAllWords(self):
return
@staticmethod
def mk_empty_trie(alpha_len):
return [[False,None] for i in range(alpha_len)]
def loadWordFile(self,filename):
# words will be loaded from the file into the Trie structure
with codecs.open(filename,'r','utf-8') as fp:
map( lambda word: self.add(word.strip()), fp.readlines() )
return
class SlowTrie(Trie):
" deque trie where number of nodes grows with time "
pass
class TamilTrie(Trie):
"Store a list of words into the Trie data structure"
@staticmethod
def buildEnglishTrie(nalpha=26):
# utility method
to_eng = lambda x: chr(x+ord('a'))
eng_idx = lambda x: ord(x) - ord('a')
obj = TamilTrie(eng_idx,to_eng,nalpha)
return obj
def __init__(self, get_idx = utf8.getidx, invert_idx = utf8.tamil, alphabet_len = utf8.TA_LETTERS_LEN):
self.L = alphabet_len
self.trie = Trie.mk_empty_trie(self.L)
self.word_limits = Trie.mk_empty_trie(self.L)
self.getidx = get_idx
self.invertidx = invert_idx
def getAllWords(self):
# list all words in the trie structure in DFS fashion
all_words = []
self.getAllWordsHelper(self.trie,self.word_limits,prefix=[],all_words=all_words)
return all_words
def getAllWordsHelper(self,ref_trie,ref_word_limits,prefix,all_words):
for letter_pos in range(0,len(ref_trie)):
if ref_trie[letter_pos][0]:
letter = self.invertidx( letter_pos )
prefix.append( letter )
if ref_word_limits[letter_pos][0]:
all_words.append( u"".join(prefix) )
if ref_trie[letter_pos][1]:
# DFS
self.getAllWordsHelper(ref_trie[letter_pos][1],ref_word_limits[letter_pos][1],prefix,all_words)
if len(prefix) > 0:
prefix.pop()
else:
pass
return
def isWord(self,word):
# see if @word is present in the current Trie; return True or False
letters = utf8.get_letters(word)
wLen = len(letters)
ref_trie = self.trie
ref_word_limits = self.word_limits
for itr,letter in enumerate(letters):
idx = self.getidx( letter )
#print(idx, letter)
if itr == (wLen-1):
break
if not ref_trie[idx][1]:
return False #this branch of Trie did not exist
ref_trie = ref_trie[idx][1]
ref_word_limits = ref_word_limits[idx][1]
return ref_word_limits[idx][0]
def add(self,word):
# trie data structure is built here
#print("*"*30,"adding","*"*30)
letters = utf8.get_letters(word)
wLen = len(letters)
ref_trie = self.trie
ref_word_limits = self.word_limits
for itr,letter in enumerate(letters):
try:
idx = self.getidx( letter )
except Exception as exp:
continue
#print(idx, itr)
ref_trie[idx][0] = True
if itr == (wLen-1):
break
if not ref_trie[idx][1]:
ref_trie[idx][1] = Trie.mk_empty_trie(self.L)
ref_word_limits[idx][1] = Trie.mk_empty_trie(self.L)
ref_trie = ref_trie[idx][1]
ref_word_limits = ref_word_limits[idx][1]
ref_word_limits[idx][0] = True
#pprint( self.trie )
#pprint( self.word_limits )
def do_stuff():
from pprint import pprint
obj = TamilTrie.buildEnglishTrie()
#pprint( obj.trie )
[obj.add(w) for w in ['apple','amma','appa','love','strangeness']]
all_words = ['apple','amma','appa','love','strangeness','purple','yellow','tail','tuna','maki','ammama']
print("###### dostuff ################################")
for w in all_words:
print(w,str(obj.isWord(w)))
#pprint( obj.trie )
pprint( obj.getAllWords() )
return obj
def do_load():
" 4 GB program - very inefficient "
obj = TamilTrie()
obj.loadWordFile('data/tamilvu_dictionary_words.txt')
print(len(obj.getAllWords()))
if __name__ == u"__main__":
do_stuff()
|
06328b450d81cdd19ee270573a0b660fea083cbd | wrojek0/python | /zadania5/frac.py | 2,405 | 3.515625 | 4 |
def add_frac(frac1, frac2): # frac1 + frac2
res = []
if frac1[1] == frac2[1]:
res.append(frac1[0]+frac2[0])
res.append(frac1[1])
reduce(res)
return res
else:
common_denominator(frac1,frac2)
res.append(frac1[0]+frac2[0])
res.append(frac1[1])
reduce(res)
return res
return res
def sub_frac(frac1, frac2): # frac1 - frac2
res = []
if frac1[1] == frac2[1]:
res.append(frac1[0]-frac2[0])
res.append(frac1[1])
reduce(res)
return res
else:
common_denominator(frac1,frac2)
res.append(frac1[0]-frac2[0])
res.append(frac1[1])
reduce(res)
return res
def mul_frac(frac1, frac2): # frac1 * frac2
res = []
res.append(frac1[0]*frac2[0])
res.append(frac1[1]*frac2[1])
reduce(res)
return res
def div_frac(frac1, frac2): # frac1 / frac2
res = []
res.append(frac1[0]*frac2[1])
res.append(frac1[1]*frac2[0])
reduce(res)
return res
def is_positive(frac): # bool, czy dodatni
if (frac[0] * frac[1]) > 0:
return True
else:
return False
def is_zero(frac): # bool, typu [0, x]
if frac[0] == 0:
return True
else:
return False
def cmp_frac(frac1, frac2): # -1 | 0 | +1
common_denominator(frac1,frac2)
if frac1[0]< frac2[0]:
return -1
elif frac1[0]> frac2[0]:
return 1
else:
return 0
def frac2float(frac): # konwersja do float
f = frac[0]/frac[1]
return f
###################################################################
#funkcja sprowadza 2 ulamki do wspolnego mianownika
def common_denominator(frac1,frac2):
if( frac1[1] == frac2[1] ):
return True
else:
frac1[0]*=frac2[1]
frac2[0]*=frac1[1]
frac1[1]*=frac2[1]
frac2[1]=frac1[1]
return True
#redukcja ulamka do najprostszej postaci
def reduce(frac):
if frac[0] > frac[1]:
larger = frac[0]
else:
larger = frac[1]
i = 1
while i<=larger:
if frac[0] % i == 0 and frac[1] % i == 0:
nwd = i
i+=1
if nwd != 0:
frac[0] /= nwd
frac[1] /= nwd
###################################################################
|
935c2ac94b28e2b188cc168a173825fbf6ea2c82 | DougOliver12/My-Python-Code | /Admissions/Admissions.py | 3,129 | 4.4375 | 4 | #!/usr/bin/python
# William Thing
# April 20, 2014
# Admissions
#
# This program will compare two different applicants
# taking in either their ACT or SAT score and overall
# GPA to determine which applicant is more competitive.
# Prints the introduction of the Admissions program
def intro_to_program():
print("This program compares two applicants to");
print("determine which one seems like the stronger");
print("applicant. For each candidate I will need");
print("either SAT or ACT scores plus a weighted GPA.");
print("");
# Ask the user if they want to either enter a student's SAT or ACT score
# and returns their overall score for comparison of competitiveness.
def use_ACT_or_SAT():
response = raw_input("do you have 1) SAT scores or 2) ACT scores? ");
if (response == '1'):
return calc_SAT();
else:
return calc_ACT();
# Returns an overall score from user's ACT score input.
# Also prints student's exam score and gpa score.
def calc_ACT():
ACT_english_score = int(raw_input("ACT English? "));
ACT_math_score = int(raw_input("ACT math? "));
ACT_reading_score = int(raw_input("ACT reading? "));
ACT_science_score = int(raw_input("ACT science? "));
exam_score = (ACT_english_score + 2*ACT_math_score +
ACT_reading_score + ACT_science_score)/1.8;
print("exam score = %.1f" % exam_score);
gpa_score = gpa_score_calc();
return exam_score + gpa_score;
# Returns an overall score from user's SAT score input.
# Also prints student's exam score and gpa score.
def calc_SAT():
SAT_math_score = int(raw_input("SAT math? "));
SAT_reading_score = int(raw_input("SAT critical reading? "));
SAT_writing_score = int(raw_input("SAT writing? "));
exam_score = float((2 * SAT_math_score + SAT_reading_score
+ SAT_writing_score)/32);
print("exam score = %.1f" % exam_score);
gpa_score = gpa_score_calc();
return exam_score + gpa_score;
# Returns overall gpa score determined by users gpa inputs
def gpa_score_calc():
gpa = float(raw_input("overall GPA? "));
max_gpa = float(raw_input("max GPA? "));
trans_mult = float(raw_input("Transcript Multiplier? "));
gpa_score = gpa/max_gpa * 100 * trans_mult;
print("GPA score = %.1f" % gpa_score);
return gpa_score;
# Takes in two applicant's score for comparison and prints outcome
def admissions_decision(app_one, app_two):
if (app_one > app_two):
print("The first applicant seems to be better");
elif (app_two > app_one):
print("The second applicant seems to be better");
else:
print("Hard decision both applicant have same scores");
def main():
intro_to_program();
print("Information for applicant #1:");
app_one_score = use_ACT_or_SAT();
print("");
print("Information for applicant #2:");
app_two_score = use_ACT_or_SAT();
print("");
print("First applicant overall score = %.1f" % app_one_score);
print("Second applicant overall score = %.1f" % app_two_score);
admissions_decision(app_one_score, app_two_score);
if __name__ == "__main__": main();
|
ddfca1b5bbaba0763299f45b4d5a2e589e9fb963 | PauloGLemos/VScodeBlueedytech | /Lista de exercícios 24.05 - 4.py | 1,495 | 4.0625 | 4 | #04 - Utilizando funções e listas faça um programa que receba uma data no formato DD/MM/AAAA e devolva uma string no formato D de mesPorExtenso de AAAA.
# Valide a data e retorne NULL caso a data seja inválida.
def Data():
Dia= int(input("Digite o Dia " ))
Mes= int(input("Digite o Mes " ))
Ano= int(input("Digite o Ano " ))
print("A data escolhida foi: " f"{Dia}/{Mes}/{Ano}")
Mes1 = ["null","Janeiro","Fevereiro","Marco","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"]
if Mes == 1:
print("A data escolhida foi: ",Dia,Mes1[1],Ano)
elif Mes == 2:
print("A data escolhida foi: ",Dia,Mes1[2],Ano)
elif Mes == 3:
print("A data escolhida foi: ",Dia,Mes1[3],Ano)
elif Mes == 4:
print("A data escolhida foi: ",Dia,Mes1[4],Ano)
elif Mes == 5:
print("A data escolhida foi: ",Dia,Mes1[5],Ano)
elif Mes == 6:
print("A data escolhida foi: ",Dia,Mes1[6],Ano)
elif Mes == 7:
print("A data escolhida foi: ",Dia,Mes1[7],Ano)
elif Mes == 8:
print("A data escolhida foi: ",Dia,Mes1[8],Ano)
elif Mes == 9:
print("A data escolhida foi: ",Dia,Mes1[9],Ano)
elif Mes == 10:
print("A data escolhida foi: ",Dia,Mes1[10],Ano)
elif Mes == 11:
print("A data escolhida foi: ",Dia,Mes1[11],Ano)
elif Mes == 12:
print("A data escolhida foi: ",Dia,Mes1[12],Ano)
else:
print("Mes inexistente")
Data()
|
13e8e3810d92c090a5a3a96a49e2d2e21c8aa7dc | NathanaelV/CeV-Python | /Aulas Mundo 3/aula16_tuplas.py | 1,775 | 4.15625 | 4 | # Challenge 72 - 77
lanche = ('Hamburguer', 'Suco', 'Pizza', 'Pudin', 'Batata Frita')
# Posso criar puplas sem usar parenteses
# Semelhante ao fatiamento de strings
print(lanche)
print('lanche[1]: ', lanche[1])
print('lanche[-1]: ', lanche[-1])
print('lanche[1:3]: ', lanche[1:3])
print('lanche[-2:]', lanche[-2:])
# Não posso atribuir valores a elementos da tupla, tenho que trocar tudo
# lanche[1] = 'Refigerante' # Esse comando é inválido
# Usando for:
print('\nUsando o for:')
for comida in lanche:
print(f'Eu vou comer {comida}')
print('Comi muito.\n')
print('length de lanche: ', len(lanche))
for cont in range(0, len(lanche)):
print(f'Vou comer {lanche[cont]}. Na posição {cont}')
for pos, cont in enumerate(lanche): # pos = enumerate; cont = lanche. Na ordem
print(f'Eu vou comer {cont}. Na posição {pos}')
# Mostrar em ordem alfabetica
print(sorted(lanche)) # Para fazer isso ele monta uma lista
print(lanche)
lanche = sorted(lanche) # Aqui lanche passa a ser uma lista e deixa de ser tupla
print(lanche)
# Criando uma nova tupla:
print('\nMontado uma tupla com int:')
a = (2, 5, 4)
b = (5, 8, 1, 2)
c = b + a
print(f'a + b = {a+b}')
print(f'b + a = c = {b+a}')
print(f'c.count(5): {c.count(5)}') # Mostra quantos tem
print(f'c.count(4): {c.count(4)}')
print(f'c.count(0): {c.count(0)}')
print(f'c.index(8): {c.index(8)}')
print(f'c.index(4): {c.index(4)}')
print(f'c.index(2): {c.index(2)}') # Pega a primeira vez que aparece
print(f'c.index(5): {c.index(5)}')
print(f'c.index(5, 1): {c.index(5, 1)}') # Procura o número 5 a partir da posição 1
# Mexendo com diferentes tipos:
print('\nMexendo com tipos diferente dentro de uma TUPLA.')
pessoa = 'Gustavo', 23, 98.5, 'M'
print(pessoa)
del(pessoa) # para apagar qualquer coisa
|
d751c9e87b4eef17e1c0af8b15fdeb884fdf7e99 | PhamQuocDatAI/TOAN-KHDL | /Toán 2.py | 716 | 3.75 | 4 | import numpy as np
import random
n = int(input("Nhập giá trị n: "))
# Tạo ma trận số nguyên cấp n ngẫu nhiên trong phạm vị cho trước
A = np.random.randint(-10, 10, (n, n))
print(A)
# Tính detA
print("Hạng của ma trận A: ", int(np.linalg.det(A)))
# Tính A^2, A^3
print("A^2 = ", A@A)
print("A^3 = ", (A@A)@A)
# Viết 1 hàm tạo ma trận random cấp n có detA != 0
# Viết 1 hàm tạo ma trận random cấp n có detA != 0 (n nhập từ bàn phím)
# Viết 1 hàm
# Input: --> n: int
# Output:
# print ma trận random cấp n
# Định thức của ma trận
# Hạng của ma trận
# Tính A^2, A^3
import numpy as np
import random
def matrix(n):
|
fb84ef210f3914e4441713f73c3c0ccfa748fcc0 | medmaster0/LonelyCiv | /Civ2/stonez/STONEZ.py | 2,151 | 3.78125 | 4 | #generates random 16 bit patterns of stonez
#smooth gentle formation
#I'm DRUNK when i wrote this!
import random
#GLOBALS
size = 16
#function to print out 2d list line by line
def print2D(list2d):
for row in list2d:
print row
#16 bits
def generateStone():
stone = [] #a 2D list for the pattern
#initialize list
for i in range(0, size):
row = [] #individual row
for j in range(0, size):
row.append(' ')
stone.append(row)
#we're gonna create a smooth stone, from bottom up, line by line
#lines are symmetrical!, centered
#to achieve smoothing effect, each line is either 1 greater or 1 less (or same) as prev
radius = random.randint(2,4) #radius is HALF the size of the line
for i in range(0,random.randint(14,15)): #will cycle through all rows except top one or two
for j in range(0,radius): #fill out a line between the two limits
try:
stone[15-i][7-j]='*'
stone[15-i][8+j]='*'
except:
z = z+1
#print "ignoring bounds error"
#Generate new radius, partly based on current radius
#maybe a little bigga, maybe a little smalla
radius = radius + random.randint(-2,+1)
# if radius < 0:
# radius = 0
# if radius == 7:
# radius = 6
#New radius to leave room for outline
if radius < 1:
radius = 1
if radius == 6:
radius = 5
return stone
######
#NOW FOR PIL IMAGE CREATION
from PIL import Image
#writes a new png image, given a filename and a weed 2d array list
def stoneWrite(filename, stone_in):
im = Image.open('Civ2/Civ2/weedz/blank.png')
#im = Image.open('test.png')
pixelMap = im.load()
img = Image.new( im.mode, im.size)
pixelsNew = img.load()
for i in range(img.size[0]):
for j in range(img.size[1]):
if stone_in[j][i] == '*':
pixelsNew[i,j] = (255,255,255,255)
#img.show()
img.save(filename,"PNG")
temp_stone = generateStone()
#print temp_stone
#Actual program
#These filenames might be a little wonky
#They are from the top level of the Cplus folder.
#It's where from the context of the C++ program calling this...
for z in range(100,200):
temp_stone = generateStone()
stoneWrite("Civ2/Civ2/stonez/"+str(z)+".png",temp_stone)
|
b834992f30616cbfb52101bd9bedc80756711f17 | yrunts/python-training-lessons | /lesson3/task1.py | 4,063 | 4.3125 | 4 | #coding: utf-8
"""Solution to task 1 from lesson 3."""
def test():
"""Prints strings in different representation."""
print 'It\'s a test python string\nwith a "newline" character.'
print r'It\'s a test python string\nwith two backslashes an no "newline" ' \
r'character.'
print '''It's a test python string
with a "newline" character and leading white-space.'''
print "It's a test python string\nwith a \"newline\" character."
print r"It's a test python string with two \"backslash\" characters."
print """It's a test python string\nwith a "newline" character."""
def draw_cat():
"""Draws cheshire cat with strings."""
print '_-_-_-_-_-_-_\n' \
'\ /\n' \
'| ^_____^ |\n' \
'/ (.) (.) \\\n' \
'| ( t ) | Miaowww\n' \
'\ ==/ /\n' \
'| |\n' \
'\'"\'"\'"\'"\'"\'"\''
print '''
_-_-_-_-_-_-_
\ /
| ^_____^ |
/ (.) (.) \\
| ( t ) | Miaowww
\ ==/ /
| |
'"'"'"'"'"'"'
'''
print r'_-_-_-_-_-_-_'
print r'\ /'
print r'| ^_____^ |'
print '/ (.) (.) \\'
print r'| ( t ) | Miaowww'
print r'\ ==/ /'
print r'| |'
print '\'"\'"\'"\'"\'"\'"\''
print """
_-_-_-_-_-_-_
\ /
| ^_____^ |
/ (.) (.) \\
| ( t ) | Miaowww
\ ==/ /
| |
'"'"'"'"'"'"'
"""
def join(*args, **kwargs):
"""Prints all positional and named argumets using string join method."""
if args:
print ', '.join([str(s) for s in args])
if kwargs:
sub_items = []
for k, v in kwargs.items():
sub_items.append(''.join([k, '=', v]))
print ', '.join(sub_items)
def format(*args, **kwargs):
"""Prints all positional and named argumets using string join and format
methods.
"""
if args:
print ', '.join([str(s) for s in args])
if kwargs:
sub_items = []
for k, v in kwargs.items():
sub_items.append('{}={}'.format(k, v))
print ', '.join(sub_items)
def split(s):
"""Restores function arguments from join and format functions.
:IVariables:
- `s`: an `string` output from join or format method;
"""
args_str, kwargs_str = s.split('\n')
args = tuple(args_str.split(', '))
kwargs = {}
for s in kwargs_str.split(', '):
k, v = s.split('=')
kwargs[k] = v
print args
print kwargs
def get_last_str(s):
"""Returns a last element (separated by a last comma) or the entire string
if there is no comma in it.
:IVariables:
- `s`: an `string`;
"""
return s.split(',')[-1] if ',' in s else s
VOWEL_LETTERS = ['a', 'e', 'i', 'o', 'u', 'y']
REPLACED_MAP = dict((l, l.upper()) for l in VOWEL_LETTERS)
def upper_vowel(s):
"""Uppercases all vowel letters in string.
:IVariables:
- `s`: an `string`;
"""
for k, v in REPLACED_MAP.iteritems():
s = s.replace(k, v)
return s
def slicing(s):
"""Returns the first 10 characters off string concatenated with the last
10 characters.
:IVariables:
- `s`: an `string`;
"""
return s[:10] + s[-10:] if len(s) > 10 else s
def to_ascii(s):
"""Returns string encoded to US-ASCII character set.
:IVariables:
- `s`: an `string`;
"""
return s.encode('ascii', 'ignore')
def main():
test()
draw_cat()
join(111, 'asdf', c='d', onemore='new_value')
format(111, 'asdf', c='d', onemore='new_value')
output = '111, asdf\n' \
'onemore=new_value, c=d'
split(output)
print get_last_str('bla bla')
print get_last_str('bla1,bla2,bla3')
print get_last_str('1,2,3,4,5,6,7')
print upper_vowel('sadfgsa dg345 dfg d')
print slicing('1234567890qwertyuiopasdfghjkl')
print slicing('123')
print to_ascii(u'1234')
print to_ascii(u'\xea\x80\x80abcd\xde\xb4')
print to_ascii(u'Ʃasd')
if __name__ == '__main__':
main()
|
55cb84b927d1d48bfa4c6b729863fdec602e94d2 | imbiginjapan/python_crash_course | /employee_test.py | 515 | 3.875 | 4 | import unittest
from employee import Employee
class TestEmployee(unittest.TestCase):
def test_give_default_raise(self):
employee = Employee("John","Smith",50000.00)
salary = employee.salary
employee.give_raise()
self.assertEqual(employee.salary, salary + 5000.00)
def test_give_custom_raise(self):
employee = Employee("John","Smith",50000.00)
salary = employee.salary
custom = 2500.00
employee.give_raise(custom)
self.assertEqual(employee.salary, salary + custom)
unittest.main()
|
70c7941ea5f40325bd1bc3c8c29807672a326a35 | tz-earl/partition-list | /partition-list.py | 3,796 | 3.859375 | 4 | from list_to_linked import ListNode, list_to_linked, linked_to_list
class Solution:
def partition_1(self, head: ListNode, x: int) -> ListNode:
# Maintain two refs p1 and p2 that form the boundary of the partitioning
# between nodes smaller than x and nodes equal to or greater than x.
# p1 points to the rightmost smaller node, p2 points to the leftmode equal/bigger node.
# p1 will shift to the right as smaller nodes are added, while p2 does not change once found.
# Iterate once through the list, processing each node.
p1 = p2 = None
prev = None
curr = head
while curr is not None:
if curr.val < x:
if p2 is None: # No large nodes found yet
prev = curr
curr = curr.next
p1 = prev
elif p1 is None: # Large nodes already found, this is the first small node
temp = curr
prev.next = curr.next # Remove this node from its original position
curr = curr.next
temp.next = head # Insert this node at the head of the list
head = temp
p1 = temp
else: # Both p1 and p2 are not None
temp = curr
prev.next = curr.next # Remove this node
curr = curr.next
temp.next = p2 # Insert this node at the boundary
p1.next = temp
p1 = temp
else: # curr.val >= x
if p2 is None: # This is the first large node seen
p2 = curr
prev = curr
curr = curr.next
return head
def partition_2(self, head: ListNode, x: int) -> ListNode:
# Build two sublists, one for small nodes, the other for large nodes.
# Iterate once through the list, processing each node.
# If it's a small node, append it to the small list. Likewise, if it's
# a large node, append it to the large list.
# After every node has been added to one of the two lists, append the list
# of large nodes to the small one, and return the head to the small list.
head_small = last_small = None
head_large = last_large = None
# Iterate through the linked list, adding each node to either the small linked list
# or the large linked list.
curr = head
while curr is not None:
nxt = curr.next
if curr.val < x:
if head_small is None:
head_small = curr
last_small = curr
else:
last_small.next = curr
last_small = curr
else: # curr.val <= x
if head_large is None:
head_large = curr
last_large = curr
else:
last_large.next = curr
last_large = curr
curr.next = None
curr = nxt
# Append the linked list of large nodes to the linked list of small nodes.
if last_small is not None:
last_small.next = head_large
return head_small
else: # There were no small numbers
return head_large
if __name__ == '__main__':
lst_1 = [1, 4, 3, 2, 5, 2]
x = 3
print(lst_1, x)
lnked_1 = list_to_linked(lst_1)
result1 = Solution().partition_1(lnked_1, x)
back_to_list1 = linked_to_list(result1)
print(back_to_list1)
lnked_2 = list_to_linked(lst_1)
result2 = Solution().partition_2(lnked_2, x)
back_to_list2 = linked_to_list(result2)
print(back_to_list2)
|
9ff599334a46ee03743fd4988149affe93705b0f | JaviCeRodriguez/Procesamiento_De_Imagenes | /python/Unidad_2/ej9.py | 1,359 | 3.671875 | 4 | # Aplique a una imagen grayscale la transformación apropiada para que su
# histograma se comprima a un cierto rango definido por el usuario (shrinking).
import numpy as np
import matplotlib.pyplot as plt
from skimage import img_as_float
from skimage.color import gray2rgb
from skimage.io import imread
from skimage.exposure import rescale_intensity
import tkinter as tk
from tkinter import filedialog
def plot_img_hist(img, num_plot, title, bins=255):
'''
Plots de imagen e histograma
'''
# Imagen
plt.subplot(num_plot)
if len(img.shape) == 3:
plt.imshow(img, cmap='gray')
else: # len(img.shape) == 2
plt.imshow(gray2rgb(img), cmap='gray')
plt.title(title)
# Histograma
plt.subplot(num_plot + 2)
plt.hist(img_as_float(img).ravel(), bins=bins)
plt.xlim(0, 1)
def file_read():
file_path = filedialog.askopenfilename()
return file_path
try:
# Busco imagen y obtengo su ruta
root = tk.Tk()
root.withdraw()
img = imread(file_read())
out_range = (0, 50)
img_shrink = rescale_intensity(img, out_range=out_range).astype(np.uint8)
plot_img_hist(img, 221, 'Imagen original')
plot_img_hist(img_shrink, 222, 'Imagen shrinking', bins=out_range[1]-out_range[0])
plt.show()
except:
print('Cerraste la ventana!')
print('👋🏽')
root.destroy() |
aed5f4205af50a9b80fa3ff42e4646a4ede8a6e8 | francistianlal/Codability-test | /Ex 3.1 frogjump.py | 636 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 5 20:16:37 2020
Frog jump problem
@author: frank
"""
import unittest
Element_range = range(1,int(1e9+1))
def solution(X,Y,D):
if X not in Element_range or Y not in Element_range or D not in Element_range :
raise TypeError('element not in range')
if X > Y:
raise ValueError('X should be smaller than Y')
if (Y-X) % D != 0:
return (Y-X)//D + 1
return (Y-X)//D
class testsolution(unittest.TestCase):
def test_1(self):
self.assertEqual(solution(10,85,30),3)
if __name__ == '__main__':
unittest.main() |
c616b111409aa727d88719c5421c2f6988a0a42c | elvisestevan/thirty-days-code-challenge | /20-sorting.py | 587 | 3.828125 | 4 | #!/bin/python3
import sys
n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
# Write Your Code Here
def swap(list_sort, i, j):
aux = list_sort[i]
list_sort[i] = list_sort[j]
list_sort[j] = aux
numberOfSwaps = 0
for i in range(n):
for j in range(n - 1):
if (a[j] > a[j + 1]):
swap(a, j, j + 1)
numberOfSwaps += 1
if (numberOfSwaps == 0):
break
print("Array is sorted in {} swaps.".format(numberOfSwaps))
print("First Element: {}".format(a[0]))
print("Last Element: {}".format(a[n - 1]))
|
855149379fd695bba0b7a73f030fb68ed24d3575 | raythurman2386/cs-algorithms | /single_number/single_number.py | 705 | 4 | 4 | '''
Input: a List of integers where every int except one shows up twice
Returns: an integer
'''
def single_number(arr, cache={}):
# Your code here
# use dict to keep track of each number
# track how many times that number is seen
# return the number from the dict whose value is 1
# INITIAL IMPLEMENTATION
for num in arr:
if num not in cache:
cache[num] = 1
else:
cache[num] += 1
for k, v in cache.items():
if v == 1:
return k
if __name__ == '__main__':
# Use the main function to test your implementation
arr = [1, 1, 4, 4, 5, 5, 3, 3, 9, 0, 0]
print(f"The odd-number-out is {single_number(arr)}")
|
f41363225d12dd535fcef03e0a5c381a9dea06b7 | SamJ2018/LeetCode | /python/python语法/pyexercise/Exercise05_13.py | 234 | 3.640625 | 4 | count = 1
for i in range(100, 201):
if not (i % 5 == 0 and i % 6 == 0) and (i % 5 == 0 or i % 6 == 0):
if count % 10 != 0:
print(i, end = " ")
else:
print(i)
count += 1
|
f4cfb676f920816104d9e16023dbdc4eecf79b3e | Raushan-Raj2552/URI-solution | /1064.py | 149 | 3.765625 | 4 | a = 0
b = 0
for i in range(6):
c = float(input())
if c>0:
a+=c
b+=1
print(b,'valores positivos')
print('%0.1f'%(a/b)) |
71afaf6dd42d966529ccc606614bf35256ef32e3 | Chock-Chaloemchai/workshop2 | /string/f_string.py | 138 | 3.90625 | 4 | name = "chock"
age = 21
result = f"My name is {name}, and I am {age}"
print("result", result) # Output : My name is chock, and I am 21
|
558f365aaaf57b81b172c0ee37e7960679c633d9 | GVargas/mtec2002_assignments | /class9/labs/boat/draw_boat.py | 642 | 3.828125 | 4 | """
"""
import turtle
boat_color = ()
while True:
print "Pick a color for your boat"
user_input = raw_input(">")
turtle.color(user_input)
turtle.forward(150)
turtle.left(45)
turtle.forward(100)
turtle.right(45)
turtle.forward(50)
turtle.left(90)
turtle.forward(20)
turtle.left(90)
turtle.forward(150)
turtle.right(90)
turtle.forward(50)
turtle.left(90)
turtle.forward(125)
turtle.right(90)
turtle.backward(50)
turtle.left(90)
turtle.forward(150)
turtle.left(90)
turtle.forward(20)
turtle.left(90)
turtle.forward(50)
turtle.right(45)
turtle.forward(100)
turtle.left(45)
turtle.forward(50)
turtle.mainloop()
|
8249c21b34838733418789faab22966b04e73411 | Fondamenti18/fondamenti-di-programmazione | /students/1811200/homework01/program01.py | 1,527 | 3.96875 | 4 | '''
Si definiscono divisori propri di un numero tutti i suoi divisori tranne l'uno e il numero stesso.
Scrivere una funzione modi(ls,k) che, presa una lista ls di interi ed un intero
non negativo k:
1) cancella dalla lista ls gli interi che non hanno esattamente k divisori propri
2) restituisce una seconda lista che contiene i soli numeri primi di ls.
NOTA: un numero maggiore di 1 e' primo se ha 0 divisori propri.
ad esempio per ls = [121, 4, 37, 441, 7, 16]
modi(ls,3) restituisce la lista con i numeri primi [37,7] mentre al termine della funzione si avra' che la lista ls=[441,16]
Per altri esempi vedere il file grade.txt
ATTENZIONE: NON USATE LETTERE ACCENTATE.
ATTENZIONE: Se il grader non termina entro 30 secondi il punteggio dell'esercizio e' zero.
'''
def conta_divisori(n):
c=0
a=2
Dmax=n//2
while a<=Dmax :
if (n%a)==0:
# print(a)
c=c+1
a= a +1
return c
# if c==0:
# print ('il numero è primo')
# else:
# print('il numero non è primo')
def modi(ls,k):
lp=[]
lt=[]
if k>=0:
for el in ls:
if conta_divisori(el)==k:
lp.append(el)
if conta_divisori(el)==0:
lt.append(el)
print(lp)
print(lt)
else:
print('Non accettabile poichè k non è maggiore o uguale a zero')
|
f16a8c25e4cb931789a06a386b55871f53e5097a | ropable/algorithmic_toolbox | /course1/fibonacci_sum_last_digit.py | 1,090 | 4.0625 | 4 | # python3
import sys
def fibonacci_sum_naive(n):
"""Stupid example solution.
"""
if n <= 1:
return n
previous = 0
current = 1
sum = 1
for _ in range(n - 1):
previous, current = current, previous + current
sum += current
return sum % 10
def fib_matrix(n):
"""Efficient algorithm to return F(n) via matrix multiplication.
"""
if (n <= 1):
return n
v1, v2, v3 = 1, 1, 0
for rec in bin(n)[3:]:
calc = v2 * v2
v1, v2, v3 = v1 * v1 + calc, (v1 + v3) * v2, calc + v3 * v3
if rec == '1':
v1, v2, v3 = v1 + v2, v1, v2
return v2
def fib_sum_last_digit(n):
"""Returns the sum of Fibonacci numbers to n.
Sn = Fn+2 - 1
Ref: https://www.quora.com/What-is-the-sum-of-n-terms-of-a-Fibonacci-series
"""
if n <= 1:
return n
n = (n + 2) % 60 # Use the characteristic of the last digit cycling every 60 numbers.
return fib_matrix(n) - 1
if __name__ == '__main__':
n = int(sys.stdin.read())
print(str(fib_sum_last_digit(n))[-1:])
|
94802b1a1e4f163ad00bc1b4967e318107f3eb21 | jsmcmahon56/DAEN-500-Final | /main.py | 915 | 4.1875 | 4 | ##Jim McMahon
##DAEN 500 Final
##Problem 2
#this is the class that will manipulate the input string
class StringManipulator:
def __init__(self, currString = ''):
self.currString = currString
#method for getting user string input
def getString(self):
print('Enter a string')
user_input = input()
myString = str(user_input)
self.currString = myString
#method for making input all caps
def printString(self):
self.currString = self.currString.upper()
print(self.currString)
#methods are repeated below to test all cases mentioned in problem statement
if __name__ == '__main__':
newManipulator = StringManipulator()
newManipulator.getString()
newManipulator.printString()
newManipulator.getString()
newManipulator.printString()
newManipulator.getString()
newManipulator.printString()
|
820ba3e9dbdf965eef188ad3170ef1fa5a3c1b12 | tinnan/python_challenge | /06_itertools/055_maximize_it.py | 619 | 3.796875 | 4 | """
You are given a function f(X) = X^2.
You are also given K lists. The ith list consists of Ni elements.
You have to pick exactly one element from each list so that the equation below is maximized:
S = (f(X1) + f(X2) + ... + f(Xk))%M
Xi denotes the element picked from the ith list . Find the maximized value Smax obtained.
% denotes the modulo operator.
"""
from itertools import product
def compute(args):
s = 0
for a in args:
s += a**2
return s % M
K, M = list(map(int, input().split()))
C = list(product(*[map(int, input().split()[1:]) for _ in range(K)]))
print(max(map(compute, C)))
|
92df996b2aef01246bdae61f409224303d0ed8ad | Adityaar/Python | /permutateString.py | 217 | 3.765625 | 4 | def permutate(s):
res = []
if len(s) == 1:
res = [s]
else:
for i in range(len(s)):
#swap(s,i,j)
def permutateWrapper(l):
print permutate(l[1:])
|
86f57bf085df75f8c5fd52bb778a93cf729d195d | ntupenn/exercises | /medium/271.py | 1,485 | 3.65625 | 4 | """
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
Machine 1 (sender) has the function:
string encode(vector<string> strs) {
// ... your code
return encoded_string;
}
Machine 2 (receiver) has the function:
vector<string> decode(string s) {
//... your code
return strs;
}
So Machine 1 does:
string encoded_string = encode(strs);
and Machine 2 does:
vector<string> strs2 = decode(encoded_string);
strs2 in Machine 2 should be the same as strs in Machine 1.
Implement the encode and decode methods.
Note:
The string may contain any possible characters out of 256 valid ascii characters. Your algorithm should be generalized enough to work on any possible characters.
Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
Do not rely on any library method such as eval or serialize methods. You should implement your own encode/decode algorithm.
"""
def encode(strs):
res = ""
for s in strs:
res += str(len(s)) + ":" + s
return res
def decode(s):
res = []
idx = 0
num = 0
while idx < len(s):
if s[idx].isdigit():
while s[idx].isdigit():
num = num * 10 + int(s[idx])
idx += 1
else:
idx += 1
res.append(s[idx:idx+num])
idx += num
num = 0
return res
|
976ce426a93a3b267b4bcc563e427e06e0da0cac | zeroWin/Python | /Core python programming(2th)/Chapter 3/3_10_makeTextFile.py | 654 | 3.90625 | 4 | 'makeTextFile.py -- create text file'
import os
# Get filename
while True:
try:
fname = input('Enter file name: ')
fobj = open(fname,'r')
except IOError as e:
# Get file context(text) lines
all = []
print("Enter lines('.' by itself to quit).")
# loop until user terminates input
while True:
entry = input('Enter str > ')
if entry == '.':
break
else:
all.append(entry)
# Write lines to file with proper line-ending
fobj = open(fname,'w')
fobj.write('\n'.join(all))
fobj.writelines([])
fobj.close()
print('Done')
break
else: # Open succeed
fobj.close()
print("ERROR: '%s' already exists" % fname)
|
4b0f5ed3e626b31b913e93bb5ac9fd055f9ad618 | Surgeon-76/KaPythoshka | /Stepik/13_function/good_password/my.py | 376 | 3.859375 | 4 | # объявление функции
def is_password_good(password):
return len(password) >= 8 and password.islower() == False and password.isupper() == False and (password.isalnum() == True and password.isalpha()== False
and password.isdigit() == False)
# считываем данные
txt = input()
# вызываем функцию
print(is_password_good(txt)) |
561840cab2e44fa1a0a95ae258720ebcf641179b | gauravssnl/Data-Structures-and-Algorithms | /python/Data Structures and Algorithms in Python Book/stacks/reverse_file_contents.py | 600 | 3.921875 | 4 | from arraystack import ArrayStack
def reverse_file(filename):
"""Overwrite a given file with contents line-by-line in reversed order"""
S = ArrayStack()
original = open(filename)
for line in original:
S.push(line.rstrip('\n')) # we will re-insert newlines while writing
original.close()
# now write the contents in LIFO order
output = open(filename, 'w')
while not S.is_empty():
output.write(S.pop() + '\n') # add trailing new line
output.close()
if __name__ == "__main__":
filename = "hello.txt"
reverse_file(filename) |
d48ec6af2efa44bcec307523aa8fccd0816f0c35 | dcoats14/Portfolio | /Blackjack/gameFunction.py | 1,253 | 3.671875 | 4 | def die(self):
print("Your pet has died, you probably shouldn't own a pet in real life.")
self.isAlive = False
def ask_yes_no(question):
response = None
while response not in ("y","n"):
response = input(question).lower()
return response
def setName(self, name):
if len(name) > 4 or len(name) < 4:
if "uck" not in name:
if "sh" not in name:
if "unt" not in name:
self.name = name
def ask_number (question,low,high):
"""Ask for a number witnin a range."""
response = None
while response not in range(low,high):
response = int(input(question))
return response
class Player(object):
def __init__(self,name,score):
self.name = name
self.name = Score()
self.isAlive = True
self.lifes = 3
class Score(object):
def __init__(self):
self.score = 0
def add_to_score(self, points):
self.score += points
def take_points(self, points):
self.score -= points
if self.points <0:
self.score = 0
if __name__ == "__main__":
print("You ran this module directly (and did not import it).")
input("\n\nPress the enter key to exit.")
|
09acd830d15808cf6bb5e0501a9d7b1e77ac9022 | shaunagm/personal | /project_euler/p21-30/problem_25_1000_digit_fibionacci_number.py | 640 | 4.0625 | 4 | # The Fibonacci sequence is defined by the recurrence relation:
# Hence the first 12 terms will be:
# F1 = 1
# F2 = 1
# F3 = 2
# F4 = 3
# F5 = 5
# F6 = 8
# F7 = 13
# F8 = 21
# F9 = 34
# F10 = 55
# F11 = 89
# F12 = 144
# The 12th term, F12, is the first term to contain three digits.
# What is the first term in the Fibonacci sequence to contain 1000 digits?
import copy
import time
# simple solution
n_minus_2 = 1
n_minus_1 = 1
n = 2
list = [1,1]
while len(str(n)) < 1000:
list.append(n)
old_n = copy.copy(n)
n_minus_2 = copy.copy(n_minus_1)
n_minus_1 = copy.copy(old_n)
n = n_minus_1 + n_minus_2
list.append(n)
print len(list)
|
6b9409d8dcedd4a6dd9bf7a68a431d1257ecc41e | Monichre/Simple-Flask-App | /server.py | 1,100 | 3.578125 | 4 | from flask import Flask
from flask import render_template
# from flask import request # -- We can also lose this as well
app = Flask(__name__)
# -- Here we are adding routes to a function we've called index -- literally only because its the landing page -- It's actually a view
# -- You can add multiple routes to a function so that your application becomes more complex and so the function performs consistently
@app.route('/')
@app.route('/<name>') # -- This line tells flask to capture anything that comes after the initial forward slash -- in this case 'name'
def index():
# name = request.args.get('name', name) # -- Therefore we can actually get rid of this line to clean up the code
return render_template("index.html")
@app.route('/add/<int:num1>/<int:num2>')
def add(num1, num2):
# return '{} + {} = {}'.format(num1, num2, num1 * num2)
return render_template("add.html", num1 = num1, num2 = num2)
@app.route('/about')
def about():
return "This is the muh fuckin about page"
@app.route('/contact')
def contact():
return "Contact me yo"
app.run(debug=True)
|
4963b9cb189e0a093df3d327f71ee5a2509f2887 | youthinnovationclub/2020Moonhack | /Moonhack2020-Python YCIC Ray Tang.py | 2,870 | 4 | 4 | #!/bin/python3
import random
events = [
("You are beginning to smell.Would you like to take a shower?(type yes or no,then hit[ENTER]):",-200,0),
("You hear a hissing sound coming from a pipe.Would you like to investigate?(type yes or no,then hit[ENTER]):",-10,-500),
("A lump of ice has fallen from the sky nearby.Would you like to retrieve it?(type yes or no,then hit[ENTER]):",100,0),
("You watched a YouTube video about the best lawns in the solar system. Do you decide to try and grow a lawn in the desolate Martian soils?(type yes or no,then hit[ENTER]):", -300, -50),
("Your cousin Harold has mysteriously appeared. Do you invite nim to stay for one night?(type yes or no,then hit[ENTER]):", -200, -50),
("Today's food ration is very salty.Would you eat it?(type yes or no,then hit[ENTER]):", -5, 0),
("You spot an oasis off in the distance, do you investigate?(type yes or no,then hit[ENTER]):", -20, 0),
("Your knee hurts.Would you put some ice on it?(type yes or no,then hit[ENTER]):",-5,0)
]
print("[MARS WATER]\n---------------------------")
print("[CODED BY:RAY TANG]\n")
print(" This game is a text-based survival and sci-fi game,in which the player must make water-conscious decisions in order to survive for as long as possible without running out of water on Mars.In the beginning,you will start with 1000 liters of water.Thoughout the game,you will encounter various descicions that you will have to decide.To input your answer,type your answer and then press the [ENTER] key.Be careful,because if you don't choose wisely,you may end up using your water faster! \n GOOD LUCK,AND HAVE FUN!!! ;)")
day=1
keepgoing=True
water = 1000
water_use=input("PLEASE ENTER HOW MANY LITERS OF WATER THAT YOU WILL DRINK IN A DAY:")
if water_use == "":
print("PLEASE ENTER A NUMBER,NOTHING ELSE")
water_use=input("PLEASE ENTER HOW MANY LITERS OF WATER THAT YOU WILL DRINK IN A DAY:")
while keepgoing:
water=1000
day=1
while water > 0:
water -= int(water_use)
print("--------------------------------")
print("[DAY",day,"]")
print("--------------------------------")
event=random.choice(events)
while True:
response=input(event[0]+"(yes/no):").lower()
if response == "yes":
water += event[1]
break
elif response == "no":
water += event[2]
break
else:
print("[PLEASE ANSWER WITH EITHER YES OR NO!]")
day=day + 1
print("[YOU HAVE",water,"LITERS OF WATER LEFT]")
print("------------------------------------------------------------------")
print("[GAME OVER]")
print("[YOU RAN OUT OF WATER]")
print("[YOU LASTED",day,"DAYS]")
qwerty=input("TO PLAY AGAIN,PRESS[ENTER]KEY ANY OTHER KEY(PLUS ENTER)TO EXIT:")
keep_going=(qwerty == "")
|
e92a1e16e5a0a6b16e51dd9a5122b5726ea3d5fa | BrothSrinivasan/leet_code | /inheritance/inheritance.py | 4,282 | 4.1875 | 4 | # Author: Barath Srinivasan
# Design the class structure for a banking system using object-oriented principles
# Your design must have at least 5 classes
# Each class must have at least 2 variables and 2 functions (doesn't need to be implemented, just declared)
# You must also use 1 enum
# Possible Clarifying Questions
"""
1) Are there different types of Accounts a person can hold?
2) Besides balance, what information should an account hold?
3) Should we implement any security features?
"""
# Possible Answers
"""
1) Yes. There is a basic checking and saving account. Then there is a premium version
2) Each account needs an id, which needs to be unique, and needs to attached to a person. Person needs to present basic information to create his/her account
3) Try to protect sensitive information about the holder
"""
import hashlib
import enum
# enum defines the different currencies of the world
class Curr(Enum):
USD = 0
EUR = 1
CNY = 2
RUP = 3
# Corporate defines the corportate structure of the Bank
class Corporate:
__CEO = "Barath Srinivasan" # notes the CEO of the bank
__LocationofHQ = "College Park, MD" # notes the location of corporate HQ
def oustCEO(new: str): # CEO is changed if method is call
pass;
# allows to merge with another company
def mergeCompanies(company: str):
pass;
# ...more functions possible... #
# BankSys is a central place for bank activties to take place.
class BankSys:
__currentInterestRate = 0.5 # current loan interest company of the bank
__lastUpgrade = "9/27/19" # notes when last upgrade of the system took place
# can allow for multiple branches with seperate accounts
def __init__():
accToName = {}
# allows holder to create a specific account. accType can be "basic" or "premium"
def createAcct(name: Holder, accId: int, acctType: str) -> Account:
pass;
# defines accounts for a transfer to take place and the amount to be transfered
def transfer(recv: Account, send: Account, amount: int):
pass;
# ...more functions possible... #
# Holder defines an account holder. Holds information about them
class Holder:
__accessRestriction = "low-access" # displays that they have low access unlike a CEO or manager
__salt = "protecting our customers" # a salt to add to sensitive information
# creates the account holder
def __init_(self, fname: str, lname: str, dob: str, ssn: str):
self.fname = fname
self.lname = lname
self.dob = hashlib.sha526(((dob + salt).encode()).hexdigest()) # hashing dob to protect holder
self.ssn = hashlib.sha256(((ssn + salt).encode()).hexdigest()) # hashing ssn to protect ssn
# changes name if holder chooses to wish
def changeName(fname: str, lname: str):
pass;
# account holder can set up notifications by passing in phone number and email address in string format
def setUpNotifications(phone: str, email: str):
pass;
# ...more functions possible... #
# Account is a base account holders can create
class Account:
__accountCost = 10 # cost of running this type of account
__minimumBalance = 15 # minimum money needed in account
# creates this accout
def __init__(self, name: Holder, accId: int):
self.name = name
self.accId = accId
self.checking = 0
self.saving = 0
# allows to deposit or withdraw from either checking or saving
def changeBalance(acctType: str, amount: int):
pass;
# allows holder to view balance of either checking or saving
def viewBalance(acctType: str) -> str:
pass;
# ...more functions possible... #
# PremiumAcct extends Account in that in addition to the shared methods, those with premiumaccts have different cost, yet more functionality
class PremiumAcct(Account):
__accountCost = 15 # overrides parent cost
__minimumBalance = 5 # overrides parent minimumbalance
# allows holder to convert currency
def convertCurr(amount: int, curr: Curr) -> int:
pass;
# allows holder to apply for a loan. Takes in principal and time, and computes with it own interest rate.
def applyLoan(princ: int, time: int) -> bool:
pass;
# ...more functions possible... #
|
53a3084e98ebf7cf8c9f3bb21043e9c70e1fd723 | JeffersonYepes/Python | /Challenges/Desafio005.py | 138 | 3.90625 | 4 | n = int(input('Type a number: '))
print('The Predecessor of {} is {}!'.format(n, n-1))
print('The Successor of {} is {}!'.format(n, n+1))
|
1e84685b98dee118455ebc79b0a56a6f461f976b | beebel/HackBulgaria | /Programming0/week3/4-Problems-Construction/solutions/5. fibonacciNum/fib_number.py | 467 | 3.84375 | 4 | def fib_number(n):
result = [1, 1]
if n == 1:
result.pop()
elif n == 2:
None
else:
for i in range(2, n):
nextNum = result[i - 2] + result[i - 1]
result.append(nextNum)
return result
def printResultAsOneNum(lst):
for e in lst:
print(e, end="")
def main():
num = input("Enter n: ")
num = int(num)
printResultAsOneNum(fib_number(num))
if __name__ == "__main__":
main()
|
c124cbe1ded5cec1f5c07eaef3edcc917d87d694 | imulan/procon | /atcoder/abc153/d.py | 93 | 3.609375 | 4 | h = int(input())
ans = 0
x = 1
while h > 0:
ans += x
x *= 2
h //= 2
print(ans)
|
750e5147e1675bf0168e4fd9aa5dcbad5dd0bd27 | bcveber/COSC101 | /lab5/lab5_c.py | 758 | 4.25 | 4 | #Appropriate variables
lot_number = 0
def lotnumber ():
'''
Prompts the user for the lot number. If the lot number does not equal 0, then
it will do the show_tax.
'''
lotnuminput = int(input("Enter the lot number: "))
while lotnuminput != 0:
show_tax()
lotnuminput = int(input("Enter the lot number: "))
def show_tax ():
'''
Prompts user for the value of the property.Shows tax of the using the equation
property_value multiplied by *.0065.
'''
property_value = int(input("What is the property value? "))
property_tax = property_value * 0.0065
print('Your property tax is', property_tax)
#Add lotnumber and show_tax together:
def main():
lotnumber()
#Print main
main()
|
fdb1e970c534ae43d1ca817b9d15573cfd05e5ed | TCmatj/learnpython | /6-2_numbers.py | 197 | 3.625 | 4 | # TC2020/9/28/21:59
numbers = {'originyyx':5,'baby':0,'annan':7,'me':9,'huangliang':7}
for name,number in numbers.items():
print(name.title() + '最喜欢的数字是: ' + str(number) + '.')
|
d769092a52c20b982f5d39d42fc9e7045f54f5a0 | GeovaniSTS/PythonCode | /49 - Classificação_Triângulos.py | 253 | 4.03125 | 4 | L1 = float(input())
L2 = float(input())
L3 = float(input())
if L1 == L2 and L1 == L3 and L2 == L3:
print('equilatero')
else:
if L1 == L2 or L1 == L3 or L2 == L3:
print('isosceles')
if L1 != L2 and L1 != L3 and L2 != L3:
print('escaleno') |
9d3600eda65412ab4eddb5c271790bb9afe8ea7f | andre-Hazim/Unit_1-04 | /circumference_calculator.py | 459 | 3.609375 | 4 | '''
Created By: Roman Beya, Raymond Octavius, Andre Hazim
Created For: ICS3U
Created On: 25-Sep-2017
Calculates the circumference of a circle given the radius inputted by a user
'''
import ui
def calculate_on_touch_up_inside(sender):
# input
radius = int(view['radius_textfield'].text)
# process
circumference = 3.14159265 * radius ** 2
# output
view['circumference_label'].text = str('Circumference : ') + str( circumference)
view = ui.load_view()
view.present('sheet')
|
b0d92ec5bd20e7747c95fe6f9344b148a3b870b1 | CivilizedWork/Tommy-J | /Day_05/5thday2.py | 263 | 3.859375 | 4 | def eval_loop(end_string):
while True:
get_string = input('>>>')
if get_string != end_string:
last_answer = eval(get_string)
print(last_answer)
else:
break
print(last_answer)
eval_loop('done')
|
963ac486768b18d278a18e947a424cd01fdb124a | Mikemraz/Data-Structure-and-Algorithms | /LeetCode/search a 2d matrix.py | 1,581 | 3.984375 | 4 | def searchMatrix(matrix, target):
# write your code here
if len(matrix)==0:
return False
row_number = len(matrix)
column_number = len(matrix[0])
if target<matrix[0][0]:
return False
if target>matrix[row_number-1][column_number-1]:
return False
# compare first element of each row and return a row index where target resides.
start_row = 0
end_row = row_number - 1
target_row = -1
while end_row-start_row>1:
mid = (end_row-start_row)//2 + start_row
if target==matrix[mid][0]:
return True
elif target<matrix[mid][0]:
end_row = mid
else:
start_row = mid
if target==matrix[start_row][0]:
return True
elif matrix[start_row][0]<target<matrix[end_row][0]:
target_row = start_row
elif target==matrix[end_row][0]:
return True
elif target>matrix[end_row][0]:
target_row = end_row
# then search in target row
start_column = 0
end_column = column_number - 1
while end_column-start_column>1:
mid = (end_column-start_column)//2 + start_column
if target==matrix[target_row][mid]:
return True
elif target<matrix[target_row][mid]:
end_column = mid
else:
start_column = mid
if target==matrix[target_row][start_column]:
return True
if target==matrix[target_row][end_column]:
return True
return False
if __name__=="__main__":
A = [[1,3,5,7],[10,11,16,20],[23,30,34,50]]
print(searchMatrix(A, 7))
|
8742647b84da22eebd6a0305e37eb8a3f9efd1aa | RawalD/Python-Data-Structures | /Anagram/anagram.py | 1,558 | 3.984375 | 4 | def anagram(one, two):
# Removes spaces and lower cases
one = one.replace(" ", "").lower()
two = two.replace(" ", "").lower()
# If length of the first is not the same as the second immediate return False
if len(one) != len(two):
return False
else:
# Create counter variable and set to empty dictionary
counter = {}
# For every letter in first word
for letter in one:
# If the letter is in the counter dictionary then add letter to counter with an additional one
if letter in counter:
# If the letter exists then add one to the key
counter[letter] += 1
# Else set the counter[letter] to a just 1
else:
counter[letter] = 1
for letter in two:
if letter in counter:
counter[letter] -= 1
else:
counter[letter] = 1
# If letter in counter is not equal to 0 then return false
for letter in counter:
if counter[letter] != 0:
return False
return True
print(anagram('dog', 'god'))
print(anagram('aa', 'bb'))
print(anagram('clint eastwood', 'old west action'))
# Simplified version
def anagram_two(one, two):
# Removes spaces and lower cases
one = one.replace(" ", "").lower()
two = two.replace(" ", "").lower()
return sorted(one) == sorted(two)
print(anagram_two('dog', 'god'))
print(anagram_two('aa', 'bb'))
print(anagram_two('clint eastwood', 'old west action'))
|
8c2409d7aa5b38bbe94384871a368246df9d0326 | AVatch/ascii-image-service | /ascii.py | 2,555 | 3.796875 | 4 | import os
import datetime
from PIL import Image, ImageDraw
ASCII_CHARS = [ '#', '?', '%', '.', 'S', '+', '.', '*', ':', ',', '@']
def scale_image(image, new_width=100):
"""Resizes an image preserving the aspect ratio.
"""
(original_width, original_height) = image.size
aspect_ratio = original_height/float(original_width)
new_height = int(aspect_ratio * new_width)
new_image = image.resize((new_width, new_height))
return new_image
def convert_to_grayscale(image):
return image.convert('L')
def map_pixels_to_ascii_chars(image, range_width=25):
"""Maps each pixel to an ascii char based on the range
in which it lies.
0-255 is divided into 11 ranges of 25 pixels each.
"""
pixels_in_image = list(image.getdata())
pixels_to_chars = [ASCII_CHARS[int(pixel_value/range_width)] for pixel_value in
pixels_in_image]
return "".join(pixels_to_chars)
def convert_image_to_ascii(image, width=100):
"""Given an image, and a target width, we generate an ASCII string
"""
image = scale_image(image, width)
image = convert_to_grayscale(image)
pixels_to_chars = map_pixels_to_ascii_chars(image)
len_pixels_to_chars = len(pixels_to_chars)
image_ascii = [pixels_to_chars[index: index + width] for index in
range(0, len_pixels_to_chars, width)]
# convert to dimensions from font
# these are calculated from the base font used
new_width = width * 6
new_height = len(image_ascii) * 15
return new_width, new_height, "\n".join(image_ascii)
def convert_ascii_to_image(ascii, width, height):
"""Given a string, and a set of dimensions we create a new image
"""
image = Image.new('RGB', (width, height), (0, 0, 0) )
draw = ImageDraw.Draw(image)
draw.text((0,0), ascii, fill=(255, 255, 255))
path = os.path.join(os.path.dirname(__file__), 'processed/' + datetime.datetime.now().isoformat() + '.png')
image.save(path, 'PNG')
return path
def handle_image_conversion(image_filepath):
"""Function that handles the conversion and returns the path to the
processed file
"""
image = None
try:
image = Image.open(image_filepath)
except Exception as e:
print("Unable to open image file {image_filepath}.".format(image_filepath=image_filepath))
print(e)
return
width, height, image_ascii = convert_image_to_ascii(image)
processed_image_filepath = convert_ascii_to_image(image_ascii, width, height)
return processed_image_filepath
|
546cdd91ed2ec01d9c548267fe8132f51d8152c2 | HystericHeeHo/testingPython | /tstp/ch8chal2.py | 134 | 3.59375 | 4 | import cubed
x = input('Please Choose a number: ')
try:
cubed.cubing(x)
except ValueError:
print('Please Choose a number.')
|
31c97cbad1b3ce42e8d871ae2ad40b7bc2edfbb6 | AhmedOmi/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/5-print_comb2.py | 117 | 3.640625 | 4 | #!/usr/bin/python3
for count in range(100):
print("{:02d}".format(count), end="\n" if count == 99 else ", ")
|
1302c6d53ae147160fcf056c0b7181e672a30df2 | stratos-gounidellis/algorithmsAssignments | /Gale-Shapley_StableMatchingAlgorithm/stable_marriage.py | 4,739 | 3.578125 | 4 | import json
import sys
import os.path
# this method returns a dictionary with
# the names and the preferences of the men/women
def parse_json(choice, filename):
dictionary = {}
f = open(filename, 'r')
j = json.load(f)
f.close()
j_string = json.dumps(j, sort_keys=True, indent=4)
data = json.loads(j_string)
selection = data[choice]
for key, value in selection.items():
dictionary[key] = value
return dictionary
class Person:
# this method initializes the objetc Person
def __init__(self, name, preferences):
self.name = name
self.preferences = preferences
self.mate = None
self.preferenceNumber = 0
self.preferencesRanking = {}
for preferenceOrder in range(len(preferences)):
self.preferencesRanking[preferences[preferenceOrder]] = preferenceOrder
# this method check if a Mate is preferable than the
# the Person already has.
def evaluateProposal(self, possible_Mate):
# if the current mate is not preferable than the possible
# future mate return true.
choice = self.preferencesRanking[possible_Mate] < self.preferencesRanking[self.mate]
return choice
# this method finds the next Person
# to propose.
def nextProposal(self):
possible_mate = self.preferences[self.preferenceNumber]
self.preferenceNumber = self.preferenceNumber + 1
return possible_mate
# method to create the male and female lists.
def createLists(filename, gender):
unmatchedPeople = []
males = parse_json('men_rankings', filename)
malesDict = {}
for key in males:
malesDict[key] = Person(key, males.get(key, 0))
females = parse_json('women_rankings', filename)
femalesDict = {}
for key in females:
femalesDict[key] = Person(key, females.get(key, 0))
return (unmatchedPeople, malesDict, femalesDict)
def createMatches(unmatchedList, malesDict, femalesDict):
check = True
if gender == "-w":
check = False
unmatchedList = list(femalesDict.keys())
else:
unmatchedList = list(malesDict.keys())
# check if there are unmatched People and if yes
# continue the loop
while len(unmatchedList) > 0:
if check is False:
x = femalesDict[unmatchedList[0]]
y = malesDict[x.nextProposal()]
else:
x = malesDict[unmatchedList[0]]
y = femalesDict[x.nextProposal()]
# if this Person does not have a mate
# then add as its mate the Person who is
# now proposing.
if y.mate is None:
unmatchedList.remove(x.name)
y.mate = x.name
x.mate = y.name
# else if this Person has a mate check
# if it prefers its current mate or
# proposing person.
elif y.evaluateProposal(x.name):
if check is False:
previousMate = femalesDict[y.mate]
else:
previousMate = malesDict[y.mate]
previousMate.mate = None
unmatchedList.append(previousMate.name)
unmatchedList.remove(x.name)
y.mate = x.name
x.mate = y.name
if check is False:
return femalesDict
else:
return malesDict
# method to print the result
# or to create a JSON file.
def printMatches(result, outputfile=None):
keys = sorted(result.keys())
marriages = {}
for person in keys:
marriages[result[person].name] = result[person].mate
result = json.dumps(marriages, sort_keys=True, indent=4)
if outputfile is None:
print(result)
else:
with open(outputfile, 'w') as fp:
json.dump(marriages, fp, sort_keys=True, indent=4)
print(result)
if len(sys.argv) < 3:
print("Error! You should give your choice " +
"of gender and the file to be read.")
sys.exit(2)
gender = str(sys.argv[1])
if not (gender == "-m" or gender == "-w"):
print("Error! You should type either -m for men or -w for women.")
sys.exit(2)
filename = str(sys.argv[2])
if not(os.path.exists(filename)):
print("Error! File does not exist.")
sys.exit(2)
if len(sys.argv) > 3:
output = str(sys.argv[3])
outputFile = None
if output == "-o":
outputFile = str(sys.argv[4])
marriageTuple = createLists(filename, gender)
printMatches(createMatches(marriageTuple[0],
marriageTuple[1],
marriageTuple[2]), outputFile)
else:
marriageTuple = createLists(filename, gender)
printMatches(createMatches(marriageTuple[0],
marriageTuple[1], marriageTuple[2]))
|
4529492766cca8166b8ad0e3fc05aacf2294876f | loghmanb/daily-coding-problem | /problem092_airbnb_courses_order.py | 1,955 | 3.65625 | 4 | '''
This problem was asked by Airbnb.
We're given a hashmap associating each courseId key with a list of courseIds values, which represents that the prerequisites of courseId are courseIds.
Return a sorted ordering of courses such that we can finish all courses.
Return null if there is no such ordering.
For example, given {'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'CSC100': []}, should return ['CSC100', 'CSC200', 'CSCS300'].
'''
def find_courses_order(courses):
ans = []
# preprocess for listing all courses
# and make a dict for { pre-crs -> set of next courses}
# for making a graph in completing the courses.
next_crs = set()
other_crs = set()
pre_req_dict = {}
for crs in courses:
if courses[crs]:
other_crs.add(crs)
for crs_pre in courses[crs]:
if crs_pre not in pre_req_dict:
pre_req_dict[crs_pre] = set()
pre_req_dict[crs_pre].add(crs)
else:
next_crs.add(crs)
no_of_turn = 0
while next_crs and no_of_turn<len(next_crs):
crs = next_crs.pop()
if crs not in other_crs:
ans.append(crs)
if crs in pre_req_dict:
items = pre_req_dict[crs]
del pre_req_dict[crs]
for course in items:
next_crs.add(course)
other_crs.clear()
for item in pre_req_dict:
other_crs.update(pre_req_dict[item])
no_of_turn = 0
else:
next_crs.add(crs)
no_of_turn += 1
if next_crs:
return None
return ans
if __name__ == "__main__":
data = [
[
{'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'CSC100': []},
['CSC100', 'CSC200', 'CSCS300']
]
]
for d in data:
print('input', d[0], 'output', find_courses_order(d[0])) |
f40991d02d3ccd34760273a2869fa793b11e8ea6 | Reikenzan/Some-Python | /HomeWork/hw43.py | 1,685 | 4.625 | 5 | """Implement the following pseudocode to draw a checkered flag to the screen.
1. Ask the user for the size of the checkered flag (n).
2. Draw an n x n grid to the screen.
3. For i = 0,2,4,...,n*n-1:
4. row = i // n
5. offset = row % 2
6. col = (i % n) + offset
7. fillSquare(row,col,"black")
You do not have to use main(), a function, or a file for this program."""
from turtle import*
# Ask the user for the size of the checkered flag (n).
def getSize():
size = eval(input('Please enter the size of the checkered flag: '))
return size
# Draw an n x n grid to the screen.
def drawGrid(turtle, n):
for i in range(0, n+1):
turtle.up()
turtle.goto(0, i)
turtle.down()
turtle.forward(n)
turtle.left(90)
for i in range(0, n+1):
turtle.up()
turtle.goto(i, 0)
turtle.down()
turtle.forward(n)
# Fill the square in the given row and column.
def fillSquare(turtle, row, col):
turtle.up()
turtle.goto(col, row)
turtle.begin_fill()
for i in range(4):
turtle.forward(1)
turtle.right(90)
turtle.end_fill()
def main():
# Get the user's input.
n = getSize()
# Set up the drawing coordinates.
screen = Screen()
screen.setworldcoordinates(-1, -1, 10, 10)
# Make a turtle object for use in drawing. Maximize its speed.
turtle = Turtle()
turtle.speed(5)
turtle.hideturtle()
# Draw the checkered flag.
drawGrid(turtle, n)
for i in range(0, n*n, 2):
row = i // n
offset = ~(n % 2) & (row % 2)
col = i % n + offset
fillSquare(turtle, row, col)
print('Hit Enter to quit.')
input()
main()
|
e5174f9fde2deb27fc93d50a0b8769e2594d2361 | P-N-S/SVP-CPro | /StringAlgo.py | 1,152 | 4.40625 | 4 | # https://www.geeksforgeeks.org/python-program-to-check-if-given-string-is-pangram/
# Python program to check if given string is pangram
# A pangram is a sentence containing every letter in the Enlish Alphabet
import string
# Approach 1
def isPangram_Naive(str):
print("isPangram_Naive() - start | 17:15 19F19")
alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in alphabet:
if char not in str.lower():
return False
return True
# Approach 2 : Using Python Set
# Convert the given string into set and then check if the alphabet set is greater
# than or equal to it or not. If the string set is greater or equal, print 'Yes'
# otherwise 'No'.
alphabets = set(string.ascii_lowercase)
def isPangram_Set(string):
print("isPangram_Set() - Start | 17:27 19F19")
return set(string.lower()) >= alphabets
# Driver code
print("ONS! Driver Code - Start | 17:18 19F19")
string = 'The quick brown fox jumps over the lazy dog'
if(isPangram_Naive(string) == True):
print("Yes, it's pangram")
else:
print("No, it's not pangram")
if(isPangram_Set(string) == True):
print("Yes")
else:
print("No") |
1238ce8f38ee61d899afa1623fcc263ba47717cf | Yamievw/class95 | /python/read_data.py | 5,332 | 3.640625 | 4 | # This file reads in the data and fills two lists: one with
# students and one with courses. This data can be readily used
# by importing this module.
import csv
import math # for ceil.
class Course():
def __init__(self, name, components, registrants):
self.name = name
# a dictionary with keys "lectures", "tutorials" or "labs" and the
# required number per student and capacity.
self.components = components
self.per_student = {}
self.registrants = registrants # a list containing students in an unknown format.
self.registrants = sorted(self.registrants) # is dit nodig of niet? hangt van format registrants af.
self.amount_registrants = len(self.registrants)
def __str__():
return self.name
def get_registrants(self):
return self.registrants
def get_amount_registrants(self):
return self.amount_registrants
def get_lectures(self):
return self.components["lectures"]
def get_tutorials(self):
return self.components["tutorials"]
def get_labs(self):
return self.components["labs"]
def get_name(self):
return self.name
def get_components(self):
return self.components
def add_registrant(self, registrant):
self.registrants.append(registrant)
def update_components(self):
tutorials_per_student = self.components["tutorials"][0]
labs_per_student = self.components["labs"][0]
tutorials_capacity = self.components["tutorials"][1]
labs_capacity = self.components["labs"][1]
tutorial_result = tutorials_per_student*len(self.registrants)/float(tutorials_capacity)
labs_result = labs_per_student*len(self.registrants)/float(labs_capacity)
self.per_student["tutorials"] = tutorials_per_student
self.per_student["labs"] = labs_per_student
self.per_student["lectures"] = self.components["lectures"][0]
self.per_student["all"] = tutorials_per_student + labs_per_student + self.components["lectures"][0]
# math.ceil to ensure enough activities
self.components["tutorials"] = (int(math.ceil(tutorial_result)), tutorials_capacity)
self.components["labs"] = (int(math.ceil(labs_result)), labs_capacity)
# determine the number of groups.
self.no_groups = max(self.components["tutorials"][0], self.components["labs"][0])
class Student():
def __init__(self, name, surname, number, courses):
self.name = name
self.surname = surname
self.number = number
self.courses = []
for course in courses:
if course != '':
# because there's a comma in the CSV.
if course == 'Zoeken':
self.courses.append('Zoeken, sturen en bewegen')
elif course != ' sturen en bewegen':
self.courses.append(course)
self.courses = sorted(self.courses)
self.coursenumber = len(self.courses)
def get_courses(self):
return self.courses
def get_coursenumber(self):
return self.coursenumber
class Room():
def __init__(self, name, capacity):
self.name = name
self.capacity = capacity
def get_name(self):
return self.name
def get_capacity(self):
return self.capacity
# dictionaries that can be used by every other module in this project.
students = {}
courses = {}
rooms = {}
# read in rooms
with open('rooms.CSV', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter = ";")
for row in reader:
name = row[0]
capacity = row[1]
# create course object.
rooms[row[0]] = Room(row[0], row[1])
# read in courses
with open('vakken.CSV', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter = ";")
for row in reader:
components = {}
tutorials_capacity = row[3]
labs_capacity = row[5]
# 1000 means unlimited capacity.
if tutorials_capacity == "nvt":
tutorials_capacity = 1000
if labs_capacity == "nvt":
labs_capacity = 1000
# tupe structure: (number per student, capacity)
components["lectures"] = (int(row[1]), 1000) # 1000 means unlimited capacity
components["tutorials"] = (int(row[2]), tutorials_capacity)
components["labs"] = (int(row[4]), labs_capacity)
# create course object.
courses[row[0]] = Course(row[0], components, [])
# read in students and add them to courses
with open('studenten_roostering.CSV', 'rb') as csvfile:
# open txt file.
reader = csv.reader(csvfile, delimiter = ",")
for row in reader:
# create students.
students[row[2]] = Student(row[1], row[0], row[2], row[3:])
for course in row[3:]:
try:
courses[course].add_registrant(row[2])
except KeyError:
continue
# update the requirement for the number of tutorials and labs
for key in courses:
courses[key].update_components()
|
367b068c671e5e49a8e5bd2072ef01796d05cf74 | Rehan710/Udacitybikeshare | /bicyle.py | 4,469 | 4.125 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters(city, month, day):
print("\nRehan's stats for bikeshare\n")
print('Hello! Let\'s explore some US bikeshare data!')
while True:
city = input("Write a city name: Chicago, New York City or Washington!\n").lower()
if city not in CITY_DATA:
print("\n Invalid answer")
continue
else:
break
while True:
time = input("Do you want to filter as month, day, all or none?").lower()
if time == 'month':
month = input("Which month? January, Feburary, March, April, May or June?").lower()
day = 'all'
break
elif time == 'day':
month = 'all'
day = input("Which day? Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or Sunday").lower()
break
elif time == 'all':
month = input("Which month? January, Feburary, March, April, May or June?").lower()
day = input("Which day? Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or Sunday").lower()
break
elif time == 'none':
month = 'all'
day = 'all'
break
else:
input("You wrote the wrong word! Please type it again. month, day, all or none?")
break
print(city)
print(month)
print(day)
print('-'*40)
return city, month, day
def load_data(city, month, day):
df = pd.read_csv(CITY_DATA[city])
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.day_name()
if month != 'all':
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month)+1
df = df[df['month']== month]
if day != 'all':
df = df[df['day_of_week'] == day.title()]
return df
def time_stats(df):
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
common_month = df['month'].mode()[0]
print(common_month)
common_day_of_week = df['day_of_week'].mode()[0]
print(common_day_of_week)
df['hour'] = df['Start Time'].dt.hour
common_hour = df['hour'].mode()[0]
print(common_hour)
print("\n This took %s seconds."% (time.time()- start_time))
print('-'*40)
def station_stats(df):
start_time = time.time()
common_start = df['Start Station'].mode()[0]
print(common_start)
common_end = df['End Station'].mode()[0]
print(common_end)
df['combination'] = df['Start Station'] + 'to' + df['End Station']
common_combination = df['combination'].mode()[0]
print(common_combination)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
print('\nCalculating Trip Duration...\n')
start_time = time.time()
total_travel = df['Trip Duration'].sum()
print(total_travel)
mean_travel = df['Trip Duration'].mean()
print(mean_travel)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df):
print('\nCalculating User Stats...\n')
start_time = time.time()
user_types = df['User Type'].count()
print(user_types)
if 'Gender' in df:
gender = df['Gender'].value_counts()
print(gender)
else:
print("There is no gender information in this city.")
# Display earliest, most recent, and most common year of birth
if 'Birth_Year' in df:
earliest = df['Birth_Year'].min()
print(earliest)
recent = df['Birth_Year'].max()
print(recent)
common_birth = df['Birth Year'].mode()[0]
print(common_birth)
else:
print("There is no birth year information in this city.")
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def data(df):
raw_data = 0
while True:
answer = input("Do you want to see the raw data? Yes or No").lower()
if answer not in ['yes', 'no']:
answer = input("You wrote the wrong word. Please type Yes or No.").lower()
elif answer == "yes":
raw_data += 5
print(df.iloc[raw_data : raw_data + 5])
again = input("Do you want to see more? Yes or No").lower()
if again == "no":
break
elif answer == 'no':
return
def main():
city = ""
month = ""
day = ""
while True:
city, month, day = get_filters(city, month, day)
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
data(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower()!='yes':
break
if __name__ == "__main__":
main()
|
0f8c3cb2cfb120c148da7746d81d845155467d2a | Hatim0110/Python_revision_tasks | /11-18/task1-2/main.py | 376 | 4.09375 | 4 | name = input("what's your name? ")
age =int(input("How old are you? "))
country = input("where are you from? ")
quots = '\ """"'
#print(f'"Hello \'{name.title()}\', How You Doing {quots} Your Age Is "{age}"" + Your Country Is: {country.title()}')
print(f'"Hello \'{name.title()}\', How You Doing \ \n{quots[1:-1]} Your Age Is "{age}"" + \nYour Country Is: {country.title()}')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.