blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
e8d9dccc13de722b93bf91f8b33e5702a2a9b96b | jtquisenberry/PythonExamples | /Jobs/stellar/triangle2.py | 557 | 3.84375 | 4 | #https://leetcode.com/problems/triangle/
from copy import deepcopy
triangle = [[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]]
def minimumTotal(triangle):
print(triangle)
#triangle2 = triangle.copy() # updates triangle and triangle2
#triangle2 = list(triangle) # updates triangle and triangle2
#triangle2 = triangle[:] # updates triangle and triangle2
triangle2 = deepcopy(triangle) # updates triangle only
triangle2[0][0] = 99
print(triangle)
print(triangle2)
if __name__ == '__main__':
minimumTotal(triangle=triangle)
|
148c6d9d37a9fd79e06e4371a30c65a5e36066b2 | jtquisenberry/PythonExamples | /Jobs/multiply_large_numbers.py | 2,748 | 4.25 | 4 | import unittest
def multiply(num1, num2):
len1 = len(num1)
len2 = len(num2)
# Simulate Multiplication Like this
# 1234
# 121
# ----
# 1234
# 2468
# 1234
#
# Notice that the product is moved one space to the left each time a digit
# of the top number is multiplied by the next digit from the right in the
# bottom number. This is due to place value.
# Create an array to hold the product of each digit of `num1` and each
# digit of `num2`. Allocate enough space to move the product over one more
# space to the left for each digit after the ones place in `num2`.
products = [0] * (len1 + len2 - 1)
# The index will be filled in from the right. For the ones place of `num`
# that is the only adjustment to the index.
products_index = len(products) - 1
products_index_offset = 0
# Get the digits of the first number from right to left.
for i in range(len1 -1, -1, -1):
factor1 = int(num1[i])
# Get the digits of the second number from right to left.
for j in range(len2 - 1, -1, -1):
factor2 = int(num2[j])
# Find the product
current_product = factor1 * factor2
# Write the product to the correct position in the products array.
products[products_index + products_index_offset] += current_product
products_index -= 1
# Reset the index to the end of the array.
products_index = len(products) -1;
# Move the starting point one space to the left.
products_index_offset -= 1;
for i in range(len(products) - 1, -1, -1):
# Get the ones digit
keep = products[i] % 10
# Get everything higher than the ones digit
carry = products[i] // 10
products[i] = keep
# If index 0 is reached, there is no place to store a carried value.
# Instead retain it at the current index.
if i > 0:
products[i-1] += carry
else:
products[i] += (10 * carry)
# Convert the list of ints to a string.
#print(products)
output = ''.join(map(str,products))
return output
class Test(unittest.TestCase):
def setUp(self):
pass
def test_small_product(self):
expected = "1078095"
actual = multiply("8765", "123")
self.assertEqual(expected, actual)
def test_large_product(self):
expected = "41549622603955309777243716069997997007620439937711509062916"
actual = multiply("654154154151454545415415454", "63516561563156316545145146514654")
self.assertEqual(expected, actual)
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
|
d59ccfe23de3862992af4e1e16cd5d67c838ca21 | jtquisenberry/PythonExamples | /Classes/getters_and_setters.py | 1,094 | 3.609375 | 4 | import unittest
class Cat():
def __init__(self, name, hair_color):
self._hair_color = hair_color
# Use of a getter to return hair_color
@property
def hair_color(self):
return self._hair_color
# Setter has the name of the property
# Use of a setter to throw AttributeError with a custom message.
@hair_color.setter
def hair_color(self, value):
# raise AttributeError("Property hair_color is read-only.")
self._hair_color = value
class Test(unittest.TestCase):
def setUp(self):
self.cat = Cat('orange', 'Morris')
self.cat._hair_color = 'black'
def test_set_hair_color_field(self):
expected = 'black'
actual = self.cat._hair_color
self.assertEqual(expected, actual, 'error at test_set_hair_color')
def test_set_hair_color_property(self):
expected = 'white'
self.cat.hair_color = 'white'
actual = self.cat.hair_color
self.assertEqual(expected,actual,'error at test_set_hair_color_property')
if __name__ == '__main__':
unittest.main() |
0812620e8371ba84710baa5a1eee9992804a3408 | jtquisenberry/PythonExamples | /Simple_Samples/array_as_tree.py | 609 | 3.75 | 4 |
# Calculate the sum of the left side and the right side
tree = [1,2,3,4,0,0,7,8,9,10,11,12,13,14,15,16]
# 1
# 2 3
# 4 5 6 7
# 8 9 10 11 12 13 14 15
# 16
left_side = 0
right_side = 0
power_of_two = 1
while len(tree) > 2**(power_of_two - 1):
left_index = (2**power_of_two) -1
right_index = (2**(power_of_two + 1)-1 -1)
if left_index < len(tree):
left_side += tree[left_index]
if right_index < len(tree):
right_side += tree[right_index]
power_of_two += 1
print('left_side', left_side)
print('right_side', right_side) |
b8b7d0a3067b776d6c712b2f229ef65448b9a4d9 | jtquisenberry/PythonExamples | /Interview_Cake/arrays/reverse_words_in_list_lists.py | 2,120 | 4.375 | 4 | import unittest
from collections import deque
# https://www.interviewcake.com/question/python/reverse-words?section=array-and-string-manipulation&course=fc1
# Solution with lists only
# Not in place
def reverse_words(message):
if len(message) < 1:
return
current_word = []
word_list = []
final_output = []
for i in range(0, len(message)):
character = message[i]
if character != ' ':
current_word.append(character)
if character == ' ' or i == len(message) - 1:
word_list.append(current_word)
current_word = []
# print(word_list)
for j in range(len(word_list) - 1, -1, -1):
final_output.extend(word_list[j])
if j > 0:
final_output.extend(' ')
# print(final_output)
for k in range(0, len(message)):
message[k] = final_output[k]
return
# Tests
class Test(unittest.TestCase):
def test_one_word(self):
message = list('vault')
reverse_words(message)
expected = list('vault')
self.assertEqual(message, expected)
def test_two_words(self):
message = list('thief cake')
reverse_words(message)
expected = list('cake thief')
self.assertEqual(message, expected)
def test_three_words(self):
message = list('one another get')
reverse_words(message)
expected = list('get another one')
self.assertEqual(message, expected)
def test_multiple_words_same_length(self):
message = list('rat the ate cat the')
reverse_words(message)
expected = list('the cat ate the rat')
self.assertEqual(message, expected)
def test_multiple_words_different_lengths(self):
message = list('yummy is cake bundt chocolate')
reverse_words(message)
expected = list('chocolate bundt cake is yummy')
self.assertEqual(message, expected)
def test_empty_string(self):
message = list('')
reverse_words(message)
expected = list('')
self.assertEqual(message, expected)
unittest.main(verbosity=2) |
5ed8d9b76cd9a1443a8f0fa9a7ee46604b6e3dfd | mansigoel/GitHackeve | /project2.py | 417 | 3.875 | 4 | def factorial(number_for_factorial):
# Add code here
return #Factorial number
def gcd(number_1, number_2):
# Add code here
return #gcd value
def is_palindrome(string_to_check):
# Add code here
return #boolean response
#Take input for fib in variable a
print(fib(a))
#Take input for is_prime in variable b, c
print(gcd(b, c))
#Take input for is_palindrome in variable d
print(is_palindrome(d)) |
7aec878186d13b42ac12dd05d1580fc47662520e | devSantos16/pythonDice | /main.py | 2,139 | 3.671875 | 4 | from builtins import dict
from Jogada import Jogada
from Jogada import mostrarTodosOsDados
from Jogada import deletar
from Jogada import verificarDadoNulo
# Modo usuario
loop = True
while loop:
menu = int(input("SEJA BEM VINDO! \n"
"Digite o modo de entrada\n"
"1 - Modo Admin\n"
"2 - Modo Usuário\n"
"0 - Sair do Programa\n"
"Digite a opção: "))
if menu == 0:
exit(4)
elif menu == 1:
menuUsuario = int(input("MENU DO USUARIO\n"
"1 - Mostrar dados e jogar\n"
"2 - Adicionar Dado e jogar\n"
"3 - Mostrar todas as jogadas\n"
"4 - Deletar Tudo\n"
"0 - SAIR\n"
"Digite a opção desejada: "))
if menuUsuario == 0:
print("SAINDO !!! ")
exit(4)
if menuUsuario == 1:
f = mostrarTodosOsDados()
verificarDadoNulo(f)
print("Todos os dados inseridos: ")
for c in range(len(f)):
print(f[c])
resultado = int(input("Digite qual dado tu quer: "))
for c in range(len(f)):
if f[c] == str(resultado):
j = Jogada(resultado)
print(j.retornarDado())
elif menuUsuario == 2:
resultado = int(input("Digite um numero para o Dado: "))
j = Jogada(resultado)
print(j.retornarDado())
elif menuUsuario == 3:
mostrarTodosOsDados()
elif menuUsuario == 4:
print("Deletando tudo")
deletar()
else:
print("ERRO, Digite novamente");
elif menu == 2:
print("Ok!")
exit(4)
else:
print("ERRO, tente novamente !")
# resultado = int(input("Digite um numero para o Dado: "))
#
# j = Jogada(resultado)
#
# print(j.retornarDado())
|
a274889dd5ea83c37dd31a7df6c5ea88d1f1f2bb | libp2p/py-libp2p | /libp2p/peer/addrbook_interface.py | 1,673 | 3.5625 | 4 | from abc import ABC, abstractmethod
from typing import List, Sequence
from multiaddr import Multiaddr
from .id import ID
class IAddrBook(ABC):
@abstractmethod
def add_addr(self, peer_id: ID, addr: Multiaddr, ttl: int) -> None:
"""
Calls add_addrs(peer_id, [addr], ttl)
:param peer_id: the peer to add address for
:param addr: multiaddress of the peer
:param ttl: time-to-live for the address (after this time, address is no longer valid)
"""
@abstractmethod
def add_addrs(self, peer_id: ID, addrs: Sequence[Multiaddr], ttl: int) -> None:
"""
Adds addresses for a given peer all with the same time-to-live. If one
of the addresses already exists for the peer and has a longer TTL, no
operation should take place. If one of the addresses exists with a
shorter TTL, extend the TTL to equal param ttl.
:param peer_id: the peer to add address for
:param addr: multiaddresses of the peer
:param ttl: time-to-live for the address (after this time, address is no longer valid
"""
@abstractmethod
def addrs(self, peer_id: ID) -> List[Multiaddr]:
"""
:param peer_id: peer to get addresses of
:return: all known (and valid) addresses for the given peer
"""
@abstractmethod
def clear_addrs(self, peer_id: ID) -> None:
"""
Removes all previously stored addresses.
:param peer_id: peer to remove addresses of
"""
@abstractmethod
def peers_with_addrs(self) -> List[ID]:
"""
:return: all of the peer IDs stored with addresses
"""
|
5d730b83244e0a0d7773556652ff0332d0857ef8 | Hananja/DQI19-Python | /01_Einfuehrung/prime_factors_simple.py | 727 | 3.90625 | 4 | # -*- coding: utf-8 -*-
# Berechnung der Primfaktoren einer Zahl in einer Liste
from typing import List
loop = True
while loop:
# Eingabe
input_number : int = int(input("Bitte Nummer eingeben: "))
number : int = input_number
# Verarbeitung
factors : List[int] = [] # Liste zum Sammeln der Faktoren
divider : int = 2
while number > 1:
while number % divider == 0:
factors.append(divider)
number //= divider # number = number // divider (integer division)
divider = divider + 1
# Ausgabe
print("{:s} = {:d}".format(" ⋅ ".join(map(str, factors)), input_number))
if input("Noch einmal ausführen (J/N)? ") not in "JjYy":
loop = False
|
c53deedb3e49ee964abe0fd4b3a83f2a327a0a08 | flofl-source/Pathfinding | /Maier_Flora_Td5.py | 3,354 | 4.03125 | 4 | # Advanced Data Structure and Algorithm
# Parctical work number 5
# Exercice 2
#Graph 2 : Negative weight so we use the
#Bellman-Ford algorithm
#Graph 1 :
#Number of edges : 13
#Number of nodes : 8
#Complexity of the dijkstra algorithm : 64
#Complexity of the Bellman-Ford algorithm : 104
#Complexity of the Floyd-Warshall algorithm : 512
#We will use Dijkstra algorithm
#Graph 3 :
#Number of edges : 13
#Number of nodes : 7
#Complexity of the dijkstra algorithm : 49
#Complexity of the Bellman-Ford algorithm : 91
#Complexity of the Floyd-Warshall algorithm : 343
#We will use Dijkstra algorithm
from queue import Queue
class vertex :
def __init__(self,name,adjacent):
self.name=name
self.adjacent = adjacent
self.d=None
self.parent=None
def __str__(self):
res = str(self.name)+"-->"
if (self.adjacent==None):
res=res+" "+str(None)
else:
for elt in self.adjacent.keys():
res=res+" "+elt.name
return res
def setd(self,k):
self.d=k
def showQ(Q):
for q_item in Q.queue:
print (q_item)
def showS(S):
for (obtained,init) in S.items():
print(obtained+" is obtained by "+init)
def showPath(path):
res=""
for vert in path:
res=res+"-->"+vert
print(res)
def min_d(Q):
min_v=None
min_d=99999
for vert_n in Q.queue:
if min_d>vert_n.d:
min_v=vert_n
min_d=vert_n.d
return(min_v)
def modifyQ(Q,vert):
print("Q is modyfied :")
temp=Queue()
for q_vertex in Q.queue:
if (q_vertex!=vert):
temp.put(q_vertex)
return temp
def findPath(S,start,end):
Res=[end.name]
current=end.name
while current!=start.name:
Res=Res+[S[current]]
current=S[current]
Res.reverse()
return Res
def dijkstra(start,end,graph):
Q=Queue()
for vert in graph:
vert.setd(99999)
start.setd(0)
for vert in graph:
Q.put(vert)
print("Queue initialization as follow :")
showQ(Q)
S={} #dictionnary {vertex obtaines by : ..., }
#while Q.empty()==False:
for q_vertex in Q.queue:
min_d_vertex=min_d(Q)
print("\nWe work on the vertex :")
print(min_d_vertex)
if (q_vertex!=end):
for v,length in min_d_vertex.adjacent.items(): #(vertex,length)
if (length+min_d_vertex.d<v.d):
S[v.name]=min_d_vertex.name
v.d=min(length+min_d_vertex.d,v.d)
Q=modifyQ(Q,min_d_vertex)
showQ(Q)
print("\nSmallest weight :"+str(end.d))
print("\nAll the movements :")
showS(S)
print("\nThe shortest path is :")
print(findPath(S,start,end))
vert_H=vertex('H',None)
vert_G=vertex('G',{vert_H:2})
vert_E=vertex('E',{vert_H:4})
vert_D=vertex('D',{vert_G:2, vert_E:4})
vert_F=vertex('F',{vert_H:7,vert_G:4,vert_D:1})
vert_C=vertex('C',{vert_D:3})
vert_B=vertex('B',{vert_F:4,vert_C:2})
vert_A=vertex('A',{vert_B:2,vert_C:5})
graph=[vert_A,vert_B,vert_C,vert_D,vert_E,vert_F,vert_G,vert_H]
dijkstra(vert_A,vert_H,graph)
|
1aa6ba8516a4e996c07028bc798bdb13064add85 | jaeyun95/Algorithm | /code/day05.py | 431 | 4.1875 | 4 | #(5) day05 재귀를 사용한 리스트의 합
def recursive(numbers):
print("===================")
print('receive : ',numbers)
if len(numbers)<2:
print('end!!')
return numbers.pop()
else:
pop_num = numbers.pop()
print('pop num is : ',pop_num)
print('rest list is : ',numbers)
sum = pop_num + recursive(numbers)
print('sum is : ',sum)
return sum
|
a76ed6a1b76c2f0771acb387e63bcafb86b73b96 | jaeyun95/Algorithm | /code/day06.py | 398 | 3.640625 | 4 | #(6) day06 가장 많이 등장하는 알파벳 개수 구하기
def counter(word):
counter_dic = {}
for alphabet in word:
if counter_dic.get(alphabet) == None:
counter_dic[alphabet] = 1
else:
counter_dic[alphabet] += 1
max = -1
for key in counter_dic:
if counter_dic[key] > max:
max = counter_dic[key]
return max
|
1786d5bd32505970f897ff9691259f3a1cc785a7 | phypm/Pedro_Motta | /Ex8_maiornota.py | 791 | 3.765625 | 4 | import sys
i=0
nota=0
boletim=[]
while True:
try:
a = int (raw_input("Digite a nota do Aluno "))
while a >= 0:
boletim.append(a)
i += 1
nota = a + nota
print "Nota total e: ", nota
a = int (raw_input("Digite a nota do Aluno "))
else:
media = nota/i
maior=0
j=0
print "O boletim e: ",boletim
for x in boletim:
if x>j:
j=x
print "A maior nota e :", j
print
print "O valor da media e: ", media
break
except:
print "Nao foi um numero valido"
#Nota: 0.8
#Comentario: media eh um valor float e nao um inteiro. Para que serve a variavel "maior?"
|
4b8c656ea711a2274df26c044ec6a7d7ce7b33bc | bojanuljarevic/Algorithms | /BST/bin_tree/bst.py | 1,621 | 4.15625 | 4 |
# Zadatak 1 : ručno formiranje binarnog stabla pretrage
class Node:
"""
Tree node: left child, right child and data
"""
def __init__(self, p = None, l = None, r = None, d = None):
"""
Node constructor
@param A node data object
"""
self.parent = p
self.left = l
self.right = r
self.data = d
def addLeft(self, data):
child = Node(self, None, None, data)
self.left = child
return child
def addRight(self, data):
child = Node(self, None, None, data)
self.right = child
return child
def printNode(self):
print(self.data.a1, self.data.a2)
'''if(self.left != None):
print("Has left child")
else:
print("Does not have left child")
if (self.right != None):
print("Has right child")
else:
print("Does not have right child")'''
class Data:
"""
Tree data: Any object which is used as a tree node data
"""
def __init__(self, val1, val2):
"""
Data constructor
@param A list of values assigned to object's attributes
"""
self.a1 = val1
self.a2 = val2
if __name__ == "__main__":
root_data = Data(48, chr(48))
left_data = Data(49, chr(49))
right_data = Data(50, chr(50))
root = Node(None, None, None, root_data)
left_child = root.addLeft(left_data)
right_child = root.addRight(right_data)
root.printNode()
left_child.printNode()
right_child.printNode()
left_child.parent.printNode()
|
99421729232987d7fe4d317883032134d21d07b3 | bojanuljarevic/Algorithms | /sorting/quicksort.py | 1,342 | 3.75 | 4 | #!/usr/bin/python
import random
import time
def random_list (min, max, elements):
list = random.sample(range(min, max), elements)
return list
def partition(A, p, r):
x = A[r]
i = p - 1
for j in range(p, r):
if A[j] <= x:
i = i + 1
A[i], A[j] = A[j], A[i]
A[i+1], A[r] = A[r], A[i+1]
return i+1
def randomized_partition(A, p, r):
i = random.randint(p, r)
A[r], A[i] = A[i], A[r]
return partition(A, p, r)
def randomized_quicksort(A, p, r):
if p < r:
q = randomized_partition(A, p, r)
randomized_quicksort(A, p, q-1)
randomized_quicksort(A, q+1, r)
l = random_list(0, 100, 100)
t1 = time.clock()
randomized_quicksort(l, 0, len(l)-1)
t2 = time.clock()
print("QUICK(100): ", t2 - t1)
l = random_list(0, 1000, 1000)
t1 = time.clock()
randomized_quicksort(l, 0, len(l)-1)
t2 = time.clock()
print("QUICK(1K): ", t2 - t1)
l = random_list(0, 10000, 10000)
t1 = time.clock()
randomized_quicksort(l, 0, len(l)-1)
t2 = time.clock()
print("QUICK(10K): ", t2 - t1)
l = random_list(0, 100000, 100000)
t1 = time.clock()
randomized_quicksort(l, 0, len(l)-1)
t2 = time.clock()
print("QUICK(100K): ", t2 - t1)
l = random_list(0, 1000000, 1000000)
t1 = time.clock()
randomized_quicksort(l, 0, len(l)-1)
t2 = time.clock()
print("QUICK(1M): ", t2 - t1) |
6157e34614e49830e4899261da0db857eac845f2 | ZhaoHuiXin/MachineLearningFolder | /Part 2 - Regression/Section 4 - Simple Linear Regression/simple_linear_regression_practice2.py | 764 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 12 17:29:51 2019
@author: zhx
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:,0:1].values
y = dataset.iloc[:,1].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
y_pred = regressor.predict(X_test)
# plot
plt.scatter(X_test, y_test, color='red')
plt.plot(X_test, regressor.predict(X_test), color='green')
plt.title('SimpleLinearRegression')
plt.xlabel('age')
plt.ylabel('salary')
plt.show() |
9956ac773c8fc68668abb55eb445a6be2b3aea4f | kalewford/Python- | /Bank/main(submission).py | 2,516 | 4 | 4 | # Dependencies
import csv
import os
# Files to Load
file_to_load = "Bank/budget_data.csv"
file_to_output = "Bank/budget_analysis.txt"
# Variables to Track
total_months = 0
total_revenue = 0
prev_revenue = 0
revenue_change = 0
great_date = ""
great_increase = 0
bad_date = ""
worst_decrease = 0
revenue_changes = []
# Read Files
with open(file_to_load) as budget_data:
reader = csv.DictReader(budget_data)
# Loop through all the rows of data we collect
for row in reader:
# Calculate the totals
total_months = total_months + 1
total_revenue = total_revenue + int(row[1])
# print(row)
# Keep track of changes
revenue_change = int(row[1]) - prev_revenue
# print(revenue_change)
# Reset the value of prev_revenue to the row I completed my analysis
prev_revenue = int(row[1])
# print(prev_revenue)
# Determine the greatest increase
if (int(row[1]) > great_increase):
great_increase = int(row[1])
great_date = row[0]
if (int(row[1]) < worst_decrease):
worst_decrease = int(row[1])
bad_date = row[0]
# Add to the revenue_changes list
revenue_changes.append(int(row[1]))
# Set the Revenue average
revenue_avg = sum(revenue_changes) / len(revenue_changes)
# Show Output
print()
print()
print()
print("Financial Analysis")
print("-------------------------")
print("Total Months: " + str(total_months))
print("Total Revenue: " + "$" + str(total_revenue))
print("Average Change: " + "$" + str(round(sum(revenue_changes) / len(revenue_changes),2)))
print("Greatest Increase: " + str(great_date) + " ($" + str(great_increase) + ")")
print("Greatest Decrease: " + str(bad_date) + " ($" + str(worst_decrease) + ")")
# Output Files
with open(file_to_output, "w") as txt_file:
txt_file.write("Total Months: " + str(total_months))
txt_file.write("\n")
txt_file.write("Total Revenue: " + "$" + str(total_revenue))
txt_file.write("\n")
txt_file.write("Average Change: " + "$" + str(round(sum(revenue_changes) / len(revenue_changes),2)))
txt_file.write("\n")
txt_file.write("Greatest Increase: " + str(great_date) + " ($" + str(great_increase) + ")")
txt_file.write("\n")
txt_file.write("Greatest Decrease: " + str(bad_date) + " ($" + str(worst_decrease) + ")") |
5f5e0b19e8b1b6d0b0142eb63621070a50227142 | steven-liu/snippets | /generate_word_variations.py | 1,109 | 4.125 | 4 | import itertools
def generate_variations(template_str, replace_with_chars):
"""Generate variations of a string with certain characters substituted.
All instances of the '*' character in the template_str parameter are
substituted by characters from the replace_with_chars string. This function
generates the entire set of possible permutations."""
count = template_str.count('*')
_template_str = template_str.replace('*', '{}')
variations = []
for element in itertools.product(*itertools.repeat(list(replace_with_chars), count)):
variations.append(_template_str.format(*element))
return variations
if __name__ == '__main__':
# use this set to test
REPLACE_CHARS = '!@#$%^&*'
# excuse the bad language...
a = generate_variations('sh*t', REPLACE_CHARS)
b = generate_variations('s**t', REPLACE_CHARS)
c = generate_variations('s***', REPLACE_CHARS)
d = generate_variations('f*ck', REPLACE_CHARS)
e = generate_variations('f**k', REPLACE_CHARS)
f = generate_variations('f***', REPLACE_CHARS)
print list(set(a+b+c+d+e+f))
|
14deebd3730600c4c34d2ef5ae3cd3f110dcaf0c | SharanSMenon/Sharan-Main | /guessTheNumber.py | 484 | 3.828125 | 4 | import random
while True:
n = random.randint(0,100)
count = 0
while True:
guess = int(input('Guess a number between 1 and 100:'))
if guess == n:
print("You win")
count += 1
print("You tried "+str(count)+" times.")
play_again = input('Do you want to play again?')
if play_again == 'no':
print('Bye')
quit()
else:
break
elif guess > n:
print('Try a smaller number')
count += 1
elif guess < n:
print('Try a larger number')
count += 1 |
f84682bb7f6a6df4644cff27e69d48cf0b1a6fc2 | cdanh-aptech/Python-Learning | /PTB2.py | 787 | 3.5 | 4 | import math
def main():
print("Giai Phuong Trinh Bac 2 (ax2 + bx + c = 0)")
hs_a = int(input("Nhap he so a: "))
hs_b = int(input("Nhap he so b: "))
hs_c = int(input("Nhap he so c: "))
giaiPT(hs_a, hs_b, hs_c)
def giaiPT(a, b, c):
if a == 0:
print(f"La phuong trinh bac 1, x = {-c/b}")
else:
delta = b*b - (4 * a * c)
if delta < 0:
print("Phuong trinh vo nghiem")
elif delta == 0:
x = -b / 2*a
print(f"Phuong trinh co nghiem kep x1 = x2 = {x}")
else:
x1 = -b + math.sqrt(delta)
x2 = -b - math.sqrt(delta)
print("Phuong trinh co 2 nghiem")
print(f"x1 = {x1}")
print(f"x2 = {x2}")
if __name__ == "__main__":
main() |
dbc393cb1fe09bc5cb54992be1294e154cf023a1 | KuleshovaY/Python_GB | /Lesson_3/task_3.5.py | 1,594 | 3.875 | 4 | # Программа запрашивает у пользователя строку чисел, разделенных пробелом.
# При нажатии Enter должна выводиться сумма чисел.
# Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter.
# Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме.
# Но если вместо числа вводится специальный символ, выполнение программы завершается.
# Если специальный символ введен после нескольких чисел,
# то вначале нужно добавить сумму этих чисел к полученной ранее сумме и после этого завершить программу.
def str_numbers():
sum_result = 0
ex = False
while ex == False:
numbers = (input('Введите несколько чисел через пробел или E для выхода: ')).split()
result = 0
for el in range(len(numbers)):
if numbers[el] == 'E':
ex = True
break
else:
result = result +int(numbers[el])
sum_result = sum_result + result
print(f'Текущий результат {sum_result}')
print(f'Финальный результат {sum_result}')
str_numbers()
str_numbers()
|
c1bdaf6db92db9e09dce8e58127041436842b4ce | KuleshovaY/Python_GB | /Lesson_2/task _2.6.py | 951 | 3.6875 | 4 | i = 1
goods = []
n = int(input('Сколько товаров хотите ввести? '))
for _ in range(n):
name = input('Введите название товара ')
price = int(input('Введите цену '))
quantity = int(input('Введите колличество '))
measure = input('введите единицы измерения ')
goods.append((i, {'название': name, 'цена': price, 'количество': quantity, 'ед': measure}))
i += 1
print(goods)
goods_dict = {'название': [], 'цена': [], 'количество': [], 'ед': []}
for good in goods:
goods_dict['название'].append(good[1]['название'])
goods_dict['цена'].append(good[1]['цена'])
goods_dict['количество'].append(good[1]['количество'])
if good[1]['ед'] not in goods_dict['ед']:
goods_dict['ед'].append(good[1]['ед'])
print(goods_dict)
|
a0e648ea664458c9752d4013b8b91b6cee690dfa | jackjyq/COMP9021_Python | /ass01/highest_scoring_words/highest_scoring_words.py | 5,438 | 3.859375 | 4 | # Author: Jack (z5129432) for COMP9021 Assignment 1
# Date: 25/08/2017
# Description: Qustion 3
from itertools import permutations
from collections import defaultdict
import sys
# Function: CombineLetters
# Dependency: itertools.permutations
# Input: a list such as ['a', 'b', 'c']
# Output: a set such as {'ab', 'bac', 'b', 'c', 'acb', 'ca', 'bc', 'cb', 'cba', 'ba', 'bca', 'ac', 'cab', 'abc', 'a'}
# Description:
def CombineLetters(letters, word_dictionary):
letters_combination = set()
for word_length in range (1, len(letters) + 1): # generate different word length
letters_combination |= set(''.join(e) for e in permutations(letters, word_length)) & word_dictionary # union all permutation()
return(letters_combination)
# Function: FindHighestScoreWords
# Dependency: ScoreWord
# Input: an unsorted dictionary contains words, such as {8: [['oui'], ['iou']], 2: [['a'], ['ie']], 7: [['eau']], 3: [['ai']]}
# Output: search in the input set. return an integer (highest score), such as 8
# followed by a list (highest score words) orderd alphabetaly, such as [['iou'], ['oui']]
# Description:
def FindHighestScoreWords(scored_word_set):
if len(scored_word_set) != 0:
highest_score = sorted(scored_word_set.keys())[len(scored_word_set) - 1]
highest_score_words = sorted(scored_word_set[highest_score])
else:
highest_score = 0
highest_score_words = []
return highest_score, highest_score_words
# Function: GenerateDict.py
# Dependency:
# Input: a string such as "wordsEn.txt"
# Output: a set of the words in the dictionary such as {'backup', 'way', 'rink'}
# Description:
def GenerateDict(file_name):
word_dictionary = set()
with open("wordsEn.txt") as book:
for line in book:
word_dictionary.add(line.strip())
return(word_dictionary)
# Function: ScoreLetter
# Dependency:
# Input: a letter 'i'
# Output: an integer(score of letter)
# Description:
def ScoreLetter(letter):
magic_book = {
'a': 2, 'b': 5, 'c': 4, 'd': 4, 'e': 1, 'f': 6, \
'g': 5, 'h': 5, 'i': 1, 'j': 7, 'k': 6, 'l': 3, \
'm': 5, 'n': 2, 'o': 3, 'p': 5, 'q': 7, 'r': 2, \
's': 1, 't': 2, 'u': 4, 'v': 6, 'w': 6, 'x': 7, \
'y': 5, 'z': 7
}
return(magic_book[letter])
# Function: ScoreWord
# Dependency: ScoreLetter
# Input: a string 'iou'
# Output: an integer (score) such as 8 for 'iou'
# Description:
def ScoreWord(word):
score = int(0)
for letter in word:
score += ScoreLetter(letter)
return(score)
# Function: ScoreWordSet
# Dependency: ScoreWord, collections.defaultdict
# Input: a set contains words, such as {'eau', 'iou', 'a', 'oui', 'ie', 'ai'}
# Output: an unsorted dictionary contains words, such as {8: [['oui'], ['iou']], 2: [['a'], ['ie']], 7: [['eau']], 3: [['ai']]}
# Description:
def ScoreWordSet(word_set):
scored_word_set = defaultdict(list)
word_set = list(word_set)
for word in word_set:
scored_word_set[ScoreWord(word)].append([word])
return(scored_word_set)
# Function: UserInput Version: 01
# Dependency: sys.exit
# Input: 3 ~ 10 lowercase letters from user
# Output: a list ['a', 'e', 'i', 'o', 'u']
# Description:
def UserInput():
converted_letters = []
try:
input_letters = input('Enter between 3 and 10 lowercase letters: ').replace(" ", "")
if len(input_letters) < 3 or len(input_letters) > 10:
raise ValueError
for e in input_letters:
if e.islower():
converted_letters.append(e)
else:
raise ValueError
except ValueError:
print('Incorrect input, giving up...')
sys.exit()
return(converted_letters)
# Function: UserOutput Version: 01
# Dependency: sys.exit
# Input: an integer (highest score), such as 8
# followed by a list (highest score words) orderd alphabetaly, such as [['iou'], ['oui']]
# Output: print
# Description:
def UserOutput(highest_score, highest_score_words):
if len(highest_score_words) == 0:
print('No word is built from some of those letters.')
elif len(highest_score_words) == 1:
print(f'The highest score is {highest_score}.')
print(f'The highest scoring word is {highest_score_words[0][0]}')
else:
print(f'The highest score is {highest_score}.')
print('The highest scoring words are, in alphabetical order:')
for the_words in highest_score_words:
print(f' {the_words[0]}')
return
##### main function
debug_mode = 0 # toggle debug_mode, print output of every functions
input_letters = UserInput()
if debug_mode == 1:
print('input_letters =', input_letters)
word_dictionary = GenerateDict("wordsEn.txt")
if debug_mode == 3:
print('word_dictionary =', word_dictionary)
letters_combination = CombineLetters(input_letters, word_dictionary)
if debug_mode == 2:
print('letters_combination =', letters_combination)
scored_word_set = ScoreWordSet(letters_combination)
if debug_mode == 5:
print('scored_word_set =', scored_word_set)
highest_score, highest_score_words = FindHighestScoreWords(scored_word_set)
if debug_mode == 6:
print('scored_word_set =', scored_word_set)
print(highest_score)
print(highest_score_words)
UserOutput(highest_score, highest_score_words) |
7b8489895a95d9870f1caff4edf870e1e496da11 | jackjyq/COMP9021_Python | /ass01/highest_scoring_words/Permutations.py | 406 | 3.765625 | 4 | # Function: Permutations
# Dependency:
# Input: list such as ['e', 'a', 'e', 'o', 'r', 't', 's', 'm', 'n', 'z'], and a integer such as 10
# Output: set of permutations of your input
# Description:
def Permutations(input_list, number):
return
# Test Codes
if __name__ == "__main__":
Letters = ['e', 'a', 'e', 'o', 'r', 't', 's', 'm', 'n', 'z']
number = 10
Permutations(Letters, number) |
54f286be437cb160aa7c49f4e9630d1a5072a8ce | jackjyq/COMP9021_Python | /quiz04/sort_ratio.py | 1,049 | 3.546875 | 4 | from get_valid_data import get_valid_data
from get_ratio import get_ratio
from get_top_n_countries import get_top_n_countries
def sort_ratio(courtry_with_ratio):
""" sort_ratio
Arguements: an unsorted list[(ratio1, country1), (ratio2, country2), (ratio3, country3) ...]
Returns: A list sorted by ratio. If two countries have same ratio, then sort by countries' name.
Such as: [[ratio1, country1], [ratio2, country2], [ratio3, country3] ...]
"""
counry_sorted_by_ratio = sorted(courtry_with_ratio, key=lambda tup: (-tup[0], tup[1]))
return counry_sorted_by_ratio
# Test Codes
if __name__ == "__main__":
agricultural_land_filename = 'API_AG.LND.AGRI.K2_DS2_en_csv_v2.csv'
forest_filename = 'API_AG.LND.FRST.K2_DS2_en_csv_v2.csv'
year_1 = 1992
year_2 = 1999
agricultural = get_valid_data(agricultural_land_filename, year_1, year_2)
forest = get_valid_data(forest_filename, year_1, year_2)
country_with_ratio = get_ratio(agricultural, forest)
print(sort_ratio(country_with_ratio))
|
2514877d40f20ee981d6cb981cdf0b0dd92b263d | jackjyq/COMP9021_Python | /ass01/pivoting_die/pivoting_die.py | 2,703 | 3.984375 | 4 | # Author: Jack (z5129432) for COMP9021 Assignment 1
# Date: 23/08/2017
# Description:
'''
'''
import sys
# function: move
# input: null
# output: die[] after moved
def move_right():
die_copy = die[:]
die[3] = die_copy[2] # right become bottom
die[2] = die_copy[0] # top become right
die[0] = die_copy[5] # left become top
die[5] = die_copy[3] # bottom become left
return
def move_left():
die_copy = die[:]
die[0] = die_copy[2] # right become top
die[5] = die_copy[0] # top become left
die[3] = die_copy[5] # left become bottom
die[2] = die_copy[3] # bottom become right
return
def move_forewards():
die_copy = die[:]
die[1] = die_copy[0] # top become front
die[3] = die_copy[1] # front become bottom
die[4] = die_copy[3] # bottom become back
die[0] = die_copy[4] # back become top
return
def move_backwards():
die_copy = die[:]
die[4] = die_copy[0] # top become back
die[0] = die_copy[1] # front become top
die[1] = die_copy[3] # bottom become front
die[3] = die_copy[4] # back become bottom
return
# user interface: input part
while True:
try:
cell = int(input('Enter the desired goal cell number: '))
if cell <= 0:
raise ValueError
break
except ValueError:
print('Incorrect value, try again')
# initialize die[]
# top front right bottom back left
# 0 1 2 3 4 5
die = [3, 2, 1, 4, 5, 6]
# initialize moving step in one direction
step = 1
# initialize counter
i = cell
# simulate moving die
# function: move
# input: null
# output: die[] after moved
while(i > 1):
for _ in range(0, step): # moving right for "step" steps
move_right()
i -= 1
if i <= 1:
break
if i <= 1:
break
for _ in range(0, step): # moving forewards for "step" steps
move_forewards()
i -= 1
if i <= 1:
break
if i <= 1:
break
step += 1 # increase step by 1
for _ in range(0, step): # moving left for "step" steps
move_left()
i -= 1
if i <= 1:
break
if i <= 1:
break
for _ in range(0, step): # moving backwards for "step" steps
move_backwards()
i -= 1
if i <= 1:
break
step += 1 # increase step by 1
# user interface: output part
print(f'On cell {cell}, {die[0]} is at the top, {die[1]} at the front, and {die[2]} on the right.') |
a4d065a288fb455ede7cf37fc3e4b4d3eabf6c9f | jackjyq/COMP9021_Python | /ass01/poker_dice/roll_dice.py | 571 | 4.03125 | 4 | from random import randint
from random import seed
def roll_dice(kept_dice=[]):
""" function
Use to generate randonly roll, presented by digits.
Arguements: a list of kept_dice, such as [1, 2]
default argument if []
Returns: a list of ordered roll, such as [1, 2, 3, 4, 5].
Dependency: random.randint
"""
roll = [randint(0, 5) for _ in range(5 - len(kept_dice))]
roll.extend(kept_dice)
roll.sort()
return roll
# Test Codes
if __name__ == "__main__":
kept_dice = [1, 2]
seed()
print(roll_dice(kept_dice))
|
cc3a1d58b9a459e87baba1db1667b8c3eafaed7a | jackjyq/COMP9021_Python | /ass01/poker_dice/hand_rank.py | 1,577 | 4.21875 | 4 | def hand_rank(roll):
""" hand_rank
Arguements: a list of roll, such as [1, 2, 3, 4, 5]
Returns: a string, such as 'Straight'
"""
number_of_a_kind = [roll.count(_) for _ in range(6)]
number_of_a_kind.sort()
if number_of_a_kind == [0, 0, 0, 0, 0, 5]:
roll_hand = 'Five of a kind'
elif number_of_a_kind == [0, 0, 0, 0, 1, 4]:
roll_hand = 'Four of a kind'
elif number_of_a_kind == [0, 0, 0, 0, 2, 3]:
roll_hand = 'Full house'
elif number_of_a_kind == [0, 0, 0, 1, 1, 3]:
roll_hand = 'Three of a kind'
elif number_of_a_kind == [0, 0, 0, 1, 2, 2]:
roll_hand = 'Two pair'
elif number_of_a_kind == [0, 0, 1, 1, 1, 2]:
roll_hand = 'One pair'
elif number_of_a_kind == [0, 1, 1, 1, 1, 1]:
if (roll == [0, 2, 3, 4, 5] or
roll == [0, 1, 3, 4, 5] or
roll == [0, 1, 2, 4, 5] or
roll == [0, 1, 2, 3, 5]):
# According to https://en.wikipedia.org/wiki/Poker_dice,
# there are only four possible Bust hands
roll_hand = 'Bust'
else:
roll_hand = 'Straight'
return roll_hand
# Test Codes
if __name__ == "__main__":
roll = [1, 1, 1, 1, 1]
print(hand_rank(roll))
roll = [1, 1, 1, 1, 2]
print(hand_rank(roll))
roll = [1, 1, 1, 3, 3]
print(hand_rank(roll))
roll = [1, 1, 1, 2, 3]
print(hand_rank(roll))
roll = [1, 1, 2, 2, 3]
print(hand_rank(roll))
roll = [0, 2, 3, 4, 5]
print(hand_rank(roll))
roll = [1, 2, 3, 4, 5]
print(hand_rank(roll))
|
c889b0c75a22a5de5204de652db5adc535c8d190 | eunic/bootcamp-final-files | /wordcount.py | 495 | 3.65625 | 4 | def words(stringofwords):
dict_of_words = {}
list_of_words = stringofwords.split()
for word in list_of_words:
if word in dict_of_words:
if word.isdigit():
dict_of_words[int(word)] += 1
else:
dict_of_words[word] += 1
else:
if word.isdigit():
dict_of_words[int(word)] = 1
else:
dict_of_words[word] = 1
return dict_of_words |
dd79781c62f4547d9d74d2ac395464642b02ec89 | mtasende/usd-uyu-dashboard | /src/data/world_bank.py | 3,125 | 4.0625 | 4 | """ Functions to access the World Bank Data API. """
import requests
from collections import defaultdict
import pandas as pd
def download_index(country_code,
index_code,
start_date=1960,
end_date=2018):
"""
Get a JSON response for the index data of one country.
Args:
country_code(str): The two letter code for the World Bank webpage
index_code(str): The code for the index to retreive
start_date(int): The initial year to retreive
end_date(int): The final year to retreive
Returns:
str: a JSON string with the raw data
"""
payload = {'format': 'json',
'per_page': '500',
'date': '{}:{}'.format(str(start_date), str(end_date))
}
r = requests.get(
'http://api.worldbank.org/v2/countries/{}/indicators/{}'.format(
country_code, index_code), params=payload)
return r.json()
def format_response(raw_res):
"""
Formats a raw JSON string, returned from the World Bank API into a
pandas DataFrame.
"""
result = defaultdict(dict)
for record in raw_res[1]:
result[record['country']['value']].update(
{int(record['date']): record['value']})
return pd.DataFrame(result)
def download_cpi(country_code, **kwargs):
"""
Downloads the Consumer Price Index for one country, and returns the data
as a pandas DataFrame.
Args:
country_code(str): The two letter code for the World Bank webpage
**kwargs: Arguments for 'download_index', for example:
start_date(int): The initial year to retreive
end_date(int): The final year to retreive
"""
cpi_code = 'FP.CPI.TOTL'
raw_res = download_index(country_code, cpi_code, **kwargs)
return format_response(raw_res)
def download_cpis(country_codes, **kwargs):
"""
Download many countries CPIs and store them in a pandas DataFrame.
Args:
country_codes(list(str)): A list with the two letter country codes
**kwargs: Other keyword arguments, such as:
start_date(int): The initial year to retreive
end_date(int): The final year to retreive
Returns:
pd.DataFrame: A dataframe with the CPIs for all the countries in the
input list.
"""
cpi_list = [download_cpi(code, **kwargs) for code in country_codes]
return pd.concat(cpi_list, axis=1)
def download_exchange_rate(country_code, **kwargs):
"""
Downloads the Exchange for one country, with respect to USD,
and returns the data as a pandas DataFrame.
Args:
country_code(str): The two letter code for the World Bank webpage
**kwargs: Arguments for 'download_index', for example:
start_date(int): The initial year to retreive
end_date(int): The final year to retreive
Returns:
pd.DataFrame: The values for the exchange rates in a dataframe.
"""
cpi_code = 'PA.NUS.FCRF'
raw_res = download_index(country_code, cpi_code, **kwargs)
return format_response(raw_res)
|
00fd9d33ece481fe3d2e98eaca624aeb2e595b1c | YuvalHelman/adventofcode2020 | /adventOfCode/day2.py | 1,368 | 3.5625 | 4 | from pathlib import Path
from typing import Callable
from itertools import filterfalse
import re
FILE_PATTERN = re.compile(r"(?P<min>[0-9]+)-(?P<max>[0-9]+)\s*(?P<letter_rule>[A-Za-z]):\s*(?P<password>[A-Za-z]+)")
INPUT_PATH = Path("inputs/day2_1.txt")
def is_count_of_char_in_sentence(char: str, sentence: str, min: int, max: int) -> bool:
counter = len(list(filterfalse(lambda x: x is not char, sentence)))
return min <= counter <= max
def day2(checker: Callable[..., bool]) -> int:
counter = 0
with open(INPUT_PATH) as fp:
for line in fp:
line = line.strip("\n")
m = re.search(FILE_PATTERN, line)
if m:
if checker(m.group("letter_rule"), m.group("password"),
int(m.group("min")), int(m.group("max"))):
counter += 1
print(line)
print(len(m.group("password")))
return counter
def are_positions_valid(char: str, sentence: str, min: int, max: int) -> bool:
counter = 0
if len(sentence) >= min and sentence[min - 1] == char:
counter += 1
if len(sentence) >= max and sentence[max - 1] == char:
counter += 1
return counter == 1
if __name__ == "__main__":
print("ex1 res: ", day2(is_count_of_char_in_sentence))
print("ex2 res: ", day2(are_positions_valid))
|
c758312e57e9cbab57c6a448cb7cfb90331ebbad | tskkst51/lplTrade | /PTP/trading_platform_shell/string_parsers.py | 2,493 | 3.59375 | 4 |
#
#
#
def string_to_value(s):
s = s.strip().lower()
if s[-1] == 'k':
try:
value = float(s[:-1])
return value * 1000.0
except ValueError:
return None
try:
value = float(s)
return value
except ValueError:
pass
try:
return float(eval(s))
except Exception:
pass
return None
#
#
#
def string_to_price(s):
s = s.strip()
if s == '' or s == 'm':
return 'MEAN_PRICE'
if s == 'M':
return 'MARKET_PRICE'
if s.upper() == 'MARKET_PRICE':
return 'MARKET_PRICE'
try:
num = float(s)
return round(num, 2)
except ValueError:
return None
#
#
#
def string_to_relative(s):
if s[-1] != '%':
return None
try:
margin = float(s[:-1])
except ValueError:
return None
return margin / 100.0
#
#
#
def string_to_price_relative(s, symbol, trade, condition='negative'):
price = string_to_price(s)
if price is not None:
return price
margin = string_to_relative(s)
if margin is None:
return None
if condition == 'negative':
if margin >= 0:
print('% must be negative')
return None
if condition == 'positive':
if margin <= 0:
print('% must be positive')
return None
try:
price = trade.get_current_price(symbol)
except ValueError as e:
print(str(e))
return None
return round(price * (1.0 + margin), 2)
#
#
#
def string_to_int(s):
try:
num = int(float(s))
return num
except ValueError:
return None
#
#
#
def string_to_session(s):
s = s.strip()
if s == '' or s == 'R':
return 'REGULAR'
if s == 'E':
return 'EXTENDED'
return None
#
#
#
def string_to_price_or_quote_price(s, trade):
s = s.strip().lower()
try:
value = float(s)
return value, False
except ValueError:
pass
try:
return float(eval(s)), False
except Exception as _:
pass
if s[-1] == '%':
return None, False
try:
value = trade.get_current_price(s)
return value, True
except ValueError as e:
print('quote request for ' + s.upper() + ': ' + str(e))
pass
return None, False
|
903ba4783c8c4e7af8d4087dfab2759cd3579919 | mailtsjp/FinPy | /Filetoticker.py | 1,825 | 3.5625 | 4 |
import pandas_datareader.data as web
import datetime
#read ticker symbols from a file to python symbol list
symbol = []
with open('tickers.txt') as f:
for line in f:
symbol.append(line.strip())
f.close
#datetime is a Python module
#datetime.datetime is a data type within the datetime module
#which allows access to Gregorian dates and today function
#datetime.date is another data type within the datetime module
#which permits arithmetic with Gregorian date components
#definition of end with datetime.datetime type must precede
#definition of start with datetime.date type
#the start expression collects data that are up to five years old
end = datetime.datetime.today()
start = datetime.date(end.year-5,1,1)
#set path for csv file
path_out = 'c:/python_programs_output/'
#loop through 50 tickers in symbol list with i values of 0 through 49
#if no historical data returned on any pass, try to get the ticker data again
#for first ticker symbol write a fresh copy of csv file for historical data
#on remaining ticker symbols append historical data to the file written for
#the first ticker symbol and do not include a header row
i=0
while i<len(symbol):
try:
df = web.DataReader(symbol[i], 'yahoo', start, end)
df.insert(0,'Symbol',symbol[i])
df = df.drop(['Adj Close'], axis=1)
if i == 0:
df.to_csv(path_out+'yahoo_prices_volumes_for_ST_50_to_csv_demo.csv')
print (i, symbol[i],'has data stored to csv file')
else:
df.to_csv(path_out+'yahoo_prices_volumes_for_ST_50_to_csv_demo.csv',mode = 'a',header=False)
print (i, symbol[i],'has data stored to csv file')
except:
print("No information for ticker # and symbol:")
print (i,symbol[i])
continue
i=i+1 |
0cadee6937b8b5954877cfd8de03660fa983407f | Miguel-21904220/pw_python_03 | /pw-python-03/Exercisio 1/analisa_ficheiro/acessorio.py | 369 | 3.625 | 4 | import os
def pede_nome():
while True:
try:
nome_ficheiro = input("Introduza o numero do ficheiro: ")
with open('analisa_ficheiro/' + nome_ficheiro, 'r') as file:
return nome_ficheiro
except:
print("Nao existe")
def gera_nome(x):
return os.path.splitext(x)[0] + ".json" |
007ef0564c214ab11f0b9ef081cb08c0b2315029 | cassiano-r/Spark | /MapReduceSparkHadoopProject/gastos-cliente.py | 787 | 3.65625 | 4 | from pyspark import SparkConf, SparkContext
# Define o Spark Context, pois o job será executado via linha de comando com o spark-submit
conf = SparkConf().setMaster("local").setAppName("GastosPorCliente")
sc = SparkContext(conf = conf)
# Função de mapeamento que separa cada um dos campos no dataset
def MapCliente(line):
campos = line.split(',')
return (int(campos[0]), float(campos[2]))
# Leitura do dataset a partir do HDFS
input = sc.textFile("hdfs://clientes/gastos-cliente.csv")
mappedInput = input.map(MapCliente)
# Operação de redução por chave para calcular o total gasto por cliente
totalPorCliente = mappedInput.reduceByKey(lambda x, y: x + y)
# Imprime o resultado
resultados = totalPorCliente.collect();
for resultado in resultados:
print(resultado)
|
cb7c7e5bdfd3b741a4b3a77d7264736ec61e184f | joker507/exercise | /UA.py | 1,229 | 3.71875 | 4 | #用于求大学物理实验中的A类不确定度和平均值,今后将考虑自动取好不确定度的有效数字和求解b类不确定度并取相应的有效数字并计算总不确定度,但现实践有限,不做实现
#physics average,求平均值
def phsaver(a):
m = len(a)
aver = []
for i in range(m):
sum = 0
for num in a[i]:
sum = sum + num
aver.append(sum/len(a[i]))
return aver
#physics undecided 求A类不确定度
def phsunde(a):
m = len(a)
ud = []
for i in range(m):
ud.append(0)
for j in range(m):
ave = phsaver(a)[j]
sum = 0
dim = len(a[j])
for num in a[j]:
sum = sum + (num - ave)**2
unde = (sum/(dim*(dim - 1)))**0.5
print ("第",j+1,"行的平均值为:",ave)
print ("第",j+1,"行的A类不确定度为:",unde)
return ud
if __name__ == "__main__":
try:
while 1:
a = input('请输入要计算的表格,同行用,(英文逗号)分隔,换行用;(英文分号)分隔:\n')
a = a.split(";")
s = len(a)
for i in range(s):
a[i] = a[i].split(',')
n = len(a[i])
for j in range(n):
a[i][j] = eval(a[i][j])
phsunde(a)
key = input("是否继续计算(y/n)")
if key == 'n':
break
except:
print("输入错误")
|
e0408bdb6b3251bf3472b3a3836ad7ec8ec0ed4d | madhurigorthi/sdet-1 | /python/Activity3.py | 537 | 3.859375 | 4 | input1=input("Enter player1 input :").lower()
input2=input("Enter player2 input :").lower()
if input1 == input2:
print("Its tie !!")
elif input1 == 'rock':
if input2 == 'scissors':
print("player 1 wins")
else:
print("player 2 wins")
elif input1 == 'scissors':
if input2 == 'rock':
print("player 1 wins")
else:
print("player 2 wins")
elif input1 == 'paper':
if input2 == 'scissors':
print("player 2 wins")
else:
print("player 1 wins")
|
54893e3be825167355e17ed579f00053945d924a | madhurigorthi/sdet-1 | /python/Acitvity1.py | 161 | 3.921875 | 4 | name=input("Enter your name ")
age=int(input("Enter your age "))
year=str((2020-age)+100)
print(name + " you will become 100 years old in the year " + year)
|
ddc9a3d2c6c1933dc8a404084ee9afc146a3cfae | wojciechuszko/random_Fibonacci_sequence | /random_fibonacci_sequence.py | 769 | 3.546875 | 4 | import numpy as np
import matplotlib.pyplot as plt
n = int(input("Enter a positive integer n: "))
vector = np.zeros(n)
vector[0] = 1
vector[1] = 1
for i in range(2,n):
rand = np.random.rand()
if rand < 0.5:
sign = -1
else:
sign = 1
vector[i] = vector[i-1] + sign * vector[i-2]
x = np.linspace(1,n,n)
v = 1.132*np.ones(n)
plt.figure()
plt.subplot(1, 2, 1)
plt.plot(x, np.absolute(vector), 'k-', label='|random f_n|')
plt.plot(x, 1.132**x, 'k--', label='1.132^n')
plt.yscale("log")
plt.xlabel("n")
plt.legend(loc='upper left')
plt.subplot(1, 2, 2)
plt.plot(x, np.absolute(vector)**(1/x), 'k-', label='|random f_n| ^ 1/n')
plt.plot(x, v, 'k--', label='1.132')
plt.ylim(1,1.3)
plt.xlabel("n")
plt.legend(loc='upper left')
plt.show() |
7947bfed24a33be65cecd3bca43eba6d76adf3eb | dkout/6.006 | /pset3/code_template_and_latex_template/search_template.py | 3,381 | 3.875 | 4 | ###################################
########## PROBLEM 3-4 ###########
###################################
from rolling_hash import rolling_hash
def roll_forward(rolling_hash_obj, next_letter):
"""
"Roll the hash forward" by discarding the oldest input character and
appending next_letter to the input. Return the new hash, and save it in rolling_hash_obj.hash_val as well
Parameters
----------
rolling_hash_obj : rolling_hash
Instance of rolling_hash
next_letter : char
New letter to append to input.
Returns
-------
hsh : int
Hash of updated input.
"""
#print('Next Letter: ', next_letter)
#print (rolling_hash_obj.alphabet_map)
# Pop a letter from the left and get the mapped value of the popped letter
# YOUR CODE HERE
last_char=rolling_hash_obj.sliding_window.popleft()
popval=rolling_hash_obj.alphabet_map[last_char]
#print ('last character: ', rolling_hash_obj.sliding_window.popleft())
#print ('last char value: ', popval)
#print('old hash value = ', rolling_hash_obj.hash_val)
# Push a letter to the right.
# YOUR CODE HERE
rolling_hash_obj.sliding_window.append(next_letter)
# Set the hash_val in the rolling hash object
# Hint: rolling_hash_obj.a_to_k_minus_1 may be useful
rolling_hash_obj.hash_val = ((rolling_hash_obj.hash_val-popval*rolling_hash_obj.a_to_k_minus_1)*rolling_hash_obj.a + rolling_hash_obj.alphabet_map[next_letter]) % rolling_hash_obj.m
#print ('new hash value = ', rolling_hash_obj.hash_val)
rolling_hash_obj.roll_history.append(next_letter)
# Return.
return rolling_hash_obj
def exact_search(rolling_hash_obj, pattern, document):
"""
Search for string pattern in document. Return the position of the first match,
or None if no match.
Parameters
----------
rolling_hash_obj : rolling_hash
Instance of rolling_hash, with parameters guaranteed to be already filled in based on the inputs we will test: the hash length (k) and alphabet (alphabet) are already set
You will need to create atleast one additional instance of rolling_hash_obj
pattern : str
String to search in document.
document : str
Document to search.
Returns
-------
pos : int or None
(zero-indexed) Position of first approximate match of S in T, or None if no match.
"""
print (rolling_hash_obj.sliding_window)
# may be helpful for you
n = len(document)
k = len(pattern)
## DO NOT MODIFY ##
rolling_hash_obj.set_roll_forward_fn(roll_forward)
rolling_hash_obj.init_hash(document[:k])
## END OF DO NOT MODIFY ##
ph=rolling_hash(k,rolling_hash_obj.alphabet)
ph.init_hash(pattern)
#print ('PATTERN, ', pattern)
#print ('DOCUMENT, ', document)
for i in range(n-k):
#print('pattern hash value, window hash value ', ph.hash_val, rolling_hash_obj.hash_val)
#print ("current window ", ''.join(rolling_hash_obj.sliding_window))
nl=document[i+k]
#print ("next letter = ", nl)
if ph.hash_val==rolling_hash_obj.hash_val:
#print('***SAME HASH VALUE***')
if pattern==document[i:i+k]:
#print("*******MATCHING STRING FOUND******** ", i)
return i
roll_forward(rolling_hash_obj, nl)
return None
|
30a9dcb344404f005a6f62031701c9b5c856d0fa | Blasius7/Python-homeworks | /guess.py | 1,274 | 3.6875 | 4 | import random
attempts = 0
end_num = [5,15,50]
while True:
difficulty = input("Milyen nehézségi fokon játszanád a játékot? \n (Könnyű, közepes vagy nehéz): \n")
if difficulty == "könnyű":
end_num = 5
break
elif difficulty == "közepes":
end_num = 15
break
elif difficulty == "nehéz":
end_num = 50
break
else:
print("Nem jó, adj meg egy nehézségi fokozatot!")
secret = random.randint(1, end_num)
with open("score.txt", "r") as score_file:
best_score = int(score_file.read())
print("Top score: " + str(best_score))
while True:
guess = int(input("Találd ki a titkos számot 1 és " + str(end_num) + "között "))
attempts += 1
if guess == secret:
print("Gratulálok, kitaláltad! Ez a szám: " + str(secret))
print("Kísérletek száma: " + str(attempts))
if best_score > attempts:
with open("score.txt", "w") as score_file:
score_file.write(str(attempts))
break
elif guess > secret:
print("Próbáld kisebbel")
print("Kísérletek száma: " + str(attempts))
elif guess < secret:
print("Próbáld nagyobbal")
print("Kísérletek száma: " + str(attempts)) |
8960e2ef84431879e95ccdaa62d78c55e8b30311 | michelle-chiu/Python | /Gauss.py | 246 | 3.984375 | 4 | #Add the numbers from 1 to 100
#Think about what happens to the variables as we go through the loop.
total = 0 #will be final total
for i in range(101): #i will be 0, 1, 2, 3, 4, 5, etc
total = total + i #change total by i
print(total) |
2e199b2cde6f32ac5008f72558d50c717657146e | hilaryweller0/talks2013 | /SS/HilaryNotes/pythonExamples_HW/GaussQuad.py | 951 | 3.59375 | 4 | # Calculate the approximate integral of sin(x) between a and b
# using 1-point Gaussiaun quadrature using N intervals
# First import all functions from the Numerical Python library
import numpy as np
# Set integration limits and number of intervals
a = 0.0 # a is real, not integer, so dont write a = 0
b = np.pi # pi is from numpy library so prefix with np.
N = 40 # N is an integer
# from these calculate the interval length
dx = (b - a)/N # since a and b are real, dx is real
# Initialise the integral
I = 0.0
# Sum contribution from each interval (end of loop at end of indentation)
for i in xrange(0,N): # : at the beginning of a loop
x = a + (i+0.5)*dx
I += np.sin(x) # sin is in the numpy library so prefix with np.
I *= dx
print 'Gaussian quadrature integral = ', I, \
'\nExact integral = ', -np.cos(b)+np.cos(a), \
' dx = ', dx, ', error = ', I + np.cos(b)-np.cos(a)
|
805a3bf16a9afccf42a465d3968bb3e2e7365abe | jgkr95/CSPP1 | /Practice/M5/p2/square_root.py | 348 | 3.875 | 4 | '''Write a python program to find the square root of the given number
using approximation method'''
def main():
'''This is main method'''
s_r = int(input())
ep_n = 0.01
g_s = 0.0
i_n = 0.1
while abs(g_s**2 - s_r) >= ep_n and g_s <= s_r:
g_s += i_n
print(g_s)
if __name__ == "__main__":
main()
|
0e9d74abf1c2592ec74bdfef35ed89f4cb480f7c | jgkr95/CSPP1 | /Practice/M3/compare_AB.py | 243 | 4.03125 | 4 | varA=input("Enter a stirng: ")
varB=input("Enter second string: ")
if isinstance(varA,str) or isinstance(varB,str):
print("Strings involved")
elif varA>varB:
print("bigger")
elif varA==varB:
print("equal")
elif varA<varB:
print("smaller")
|
05736db1424292838f160b8ca66ea94d911a752e | jgkr95/CSPP1 | /Practice/M3/iterate_even.py | 139 | 4.0625 | 4 | count = 0
n=input()
print(n)
for letter in 'Snow!':
print('Letter # ' + str(3)+ ' is ' + letter)
count += 1
break
print(count) |
8dbfcde0a480f44ea8f04d113a5214d7ddb9d290 | jgkr95/CSPP1 | /Practice/M6/p1/fizz_buzz.py | 722 | 4.46875 | 4 | '''Write a short program that prints each number from 1 to num on a new line.
For each multiple of 3, print "Fizz" instead of the number.
For each multiple of 5, print "Buzz" instead of the number.
For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
'''
def main():
'''Read number from the input, store it in variable num.'''
num_r = int(input())
i_i = 1
while i_i <= num_r:
if (i_i%3 == 0 and i_i%5 == 0):
print("Fizz")
print("Buzz")
elif i_i%3 == 0:
print("Fizz")
elif i_i%5 == 0:
print("Buzz")
else:
print(str(i_i))
i_i = i_i+1
if __name__ == "__main__":
main()
|
86c07784b9a2a69756a3390e8ff70b2a4af78652 | Ashishrsoni15/Python-Assignments | /Question2.py | 391 | 4.21875 | 4 | # What is the type of print function? Also write a program to find its type
# Print Funtion: The print()function prints the specified message to the screen, or other
#standard output device. The message can be a string,or any other object,the object will
#be converted into a string before written to the screen.
print("Python is fun.")
a=5
print("a=",a)
b=a
print('a=',a,'=b')
|
6575bbd5e4d495bc5f8b5eee9789183819761452 | Ashishrsoni15/Python-Assignments | /Question1.py | 650 | 4.375 | 4 | #Write a program to find type of input function.
value1 = input("Please enter first integer:\n")
value2 = input("Please enter second integer:\n")
v1 = int(value1)
v2 = int(value2)
choice = input("Enter 1 for addition.\nEnter 2 for subtraction.\nEnter 3 for multiplication:\n")
choice = int(choice)
if choice ==1:
print(f'you entered {v1} and {v2} and their addition is {v1+ v2}')
elif choice ==2:
print(f'you entered {v1} and {v2} and their subtraction is {v1 - v2}')
elif choice ==3:
print(f'you entered {v1} and {v2} and their multiplication is {v1 * v2}')
else:
print("Wrong Choice, terminating the program.")
|
a745d249dcd6eaf6bbd7c4b08bf1f8a9998291df | LeoM98/Nomina-industrial | /Explosiones.py | 3,338 | 3.796875 | 4 | def caso_explosion(): #definimos el algoritmo
mezclas=int(input("digite el numero de mezclas "))#pedimos al usuario que introduzca un valor
nombre_o=[raw_input("ingrese el nombre del operario " + str (a+1)+ ": ")for a in range(5)]# establecemos los nombres de los operarios en la lista
explosion=[[0 for a in range(mezclas)] for a in range(5)]#establecemos la matriz en cuanto a la explosion de 5 listas
for a in range(5):#creamos un ciclo que itere 5 veces
for l in range(mezclas):#dentro del ciclo volvemos a poner otro ciclo que itere (mezclas)veces
explosion[a][l]=float(input("digite la fuerza de la mezcla " + str (l+1)+ ": "))#pedimos al usuario que ingrese valor
while explosion[a][l]<=0:#condicionamos dentro del ciclo, no debe ser menor o igual a 0 de lo contrario se pedira otra vez
explosion[a][l]= float(input("digite la fuerza de la mezcla " + str (l+1)+ ": "))
sumador=[0 for i in range(5)]#establecemos un sumador
for j in range(5):#creamos un ciclo que itere 5 veces
for i in range(0, mezclas):#dentro del ciclo volvemos a crear otro ciclo que itere (mezclas) veces
sumador[j]+=explosion[j][i]#le vamos sumando al sumador
prom=[sumador[i]/mezclas for i in range(5)]#identificamos la operacion para hallar el promedio
for i in range(1,len(prom)):#creamos otro ciclo
for l in range(len(prom)-i):#creamos un ciclo dentro de otro ciclo para iterar
if prom[l]>prom[l+1]:# condicionamos el algoritmo para establecer valores menores y mayores, utilizando la tecnica de la burbuja
var=prom[l]
var2=nombre_o[l]
var3=explosion[l]
prom[l]=prom[l+1]
nombre_o[l]=nombre_o[l+1]
explosion[l]=explosion[l+1]
prom[l+1]=var
nombre_o[l+1]=var2
explosion[l+1]=var3
posicion=3# se establece un contador
for r in range(2):#se crea un contador
for o in range(1,mezclas):#creamos otro ciclo que itere desde uno hasta (mezclas) veces
for a in range(mezclas-o):#creamos otro ciclo que itere desde (mezclas) y a ese le restamos el valor de o
if explosion[posicion][a]>explosion[posicion][a+1]:#condicionamos siempre y cuando los valores de la lista sea unos mayores que otros. utilizando la tecnica de la burbuja
var4=explosion[posicion][a]
explosion[posicion][a]=explosion[posicion][a+1]
explosion[posicion][a+1]=var4
posicion+=1# se le aumente uno en valor al contador
#en todo esto se imprimen los mensajes mostrandole al usuario los datos de promedio, operarios,explosion y el orden
print "los promedios fueron", prom
print "operariso en orden", nombre_o
print "explosiones en orden",explosion
print nombre_o[3],"la menor fuerza de la mezcla fue ", explosion[3][0],"_ su fuerza mayor fue ", explosion[3][mezclas-1],">>>", nombre_o[4], " la fuerza menor fue de ", explosion[4][0], "_ y su fuerza mayor fue de ", explosion[4][mezclas-1]
caso_explosion()#cerramos el algoritmo para poder ejecutarlo |
ea4c7aaefa309e8f0db99f4f43867ebd1bd52282 | Shahriar2018/Data-Structures-and-Algorithms | /Task4.py | 1,884 | 4.15625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
print("These numbers could be telemarketers: ")
calling_140=set()
receving_140=set()
text_sending=set()
text_receiving=set()
telemarketers=set()
def telemarketers_list(calls,texts):
global calling_140,receving_140,text_sending,text_receiving,telemarketers
m=len(calls)
n=len(texts)
# making a list of calling/reciving numbers
for row in range(m):
if '140'in calls[row][0][:4]:
calling_140.add(calls[row][0])
if '140'in calls[row][1][:4]:
receving_140.add(calls[row][1])
# making a list of sending/receiving texts
for row in range(n):
if '140'in texts[row][0][:4]:
text_sending.add(calls[row][0])
if '140'in texts[row][1][:4]:
text_receiving.add(calls[row][1])
#Getting rid of unnecessary numbers
telemarketers=calling_140-receving_140-text_sending-text_receiving
telemarketers=sorted(list(telemarketers))
# Printing all the numbers
for i in range(len(telemarketers)):
print(telemarketers[i])
return ""
telemarketers_list(calls,texts)
|
be6417755aa43edf9a4eab63392fe474a08c561d | killercatfish/AdventCode | /2018/Advent2018/Tree.py | 2,945 | 3.828125 | 4 | # http://openbookproject.net/thinkcs/python/english2e/ch21.html
class Tree:
def __init__(self, cargo, left=None, right=None):
self.cargo = cargo
self.left = left
self.right = right
def __str__(self):
return str(self.cargo)
def total(tree):
if tree == None: return 0
return total(tree.left) + total(tree.right) + tree.cargo
def print_tree(tree):
if tree == None: return
print(tree.cargo,end='')
print_tree(tree.left)
print_tree(tree.right)
def print_tree_postorder(tree):
if tree == None: return
print_tree_postorder(tree.left)
print_tree_postorder(tree.right)
print(tree.cargo,end='')
def print_tree_inorder(tree):
if tree == None: return
print_tree_inorder(tree.left)
print(tree.cargo,end='')
print_tree_inorder(tree.right)
def print_tree_indented(tree, level=0):
if tree == None: return
print_tree_indented(tree.right, level+1)
print(' ' * level + str(tree.cargo))
print_tree_indented(tree.left, level+1)
# Check if a character is an int
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
def parse_expression(exp):
exp = exp.replace(' ','')
exp = list(exp)
for i in range(len(exp)):
if RepresentsInt(exp[i]):
exp[i] = int(exp[i])
exp.append('end')
# print(exp)
return exp
def get_token(token_list, expected):
if token_list[0] == expected:
del token_list[0]
return True
return False
def get_number(token_list):
x = token_list[0]
if type(x) != type(0): return None
del token_list[0]
return Tree(x, None, None)
def get_product(token_list):
a = get_number(token_list)
if get_token(token_list, '*'):
b = get_product(token_list)
return Tree('*',a,b)
else:
return a
def get_sum(token_list):
a = get_product(token_list)
if get_token(token_list,'+'):
b = get_sum(token_list)
return Tree('+',a,b)
else:
return a
# left = Tree(2)
# right = Tree(3)
# tree = Tree(1, left, right)
#
# print(total(tree))
# tree = Tree('+', Tree(1), Tree('*', Tree(2), Tree(3)))
# print_tree(tree)
# print('')
# print_tree_postorder(tree)
# print('')
# print_tree_inorder(tree)
# print('')
# print_tree_indented(tree)
# expression = '(3 + 7) * 9'
# token_list = parse_expression(expression)
# print(token_list)
# token_list = [9, 11, 'end']
# x = get_number(token_list)
# print_tree_postorder(x)
# print('')
# print(token_list)
# token_list = [9,'*',11,'end']
# tree = get_product(token_list)
# print_tree_postorder(tree)
# token_list = [9,'+',11,'end']
# tree = get_product(token_list)
# print_tree_postorder(tree)
# token_list = [2,'*',3,'*',5,'*',7,'end']
# tree = get_product(token_list)
# print_tree_postorder(tree)
token_list = [9, '*', 11, '+', 5, '*', 7, 'end']
tree = get_sum(token_list)
print_tree_postorder(tree)
|
15ded2b85a743b4c14f7c816f6284a5496f0a2bf | killercatfish/AdventCode | /2018/Advent2018/Day2/day2_part1.py | 829 | 4.03125 | 4 | '''
Advent of code 2018
1) How do you import from a file
a) Did you create a file for input?
2) What format would you like the input to be in?
a) Ideally, what type of value would the input have been?
3) What data structure could you use to organize your input?
4) What is the question asking?
a) How should you compute it?
5) Wrong answer?
'''
two = 0
three = 0
def parse_entry(cur):
letter_count = {}
for i in cur:
if i in letter_count:
letter_count[i] = letter_count[i] + 1
else:
letter_count[i] = 1
return letter_count
with open("../input/inputday2.txt") as f:
for line in f:
l = line.strip()
cur = parse_entry(l)
if 2 in cur.values():
two += 1
if 3 in cur.values():
three += 1
print(two * three) |
8e32b2bb8de4fff23664083acc690e27e145447a | killercatfish/AdventCode | /2018/Advent2018/Day7/day7_try2.py | 4,027 | 3.828125 | 4 | '''
In order to copy an inner list not by reference:
https://stackoverflow.com/questions/8744113/python-list-by-value-not-by-reference
'''
from copy import deepcopy
input_list = []
'''
step_time: list of letter values
printable: heading for printing
second_list: [workers current job, seconds remaining], done list
'''
'''
Test input
'''
# with open("test.txt") as f:#Test File
# for line in f:
# l = line.strip().split(" ")
# print(l)
# j = [l[1],l[7]]
# input_list.append(j)
# step_time = {chr(64+i):i for i in range(1,27)}
# printable = "%-*s%-*s%-*s%-*s" % (12,'Second',12,'Worker 1', 12,'Worker 2', 12,'Done')
# second_list = [[[],[],[]]]
'''
Real input
'''
with open("../input/inputday7.txt") as f:#Input File
for line in f:
l = line.strip().split(" ")
print(l)
j = [l[1],l[7]]
input_list.append(j)
step_time = {chr(64+i):60+i for i in range(1,27)}
printable = "%-*s%-*s%-*s%-*s%-*s%-*s%-*s" % (12,'Second',12,'Worker 1', 12,'Worker 2',12,'Worker 3', 12,'Worker 4',12,'Worker 5', 12,'Done')
second_list = [[[],[],[],[],[],[]]]
# print(input_list)
# print(step_time)
# print(printable)
# Dictionary containing the letter key, and a list of what letter needs to come first.
order = {}
'''
order dictionary: list of what needs to come before a letter
'''
for i in input_list:
if i[0] not in order.keys():
order[i[0]] = []
if i[1] not in order.keys():
order[i[1]] = []
for i in input_list:
order[i[1]].append(i[0])
#
# for i in order:
# print(i,":",order[i])
final_size = len(order.keys())
# print(len(second_list[len(second_list)-1]))
#len(second_list[len(second_list)-1]) #get length of finished list
'''
find any parts that no longer have to wait
'''
def find_available_parts():
found = []
for i in order:
if order[i] == []:
found.append(i)
return sorted(found)
# available = find_available_parts()
# print(available)
# remove a completed project from list
def remove_from_values(val):
# print("val in remove from values:",val)
for i in order:
if val in order[i]:
# print("removing:",val)
order[i].remove(val)
#check if there are workers available and a part ready.
def update_second_workers(next):
ready = find_available_parts()
for i in range(0, len(next) - 1):
if next[i] == []:
# print(second_list[0][i])
if len(ready) > 0:
r = ready.pop(0)
time = step_time[r]
next[i] = [r, time]
del order[r]
return next
#Create next second list entry
def decrease_times(cur):
#goes through and decreases any current work times by 1 second and returns list.
#moves to finished list if at 0
for i in range(len(cur)-1):
next = cur
# print("i:",i, "next[i]", next[i])
if next[i] != []:
next[i][1]-=1
if next[i][1] == 0:
next[len(next)-1].append(next[i][0])
needs_removal = next[i][0]
next[i] = []
# print("i:",i)
remove_from_values(needs_removal)
next = update_second_workers(next)
#add any available parts to any available worker.
return next
#update another second
def update_second_list():
current_index = len(second_list)-1
# print(current_index)
cur = deepcopy(second_list[current_index])
second_list.append(decrease_times(cur))
#method to update available, check if its in the done list too.
#update what workers are doing
#Initialize seconds list
update_second_workers(second_list[0])
# print(second_list)
#while the done lists length is less than the total letters needing completion
while len(second_list[len(second_list)-1][len(second_list[len(second_list)-1])-1]) <final_size:
update_second_list()
#print(len(second_list[len(second_list)-1][len(second_list[len(second_list)-1])-1]))
for i in range(len(second_list)):
print(i,second_list[i]) |
0ba5f660e4518f026991b66f02b793d5aa836199 | kiner-shah/CompetitiveProgramming | /Hackerrank/Pythonist 2/find_angle_mbc.py | 254 | 3.765625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
x=int(raw_input())
y=int(raw_input())
h=math.hypot(x,y)
v=math.asin(x/h)*180/math.pi
if v<math.floor(v)+0.5:
print int(math.floor(v))
else:
print int(math.ceil(v))
|
586d1398fa085b65390f464ae8a6d23b3f4cdef9 | kiner-shah/CompetitiveProgramming | /Hackerrank/Pythonist 2/swap_case.py | 269 | 3.640625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
x=raw_input()
l=list(x)
for i in range(0,len(l)):
if l[i]>='a' and l[i]<='z':
l[i]=chr(ord(l[i])-32)
elif l[i]>='A' and l[i]<='Z':
l[i]=chr(ord(l[i])+32)
p="".join(l)
print p
|
75f8fb51306ab728df6ea35bf73fc6a04f88bfba | jpalat/AdventOfCode-2020 | /day5/day51.py | 1,279 | 3.53125 | 4 | import struct
import math
def seatDecoder(passid):
print('passid:', passid)
instructions = list(passid)
row_instructions = instructions[:7]
col_instructions = instructions[-3:]
row = parseRow(row_instructions)
col = parseCol(col_instructions)
seat = (row * 8) + col
# print(row_instructions, seat_instructions)
return (row, col, seat)
def parseRow(instructions):
row = 0
for index, r in enumerate(reversed(instructions)):
if r == 'B':
row = (2**index) + row
return row
def parseCol(instructions):
column = 0
for index,c in enumerate(reversed(instructions)):
if c == 'R':
column = (2**index) + column
return column
if __name__ == "__main__":
f = open('input.txt')
l = list(f)
l.sort()
bigseat = 0
seats = []
for index, seat in enumerate(l):
row, col, seat = seatDecoder(seat.strip())
print (index, ': ',row, col, seat, bigseat)
if seat > bigseat:
bigseat = seat
seats.append(seat)
seats.sort()
seats_total = sum(seats)
seats_possible = sum(range(seats[0], seats[-1]+1))
my_seat = seats_possible - seats_total
print("Highest Seat ID:", bigseat)
print("My seat", my_seat)
|
e5f5ccdcada9074dbc77cda74ff0af195394ec11 | uva-slpl/nlp2 | /resources/project_neuralibm-2019/vocabulary.py | 3,647 | 3.53125 | 4 | #!/usr/bin/env python3
from collections import Counter, OrderedDict
import numpy as np
class OrderedCounter(Counter, OrderedDict):
"""A Counter that remembers the order in which items were added."""
pass
class Vocabulary:
"""A simple vocabulary class to map words to IDs."""
def __init__(self, corpus=None,
special_tokens=('<PAD>', '<UNK>', '<S>', '</S>', '<NULL>'), max_tokens=0):
"""Initialize and optionally add tokens in corpus."""
self.counter = OrderedCounter()
self.t2i = OrderedDict()
self.i2t = []
self.special_tokens = [t for t in special_tokens]
if corpus is not None:
for tokens in corpus:
self.counter.update(tokens)
if max_tokens > 0:
self.trim(max_tokens)
else:
self.update_dicts()
def __contains__(self, token):
"""Checks if a token is in the vocabulary."""
return token in self.counter
def __len__(self):
"""Returns number of items in vocabulary."""
return len(self.t2i)
def get_token_id(self, token):
"""Returns the ID for token, if we know it, otherwise the ID for <UNK>."""
if token in self.t2i:
return self.t2i[token]
else:
return self.t2i['<UNK>']
def tokens2ids(self, tokens):
"""Converts a sequence of tokens to a sequence of IDs."""
return [self.get_token_id(t) for t in tokens]
def get_token(self, i):
"""Returns the token for ID i."""
if i < len(self.i2t):
return self.i2t[i]
else:
raise IndexError("We do not have a token with that ID!")
def add_token(self, token):
"""Add a single token."""
self.counter.add(token)
def add_tokens(self, tokens):
"""Add a list of tokens."""
self.counter.update(tokens)
def update_dicts(self):
"""After adding tokens or trimming, this updates the dictionaries."""
self.t2i = OrderedDict()
self.i2t = list(self.special_tokens)
# add special tokens
self.i2t = [t for t in self.special_tokens]
for i, token in enumerate(self.special_tokens):
self.t2i[token] = i
# add tokens
for i, token in enumerate(self.counter, len(self.special_tokens)):
self.t2i[token] = i
self.i2t.append(token)
def trim(self, max_tokens):
"""
Trim the vocabulary based on frequency.
WARNING: This changes all token IDs.
"""
tokens_to_keep = self.counter.most_common(max_tokens)
self.counter = OrderedCounter(OrderedDict(tokens_to_keep))
self.update_dicts()
def batch2tensor(self, batch, add_null=True, add_end_symbol=True):
"""
Returns a tensor (to be fed to a TensorFlow placeholder) from a batch of sentences.
The batch input is assumed to consist of tokens, not IDs.
They will be converted to IDs inside this function.
"""
# first we find out the shape of the tensor we return
batch_size = len(batch)
max_timesteps = max([len(x) for x in batch])
if add_end_symbol:
max_timesteps += 1
if add_null:
max_timesteps += 1
# then we create an empty tensor, consisting of zeros everywhere
tensor = np.zeros([batch_size, max_timesteps], dtype='int64')
# now we fill the tensor with the sequences of IDs for each sentence
for i, sequence in enumerate(batch):
start = 1 if add_null else 0
tensor[i, start:len(sequence)+start] = self.tokens2ids(sequence)
if add_null:
tensor[i, 0] = self.get_token_id("<NULL>")
if add_end_symbol:
tensor[i, -1] = self.get_token_id("</S>") # end symbol
return tensor
|
3e019a6dda73376db4bcc04bb99f07c9fdf214bc | jucariasar/Proyecto_POO_UNAL_2017-1_Python | /ingenierotecnico.py | 1,385 | 3.6875 | 4 | from empleado import Empleado
class IngenieroTecnico(Empleado):
MAX_IT = 4 # Constante de clase para controlar el numero máximo de elementos que puede prestar
#un IngenieroTecnico
areas = {'1':'Mantenimiento', '2':'Produccion',
'3':'Calidad'}
def __init__(self, ident=0, nombre="", apellido="", numElementPrest=0, roll="", email="", area=""):
super().__init__(ident, nombre, apellido, numElementPrest, roll, email)
self._areaEncargada = area # Los tipos definidos en el diccionario estatico de areas
def getArea(self):
return self._areaEncargada
def setArea(self, area):
self._areaEncargada = area
@staticmethod
def registrarEmpleado(listEmpleados):
empleado = IngenieroTecnico()
empleado.setIdent(int(input("Ingrese el id del ingeniero:")))
empleado.setNombre(str(input("Ingrese el nombre del ingeniero:")))
empleado.setApellido(str(input("Ingrese el apellido del ingeniero:")))
empleado.setEmail(str(input("Ingrese el correo del ingeniero:")))
empleado.setRoll(Empleado().tiposEmpleado['3'])
empleado.setArea(str(input("Establezca area del Ingeniero:")))
listEmpleados.append(empleado)
def __str__(self):
return (super().__str__() + "\nArea Encargada: " + self.getArea())
|
b440521c3f550e35b63bfb7687f6a94d3d0d61a0 | arnizamani/Networks | /AdditionEnv.py | 1,984 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created 17 Feb 2016
@author: Abdul Rahim Nizamani
"""
from network import Network
import random
class AdditionEnv(object):
"""Environment feeds activation to the sensors in the network"""
def __init__(self,network):
print("Initializing Environment...")
self.network = network
self.sensors = network.sensors
self.history = [] # history of activated sensors
self.score = 0 # total correct answers
self.examples = 0 # total examples
def Begin(self,count=0):
"""Start feeding activation to the sensors. Activate a single sensor randomly."""
if(not self.sensors): raise SyntaxError
if(count<=0): count=1000
reward = 0.0
active = random.choice(sorted(list(self.sensors)))
while(count>0):
result = filter(lambda x:x!="",self.network.result)
self.network.Tick({active},reward)
reward = 0.0
if not self.history:
reward = 0.0
else:
if list(reversed(self.history))[0:3] == list(reversed(["3","+","4"])):
self.examples += 1
#print(list(reversed(self.history))[0])
if(result==["7"]):
if list(reversed(self.history))[0:3] == list(reversed(["3","+","4"])):
reward = 100.0
self.score += 1
else: reward = -10.0
else:
if list(reversed(self.history))[0:3] == list(reversed(["3","+","4"])):
reward = -100.0
else: reward = 0.0
if result==["7"] and list(reversed(self.history))[0:3] == list(reversed(["3","+","4"])):
active = "7"
else:
#active = random.choice(sorted(list(self.sensors)))
active = random.choice(["3","+","4"])
count -= 1
self.history.append(active)
|
67354d9d9ffdbe84f8348ecf1efa127c56ec33c5 | dickersonsteam/CircuitPython_ToneOnA0 | /main.py | 2,451 | 3.796875 | 4 | # This example program will make a single sound play out
# of the selected pin.
#
# The following are the default parameters for which pin
# the sound will come out of, sample rate, note pitch/frequency,
# and note duration in seconds.
#
# audio_pin = board.A0
# sample_rate = 8000
# note_pitch = 440
# note_length = 1
#
# This example makes use of print messages to help debug
# errors. As you make changes and then run your code, watch
# these messages to understand what is happening (or not happening).
# When you add features, add messages to help you debug your own
# code. Ultimately, these print messages do slow things down a bit,
# but they will make you life easier in the long run.
import audioio
import board
import array
import time
import math
# record current time
start_time_pgm = time.monotonic()
# for Feather M0 use A0 only
# for Feather M4 either A0 or A1 work
audio_pin = board.A0
# Sample rate roughly determines the quality of the sound.
# A larger number may sound better, but will take
# more processing time and memory.
sample_rate = 8000
# Set the pitch for the note you would like to play.
# http://pages.mtu.edu/~suits/notefreqs.html
note_pitch = 440
# Set how many seconds the note will last.
# Try 0.1 - 1.0 or any number.
note_length = 1
# Now you must "draw" the sound wave in memory.
# This will take more or less time depending on the
# frequency and sample_rate that you selected.
print("Generate sound wave.")
start_time_gen = time.monotonic()
length = sample_rate // note_pitch
sine_wave = array.array("h", [0] * length)
for i in range(length):
sine_wave[i] = int(math.sin(math.pi * 2 * i / 18) * (2 ** 15))
time_to_completion = time.monotonic() - start_time_gen
print("Generating the sound wave took " + str(time_to_completion) + " seconds.")
# Now initialize you DAC (aka speaker pin)
print("Initialize DAC.")
dac = audioio.AudioOut(audio_pin)
# Convert the sine wave you generated earlier into a
# sample that can be used with the dac.
print("Converting to RawSample.")
sine_wave = audioio.RawSample(sine_wave)
# Play the sine wave on the dac and loop it for however
# many seconds you set with note_length.
print("Playing sound.")
dac.play(sine_wave, loop=True)
time.sleep(note_length)
dac.stop()
# Print program execution time
print("Program completed execution.")
time_to_completion = time.monotonic() - start_time_pgm
print("Execution took " + str(time_to_completion) + " seconds.") |
3842e494b165c2442a0205ea752e0f3aeafb5c12 | WillGreen98/Project-Euler | /Tasks 1-99/Task 15/Task-15.py | 641 | 3.75 | 4 | # Task 15 - Python
# Lattice Paths
import time
from functools import reduce
binomial = lambda grid_size: reduce(lambda hoz, vert: hoz * vert, range(1, grid_size + 1), 1)
def path_route_finder(grid_size_to_check):
# As size is perfect cube - I have limited calculations instead of n & m
size = grid_size_to_check
if grid_size_to_check == 0: return 1
return binomial(2*size) // binomial(size) // binomial(size)
def main():
time_start = time.time()
route_num = path_route_finder(20)
print("Answer: {0} => Calculated in: {1}".format(route_num, (time.time() - time_start)))
if __name__ == '__main__':
main() |
50f0cbdf511231ae28bff1dbe993b9a57befc6f5 | WillGreen98/Project-Euler | /Tasks 1-99/Task 10/Task-10.py | 898 | 4.03125 | 4 | # Task 10 - Python
# Summations Of Primes
import math
import time
is_prime = lambda num_to_check: all(num_to_check % i for i in range(3, int(math.sqrt(num_to_check)) + 1, 2))
def sum_of_primes(upper_bound):
fp_c = 2
summation = 0
eratosthenes_sieve = ((upper_bound + 1) * [True])
while math.pow(fp_c, 2) < upper_bound:
if is_prime(eratosthenes_sieve[fp_c]):
multiple = fp_c * 2
while multiple < upper_bound:
eratosthenes_sieve[multiple] = False
multiple += fp_c
fp_c += 1
for i in range(fp_c, upper_bound + 1):
if eratosthenes_sieve[i]:
summation += 1
return summation
def main():
time_start = time.time()
prime_sum = sum_of_primes(11)
print("Answer: {0} => Calculated in: {1}".format(prime_sum, (time.time() - time_start)))
if __name__ == '__main__':
main() |
74083ac38b480e5c26bf58cd405728e1f2999e9d | AJSterner/UnifyID | /atmosphere_random.py | 2,851 | 3.703125 | 4 | import urllib2
from urllib import urlencode
from ctypes import c_int64
def random_ints(num=1, min_val=-1e9, max_val=1e9):
"""
get random integers from random.org
arguments
---------
num (int): number of integers to get
min_val (int): min int value
max_val (int): max int value
timeout (int): timeout in seconds (should be long as random.org may ban)
"""
num = int(num)
min_val = int(min_val)
max_val = int(max_val)
assert 1 <= num, "num must be positive"
assert min_val < max_val, "min must be less than max"
rand_ints = []
while num > 0:
to_get = min(num, 1E4)
rand_ints.extend(random_ints_helper(to_get, min_val, max_val))
num -= to_get
return rand_ints
def random_ints_helper(num=1, min_val=-1e9, max_val=1e9):
"""
get random integers from random.org (not to be called directly)
arguments
---------
num (int): number of integers to get
min_val (int): min int value
max_val (int): max int value
timeout (int): timeout in seconds (should be long as random.org may ban)
"""
num = int(num)
min_val = int(min_val)
max_val = int(max_val)
assert 1 <= num <= 1E4, "num invalid (if too great use many_random_ints)"
assert min_val < max_val, "min must be less than max"
req = urllib2.Request(random_request_url(num, min_val, max_val))
try:
response = urllib2.urlopen(req).read()
except urllib2.HTTPError as e:
print('Request could\'t be filled by the server')
print('Error code: ' + e.code)
except urllib2.URLError as e:
print('Connection error')
print('Reason: ' + e.reason)
return [int_from_hexstr(line) for line in response.splitlines()]
def random_request_url(num, min_val, max_val):
""" return GET random request URL (see https://www.random.org/clients/http/) """
assert isinstance(num, int) and isinstance(min_val, int) and isinstance(max_val, int)
req_data = dict(num=num,
min=min_val,
max=max_val,
col=1,
base=16,
format='plain',
rnd='new')
return "https://www.random.org/integers/?" + urlencode(req_data)
def int_from_hexstr(hexstr):
"""
returns a python integer from a string that represents a twos complement integer in hex
"""
uint = int(hexstr, base=16) # python assumes positive int from string
return c_int64(uint).value
|
fae39f809f9202288cfe12ab7de8e63a05fd6341 | Rayban63/Coffee-Machine | /Problems/Calculator/task.py | 583 | 4 | 4 | first_num = float(input())
second_num = float(input())
operation = input()
no = ["mod", "div", "/"]
if second_num == (0.0 or 0) and operation in no:
print("Division by 0!")
elif operation == "mod":
print(first_num % second_num)
elif operation == "pow":
print(first_num ** second_num)
elif operation == "*":
print(first_num * second_num)
elif operation == "div":
print(first_num // second_num)
elif operation == "/":
print(first_num / second_num)
elif operation == "+":
print(first_num + second_num)
elif operation == "-":
print(first_num - second_num) |
d54a81b17a5d535737681a88420bbc1c87fdad97 | mattikus/advent2017 | /day_1/1.py | 307 | 3.640625 | 4 | #!/usr/bin/env python3
import sys
def inverse_captcha(captcha):
arr = list(map(int, captcha))
return sum(i for idx, i in enumerate(arr) if i == (arr[0] if idx == (len(arr) - 1) else arr[idx+1]))
if __name__ == "__main__":
problem_input = sys.argv[1]
print(inverse_captcha(problem_input))
|
cc50953b5b3fb569c4ee7b792b2b4ef02ddaa182 | MatiasLeon1/MCOC2020-P0 | /MIMATMUL.py | 615 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
def mimatmul(A,B):
f=len(A)
c=len(B)
result=np.zeros([f,c]) #Creamos una matriz de puros ceros
for i in range(len(A)): #Itera las filas de la matriz A
for j in range(len(B[0])): #Itera las columnas de B
for k in range(len(B)): #Itera las filas de B
# Utilizamos la formula de calculo de matrices ordenando
# el calculo entre dilas y columnas respectivas
result[i][j] += A[i][k]*B[k][j]
return result
|
9e8b97dfce807ab9655b0d7c32c344f875c4fdec | SiddharthaPramanik/Assessment-VisualBI | /music_app/songs/models.py | 1,061 | 3.5625 | 4 | from music_app import db
class Songs(db.Model):
"""
A class to map the songs table using SQLAlchemy
...
Attributes
-------
song_id : Integer database column
Holds the id of the song
song_title : String databse column
Holds the song name
seconds : String databse column
Holds the duration in seconds
thumbnail_url: String databse column
Holds the thumbnail url for song
album_id : Integer database column
Holds the foreign key for albums table
Methods
-------
__repr__()
Method to represent the class object
"""
song_id = db.Column(db.Integer, primary_key=True)
song_title = db.Column(db.String(60), nullable=False)
seconds = db.Column(db.Integer, nullable=False)
thumbnail_url = db.Column(db.String(200), default='thumbnail.png')
album_id = db.Column(db.Integer, db.ForeignKey('albums.album_id'), nullable=False)
def __repr__(self):
return f"Songs('{self.song_title}', '{self.seconds}', {self.album_id})" |
9d8a9f005a7261d963be2c06d7281563deddf157 | PowersYang/houseSpider | /houseSpider/test.py | 1,772 | 3.703125 | 4 | # -*- coding: utf-8 -*-
import time, datetime
kHr = 0 # index for hour
kMin = 1 # index for minute
kSec = 2 # index for second
kPeriod1 = 0 # 时间段,这里定义了两个代码执行的时间段
kPeriod2 = 1
starttime = [[9, 30, 0], [13, 0, 0]] # 两个时间段的起始时间,hour, minute 和 second
endtime = [[11, 30, 0], [15, 0, 0]] # 两个时间段的终止时间
sleeptime = 5 # 扫描间隔时间,s
def DoYourWork(): # 你的工作函数
print('Now it\'s the time to work!')
def RestYourSelf(): # 你的休息函数
print('Now it\'s the time to take a rest!')
def T1LaterThanT2(time1, time2): # 根据给定时分秒的两个时间,比较其先后关系
# t1 < t2, false, t1 >= t2, true
if len(time1) != 3 or len(time2) != 3:
raise Exception('# Error: time format error!')
T1 = time1[kHr] * 3600 + time1[kMin] * 60 + time1[kSec] # s
T2 = time2[kHr] * 3600 + time2[kMin] * 60 + time2[kSec] # s
if T1 < T2:
return False
else:
return True
def RunNow(): # 判断现在是否工作
mytime = datetime.datetime.now()
currtime = [mytime.hour, mytime.minute, mytime.second]
if (T1LaterThanT2(currtime, starttime[kPeriod1]) and (not T1LaterThanT2(currtime, endtime[kPeriod1]))) or (
T1LaterThanT2(currtime, starttime[kPeriod2]) and (not T1LaterThanT2(currtime, endtime[kPeriod2]))):
return True
else:
return False
if __name__ == "__main__":
if len(starttime) != len(endtime):
raise Exception('# Error: the run time format is not correct!')
else:
while True:
if RunNow():
DoYourWork()
else:
RestYourSelf()
time.sleep(sleeptime) # sleep for 5 s
|
f24a10c953482e69f0131e4acf6e13d83fc36cdd | sushrao1996/DSA | /Recursion/Factorial.py | 276 | 4 | 4 | def myFact(n):
if n==1:
return 1
else:
return n*myFact(n-1)
num=int(input("Enter a number: "))
if num<0:
print("No negative numbers")
elif(num==0):
print("Factorial of 0 is 1")
else:
print("Factorial of",num,"is",myFact(num))
|
22ad07d51d6377717ab69018e34652e03140f837 | sushrao1996/DSA | /Queue/CircularQueue.py | 1,868 | 3.953125 | 4 | class CircularQueue:
def __init__(self,size):
self.size=size
self.queue=[None for i in range(size)]
self.front=self.rear=-1
def enqueue(self,data):
if ((self.rear+1)%self.size==self.front):
print("Queue is full")
return
elif (self.front==-1):
self.front=0
self.rear=0
self.queue[self.rear]=data
else:
self.rear=(self.rear+1)%self.size
self.queue[self.rear]=data
def dequeue(self):
if (self.front==-1):
print("Queue is already empty")
elif (self.front==self.rear):
popvalue=self.queue[self.front]
self.front=-1
self.rear=-1
return popvalue
else:
popvalue=self.queue[self.front]
self.front=(self.front+1)%self.size
return popvalue
def display(self):
if(self.front==-1):
print("Queue is empty")
elif(self.rear>=self.front):
print("Elements in the circular queue are: ")
for i in range(self.front,self.rear+1):
print(self.queue[i],end=" ")
print()
else:
print("Elements in the circular queue are: ")
for i in range(self.front,self.size):
print(self.queue[i],end=" ")
for i in range(0,self.rear+1):
print(self.queue[i],end=" ")
print()
if((self.rear+1)%self.size==self.front):
print("Queue is full")
ob = CircularQueue(5)
ob.enqueue(14)
ob.enqueue(22)
ob.enqueue(13)
ob.enqueue(-6)
ob.display()
print ("Deleted value = ", ob.dequeue())
print ("Deleted value = ", ob.dequeue())
ob.display()
ob.enqueue(9)
ob.enqueue(20)
ob.enqueue(5)
ob.display()
|
7add6d6db4a6824b60f4ee5d5ea150e55f0cb69c | amites/davinci_2017_spring | /codewars/carry_over.py | 852 | 3.625 | 4 | # https://www.codewars.com/kata/simple-fun-number-132-number-of-carries/train/python
def number_of_carries(a, b):
y = [int(n) for n in list(str(a))]
x = [int(n) for n in list(str(b))]
# reverse order so beginning with smallest
# and going to biggest
y.reverse()
x.reverse()
# figure out which list contains more digits
if a > b:
longer = y
shorter = x
else:
longer = x
shorter = y
# define starting values
carry = 0
count = 0
for i in range(0, len(longer)):
# skip adding from a column that does not exist
if i < len(shorter):
num = longer[i] + shorter[i] + carry
else:
num = longer[i] + carry
if num > 9:
count += 1
carry = 1
else:
carry = 0
return count
|
d9177b87da9f04a0d1c4406abf65d2996449fc11 | v-lubomski/python_start | /old_lessons/func_with_param.py | 134 | 4.125 | 4 | def printMax(a, b):
if a > b:
print(a, 'is max')
elif a == b:
print(a, 'equal', b)
else:
print(b, 'is max')
printMax(5, 8)
|
41f729db17f24ba77f849434e75b4519ea93c9af | kordaniel/AoC | /2020/day8/main.py | 2,212 | 3.671875 | 4 | import sys
sys.path.insert(0, '..')
from helpers import filemap
# Part1
def walk(code):
''' Executes the instructions, stops when reach infinite loop and returns the value'''
idx, accumulator = 0, 0
visited = set()
while True:
if idx in visited:
break
visited.add(idx)
instruction, arg = code[idx]
if instruction == 'jmp':
idx += arg
continue
if instruction == 'acc':
accumulator += arg
idx += 1
return accumulator
# Part2
def walk_fix(code):
''' Executes the instructions and tries to fix the code so that it won't end
up in an infinite loop'''
idx, end_idx = 0, len(code)
end_reached = False
while not end_reached and idx < end_idx:
code_arg = code[idx]
if code_arg[0] == 'acc':
idx += 1
continue
elif code_arg[0] == 'jmp':
code[idx] = ('nop', code_arg[0])
elif code_arg[0] == 'nop':
code[idx] = ('jmp', code_arg[1])
end_reached = can_reach_end(code)
if not end_reached:
code[idx] = code_arg
else:
return end_reached
idx += 1
raise Exception('ERRORRORORROROROROR')
def can_reach_end(code):
end_idx = len(code)
idx, accumulator = 0, 0
visited = set()
while True:
if idx == end_idx:
return True, accumulator
if idx in visited:
return False
visited.add(idx)
instruction, arg = code[idx]
if instruction == 'jmp':
idx += arg
continue
if instruction == 'acc':
accumulator += arg
idx += 1
return accumulator
def main():
# Test data
data = [
('nop', 0),
('acc', 1),
('jmp', 4),
('acc', 3),
('jmp', -3),
('acc', -99),
('acc', 1),
('jmp', -4),
('acc', 6)
]
data = filemap('input.txt', lambda s: s.split())
data = list(map(lambda l: (l[0], int(l[1])), data))
#print(data)
# Part 1
print('Part1:', walk(data))
# Part 2
print('Part2:', walk_fix(data))
if __name__ == '__main__':
main()
|
95a68ebdcb01557a83900a8f34f3c57417a0c60f | abnormalmakers/object-oriented | /super.py | 378 | 3.53125 | 4 | class A():
def fn(self):
print("A被调用")
def run(self):
print('A run')
class B(A):
def fn(self):
print("B被调用")
def run(self):
super(B,self).run()
super(__class__,self).run()
super().run()
a = A()
a.fn()
b = B()
b.fn()
b.__class__.__base__.fn(b)
print('aaaa')
super(B,b).fn()
print('aaaa')
b.run()
|
cd44060db334e79d426b1cd69aa2f5e798a9a1cb | thaynnara007/ATAL_listas | /lista02/questao03.py | 1,368 | 3.71875 | 4 | PESO = 0
VALOR = 1
def mochilaBinaria( valorAtual, capacidadeAtual, i, conjuntoAtual):
global capacidadeMochila
global itens
global qntdItens
global conjunto
global maiorValor
if i <= qntdItens:
if capacidadeAtual <= capacidadeMochila:
if valorAtual > maiorValor:
maiorValor = valorAtual
conjunto = conjuntoAtual
for iten in xrange(i, qntdItens):
# Parte abaixo necessária pois em python, não é passado listas como parámetros, mas sim a referência para a lista, implicitamente,
#o que ocaciona da lista continuar modificada por chamadas recursivas a frente, mesmo depois de ter voltado na recursão
#gerando um comportamento inesperado tendo em vista a teoria da recursão.
conjuntoAtual2 = conjuntoAtual[:]
conjuntoAtual2.append(itens[iten])
mochilaBinaria( itens[iten][VALOR] + valorAtual, capacidadeAtual + itens[iten][PESO], iten + 1, conjuntoAtual2)
capacidadeMochila = int(raw_input())
qntdItens = int(raw_input())
itens = []
maiorValor = 0
conjunto = []
for iten in xrange(qntdItens):
peso, valor = map(int, raw_input().split())
itens.append((peso, valor))
itens.sort()
mochilaBinaria(0,0,0,[])
print maiorValor
print conjunto
|
d218fc784ea19385eb5aff0517529af3c6a513f0 | LucHighwalker/CaptainRainbowSpaceMan | /spaceman.py | 3,855 | 3.5 | 4 |
import random
import os
secret_word = ''
blanks = list()
guessed = list()
attempts_left = 7
game_won = False
game_lost = False
help_prompt = False
running = True
def load_word():
global secret_word
f = open('words.txt', 'r')
words_list = f.readlines()
f.close()
words_list = words_list[0].split(' ')
secret_word = random.choice(words_list)
def gen_blanks():
global secret_word
global blanks
blanks = list('-' * len(secret_word))
def initialize():
global secret_word
global blanks
global guessed
global attempts_left
global game_won
global game_lost
global help_prompt
secret_word = ''
blanks = list()
guessed = list()
attempts_left = 7
game_won = False
game_lost = False
help_prompt = False
load_word()
gen_blanks()
def draw_spaceman():
global attempts_left
if attempts_left == 7:
return '\n\n'
elif attempts_left == 6:
return ' o \n\n'
elif attempts_left == 5:
return ' o \n | \n'
elif attempts_left == 4:
return ' o \n/| \n'
elif attempts_left == 3:
return ' o \n/|\\\n'
elif attempts_left == 2:
return ' o \n/|\\\n/ '
elif attempts_left == 1:
return ' o \n/|\\\n/ \\'
def render_screen():
global blanks
global guessed
global attempts_left
global help_prompt
global game_won
global game_lost
os.system('cls' if os.name == 'nt' else 'clear')
if game_won:
print('CONGRATS!!! You survive another day! :D\n\n' + 'The word was: ' + secret_word + '\n')
elif game_lost:
print('RIP! You got shot into space. GG :\'(\n\n' + 'The word was: ' + secret_word + '\n')
else:
blank_lines = ''
guesses = ''
for i in blanks:
blank_lines = blank_lines + i
for i in guessed:
guesses = guesses + i + ' '
print(blank_lines)
print('\n\nGuessed: ' + guesses + '\n')
print(draw_spaceman())
print('\n')
if help_prompt:
print('Enter a single letter or \'quit\' to exit the program.\n')
help_prompt = False
def user_input(prompt):
try:
user_input = input(prompt)
return user_input
except EOFError:
return ''
def check_guess(guess):
global secret_word
global blanks
global guessed
global attempts_left
correct_letter = False
letter_index = 0
for i in secret_word:
if i == guess:
blanks[letter_index] = guess
correct_letter = True
letter_index += 1
if not correct_letter:
for i in guessed:
if i == guess:
return
attempts_left -= 1
guessed.append(guess)
def process_input(inp):
global help_prompt
global running
if inp == 'quit':
running = False
elif len(inp) == 1 and inp.isalpha():
check_guess(inp.lower())
render_screen()
else:
help_prompt = True
render_screen()
def check_win():
global blanks
global attempts_left
global game_won
global game_lost
if attempts_left <= 0:
game_lost = True
return
found_blank = False
for i in blanks:
if i == '-':
found_blank = True
break
if not found_blank:
game_won = True
return
initialize()
render_screen()
while running:
if not game_won and not game_lost:
inp = user_input('Enter guess: ')
process_input(inp)
check_win()
else:
render_screen()
inp = user_input('Press enter to replay or enter \'quit\' to exit: ')
if inp == 'quit' or inp == 'q':
running = False
elif not inp:
initialize()
render_screen()
|
e29240d2ac37a9fdeedfd1795ed92bc4d5c59359 | MagdaM91/Python | /GUI.py | 573 | 3.609375 | 4 | from tkinter import *
root = Tk()
#thLable = Label(root, text="This is to easy")
#thLable.pack()
''
topFrame = Frame(root)
topFrame.pack()
bottomFram = Frame(root)
bottomFram.pack(side=BOTTOM)
Firstbutton = Button(topFrame, text="FirstButton",fg="red")
Secondbutton = Button(topFrame, text="SecondButton",fg="blue")
Thirdbutton = Button(topFrame, text="ThirdButton",fg="green")
Fourbutton = Button(topFrame, text="ThirdButton",fg="yellow")
Firstbutton.pack(side=LEFT)
Secondbutton.pack(side=LEFT)
Thirdbutton.pack(side=LEFT)
Fourbutton.pack(side=BOTTOM)
root.mainloop() |
f728bb9426eeb04961d39186b2bd98532e02a167 | TaiCobo/practice | /checkio/to_encrypt.py | 819 | 3.796875 | 4 | def to_encrypt(text, delta):
#replace this for solution
alphabet = "abcdefghijklmnopqrstuvwxyz"
ret = ""
for word in range(len(text)):
if text[word] == " ":
ret += " "
else:
ret += alphabet[(alphabet.index(text[word]) + delta) % 26]
return ret
if __name__ == '__main__':
print("Example:")
print(to_encrypt('abc', 10))
#These "asserts" using only for self-checking and not necessary for auto-testing
print(to_encrypt("a b c", 3))# == "d e f"
print(to_encrypt("a b c", -3))# == "x y z"
print(to_encrypt("simple text", 16))# == "iycfbu junj"
print(to_encrypt("important text", 10))# == "swzybdkxd dohd"
print(to_encrypt("state secret", -13))# == "fgngr frperg"
print("Coding complete? Click 'Check' to earn cool rewards!") |
f5a72e136b367e877afd5632cadb843e5944d8db | TaiCobo/practice | /checkio/left_right.py | 1,049 | 3.765625 | 4 | def left_join(phrases):
"""
Join strings and replace "right" to "left"
"""
ret = ""
return ",".join(phrases).replace("right", "left")
def checkio(number: int) -> int:
nnn = str(number)
ret = 1
for i, val in enumerate(range(0, len(nnn))):
if nnn[i] == "0":
continue
ret = ret * int(nnn[i])
return ret
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
# print(left_join(("left", "right", "left", "stop")))# == "left,left,left,stop", "All to left"
# print(left_join(("bright aright", "ok")))# == "bleft aleft,ok", "Bright Left"
# print(left_join(("brightness wright",)))# == "bleftness wleft", "One phrase"
# print(left_join(("enough", "jokes")))# == "enough,jokes", "Nothing to replace"
# print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
print(checkio(123405))
print(checkio(999))# == 729
print(checkio(1000))# == 1
print(checkio(1111))# == 1 |
05d3835f466737814bb792147e8d7b34a28d912f | qiqi06/python_test | /python/static_factory_method.py | 1,038 | 4.1875 | 4 | #-*- coding: utf-8 -*-
"""
练习简单工厂模式
"""
#建立一工厂类,要用是,再实例化它的生产水果方法,
class Factory(object):
def creatFruit(self, fruit):
if fruit == "apple":
return Apple(fruit, "red")
elif fruit == "banana":
return Banana(fruit, "yellow")
class Fruit(object):
def __init__(self, name, color):
self.color = color
self.name = name
def grow(self):
print "%s is growing" %self.name
class Apple(Fruit):
def __init__(self, name, color):
super(Apple, self).__init__(name, color)
class Banana(Fruit):
def __init__(self, name, color):
super(Banana, self).__init__(name, color)
self.name = 'banana'
self.color = 'yellow'
def test():
#这里是两个对象, 一个是工厂,一个是我要订的水果
factory = Factory()
my_fruit = factory.creatFruit('banana')
my_fruit.grow()
if __name__ == "__main__":
print "The main module is running!"
test() |
bf1579ed5e6abab53aa502637d8be30591fef51a | sdurgut/ToyProjects | /NetflixMovieRecommendationSystem/testProject2Phase1a.py | 2,066 | 3.59375 | 4 | '''
>>> userList = createUserList()
>>> len(userList)
943
>>> userList[10]["occupation"]
'other'
>>> sorted(userList[55].values())
[25, '46260', 'M', 'librarian']
>>> len([x for x in userList if x["gender"]=="F"])
273
>>> movieList = createMovieList()
>>> len(movieList)
1682
>>> movieList[27]["title"]
'Apollo 13 (1995)'
>>> movieList[78]["title"].split("(")[0]
'Fugitive, The '
>>> sorted(movieList[1657].values())
[[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], '', '06-Dec-1996', 'Substance of Fire, The (1996)', 'http://us.imdb.com/M/title-exact?Substance%20of%20Fire,%20The%20(1996)']
>>> numUsers = len(userList)
>>> numMovies = len(movieList)
>>> rawRatings = readRatings()
>>> rawRatings[:2]
[(196, 242, 3), (186, 302, 3)]
>>> len(rawRatings)
100000
>>> len([x for x in rawRatings if x[0] == 1])
272
>>> len([x for x in rawRatings if x[0] == 2])
62
>>> sorted([x for x in rawRatings if x[0] == 2][:11])
[(2, 13, 4), (2, 50, 5), (2, 251, 5), (2, 280, 3), (2, 281, 3), (2, 290, 3), (2, 292, 4), (2, 297, 4), (2, 303, 4), (2, 312, 3), (2, 314, 1)]
>>> [x for x in rawRatings if x[1] == 1557]
[(405, 1557, 1)]
>>> [rLu, rLm] = createRatingsDataStructure(numUsers, numMovies, rawRatings)
>>> len(rLu)
943
>>> len(rLm)
1682
>>> len(rLu[0])
272
>>> min([len(x) for x in rLu])
20
>>> min([len(x) for x in rLm])
1
>>> sorted(rLu[18].items())
[(4, 4), (8, 5), (153, 4), (201, 3), (202, 4), (210, 3), (211, 4), (258, 4), (268, 2), (288, 3), (294, 3), (310, 4), (313, 2), (319, 4), (325, 4), (382, 3), (435, 5), (655, 3), (692, 3), (887, 4)]
>>> len(rLm[88])
275
>>> movieList[88]["title"]
'Blade Runner (1982)'
>>> rLu[10][716] == rLm[715][11]
True
>>> commonMovies = [m for m in range(1, numMovies+1) if m in rLu[0] and m in rLu[417]]
>>> commonMovies
[258, 269]
>>> rLu[0][258]
5
>>> rLu[417][258]
5
>>> rLu[0][269]
5
>>> rLu[417][269]
5
'''
#-------------------------------------------------------
from project2Phase1a import *
#-------------------------------------------------------
if __name__ == "__main__":
import doctest
doctest.testmod()
|
c056c7e6e90f54a6a42b7a7d5c408c749debffed | michaszo18/python- | /serdnio_zaawansowany/sekcja_1/funkcja_id_operator_is.py | 1,399 | 4 | 4 | a = "hello world"
b = a
print(a is b)
print(a == b)
print(id(a), id(b))
b += "!"
print(a is b)
print(a == b)
print(id(a), id(b))
b = b[:-1]
print(a is b)
print(a == b)
print(id(a), id(b))
a = 1
b = a
print(a is b)
print(a == b)
print(id(a), id(b))
b += 1
print(a is b)
print(a == b)
print(id(a), id(b))
b -= 1
print(a is b)
print(a == b)
print(id(a), id(b))
# Wniosek - int w pythonie przehowowany są pod tym samym adresem (optymalizator pythona), a string po zmianie
# Zadanie
print("\n\n#################################\n\n")
a = b = c = 10
print(a, id(a))
print(b, id(b))
print(c, id(c))
a = 20
print(a, id(a))
print(b, id(b))
print(c, id(c))
print("\n\n#################################\n\n")
a = b = c = [1, 2, 3]
print(a, id(a))
print(b, id(b))
print(c, id(c))
a.append(4)
print(a, id(a))
print(b, id(b))
print(c, id(c))
"""
W pierwszym przykładzie a, b, c były wskaźnikami do komórki pamięci, w której była zapisana liczba, czyli końcowa wartość.
W drugim przykładzie a, b, c to wskaźnik do komórki pamięci, w której jest lista. Lista jest wskaźnikiem do elementów tej listy.
Kiedy dodajesz nowy element do listy, nie modyfikujesz podstawowej komórki pamięci z listą, dlatego id się nie zmienił.
"""
print("\n\n#################################\n\n")
x = 10
y = 10
print(x, id(x))
print(y, id(y))
y = y + 1234567890 - 1234567890
print(x, id(x))
print(y, id(y)) |
f98a82205815d1acef54f565f03bfafe1df4f0aa | mertcankurt/temizlik_robotu_simulasyonu | /evarobotmove_gazebo/scripts/Interface/Database.py | 583 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlite3
def createTable():
connection = sqlite3.connect('login.db')
connection.execute("CREATE TABLE USERS(USERNAME TEXT NOT NULL,EMAIL TEXT,PASSWORD TEXT)")
connection.execute("INSERT INTO USERS VALUES(?,?,?)",('motar','motar@gmail.com','motar'))
connection.commit()
result = connection.execute("SELECT * FROM USERS")
for data in result:
print("Username : ",data[0])
print("Email : ",data[1])
print("Password :",data[2])
connection.close()
createTable()
|
478ea10daafffde5120ff8962eba92c173cd1ade | nosy0411/Object_Oriented_Programming | /homework2/example.py | 285 | 3.546875 | 4 | # import turtle
# # t=turtle.Turtle()
# # for i in range(5):
# # t.forward(150)
# # t.right(144)
# # turtle.done()
# spiral = turtle.Turtle()
# for i in range(20):
# spiral.forward(i*20)
# spiral.right(144)
# turtle.done()
# import turtle
# pen = turtle.Turtle()
|
e3c32038f58505113c4477596d1708390c510d98 | dgriffis/autocomplete | /MyAutoComplete.py | 3,298 | 4.15625 | 4 | #!/usr/bin/env python
import sys
class Node:
def __init__(self):
#establish node properties:
#are we at a word?
self.isaWord = False
#Hash that contains all of our keys
self.keyStore = {}
def add_item(self, string):
#Method to build out Trie
#This is done using recursive call
#Method entry to check for end of recursion
if len(string) == 0:
#We are adding full words so if the string len is now 0 then
#we are at a word marker - set the bool and get out
self.isaWord = True
return
#Now check to see if key exists and react accordingly
key = string[0] #key is the first character
string = string[1:] #and the string will be one less
if self.keyStore.has_key(key):
self.keyStore[key].add_item(string) #if the key exists then recurse
else:
node = Node() #create a new node
self.keyStore[key] = node #set the node into the keyStore
node.add_item(string) #recurse
def traverseTrie(self, foundWords=""):
# traverse the trie from this point on looking for words
#if we're at the end of the hash then print out what we have and return
if self.keyStore.keys() == []:
print 'A match is',foundWords
return
#or if we are at a word then print that but but also continue
#to traverse the trie looking for more words that start with our input string
if self.isaWord == True:
print 'A match is',foundWords
for key in self.keyStore.keys():
self.keyStore[key].traverseTrie(foundWords+key)
def search(self, string, foundWords=""):
#Method to traverse the trie and match and wildcard match the given string
#This is a recursive method
#Method entry check
if len(string) > 0 : #start gathering characters
key = string[0] #get our key
string = string[1:] #reduce the string length
if self.keyStore.has_key(key):
foundWords = foundWords + key
self.keyStore[key].search(string, foundWords)
else:
print 'No Match'
else:
if self.isaWord == True:
print 'A match is',foundWords
#Now we need to traverse the rest of the trie for wildcard matchs (word*)
for key in self.keyStore.keys():
self.keyStore[key].traverseTrie(foundWords+key)
def fileparse(filename):
'''Parse the input dictionary file and build the trie data structure'''
fd = open(filename)
root = Node()
line = fd.readline().strip('\r\n') # Remove newline characters \r\n
while line !='':
root.add_item(line)
line = fd.readline().strip('\r\n')
return root
if __name__ == '__main__':
#read in dictionary
#set root Node
#do search
myFile = 'dictionary.txt'
#root = fileparse(sys.argv[1])
root = fileparse(myFile)
#input=raw_input()
input = "win"
print "Input:",input
root.search(input) |
deae850e32102c9f22d108c817cfd69eebd4344f | szzhe/Python | /ActualCombat/TablePrint.py | 854 | 4.28125 | 4 | tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
# 要求输出如下:
# apples Alice dogs
# oranges Bob cats
# cherries Carol moose
# banana David goose
def printTable(data):
str_data = ''
col_len = []
for row in range(0, len(data[0])): # row=4
for col in range(0, len(data)): # col=3
col_len.append(len(data[col][row]))
max_col_len = max(col_len)
print("列表各元素长度为:", col_len)
print("列表中最大值为:", max_col_len) # 8
for row in range(0, len(data[0])):
for col in range(0, len(data)):
print(data[col][row].rjust(max_col_len), end='')
print()
return str_data
f_data = printTable(tableData)
print(f_data)
|
54033a39aaf84badb53bb8266b6f882ca5d5a96c | christophemcguinness/The-Art-of-Doing-Code-40-Challenging-Python-Programs-Today | /Grocery_List/main.py | 697 | 3.8125 | 4 | def remove_smallest(numbers):
y = numbers
if len(numbers) == 0:
return y , NotImplementedError("Wrong result for {0}".format(numbers))
y = numbers
y.remove(min(numbers))
return y, NotImplementedError("Wrong result for {0}".format(numbers))
print(remove_smallest([1, 2, 3, 4, 5])) # , [2, 3, 4, 5], "Wrong result for [1, 2, 3, 4, 5]")
print(remove_smallest([5, 3, 2, 1, 4])) # , [5, 3, 2, 4], "Wrong result for [5, 3, 2, 1, 4]")
print(remove_smallest([1, 2, 3, 1, 1])) # , [2, 3, 1, 1], "Wrong result for [1, 2, 3, 1, 1]")
print(remove_smallest([])) # [], "Wrong result for []"
def remove_smallest(numbers):
raise NotImplementedError("Wrong result for {0}")
|
91308a237cd5b5ac06c0c26d67f8dd1795819687 | christophemcguinness/The-Art-of-Doing-Code-40-Challenging-Python-Programs-Today | /BinaryHexadecimalConversion/main.py | 1,164 | 4.03125 | 4 | print("\n:: Welcome to the Binary/Hexadecimal Converter App ::")
computeCounter = int(input("\nCompute binary and hexadecimal value up to the following decimal number: "))
dataLists = []
for nums in range(computeCounter+1):
dataLists.append([nums, bin(nums), hex(nums)])
print(":: Generating Lists....complete! ::")
start = int(input("\nWhat decimal number would you like to start at? "))
stop = int(input("What decimal number would you like to stop at? "))
print("\nDecimal values from {0} to {1}".format(start, stop))
for nums in range(start, stop+1):
print(dataLists[nums][0])
print("\nBinary values from {0} to {1}".format(start, stop))
for nums in range(start, stop+1):
print(dataLists[nums][1])
print("\nHexadecimal values from {0} to {1}".format(start, stop))
for nums in range(start, stop+1):
print(dataLists[nums][2])
# Remove item 0
dataLists.pop(0)
x = input("\nPress Enter to see all values from 1 to {0}.".format(computeCounter))
print("\nDecimal ---- Binary ---- Hexadecimal")
print("-----------------------------------------------")
for nums in dataLists:
print('{0} --- {1} --- {2}'.format(nums[0], nums[1], nums[2])) |
30ad077dc68f5b4f369d146dd278be4d69c89fa9 | christophemcguinness/The-Art-of-Doing-Code-40-Challenging-Python-Programs-Today | /GuessMyNumberApp/main.py | 879 | 4.09375 | 4 | from random import randint
print(":: Welcome to the Guess My Number App ::\n")
name = input("Please input your name:\n")
number = randint(1, 20)
print("We the computer are thinking of a number between 1 - 20")
print("You have 5 tries to guess the number before we blow you up. Choose wisely\n")
for x in range(1,6):
guess = int(input("What is your guess number {0}?\n".format(x)))
if guess == number:
print("Well done {0} you get to live.\n".format(name))
break
elif x == 5:
print("You guessed wrong 5 times, to the processing plant with {0}\n".format(name))
else:
if guess > number:
print("Your guess is {0}, its to high.\n".format(guess))
else:
print("Your guess is {0}, its to low.".format(guess))
print("You have failed to guess right, you have {0} trie(s) left.".format(5-x))
|
52a4a2e5afcf1f190f75dc69e38ef404e392be79 | rudyardrichter/globus-automate-client | /globus_automate_client/cli/callbacks.py | 6,310 | 3.5625 | 4 | import json
import os
import pathlib
from typing import AbstractSet, List
from urllib.parse import urlparse
from uuid import UUID
import typer
import yaml
def url_validator_callback(url: str) -> str:
"""
Validates that a user provided string "looks" like a URL aka contains at
least a valid scheme and netloc [www.example.org].
Logic taken from https://stackoverflow.com/a/38020041
"""
if url is None:
return url
url = url.strip()
try:
result = urlparse(url)
if result.scheme and result.netloc:
return url
except:
pass
raise typer.BadParameter("Please supply a valid url")
def text_validator_callback(message: str) -> str:
"""
A user may supply a message directly on the command line or by referencing a
file whose contents should be interpreted as the message. This validator
determines if a user supplied a valid file name else use the raw text as the
message. Returns the text to be used as a message.
"""
# Reading from a file was indicated by prepending the filename with the @
# symbol -- for backwards compatability check if the symbol is present and
# remove it
if message.startswith("@"):
message = message[1:]
message_path = pathlib.Path(message)
if message_path.exists() and message_path.is_file():
with message_path.open() as f:
return f.read()
return message
def _base_principal_validator(
principals: List[str], *, special_vals: AbstractSet[str] = frozenset()
) -> List[str]:
"""
This validator ensures the principal IDs are valid UUIDs prefixed with valid
Globus ID beginnings. It will optionally determine if a provided principal
exists in a set of "special" values.
"""
groups_beginning = "urn:globus:groups:id:"
auth_beginning = "urn:globus:auth:identity:"
for p in principals:
if special_vals and p in special_vals:
continue
valid_beggining = False
for beggining in [groups_beginning, auth_beginning]:
if p.startswith(beggining):
uuid = p[len(beggining) :]
try:
UUID(uuid, version=4)
except ValueError:
raise typer.BadParameter(
f"Principal could not be parsed as a valid identifier: {p}"
)
else:
valid_beggining = True
if not valid_beggining:
raise typer.BadParameter(
f"Principal could not be parsed as a valid identifier: {p}"
)
return principals
def principal_validator(principals: List[str]) -> List[str]:
"""
A principal ID needs to be a valid UUID.
"""
return _base_principal_validator(principals)
def principal_or_all_authenticated_users_validator(principals: List[str]) -> List[str]:
"""
Certain fields expect values to be a valid Globus Auth UUID or one of a set
of special strings that are meaningful in the context of authentication.
This callback is a specialized form of the principal_validator where the
special value of 'all_authenticated_users' is accepted.
"""
return _base_principal_validator(
principals, special_vals={"all_authenticated_users"}
)
def principal_or_public_validator(principals: List[str]) -> List[str]:
"""
Certain fields expect values to be a valid Globus Auth UUID or one of a set
of special strings that are meaningful in the context of authentication.
This callback is a specialized form of the principal_validator where the
special value of 'public' is accepted.
"""
return _base_principal_validator(principals, special_vals={"public"})
def flows_endpoint_envvar_callback(default_value: str) -> str:
"""
This callback searches the caller's environment for an environment variable
defining the target Flow endpoint.
"""
return os.getenv("GLOBUS_AUTOMATE_FLOWS_ENDPOINT", default_value)
def input_validator_callback(body: str) -> str:
"""
Checks if input is a file and loads it, otherwise
returns the body string passed in
"""
# Callbacks are run regardless of whether an option was explicitly set.
# Handle the scenario where the default value for an option is empty
if not body:
return body
# Reading from a file was indicated by prepending the filename with the @
# symbol -- for backwards compatability check if the symbol is present and
# remove it
body = body.lstrip("@")
body_path = pathlib.Path(body)
if body_path.exists() and body_path.is_file():
with body_path.open() as f:
body = f.read()
elif body_path.exists() and body_path.is_dir():
raise typer.BadParameter("Expected file, received directory")
return body
def flow_input_validator(body: str) -> str:
"""
Flow inputs can be either YAML or JSON formatted
We can encompass these with just the YAML load checking,
but we need a more generic error message than is provided
by the other validators
"""
# Callbacks are run regardless of whether an option was explicitly set.
# Handle the scenario where the default value for an option is empty
if not body:
return body
# Reading from a file was indicated by prepending the filename with the @
# symbol -- for backwards compatability check if the symbol is present
# remove it if present
body = body.lstrip("@")
body_path = pathlib.Path(body)
if body_path.exists() and body_path.is_file():
with body_path.open() as f:
try:
yaml_body = yaml.safe_load(f)
except yaml.YAMLError as e:
raise typer.BadParameter(f"Invalid flow input: {e}")
elif body_path.exists() and body_path.is_dir():
raise typer.BadParameter("Expected file, received directory")
else:
try:
yaml_body = yaml.safe_load(body)
except yaml.YAMLError as e:
raise typer.BadParameter(f"Invalid flow input: {e}")
try:
yaml_to_json = json.dumps(yaml_body)
except TypeError as e:
raise typer.BadParameter(f"Unable to translate flow input to JSON: {e}")
return yaml_to_json
|
8c9bf8a07c5057a5b2bdd73f2b8a84d20b4b6b7d | CichonN/BikeRental | /BikeRental.py | 3,607 | 3.984375 | 4 | # ----------------------------------------------------------------------------------------------------------------------------------
# Assignment Name: Bicycle Shop
# Name: Neina Cichon
# Date: 2020-07-26
# ----------------------------------------------------------------------------------------------------------------------------------
#Declare Global Variables
rentHourly = 5.00
rentDaily = 20.00
rentWeekly = 60.00
discount = .3
bikeStock = 20
class Rental:
def __init__(self, rentalQty, rentalType):
self.rentalQty = rentalQty
self.rentalType = rentalType
#Get Rental type and Display Amount
def calcRental(self):
global bikeStock
if self.rentalQty <= 0:
raise Exception('Bike rental quantity must be greater than zero. You entered: {}'.format(self.rentalQty))
elif self.rentalQty > bikeStock:
print("We currently only have ", bikeStock, "bikes in stock.")
else:
if self.rentalType == 'hourly':
bikeStock -= self.rentalQty
global rentHourly
global rentAmount
rentAmount = rentHourly
return rentAmount
#Get Day/Time of Rental
elif self.rentalType == "daily":
bikeStock -= self.rentalQty
global rentDaily
rentAmount = rentDaily
#Get Day/Time of Rental
elif self.rentalType == "weekly":
bikeStock -= self.rentalQty
global rentWeekly
rentAmount = rentWeekly
return rentAmount
#Get Day/Time of Rental
else:
raise Exception('Rental Type was not "hourly", "daily", or "weekly". You entered: {}'.format(self.rentalType))
return rentalType
class Return:
def __init__(self, rentalQty, rentalType, rentalTime):
self.rentalQty = rentalQty
self.rentalType = rentalType
self.rentalTime = rentalTime
global bikeStock
bikeStock += rentalQty
#Process Return, add returned bikes to inventory, and display amount due
def calcReturn(self):
if self.rentalType == "daily":
global rentDaily
#Get Day/Time of Return
rentalAmount = (rentDaily * rentalTime) * rentalQty
elif self.rentalType == "weekly":
global rentWeekly
#Get Day/Time of Return
rentalAmount = (rentweekly * rentalTime) * rentalQty
else:
global rentHourly
#Get Day/Time of Return
rentalAmount = (rentHourly * rentalTime) * rentalQty
if rentalQty >= 3 and rentalQty <= 5:
print("Family Discount: $", (rentalAmount * discount))
amountDue = rentalAmount * (rentalAmount * discount)
return amountDue
else:
amountDue = rentalAmount
return amountDue
print("Amount Due: $", amountDue)
#-----------------------------------------------------
Rental1 = Rental(1, 'daily')
Rental2 = Rental(10, 'hourly')
Return1 = Return(1, "daily", 2)
#Return2 = Return(1, 2)
print( 'Qty of bikes in stock: ', (bikeStock))
#print("Renting", str(Rental.calcRental(rentalQty)), "bikes." "\nYou will be charged $", str(Rental.calcRental(rentAmount)), str(Rental(rentalType)), "for each bike.")
#print("Renting", Rental.calcRental(rentalQty), "bikes." "\nYou will be charged $", "per week for each bike.") |
63fbe3a8ecd0fd1716226f819458bc604a8faefe | dxfl/pywisdom | /try_one.py | 1,182 | 3.53125 | 4 | #!/usr/bin/env python3
'''
example adapted from stackoverflow:
https://stackoverflow.com/questions/26494211/extracting-text-from-a-pdf-file-using-pdfminer-in-python
'''
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
import io
import re
def convert_pdf_to_txt(path):
rsrcmgr = PDFResourceManager()
retstr = io.BytesIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
fp = open(path, 'rb')
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
maxpages = 50 #max pages to process
caching = True
pagenos=set()
for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
interpreter.process_page(page)
text = retstr.getvalue()
fp.close()
device.close()
retstr.close()
return text
raw_text = convert_pdf_to_txt("DSCD-12-CO-203.PDF")
text = re.sub('\n+', '\n', raw_text.decode("utf-8", "ignore"))
print(text)
|
c6d84e1f238ac03e872eea8c8cb3566ac0913646 | Cpeters1982/DojoPython | /hello_world.py | 2,621 | 4.21875 | 4 | '''Test Document, leave me alone PyLint'''
# def add(a,b):
# x = a + b
# return x
# result = add(3, 5)
# print result
# def multiply(arr, num):
# for x in range(len(arr)):
# arr[x] *= num
# return arr
# a = [2,4,10,16]
# b = multiply(a,5)
# print b
'''
The function multiply takes two parameters, arr and num. We pass our arguments here.
for x in range(len(arr)) means
"for every index of the list(array)" and then "arr[x] *= num" means multiply
the indices of the passed in array by the value of the variable "num"
return arr sends arr back to the function
*= multiplies the variable by a value and assigns the result to that variable
'''
# def fun(arr, num):
# for x in range (len(arr)):
# arr[x] -= num
# return arr
# a = [3,6,9,12]
# b = fun(a,2)
# print b
'''
Important! The variables can be anything! Use good names!
'''
# def idiot(arr, num):
# for x in range(len(arr)):
# arr[x] /= num
# return arr
# a = [5,3,6,9]
# b = idiot(a,3)
# print b
# def function(arr, num):
# for i in range(len(arr)):
# arr[i] *= num
# return arr
# a = [10, 9, 8, 7, 6]
# print function(a, 8)
# def avg(arr):
# avg = 0
# for i in range(len(arr)):
# avg = avg + arr[i]
# return avg / len(arr)
# a = [10,66,77]
# print avg(a)
# Determines the average of a list (array)
weekend = {"Sun": "Sunday", "Sat": "Saturday"}
weekdays = {"Mon": "Monday", "Tue": "Tuesday", "Wed": "Wednesday", "Thu": "Thursday",
"Fri": "Friday"}
months = {"Jan": "January", "Feb": "February", "Mar": "March", "Apr": "April",
"May": "May", "Jun": "June", "Jul": "July",
"Aug": "August", "Sep": "September", "Oct": "October", "Nov": "November",
"Dec": "December"}
# for data in months:
# print data
# for key in months.iterkeys():
# print key
# for val in months.itervalues():
# print val
# for key,data in months.iteritems():
# print key, '=', data
# print len(months)
# print len(weekend)
# print str(months)
# context = {
# 'questions': [
# { 'id': 1, 'content': 'Why is there a light in the fridge and not in the freezer?'},
# { 'id': 2, 'content': 'Why don\'t sheep shrink when it rains?'},
# { 'id': 3, 'content': 'Why are they called apartments when they are all stuck together?'},
# { 'id': 4, 'content': 'Why do cars drive on the parkway and park on the driveway?'}
# ]
# }
# userAnna = {"My name is": "Anna", "My age is": "101", "My country of birth is": "The U.S.A", "My favorite language is": "Python"}
# for key,data in userAnna.iteritems():
# print key, data |
12769258a066d58da3c740c75205211755481d0f | Cpeters1982/DojoPython | /OOP_practice.py | 5,376 | 4.40625 | 4 | # # pylint: disable=invalid-name
# class User(object):
# '''Make a class of User that contains the following attributes and methods'''
# def __init__(self, name, email):
# '''Sets the User-class attributes; name, email and whether the user is logged in or not (defaults to true)'''
# self.name = name
# self.email = email
# self.logged = True
# # Login method changes the logged status for a single instance (the instance calling the method)
# def login(self):
# '''Creates a Login method for the User-class. This method logs the user in'''
# self.logged = True
# print self.name + " is logged in."
# return self
# # logout method changes the logged status for a single instance (the instance calling the method)
# def logout(self):
# '''Creates a Logout method for the User-class. This method logs the user out.'''
# self.logged = False
# print self.name + " is not logged in."
# return self
# def show(self):
# '''Creates a Show method for the User-class. Prints the users' name and email'''
# print "My name is {}. You can email me at {}".format(self.name, self.email)
# return self
# new_user = User("Chris", "chris@chris.com")
'''
Instantiates a new instance of the User_class with the name and email attributes assigned to "chris" and "chris@chris.com" respectively
'''
# print "Hello, my name is " + new_user.name, "and my email address is " + new_user.email
'''
Remember, objects have two important features: storage of information and ability to execute some
logic.
To review:
A class: Instructions on how to build many objects that share characteristics.
An object: A data type built according to specifications provided by the class definition.
An attribute: A value. Think of an attribute as a variable that is stored within an object.
A method: A set of instructions. Methods are functions that are associated with an object.
Any function included in the parent class definition can be called by an object of that class.
1. If we wanted to define a new class we would start with which line
def ClassName(object):
def ClassName(self):
class ClassName(self):
[x] class ClassName(object):
None of the above
2. How can we set attributes to an instance of a class
A. Initializing our attributes with the __init__() function
B. We create attributes by defining multiple setter methods in our class
C. This is impossible
D. We can set individual attributes to each instance - one by one
[x] Both A & D
3. The __init__() function gets called while the object is being constructed
True
[x] False
4. You cannot define an __init__() function that has parameters
True
[x] False
5. How do you pass arguments to the __init__() function?
Creating an object instance and calling the __init__() function on the object passing in the specified parameters
You cannot pass arguments into a __init__() function
[x] When creating an object instance you pass the arguments to the specified class you are creating an instance of
Creating an object within the class and calling the __init__() function passing the specified parameters
6. What is the purpose of an __init__() function?
To prevent you from rewriting the same code each time you create a new object
To set properties required to execute certain instance methods as soon as the object is instantiated
To execute whatever logic we want to for each object that is created
[x] All of the above
7. A constructor function cannot call any other methods inside the class.
True
[x] False
'''
# class Bike(object):
# '''
# Bike class!
# '''
# def __init__(self, price, max_speed, miles):
# self.price = price
# self.max_speed = max_speed
# self.miles = 0
# def displayinfo(self):
# '''
# Get that info, son!
# '''
# print "This bike costs ${}. It has a max speed of {}. It has been ridden {} miles.".format(self.price, self.max_speed, self.miles)
# return self
# def ride(self):
# '''
# Ride that bike!
# '''
# print "Riding "
# self.miles = self.miles+10
# return self
# def reverse(self):
# '''
# Better backpedal...
# '''
# self.miles = self.miles-5 if self.miles-5 > 0 else 0
# return self
# bike1 = Bike(200, 10, 0)
# bike2 = Bike(300, 20, 0)
# bike3 = Bike(600, 60, 0)
# bike1.ride().ride().ride().reverse().displayinfo()
# bike2.ride().ride().reverse().reverse().displayinfo()
# bike3.reverse().reverse().reverse().displayinfo()
# class Car(object):
# def __init__(self, price, speed, fuel, mileage):
# self.price = price
# self.speed = speed
# self.fuel = fuel
# self.mileage = mileage
# if self.price > 10000:
# self.tax = 0.15
# else:
# self.tax = 0.12
# self.display_all()
# def display_all(self):
# print 'Price: ' + str(self.price)
# print 'Speed: ' + self.speed
# print 'Fuel: ' + self.fuel
# print 'Mileage: ' + self.mileage
# print 'Tax: ' + str(self.tax)
# return self
# car1 = Car(20000, '100mph', 'Full', '30mpg')
# car2 = Car(1000, '45mph', 'Not full', '15mpg')
# car3 = Car(10000, '75mph', 'Full', '32mpg')
|
787b69242140019629701eaf9e35c4eb97eaec44 | Doctus5/FYS-STK4155 | /project2/nn.py | 11,991 | 3.625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math as m
#Fully Connected Neural Network class for its initialization and further methods like the training and test. Time computation is quite surprisingly due to the matrix operations with relative smallamount of datasets compared to life example datasets for training (near 10'000).
class NeuralNetwork:
#Function for initializing the Weights ands Biases of each layer of the NN accoirding to the specified architecture.
#Inputs:
#- input_size, number of hidden layers, number of neurons (list of numbers of neurons per each hidden layer), number of nodes for output, number of iterations, learning rate, activation function to use, penalty value (default is 0.0), parameter to define if softmax is to be used at the end or not (not recomenen for regression problems).
#Output:
#- the entire architecture with initialized weights and biases (type dictionary).
def __init__(self, X_input, Y_input, num_nodes, num_outputs, epochs, lr, act_type='relu', penalty=0.0, prob=True):
self.X_input = X_input
self.n_inputs, self.n_features = X_input.shape
self.W, self.B = {}, {}
self.Z, self.A = {}, {}
self.dW, self.dB = {}, {}
self.Y = Y_input
self.num_outputs = num_outputs
self.num_nodes = num_nodes
self.lr = lr
self.act_type = act_type
self.penalty = penalty
self.epochs = int(epochs)
self.prob = prob
for i in range(len(self.num_nodes)+1):
if i == 0:
self.W['W'+str(i)] = np.random.rand(self.n_features, self.num_nodes[i])
self.B['B'+str(i)] = np.zeros(self.num_nodes[i]) + 0.01
elif i == len(self.num_nodes):
self.W['W'+str(i)] = np.random.rand(self.num_nodes[i-1], self.num_outputs)
self.B['B'+str(i)] = np.zeros(self.num_outputs) + 0.01
else:
self.W['W'+str(i)] = np.random.rand(self.num_nodes[i-1], self.num_nodes[i])
self.B['B'+str(i)] = np.zeros(self.num_nodes[i]) + 0.01
def init_check(self):
print('report of Data, Weights and Biases shapes at Initialization:')
print(self.X_input.shape)
for ind in self.W.keys():
print(ind, self.W[ind].shape)
for ind in self.B.keys():
print(ind, self.B[ind].shape)
print(self.Y.shape)
#Sigmoid function used as an activation function.
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def sigmoid(self, x):
return 1/(1 + np.exp(-x))
#Derivative of the Sigmoid function used as an activation function for backprop.
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def dev_sigmoid(self, x):
return self.sigmoid(x)*(1 - self.sigmoid(x))
#Sigmoid function used as an activation function.
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def tanh(self, x):
return np.tanh(x)
#Derivative of the Sigmoid function used as an activation function for backprop.
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def dev_tanh(self, x):
return 1 - self.tanh(x)**2
#ReLU function used as an activation function.
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def ReLu(self, x):
x[x <= 0] = 0
return x
#Heaviside function (derivative of ReLu) used as an activation function for backprop.
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def dev_ReLu(self, x):
x[x <= 0] = 0
x[x > 0] = 1
return x
#Leaky ReLU function used as an activation function.
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def Leaky_ReLu(self, x):
x[x <= 0] *= 0.01
return x
#Leaky_ReLU derivative function used as an activation function for backprop.
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def dev_Leaky_ReLu(self, x):
x[x <= 0] = 0.01
x[x > 0] = 1
return x
#Softmax function used in the last layer for targeting probabilities
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def softmax(self, x):
return np.exp(x)/np.sum(np.exp(x), axis=1, keepdims=True)
#Function for evaluationg which activation function to use according to the desired activation function initialized in the Neural Network
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x..
def activation(self, x):
if self.act_type == 'relu':
return self.ReLu(x)
elif self.act_type == 'sigmoid':
return self.sigmoid(x)
elif self.act_type == 'tanh':
return self.tanh(x)
elif self.act_type == 'leaky_relu':
return self.Leaky_ReLu(x)
#Function for evaluationg which derivate function to use according to the desired activation function initialized in the Neural Network
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def derivative(self, x):
if self.act_type == 'relu':
return self.dev_ReLu(x)
elif self.act_type == 'sigmoid':
return self.dev_sigmoid(x)
elif self.act_type == 'tanh':
return self.dev_tanh(x)
elif self.act_type == 'leaky_relu':
return self.dev_Leaky_ReLu(x)
#Feed Forwards function
#Input:
#- Initial parameters of weights, data set, biases and probability boolean to decide if Aoftmax is used or not.
#Output:
#- Calculated A and Z values for each hidden layer.
def feed_forward(self, X, W, B, prob):
iterations = len(W)
Z = {}
A = {}
for i in range(iterations):
if i == 0:
Z['Z'+str(i+1)] = X @ W['W'+str(i)] + B['B'+str(i)]
A['A'+str(i+1)] = self.activation(Z['Z'+str(i+1)])
elif i == (iterations - 1):
Z['Z'+str(i+1)] = A['A'+str(i)] @ W['W'+str(i)] + B['B'+str(i)]
if prob == True:
A['A'+str(i+1)] = self.softmax(Z['Z'+str(i+1)])
else:
A['A'+str(i+1)] = Z['Z'+str(i+1)]
else:
Z['Z'+str(i+1)] = A['A'+str(i)] @ W['W'+str(i)] + B['B'+str(i)]
A['A'+str(i+1)] = self.activation(Z['Z'+str(i+1)])
return Z, A
#Back Propagation function
#Input:
#- Initial parameters of weights, data set, biases, A and Z values of the hidden layers.
#Output:
#- Gradients for Weights and Biases in each hidden layer to use in the upgrade step.
def back_propagation(self, X, Y, W, B, A, Z):
layers = len(A)
m = len(X)
dW = {}
dB = {}
for i in range(layers-1,-1,-1):
if i == layers-1:
delta = A['A'+str(i+1)] - Y
dW['dW'+str(i)] = (1/m) * A['A'+str(i)].T @ delta
dB['dB'+str(i)] = (1/m) * np.sum(delta, axis=0)
elif i == 0:
delta = (delta @ W['W'+str(i+1)].T) * self.derivative(Z['Z'+str(i+1)])
dW['dW'+str(i)] = (1/m) * X.T @ delta
dB['dB'+str(i)] = (1/m) * np.sum(delta, axis=0)
else:
delta = (delta @ W['W'+str(i+1)].T) * self.derivative(Z['Z'+str(i+1)])
dW['dW'+str(i)] = (1/m) * A['A'+str(i)].T @ delta
dB['dB'+str(i)] = (1/m) * np.sum(delta, axis=0)
return dW, dB
#Parameters Upgrade function
#Input:
#- Weights and biases, gradients for update, learning rate and penalty parameter (0.0 if there is no penalty).
#Output:
#- Updates Weights and Biases per hidden layer.
def upgrade_parameters(self, dW, dB, W, B, lr, penalty):
for i in range(len(dW)):
if penalty != 0.0:
dW['dW'+str(i)] += penalty * W['W'+str(i)]
W['W'+str(i)] -= lr * dW['dW'+str(i)]
B['B'+str(i)] -= lr * dB['dB'+str(i)]
return W, B
#Train function.
#Do all the processes of feed_forward, back_propagation and upgrade_parameters for a certain amount of epochs until Weights and Biases are updated completely for this training set
#Input:
#-
#Output:
#-
def train(self):
for i in range(self.epochs):
#print(i)
self.Z, self.A = self.feed_forward(self.X_input, self.W, self.B, self.prob)
self.dW, self.dB = self.back_propagation(self.X_input, self.Y, self.W, self.B, self.A, self.Z)
self.W, self.B = self.upgrade_parameters(self.dW, self.dB, self.W, self.B, self.lr, self.penalty)
#Predict function.
#Based on an already train NN, it predicts the classes or output of a test set passed as argument.
#Input:
#- Test_set in the same type as the Train set used to initialize the NN.
#Output:
#- Values predicted or probabilities per nodes. To use as it is for regression problems, or probability logits to be decoded with the decoder function in method.py
def predict(self, test_set):
Zetas, As = self.feed_forward(test_set, self.W, self.B, self.prob)
classes = As['A'+str(len(self.num_nodes)+1)]
return classes
#Logistic Regression class and further methods like the training and test.
class Logistic_Regression:
#Function for initializing the Parameters, including the initial coefficients from 0 to 1.
#Inputs:
#- input data, target values, number of iterations, learning rate, penalty value (default is 0.0), threshold for binary classification in probability distribution (default is 0.5).
#Output:
#- initialized values.
def __init__(self, X_input, Y_input, epochs, lr, penalty=0.0, threshold=0.5):
self.X = X_input
self.n_inputs, self.n_features = X_input.shape
self.Y = Y_input
self.lr = lr
self.B = np.random.rand(self.n_features,1)
self.penalty = penalty
self.epochs = int(epochs)
self.prob = threshold
#Probability calculation function (Sigmoid function)
#Inputs:
#- values (array of values in column).
#Output:
#- evaluated values in sigmoid fucntion (array with size equal to the Input).
def probability(self, values):
return 1/(1 + np.exp(-values))
#Train function.
#Do all the processes of gradient descent, with a cost function defined on probabilty comparison. Penalty parametr also taked into accountto compute another gradient regularized in case that penalty is different from 0.0
#Input:
#-
#Output:
#-
def train(self):
t0, t1 = 5, 50
#print(self.B)
for i in range(self.epochs):
if self.penalty != 0.0:
G = self.X.T @ (self.Y - self.probability( self.X @ self.B )) + (self.penalty * self.B)
else:
G = self.X.T @ (self.Y - self.probability( self.X @ self.B ))
self.B += self.lr * G
#Predict function.
#Based on an already train Logistic Regression (updated coefficients).
#Input:
#- Test_set in the same type as the Train set used to initialize the class.
#Output:
#- Values predicted in the way of probabilities. It instantly translates to the desired class (0 or 1) (binary classification).
def predict(self, values):
results = self.probability( values @ self.B )
results[results < self.prob] = 0
results[results >= self.prob] = 1
return results
|
c02f664998073d00a27a016e5edfe0f289b785b9 | aditdamodaran/incan-gold | /deck.py | 898 | 3.875 | 4 | import random
class Deck:
# The game starts off with:
# 15 treasure cards
# represented by their point values,
# 15 hazards (3 for each type)
# represented by negative numbers
# 1 artifact (worth 5 points) in the deck
def __init__(self):
self.cards = [1,2,3,4,5,5,7,7,9,11,11,13,14,15,17] \
+ ([-1]*3) \
+ ([-2]*3) \
+ ([-3]*3) \
+ ([-4]*3) \
+ ([-5]*3) \
+ [50]
# Shuffles the deck
def shuffle(self):
random.shuffle(self.cards)
# Removes a card from the deck
def remove(self, value):
# print('removing')
counter = 0
for i, card in enumerate(self.cards):
if (card == value and counter == 0):
# print('popping', card)
self.cards.pop(i)
counter+=1
# Draws a card
def draw(self):
drawn = self.cards[0]
self.cards = self.cards[1:len(self.cards)]
return drawn |
c8633e4755e9dfd08535a9806245154b042526b2 | gersongroth/maratonadatascience | /Semana 01/01 - Estruturas Sequenciais/07.py | 135 | 3.84375 | 4 | lado = float(input("Informe o lado do quadrado: "))
area = lado ** 2
dobroArea = area * 2
print("dobro do área é %.1f" % dobroArea) |
cbbe2be00332fe79c2b2f47a9ee1abf4e3606d1c | gersongroth/maratonadatascience | /Semana 01/03 - Estruturas de Repetição/02.py | 444 | 3.859375 | 4 | """
Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações.
"""
def getUser():
user=input("Informe o nome de usuário: ")
password= input("Informe a senha: ")
return user,password
user,password=getUser()
while(user == password):
print("Senha não pode ser igual ao usuário")
user,password=getUser() |
44b81e47c1cd95f7e08a8331b966cf195e8c514d | gersongroth/maratonadatascience | /Semana 01/02 - Estruturas de Decisão/11.py | 1,156 | 4.1875 | 4 | """
As Organizações Tabajara resolveram dar um aumento de salário aos seus colaboradores e lhe contraram para desenvolver o programa que calculará os reajustes.
Faça um programa que recebe o salário de um colaborador e o reajuste segundo o seguinte critério, baseado no salário atual:
salários até R$ 280,00 (incluindo) : aumento de 20%
salários entre R$ 280,00 e R$ 700,00 : aumento de 15%
salários entre R$ 700,00 e R$ 1500,00 : aumento de 10%
salários de R$ 1500,00 em diante : aumento de 5% Após o aumento ser realizado, informe na tela:
o salário antes do reajuste;
o percentual de aumento aplicado;
o valor do aumento;
o novo salário, após o aumento.
"""
salario = float(input("Informe o salário: R$ "))
aumento = 0
if salario <= 280.0:
aumento = 20
elif salario < 700.0:
aumento = 15
elif salario < 1500:
aumento = 10
else:
aumento = 5
valorAumento = salario * (aumento / 100)
novoSalario = salario + valorAumento
print("Salario original: R$ %.2f" % salario)
print("Porcentagem de aumento: %d%%" % aumento)
print("Valor do aumento: R$ %.2f" % valorAumento)
print("Salario após reajuste: R$ %.2f" % novoSalario) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.