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 |
|---|---|---|---|---|---|---|
0b240efcf6056322b8f4768da1f33690adf52686 | PY309-2353/eight_homework | /task_5.py | 1,137 | 3.640625 | 4 | class Deck:
deck = []
def push_front(self, n):
self.deck.insert(-1, n)
print('ok')
def push_back(self, n):
self.deck.insert(0, n)
print('ok')
def pop_front(self):
out_elem = self.deck[-1]
self.deck.pop()
print(out_elem)
def pop_back(self):
out_elem = self.deck[0]
del(self.deck[0])
print(out_elem)
def front(self):
print(self.deck[-1])
def back(self):
print(self.deck[0])
def size(self):
print(len(self.deck))
def clear(self):
self.deck.clear()
print('ok')
def exit(self):
print('bye')
quit()
finish = False
while finish == False:
s = Deck()
func = ''
param = ''
input_str = input()
if input_str == 'exit':
finish = True
for element in input_str:
if element not in (' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'):
func += element
elif element != ' ':
param += element
a = 's' + '.' + func + f'({param})'
eval(a) |
86365d3c2672ca4ef6e627cc8c9c072ee3c22f05 | ISHARRR/hackerrank | /Python/sorting-BubbleSort.py | 360 | 3.6875 | 4 | def countSwaps(a):
count = 0
print (a)
for i in range(len(a)-1):
for j in range(len(a)-1):
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1], a[j]
count = count + 1
print ('Array is sorted in', count, 'swaps.')
print ('First Element:', a[0])
print ('Last Element:', a[-1])
countSwaps([3,2,1])
|
49dbae624f7695959e79f62a34837ed32fa6041a | vandlaw7/piro12 | /2주차 금요일 과제/3.py | 1,177 | 3.625 | 4 | n = int(input())
def arrange(ps):
newps = [value for index, value in enumerate(ps) if
not ((ps[index] == '(' and ps[index + 1] == ')') or (ps[index - 1] == '(' and ps[index] == ')'))]
return newps
def if_vps(ps):
# initial screen
if len (ps) == 0:
print("YES")
return
elif len(ps) % 2 == 1:
print("NO")
return
elif ps[0] == ')' or ps[-1] == '(':
print("NO")
return
while arrange(ps) != ps:
# first screen
if len(ps) == 0:
print("YES")
return
elif len(ps) % 2 == 1:
print("NO")
return
elif ps[0] == ')' or ps[-1] == '(':
print("NO")
return
ps = arrange(ps)
# second screen
if len(ps) == 0:
print("YES")
return
elif len(ps) & 2 == 1:
print("NO")
return
elif ps[0] == ')' or ps[-1] == '(':
print("NO")
return
for i in range(n):
ps_raw = input()
ps = [p for p in ps_raw]
if_vps(ps)
|
11611feeaa8586728e69cd3d902fb1c67fa35317 | Marist-CMPT120-FA19/Nathan-Raia-Lab-12 | /atm.py | 4,965 | 3.78125 | 4 | #Nathan Raia
class Account:
def __init__(self , id , pin , savings , checking):
self.ID = id
self.PIN = pin
self.savings = int(savings)
self.checking = int(checking)
def getID(self):
return self.ID
def getPIN(self):
return self.PIN
def getSavings(self):
return self.savings
def getChecking(self):
return self.checking
def withdraw(self , account , amm):
if account == "savings":
self.savings = self.savings - int(amm)
elif account == "checking":
self.checking = self.checking - int(amm)
def transfer(self , toAcc , amm):
if toAcc == "savings":
self.savings = self.savings + int(amm)
self.checking = self.checking - int(amm)
elif toAcc == "checking":
self.savings = self.savings - int(amm)
self.checking = self.checking + int(amm)
def toString(self):
return str(str(self.ID) + "\t" + str(self.PIN) + "\t" + str(self.savings) + "\t" + str(self.checking))
def checkCredentials(id , pin):
accountsFile = open("accounts.txt" , "r")
for i in accountsFile:
a = createAccount(i.split("\t"))
if id == a.getID():
if pin == a.getPIN():
accountsFile.close()
return True
def createAccount(info):
return Account(info[0] , info[1] , info[2] , info[3])
def accountMenu(acc):
b = True
while b:
print("Your current balances are... \n Savings Account: $" , acc.getSavings() , "\n Checking Account: $" , acc.getChecking())
print("\nWhat would you like to do? \n1) Withdraw cash \n2) Transfer funds \n3) Quit")
action = int(input("Answer with 1, 2, or 3: "))
if action == 1:
ammount = int(input("How much cash would you like to withdraw: "))
account = input("From which account: ")
if account.lower() == "savings":
if ammount <= acc.getSavings():
acc.withdraw(account.lower() , ammount)
print("Your transaction was completed... \n")
else:
print("The requested ammount of money was more than there is in the account.")
elif account.lower() == "checking":
if ammount <= acc.getChecking():
acc.withdraw(account.lower() , ammount)
print("Your transaction was completed... \n")
else:
print("The requested ammount of money was more than there is in the account.")
print("Sending you back to the top... \n")
elif action == 2:
ammount = int(input("How much money would you like to transfer: "))
account = input("From which account: ")
if account.lower() == "savings":
if ammount <= acc.getSavings():
acc.transfer(account.lower() , ammount)
print("Your transaction was completed... \n")
else:
print("The requested ammount of money was more than there is in the account.")
elif account.lower() == "checking":
if ammount <= acc.getChecking():
acc.transfer(acc.lower() , ammount)
print("Your transaction was completed... \n")
else:
print("The requested ammount of money was more than there is in the account.")
print("Sending you back to the top... \n")
elif action == 3:
b = False
else:
print("That was an invalid selection! \n")
print("Sending you back to the top... \n")
accountsFile = open("accounts.txt" , "r")
counter = -1
newFile = []
for i in accountsFile:
counter += 1
newFile = newFile + [i]
if i.split("\t")[0] == acc.getID():
newFile[counter] = acc.toString()
else:
newFile[counter] = i
accountsFile.close()
accountsFile = open("accounts.txt" , "w")
for i in range(counter+1):
accountsFile.write(newFile[i])
if i == 0:
accountsFile.write("\n")
accountsFile.close()
def main():
b = True
while b:
id = input("Enter your account ID: ")
pin = input("Enter your corresponding PIN: ")
if checkCredentials(id , pin):
b = False
accountsFile = open("accounts.txt" , "r")
for i in accountsFile:
a = createAccount(i.split("\t"))
if id == a.getID():
if id == a.getPIN():
accountMenu(a)
else:
print("Invalid Credentials! \nPlease try again... \n")
if __name__ == '__main__':
main()
|
7ac0a41699aad4c673e83b4d5ce6d3b3ff1beb86 | JoaoLeal92/registro-transacoes-financeiras | /db_access/conexao_db.py | 4,320 | 3.640625 | 4 | import psycopg2
class BancoDeDados:
"""
Arquivo definindo rotinas para fazer a conexão e queries de select, imports e deletes de dados no banco de dados
Atributos:
user: nome do usuário de acesso ao banco de dados
password: senha de acesso ao banco de dados
database: nome do banco de dados acessado
host: endereço de IP do host (localhost para bancos locais)
port: número da porta de acesso
"""
def __init__(self, user, password, database, host, port):
self.user = user
self.password = password
self.database = database
self.host = host
self.port = port
# Estabelece conexão com o banco
self.connection = psycopg2.connect(user=self.user, password=self.password, database=self.database,
host=self.host, port=self.port)
self.cursor = self.connection.cursor()
def get_params(self):
"""
Retorna para o usuário os parâmetros da conexão com o banco de dados
:return: dicionário contendo dados da conexão
"""
return self.connection.get_dsn_parameters()
def add_rows(self, dados, tabela):
"""
Adiciona linhas à tabela de interesse no banco de dados
:param dados: lista de tuplas contendo os dados a serem inseridos na tabela
:param tabela: nome da tabela onde os dados serão inseridos
"""
len_inputs = len(dados[0])
self.cursor.executemany(f'INSERT INTO {tabela} VALUES ({"%s, " * (len_inputs - 1)}%s)', dados)
self.connection.commit()
print("Dados inseridos na tabela")
def delete_rows(self, ids, tabela):
"""
Deleta linhas da tabela com base em seu id
:param ids: lista contendo os ids das transações a serem deletadas
:param tabela: nome da tabela de onde os dados serão removidos
"""
# Formata os ids para poderem ser consumidos pela função
dados = [(id_,) for id_ in ids]
self.cursor.executemany(f'DELETE FROM {tabela} WHERE "id" = %s', dados)
self.connection.commit()
print("Dados removidos da tabela")
def select(self, tabela, cols=None):
"""
Realiza select nas tabelas do banco de dados para consulta
:param tabela: nome da tabela a ser consultada
:param cols: colunas de interesse da tabela. Caso não seja fornecido, serão retornadas todas as colunas
:return: dados da tabela consultada
"""
if cols is None:
self.cursor.execute(f'SELECT * FROM {tabela}')
else:
assert (type(cols == list)), 'Argumentos para SELECT devem ser passados em formato de lista de strings'
colunas = ', '.join(cols)
self.cursor.execute(f'SELECT {colunas} FROM {tabela}')
return self.cursor.fetchall()
def select_date(self, tabela, data, cols=None):
"""
Realiza select para uma data específica nas tabelas do banco de dados para consulta
:param tabela: nome da tabela a ser consultada
:param cols: colunas de interesse da tabela. Caso não seja fornecido, serão retornadas todas as colunas
:param data: data a ser pesquisada na tabela
:return: dados da tabela consultada
"""
if cols is None:
self.cursor.execute(f'SELECT * FROM {tabela} WHERE data LIKE \'%{data}\'')
else:
assert (type(cols == list)), 'Argumentos para SELECT devem ser passados em formato de lista de strings'
colunas = ', '.join(cols)
self.cursor.execute(f'SELECT {colunas} FROM {tabela}')
return self.cursor.fetchall()
def get_last_id(self, tabela):
"""
Busca o id da última transação lançada no banco
:param tabela: nome da tabela a ser consultada
:return: valor do id no banco (caso exista)
"""
self.cursor.execute(f'SELECT * FROM {tabela} ORDER BY id DESC LIMIT 1')
last_id = self.cursor.fetchall()[0][0]
return last_id
def close_connection(self):
"""
Encerra a conexão com o banco de dados
"""
self.cursor.close()
self.connection.close()
print('Conexão encerrada')
|
16e225e621786b9a40ef1834465d4bdf0964b9e3 | aisu-programming/Numerical-Method | /Homework_02_Bisection.py | 852 | 3.59375 | 4 | import math
def bisection(function, interval, precise=None):
start = interval[0]
end = interval[1]
for i in range(100):
middle = (start + end) / 2.0
print(f'{i+1:3d}: {middle}')
if precise is not None:
if (end - start) < precise: return middle
if function(middle) < 0:
start = middle
continue
else:
end = middle
return middle
def fixed_point_iteration(function, start, precise=None):
n = start
for i in range(100):
n_next = function(n)
print(f'{i+1:3d}: {n_next}')
if precise is not None:
if abs(n_next - n) < precise: return n_next
n = n_next
return n_next
# For bisection, f(x); For FPI, g(x).
def function(x):
return x**3.0 - 2.0*x + 2
# return (2.0*x + 2.0)**(1./3.)
if __name__ == '__main__':
answer = bisection(function, [0., 3.538])
# answer = fixed_point_iteration(function, 2.0)
# print(answer) |
f0eb2a695f110c0f81777d0d6c64b60a003fcc51 | chetan113/python | /moreprograms/rightangletriangle.py | 270 | 4.21875 | 4 | """" n = int(input("enter a number of rows:"))
for i in range(1,n+1):
for j in range(1,i+1):
print(" * ",end ="")
print()"""
"""one for loop statement"""
n =int(input("enter the number of rows:"))
for i in range(1,n+1):
print(" $ "*i)
|
3dfcb3368a60024ff4a3ae96b61e343d7ac0b10c | chetan113/python | /moreprograms/stringreversal.py | 344 | 3.796875 | 4 | """s =input("enter a string:")
print(s[::-1])
"""
"""palendrom"""
"""
s= input("enter a string:")
i= len(s)-1
result = ''
while i>=0:
result =result+s[i]
i=i-1
print(result)
"""
""" join the string use reverse"""
s='---'.join(['a','b','c'])
print(s)
s1=input("enter a string:")
print(','.join(reversed(s1)))
|
c93da5b5ba3c3d87755ad07fc880704da4278c92 | leomrocha/legi.py | /legi/roman.py | 764 | 3.703125 | 4 | """
Conversion functions for roman numbers
"""
from __future__ import division, print_function, unicode_literals
ROMAN_NUMERALS = (
('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100),
('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5),
('IV', 4), ('I', 1)
)
def decimal_to_roman(i):
r = ''
for numeral, value in ROMAN_NUMERALS:
count = i // value
r += numeral * count
i -= value * count
return r
def roman_to_decimal(s):
r = 0
i = 0
for numeral, value in ROMAN_NUMERALS:
l = len(numeral)
while s[i:i+l] == numeral:
r += value
i += l
if i != len(s):
raise ValueError('"%s" is not a valid roman number' % s)
return r
|
34153f219c89f9f2b926fcc9ded5e62f28b23f74 | 26prajval98/OOP-in-python | /OOP in Python/4_multiple-inheritance.py | 522 | 3.6875 | 4 | class A:
def __init__(self):
print('A')
super().__init__()
class B(A):
def __init__(self,first, **k):
self.first = first
print('B: {}'.format(self.first))
super().__init__(**k)
class C(A):
def __init__(self,last, **k):
self.last = last
print('C: {}'.format(self.last))
super().__init__(**k)
class D(B,C):
def __init__(self,first,last):
print('D')
super().__init__(first=first,last=last)
D('first','last')
print(D.__mro__) |
93b9eb93bbf23b5cd5de05e8b693703d1c8d747e | 26prajval98/OOP-in-python | /OOP in Python/8_metaclasses_1.py | 351 | 3.65625 | 4 | required = input('y or n\n')
isTrue = True if required == 'y' else False
# Similar to meta classes decorator for that class
def classDecorator(cls):
if isTrue:
cls.Hallo = 'Hello'
print('Hello')
return cls
@classDecorator
class A:
def __init__(self):
print('initialised')
print(self.__dict__)
a = A() |
9a9fe0973e853ab8c5c9e80c217890ce00e3d881 | ratansingh98/100_Days_of_ML_Code | /days/Day 20 : Understanding NLTK/lemmatization.py | 674 | 3.578125 | 4 | from nltk.stem import WordNetLemmatizer
input_words = ['writing','calves','be','branded','horse','randomize',
'possibly','provision','hospital','kept','scratchy','code']
# Create lemmatizer object
lemmatizer = WordNetLemmatizer()
# Create a List of lemmatizer names for display
lemmatizer_names = ['NOUN LEMMATIZER',"VERN LEMMATIZER"]
formatted_text = '{:>24}' * (len(lemmatizer_names)+1)
print('\n',formatted_text.format('INPUT WORD',*lemmatizer_names),'\n','='*75)
# Lemmatize each word and display the output
for word in input_words:
output = [word, lemmatizer.lemmatize(word,pos='n'), lemmatizer.lemmatize(word,pos='v')]
print(formatted_text.format(*output)) |
6d3fd57f669b763a4a72d04a429f5f18bab9bfa0 | ratansingh98/100_Days_of_ML_Code | /days/Day 25 : Tic-Tac-Toe Bot/TreePlot.py | 3,425 | 3.5 | 4 | import pydot
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import pylab as pl
import Config
class TreePlot:
"""
This class creates tree plot for search tree
"""
def __init__(self):
"""
Constructor
"""
# create graph object
self.graph = pydot.Dot( graph_type='graph', dpi = 800)
#index of node
self.index = 0
def createGraph(self, node, bestMove):
"""
This method adds nodes and edges to graph object
Similar to printTree() of Node class
"""
#create html code for the boardValues
boardValues = node.state.boardValues
htmlString = "<<table>"
rows, cols = boardValues.shape
for i in range(rows):
htmlString += "<tr>"
for j in range(cols):
if boardValues[i, j] == -1:
htmlString += "<td bgcolor='#FF0000'> </td>"
elif boardValues[i, j] == 0:
htmlString += "<td bgcolor='#00FF00'>" + Config.moveTexts[0] + \
"</td>"
elif boardValues[i, j] == 1:
htmlString += "<td bgcolor='#0000FF'>" + Config.moveTexts[1] + \
"</td>"
htmlString += "</tr>"
htmlString += "</table>>"
#decide shape based on whether node is at depth 1 and node's move is bestMove
shape = "plaintext"
if node.depth == 1 and node.move == bestMove:
#draw extra border
shape = "plain"
#annotate score if leaf or else alpha-beta
annotation = ""
if len(node.children) == 0:
annotation = node.score
else:
annotation = str(node.alpha) + "," + str(node.beta) + "," + str(node.score)
#create node
parentGraphNode = pydot.Node(str(self.index), shape = shape,
label = htmlString, xlabel = annotation)
self.index += 1
#add node
self.graph.add_node(parentGraphNode)
#call this method for child nodes
for childNode in node.children:
childGraphNode = self.createGraph(childNode, bestMove)
#create edge
edge = pydot.Edge(parentGraphNode, childGraphNode, label = "[" +
str(childNode.move.row) + "," + str(childNode.move.col) + "]")
#add edge
self.graph.add_edge(edge)
return parentGraphNode
def generateDiagram(self, rootNode, bestMove):
"""
This method generates diagram
"""
#add nodes to edges to graph
self.createGraph(rootNode, bestMove)
f = pl.figure()
f.add_subplot(1, 1, 1)
# show search tree
self.graph.write_png('graph.png')
img = mpimg.imread('graph.png')
pl.imshow(img)
pl.axis('tight')
pl.axis('off')
mng = plt.get_current_fig_manager()
#mng.window.state('zoomed')
plt.axis('tight')
plt.axis('off')
plt.savefig("figure.jpg")
plt.show()
|
eebd301ffac344f8fe7bdf16a8cf9677bb542d3a | G00398275/PandS | /Week 05 - Datastructures/prime.py | 566 | 4.28125 | 4 | # This program lists out the prime numbers between 2 and 100
# Week 05, Tutorial
# Author: Ross Downey
primes = []
upto = 100000
for candidate in range (2, upto):
isPrime = True # Required only to check if divisible by prime number
for divisor in primes: # If it is divisible by an integer it isn't a prime number
if (candidate % divisor == 0):
isPrime = False
break # No reason to keep checking if not prime number
if isPrime:
primes.append(candidate) # If it is a prime number, append it to the list
print (primes) |
75a5d8161498d62cbdce415742715a9baac22543 | G00398275/PandS | /Week 02/hello3.py | 235 | 4.21875 | 4 | # Week 02 ; hello3.py, Lab 2.2 First Programs
# This program reads in a person's name and prints out that persons name using format
# Author: Ross Downey
name = input ("Enter your name")
print ('Hello {} \nNice to meet you'.format (name)) |
8cc33ccb44add40fb374f791f9e819049cc47af1 | G00398275/PandS | /Week 03/Lab 3.2.1-round.py | 277 | 3.96875 | 4 | # Week 03: Lab 3.2.1 Fun with numbers
# This program takes in a float and outputs an integer
# Author: Ross Downey
numberToRound = float (input("Please enter a float number: "))
roundedNumber = round(numberToRound)
print ( '{} rounded is {}' .format(numberToRound, roundedNumber)) |
a0986698fa2430008eb4d33ebf02b50e933fc09c | G00398275/PandS | /Week 03/Lab 3.3.1-len.py | 270 | 4.15625 | 4 | # Week 03: Lab 3.3.1 Strings
# This program reads in a strings and outputs how long it is
# Author: Ross Downey
inputString = input ('Please enter a string: ')
lengthOfString = len(inputString)
print('The length of {} is {} characters' .format(inputString, lengthOfString)) |
8ff8959b62adcc0f3455ca00c1e9108a16fbf97e | G00398275/PandS | /Week 03/Lab 3.3.3 normalize.py | 575 | 4.46875 | 4 | # Week 03: Lab 3.3.2 Strings
# This program reads in a string and removes any leading or trailing spaces
# It also converts all letters to lower case
# This program also outputs the length of the original string
# Author: Ross Downey
rawString = input("Please enter a string: ")
normalisedString = rawString.strip().lower()
lengthOfRawString = len(rawString)
lengthOfNormalised = len(normalisedString)
print("That string normalised is: {}" .format(normalisedString))
print("We reduced the input string from {} to {} characters" .format (
lengthOfRawString, lengthOfNormalised)) |
661c5df851bebf8a40806b42288f068885a4200f | G00398275/PandS | /Week 02/Simple Arithmetic 02.py | 158 | 3.671875 | 4 | # Week 02: Simple Arithmetic 02.py, Lab 2.2 First Programs - Extra
# This program outputs whether 2 is equal to 3
# Author: Ross Downey
import math
print (2 == 3) |
59fc57e8d10d9f71c59999d297edfaf310676efd | G00398275/PandS | /Week 04-flow/w3Schools-ifElse.py | 1,257 | 4.40625 | 4 | # Practicing ifElse loops, examples in https://www.w3schools.com/python/python_conditions.asp
# Author: Ross Downey
a = 33
b = 200
if b > a: # condition is IF b is greater than a
print("b is greater than a") # Ensure indentation is present for print, i.e. indent for condition code
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b: # condition is ELSE/IF a and b are equal
print("a and b are equal")
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else: # Condition is ELSE, when the preceding if/elif conditions aren't met
print("a is greater than b")
a = 200
b = 33
if b > a:
print("b is greater than a")
else: # same above without the elif condition, can use just IF and ELSE if needed
print("b is not greater than a")
if a > b: print("a is greater than b")
# shorthand if, can do on one line if only one simple condition needed
a = 2
b = 330
print("A") if a > b else print("B")
# shorthand if / else, done on one line
a = int(input("Please enter integer a:"))
b = int(input("Please enter integer b:")) # changing code to inputs, ensure integer is used
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b") |
3894d02f1d98a3cab86988ae48c164b300882603 | G00398275/PandS | /Week 08/Lab-8.1-8.4_salaries.py | 774 | 4.09375 | 4 | # Lab 8.1 - 8.4 plotting; salaries.py
# This program generated 10 random salaries that are modified as requested
# Author: Ross Downey
import numpy as np
minSalary = 20000
maxSalary = 80000
numberOfEntries = 10 # specifying min, max and how many numbers needed
np.random.seed(1) # ensures "random" array called is the same each time
salaries = np.random.randint(minSalary, maxSalary, numberOfEntries)
print (salaries)
salariesPlus = salaries + 5000 # adding 5000 to each salary in original array
print (salariesPlus)
salariesMult = salaries * 1.05 # multiplying original salaries by 1.05 to increase by 5%
print(salariesMult)
# As this array is a float it is better to convert to an array, the below gives a floor
newSalaries = salariesMult.astype(int)
print(newSalaries)
|
c680ffcb0cb897828bb5345cca25dca196d87882 | xiaomiaoright/Credit-Risk-Analysis | /BuildingClassificationModel_3_FeatureSelection.py | 6,840 | 3.8125 | 4 | # Feature selection
# including features in a model which do not provide information on the label is useless at best and may prevent generalization at worst.
"""
1. Eliminating features with low variance and zero variance.
2. Training machine learning models with features that are uninformative can create a variety of problems
"""
# Load Data Set
import pandas as pd
from sklearn import preprocessing
import sklearn.model_selection as ms
from sklearn import linear_model
import sklearn.metrics as sklm
from sklearn import feature_selection as fs
from sklearn import metrics
from sklearn.model_selection import cross_validate
import numpy as np
import numpy.random as nr
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.stats as ss
import math
%matplotlib inline
Features = np.array(pd.read_csv('Credit_Features.csv'))
Labels = np.array(pd.read_csv('Credit_Labels.csv'))
print(Features.shape)
print(Labels.shape)
## -->> Eliminate low variance features
# VarianceThreshold function
print(Features.shape)
## Define the variance threhold and fit the threshold to the feature array.
sel = fs.VarianceThreshold(threshold=(.8 * (1 - .8)))
Features_reduced = sel.fit_transform(Features)
## Print the support and shape for the transformed features
print(sel.get_support())
print(Features_reduced.shape)
## -->>Select k best features
# RFECV function
## Reshape the Label array
Labels = Labels.reshape(Labels.shape[0],)
## Set folds for nested cross validation
nr.seed(988)
feature_folds = ms.KFold(n_splits=10, shuffle = True)
## Define the model
logistic_mod = linear_model.LogisticRegression(C = 10, class_weight = {0:0.45, 1:0.55})
## Perform feature selection by CV with high variance features only
nr.seed(6677)
selector = fs.RFECV(estimator = logistic_mod, cv = feature_folds,
scoring = 'roc_auc')
selector = selector.fit(Features_reduced, Labels)
selector.support_
# relative ranking of the features
selector.ranking_
# transform method applies the selector to the feature array
Features_reduced = selector.transform(Features_reduced)
Features_reduced.shape
# plot of AUC (the metric) vs. the number of features
plt.plot(range(1, len(selector.grid_scores_) + 1), selector.grid_scores_)
plt.title('Mean AUC by number of features')
plt.ylabel('AUC')
plt.xlabel('Number of features')
## -->> Apply nested cross validation to create model
# optimize the model hyperparameter (inner) and test the model performance (outer)
nr.seed(123)
inside = ms.KFold(n_splits=10, shuffle = True)
nr.seed(321)
outside = ms.KFold(n_splits=10, shuffle = True)
# performs the grid search for the optimal model hyperparameter
nr.seed(3456)
## Define the dictionary for the grid search and the model object to search on
param_grid = {"C": [0.1, 1, 10, 100, 1000]}
## Define the logistic regression model
logistic_mod = linear_model.LogisticRegression(class_weight = {0:0.45, 1:0.55})
## Perform the grid search over the parameters
clf = ms.GridSearchCV(estimator = logistic_mod, param_grid = param_grid,
cv = inside, # Use the inside folds
scoring = 'roc_auc',
return_train_score = True)
## Fit the cross validated grid search over the data
clf.fit(Features_reduced, Labels)
## And print the best parameter value
clf.best_estimator_.C
# Result showed the optimal value of the hyperparameter is 1.
# perform the outer loop of the nested cross validation to evaluate the model
nr.seed(498)
cv_estimate = ms.cross_val_score(clf, Features, Labels,
cv = outside) # Use the outside folds
print('Mean performance metric = %4.3f' % np.mean(cv_estimate))
print('SDT of the metric = %4.3f' % np.std(cv_estimate))
print('Outcomes by cv fold')
for i, x in enumerate(cv_estimate):
print('Fold %2d %4.3f' % (i+1, x))
# Result showed The performance metric is not significantly different than for the inner loop of the cross validation.
## -->> Test the model
## Randomly sample cases to create independent training and test data
nr.seed(1115)
indx = range(Features_reduced.shape[0])
indx = ms.train_test_split(indx, test_size = 300)
X_train = Features_reduced[indx[0],:]
y_train = np.ravel(Labels[indx[0]])
X_test = Features_reduced[indx[1],:]
y_test = np.ravel(Labels[indx[1]])
## Define and fit the logistic regression model
logistic_mod = linear_model.LogisticRegression(C = 1, class_weight = {0:0.45, 1:0.55})
logistic_mod.fit(X_train, y_train)
# score the model and display a sample of the resulting probabilities
# threshold = 0.3
def score_model(probs, threshold):
return np.array([1 if x > threshold else 0 for x in probs[:,1]])
probabilities = logistic_mod.predict_proba(X_test)
print(probabilities[:15,:])
scores = score_model(probabilities, 0.3)
# Examine the performance metrics
def print_metrics(labels, probs, threshold):
scores = score_model(probs, threshold)
metrics = sklm.precision_recall_fscore_support(labels, scores)
conf = sklm.confusion_matrix(labels, scores)
print(' Confusion matrix')
print(' Score positive Score negative')
print('Actual positive %6d' % conf[0,0] + ' %5d' % conf[0,1])
print('Actual negative %6d' % conf[1,0] + ' %5d' % conf[1,1])
print('')
print('Accuracy %0.2f' % sklm.accuracy_score(labels, scores))
print('AUC %0.2f' % sklm.roc_auc_score(labels, probs[:,1]))
print('Macro precision %0.2f' % float((float(metrics[0][0]) + float(metrics[0][1]))/2.0))
print('Macro recall %0.2f' % float((float(metrics[1][0]) + float(metrics[1][1]))/2.0))
print(' ')
print(' Positive Negative')
print('Num case %6d' % metrics[3][0] + ' %6d' % metrics[3][1])
print('Precision %6.2f' % metrics[0][0] + ' %6.2f' % metrics[0][1])
print('Recall %6.2f' % metrics[1][0] + ' %6.2f' % metrics[1][1])
print('F1 %6.2f' % metrics[2][0] + ' %6.2f' % metrics[2][1])
def plot_auc(labels, probs):
## Compute the false positive rate, true positive rate
## and threshold along with the AUC
fpr, tpr, threshold = sklm.roc_curve(labels, probs[:,1])
auc = sklm.auc(fpr, tpr)
## Plot the result
plt.title('Receiver Operating Characteristic')
plt.plot(fpr, tpr, color = 'orange', label = 'AUC = %0.2f' % auc)
plt.legend(loc = 'lower right')
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.show()
print_metrics(y_test, probabilities, 0.3)
plot_auc(y_test, probabilities)
# Results showed these performance metrics look quite good.
# But over optimistic resulted from single split evluation
|
472fca79ecd452858dbfe9a8fee77630b02e4b8b | ChloeChepigin/HPM573S18_CHEPIGIN_HW1 | /Question 1.py | 308 | 3.75 | 4 |
x = 17
print ('Setting x =', x)
# integer
y1 = x
print (type(y1))
print ('y1 is a', type(y1))
# float
y2 = float(x)
print (type(y2))
print ('y2 is a', type(y2))
# string
y3 = str(x)
print ('y3 is a ', type(y3))
print ('y3 is a', type(y3))
# boolean, 17 > 2
y4 = bool(x > 2)
print ('y4 is a ', type(y4))
|
6c038b46b9e5901c5fd970ca3741c4c65132c140 | mikeyags1016/100DayCodingChallenge | /flash_card.py | 574 | 3.703125 | 4 | import random
flash_cards = {}
def add_flash_card(front, back):
flash_cards.update({front: back})
def trivia_mode(cards):
selected_keys = []
i = 0
while i < len(cards):
current_selection = random.choice(tuple(cards.keys()))
if current_selection not in selected_keys:
guess = input(current_selection + ": ")
if guess == cards[current_selection]:
selected_keys.append(current_selection)
i += 1
else:
print("Wrong, answer: " + cards[current_selection])
|
2e60abd703a5013e8ee5f7d2ce30b066833a7872 | arnavgupta50/BinarySearchTree | /BinaryTreeTraversal.py | 1,155 | 4.3125 | 4 | #Thsi Program traverses the Binary Tree in 3 Ways: In/Post/Pre-Order
class Node:
def __init__ (self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
if root is None:
return Node(key)
else:
if root.val==key:
return root
elif root.val<key:
root.right=insert(root.right, key)
else:
root.left=insert(root.left, key)
return root
def preorder(root):
if root:
print(root.val)
preorder(root.left)
preorder(root.right)
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)
def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
print(root.val)
r = Node(50)
r = insert(r, 30)
r = insert(r, 20)
r = insert(r, 40)
r = insert(r, 70)
r = insert(r, 60)
r = insert(r, 80)
print("Pre-Order Traversal: ")
preorder(r)
print("In-Order Traversal: ")
inorder(r)
print("Post-Oder Traversal: ")
postorder(r)
|
4f8d6dd2da113c78ec1a158d423910442a561993 | eri3l/skinks | /apps/home.py | 3,074 | 3.71875 | 4 | import streamlit as st
def app():
st.write("## Welcome to the Skink Search Tool app")
st.write("""
The app filters existing skink data by multiple criteria in order to help with the identification of skinks.
Latest data update: 10 Apr 2020. \n
Use the navigation bar to select the type of search you would like to perform.
""")
st.markdown("### Toes")
st.write("Use this option to search by missing toes only")
with st.beta_expander("More information"):
st.markdown("""
- This search filters by all possible combinations of **`missing toes`** and excludes other missing toes. \n
Example:
> `selected toes` = [LF1, LF2] \n
> Results: \n
> The search returns all skinks where [LF1], [LF2], [LF1, LF2] or [none] toes are missing.
""")
st.markdown("### Search")
st.write("Use this option to search by multiple criteria:")
st.markdown("""
- SVL (snout to vent length) (mm) \n
Existing skinks above 70mm are classified as adults and labelled with `projected_SVL`=100
""")
with st.beta_expander("More information"):
st.markdown("""
The search considers matches within 5 mm of the selected length. All skinks above 70 mm (`@adult`) are classified as adults.
In finding matches, it is assumed that skinks grow by **10** mm per year (`@delta`) and reach adult size at **70** mm (`@adult`).
Search is performed on a calculated variable, `projected_SVL`:
```python
projected_SVL= skink_SVL + delta*(current_year – skink_Year)
```
""")
st.markdown("""
- Paddock/traplist \n
Each paddock contains multiple traps, click below to view the full list of traps
""")
with st.beta_expander("See traps"):
st.markdown("""
| Paddock | Traps |
| ------ | ------ |
| pdk_R66 | ['R66', 'board', 'R67', 'M14', 'R68', 'R69', 'R70', 'M11', 'PR1'] |
| pdk_R71 | ['R71', 'PR2', 'R72', 'M9', 'P3', 'PR3', 'R73', 'M8', 'PR4', 'R74', 'M7', 'PR5', 'R75', 'PR6', 'R76', 'M5', 'PR7'] |
| pdk_R77 | ['R2', 'PR13', 'R3', 'PR14', 'R4', 'PR15', 'P16', 'PR16', 'R6', 'PR17'] |
| pdk_R02 | ['W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8', 'W9', 'W10', 'W11', 'W12', 'W13'] |
| ... | ... |
""")
st.markdown("""
- Toes \n
Search by intact or missing toes.
""")
image = 'data/P1060519.jpg'
st.image(image, caption='El pretty skinko', use_column_width = True)
with st.sidebar.beta_expander("About"):
st.markdown(''' Copyright © 2021 Polina Stucke.
This app is open source. You can find it on [GitHub](https://github.com/eri3l/skinks) ''')
|
ee5a5fa8ed15f91074dadc78587bc70671257308 | marleentheyoung/cs_airport | /node.py | 4,187 | 4.0625 | 4 | class Node(object):
def __init__(self, key, value=None):
self.key = key
self.value = value
self.left = None
self.right = None
self.parent = None
self.height = 0
def get_key(self):
"""Return the key of this node."""
return self.key
def get_value(self):
"""Return the value of this node."""
return self.value
def get_parent(self):
"""Return the parent node of this node."""
return self.parent
def get_left_child(self):
"""Return the left child node of this node."""
return self.left
def get_right_child(self):
"""Return the right child node of this node."""
return self.right
def get_height(self):
"""Return the height of this node."""
return self.height
def update_height(self):
"""Update the height based on the height of the left and right nodes."""
if self.left == None and self.right == None:
self.height = 0
else:
self.height = max(self.left.height, self.right.height) + 1
def get_children(self):
if self.right == None and self.left == None:
return 0
return 1
#
# You can add any additional node functions you might need here
#
def __eq__(self, other):
"""Returns True if the node is equal the other node or value."""
if self is other or self.key is other:
return True
if (self is None and other is not None):
return False
if (other is None and self is not None):
return False
if not isinstance(other, int):
if self.key is other.key:
return True
return False
def __neq__(self, other):
"""Returns True if the node is not equal the other node or value."""
if self is not other:
return True
if self.key is not other:
return True
return False
def __lt__(self, other):
"""Returns True if the node is less than the other node or value."""
if isinstance(self, int) and isinstance(other,int):
if self < other:
return True
if self.key < other or self.key < other.key:
return True
if self.value is None or other is None:
return False
if self.value < other:
return True
return False
def __le__(self, other):
"""Returns True if the node is less or equal to the other node or value."""
if isinstance(self, int) and isinstance(other,int):
if self <= other:
return True
if self.key <= other or self.key <= other.key:
return True
if self.value is None or other is None:
return False
if self.value <= other:
return True
return False
def __gt__(self, other):
"""Returns True if the node is greater than the other node or value."""
if isinstance(self, int) and isinstance(other,int):
if self > other:
return True
if self.key > other or self.key > other.key:
return True
if self.value is None or other is None:
return False
if self.value > other:
return True
return False
def __ge__(self, other):
"""Returns True if the node is greater or equal to the other node or value."""
if isinstance(self, int) and isinstance(other,int):
if self >= other:
return True
if self.key >= other or self.key >= other.key:
return True
if self.value is None or other is None:
return False
if self.value >= other:
return True
return False
def __str__(self):
"""Returns the string representation of the node in format: 'key/value'.
If no value is stored, the representation is just: 'key'."""
if self.value != None:
return '{}/{}'.format(self.key, self.value)
return '{}'.format(self.key)
|
4b44a4f293bcf14b0b77d5677159cc5fb90950b5 | walkerwell/algorithm-data_structure | /src/main/python/algorithm/run_LCS.py | 719 | 3.734375 | 4 | def findTheMax(matrix):
index=0
res=matrix[0]
for i in range(len(matrix)):
if matrix[i]>res:
res=matrix[i]
index=i
return res,index
def findDPMatrix(matrix):
dp=[]
for i in range(len(matrix)):
n=1
j=i-1
now_=matrix[i]
while(j>=0):
if now_>matrix[j]:
n+=1
now_=matrix[j]
j-=1
dp.append(n)
return dp
matrix=[2,3,5,9,6]
dp=findDPMatrix(matrix)
print dp
a,b = findTheMax(dp)
print a,b
index=b-1
res=""+(str)(matrix[b])
now_=matrix[b]
while(index>=0):
if(matrix[index]<now_):
res+=(str)(matrix[index])
now_=matrix[index]
index-=1
print res
|
76e1642a0e8364e876237ca27dad46f1ec982cd6 | walkerwell/algorithm-data_structure | /src/main/python/codeforces/run_131A.py | 353 | 3.953125 | 4 | s=raw_input()
allUp=1
otherUp=1
for i in range(len(s)):
if(s[i].islower()):
allUp=0
if(i<>0 and s[i].islower()):
otherUp=0
res=""
for i in range(len(s)):
if(allUp or otherUp):
if(s[i].isupper()):
res+=s[i].lower()
else:
res+=s[i].upper()
else:
res=s
break
print res |
8fa847e2f205c9afb06672ac2bd679810af16e64 | walkerwell/algorithm-data_structure | /src/main/python/codeforces/run_41A.py | 245 | 3.609375 | 4 | a=raw_input()
b=raw_input()
if(len(a)<>len(b)):
print "NO"
exit(0)
else:
index=len(a)-1
i=0
while(index>=0):
if(a[i]<>b[index]):
print "NO"
exit(0)
index-=1
i+=1
print "YES" |
c09e3727d8ad74bdd459a9f4109a282ff5bc636e | walkerwell/algorithm-data_structure | /src/main/python/codeforces/run_69A.py | 168 | 3.546875 | 4 | n=input()
x=0
y=0
z=0
for i in range(n):
x1,y1,z1=(map(int,raw_input().split()))
x+=x1
y+=y1
z+=z1
if((x|y|z)==0):
print "YES"
else:
print "NO"
|
6fafa89090f526c6b7cb9f9b528d0b31eba4e03f | walkerwell/algorithm-data_structure | /src/main/python/codeforces/run_118A.py | 156 | 3.65625 | 4 | s=raw_input().lower()
res=''
for i in range(len(s)):
if s[i] not in ['A','a','O','o','Y','y','E','e','U','u','I','i']:
res+='.'+s[i]
print(res)
|
c2043f1e650a2a770680d1514493c95dd011e3e1 | walkerwell/algorithm-data_structure | /src/main/python/codeforces/run_443A.py | 132 | 3.546875 | 4 | s=raw_input()
m={}
n=len(s)
ignore=['{',',',' ','}']
for i in range(n):
if s[i] not in ignore:
m[s[i]]=s[i]
print len(m) |
eaf45a8f38bcbf4d14bc29d05eff3d9b0fc6cc04 | autumind/huffman_code | /Utils.py | 2,176 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on Jul 22, 2015
@author: shenzb
'''
from Node import Node
def stringToPriorityQueue(text):
'''
Transfer every character of a string to priority queue.
Priority order is according to character's count of the string.
'''
chars = list(text)
char_dict = dict([(c, 0) for c in chars])
for char in chars:
char_dict[char] = char_dict[char] + 1
''' Get a priority queue list. '''
char_list = sorted(char_dict.items(), lambda x, y: cmp(x[1], y[1]))
return char_list
def generateHuffmanTree(nodeList):
'''
Generate a Huffman Tree from a Priority Queue.
'''
nodeNew = nodeList[0].plus(nodeList[1])
nodeNew.setLeftChild(nodeList[0])
nodeNew.setRightChild(nodeList[1])
nodeList.append(nodeNew)
nodeList.pop(0)
nodeList.pop(0)
nodeList.sort(Node.compare)
if len(nodeList) == 1:
return nodeList[0]
return generateHuffmanTree(nodeList);
def generateHuffmanCodes(huffmanTree, curCode, huffmanCode):
'''
Generate Huffman codes from a Huffman Tree.
'''
if huffmanTree.isLeaf():
huffmanCode[huffmanTree.getCharacter()] = curCode
return;
lCode = curCode + "1"
rCode = curCode + "0"
generateHuffmanCodes(huffmanTree.getLeftChild(), lCode, huffmanCode)
generateHuffmanCodes(huffmanTree.getRightChild(), rCode, huffmanCode)
# codeFlg = False
# if huffmanTree.getCharacter() != None:
# codeFlg = True
#
# leftTree = huffmanTree.getLeftChild()
# rightTree = huffmanTree.getRightChild()
#
# if leftTree.hasRealLeft() or leftTree.hasRealRight():
# if codeFlg:
# huffmanCodes[huffmanTree.getCharacter()] = ("").join(seq) + "0"
# return generateHuffmanCodes(leftTree, seq.append("0"), huffmanCodes)
# else:
# return huffmanCodes
#
# if rightTree.hasRealLeft() or rightTree.hasRealRight():
# if codeFlg:
# huffmanCodes[huffmanTree.getCharacter()] = ("").join(seq) + "1"
# return generateHuffmanCodes(rightTree, seq.append("1"), huffmanCodes)
# else:
# return huffmanCodes
|
1ad84fc6335ea62b64fa8370c918c136f55ebf52 | liufengyuqing/PythonPractice | /demo.py | 266 | 3.765625 | 4 |
print("I\'m liuzhiwei\nhello world!")
# 字符串和编码 unicode utf-8
print(ord("A"))
print(chr(66))
print(b"ABC") # 字节
print("ABC") # 字符串 str
print(sum(range(101)))
for i in range(1,101):
print(i,end='\n') if i % 10 == 0 else print(i,end=' ')
|
09df092b48e2059def51ecc22a0bca8ab99befe1 | liufengyuqing/PythonPractice | /DemoPractice.py | 3,439 | 3.671875 | 4 | # coding=utf-8
'''python一个.py文件就是一个包,一个模块
sys 模块是和系统相关的一些对象
os与sys模块的官方解释如下:
os: This module provides a portable way of using operating system dependent functionality.
这个模块提供了一种方便的使用操作系统函数的方法。
sys: This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.
这个模块可供访问由解释器使用或维护的变量和与解释器进行交互的函数。
os 常用方法
os.remove() 删除文件
os.rename() 重命名文件
os.walk() 生成目录树下的所有文件名
os.chdir() 改变目录
os.mkdir/makedirs 创建目录/多层目录
os.rmdir/removedirs 删除目录/多层目录
os.listdir() 列出指定目录的文件
os.getcwd() 取得当前工作目录
os.chmod() 改变目录权限
os.path.basename() 去掉目录路径,返回文件名
os.path.dirname() 去掉文件名,返回目录路径
os.path.join() 将分离的各部分组合成一个路径名
os.path.split() 返回( dirname(), basename())元组
os.path.splitext() 返回 (filename, extension) 元组
作者:Aceeie
链接:https://www.zhihu.com/question/31843617/answer/150854646
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
os.path.getatime\ctime\mtime 分别返回最近访问、创建、修改时间
os.path.getsize() 返回文件大小
os.path.exists() 是否存在
os.path.isabs() 是否为绝对路径
os.path.isdir() 是否为目录
os.path.isfile() 是否为文件
sys 常用方法
sys.argv 命令行参数List,第一个元素是程序本身路径
sys.modules.keys() 返回所有已经导入的模块列表
sys.exc_info() 获取当前正在处理的异常类,exc_type、exc_value、exc_traceback当前处理的异常详细信息
sys.exit(n) 退出程序,正常退出时exit(0)
sys.hexversion 获取Python解释程序的版本值,16进制格式如:0x020403F0
sys.version 获取Python解释程序的版本信息
sys.maxint 最大的Int值
sys.maxunicode 最大的Unicode值
sys.modules 返回系统导入的模块字段,key是模块名,value是模块
sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform 返回操作系统平台名称
sys.stdout 标准输出
sys.stdin 标准输入
sys.stderr 错误输出
sys.exc_clear() 用来清除当前线程所出现的当前的或最近的错误信息
sys.exec_prefix 返回平台独立的python文件安装的位置
sys.byteorder 本地字节规则的指示器,big-endian平台的值是'big',little-endian平台的值是'little'
sys.copyright 记录python版权相关的东西
sys.api_version 解释器的C的API版本
总结:
os模块负责程序与操作系统的交互,提供了访问操作系统底层的接口;
sys模块负责程序与python解释器(interpretor)的交互,提供了一系列的函数和变量,用于操控python的运行时环境。
'''
import sys
import os
sys.stdout.write("Hello World")
print()
print(sys.path)
print(sys.platform)
print(sys.version)
print(sys.argv)
# -------------------------------
#列表解析
print([x * (x + 1) for x in range(1, 100, 2)])
print([x ** 2 for x in range(1, 10)])
print([x for x in range(1, 10) if not x % 2]) # not 偶数
print([x ** 2 for x in range(1, 10) if not x % 2]) # not 偶数
|
0838fcd3cd4ab10f7dffb318fdf9534e7db0e079 | rongduan-zhu/codejam2016 | /1a/c/c.py | 2,061 | 3.578125 | 4 | #!/usr/bin/env python
import sys
class Node:
def __init__(self, outgoing, incoming):
self.outgoing = outgoing
self.incoming = incoming
def solve(fname):
with open(fname) as f:
tests = int(f.readline())
for i in xrange(tests):
f.readline()
deps = map(int, f.readline().split(' '))
two_node_cycles = []
nodes = {}
for j in xrange(1, len(deps) + 1):
# setup outgoing nodes
if j in nodes:
nodes[j].outgoing = deps[j - 1]
else:
nodes[j] = Node(deps[j - 1], [])
# setup incoming nodes
if deps[j - 1] in nodes:
nodes[deps[j - 1]].incoming.append(j)
else:
nodes[deps[j - 1]] = Node(None, incoming=[j])
# setup two node cycles
if nodes[j].outgoing in nodes and j == nodes[nodes[j].outgoing].outgoing:
two_node_cycles.append((j, nodes[j].outgoing))
print 'Case #{}: {}'.format(i + 1, traverse(nodes, two_node_cycles))
def traverse(nodes, two_node_cycles):
bff_cycle = 0
visited = {}
for n1, n2 in two_node_cycles:
visited[n1] = True
visited[n2] = True
bff_cycle += traverse_up(n1, nodes, visited, 1)
bff_cycle += traverse_up(n2, nodes, visited, 1)
for node in nodes:
if node not in visited:
visited_in_path = set()
visited_in_path.add(node)
start = node
current = nodes[start].outgoing
longest_cycle = 1
while current not in visited_in_path:
visited_in_path.add(current)
current = nodes[current].outgoing
longest_cycle += 1
if start == current and longest_cycle > bff_cycle:
bff_cycle = longest_cycle
return bff_cycle
def traverse_up(node, nodes, visited, length):
max_len = length
for up_node in nodes[node].incoming:
if up_node not in visited:
visited[up_node] = True
up_length = traverse_up(up_node, nodes, visited, length + 1)
max_len = up_length if up_length > max_len else max_len
return max_len
if __name__ == '__main__':
solve(sys.argv[1])
|
e6657c32a76d198d60ad812ef1fc5587e8a74465 | subham-paul/Python-Programming | /Swap_Value.py | 291 | 4.1875 | 4 | x = int(input("Enter value x="))
y = int(input("Enter value y="))
print("The value are",x,"and",y)
x = x^y
y = x^y
x = x^y
print("After the swapping value are",x,"and",y)
"""Enter value x=10
Enter value y=20
The value are 10 and 20
After the swapping value are 20 and 10
"""
|
447135a4daada255fa5639f0f36abeb318d17cad | subham-paul/Python-Programming | /SortAlphabetical_41.py | 373 | 3.9375 | 4 | """str=input("Enter Your Word = ")
x=str.split()
print(x)
x.sort()
print(x)
for i in x:
print(i, end=" ")"""
"""
Enter Your Word = i am subham
['i', 'am', 'subham']
['am', 'i', 'subham']
am i subham"""
str=input("Enter Your Word = ")
x=str.split()
x.sort()
for i in x:
print(i, end=" ")
"""
Enter Your Word = i am subham
am i subham
"""
|
e842bcc485fa3a6a7be041b39f5265960a5a0cf0 | subham-paul/Python-Programming | /N_27(b).py | 142 | 3.53125 | 4 | n=int (input("Enter Limit= "))
a=100
b=5
while a>=n:
print(a)
a=a-b
b=b*2
"""
Enter Limit= 5
100
95
85
65
25
"""
|
d1e6842ea9c8182590d29e76c0bb9b1ca2ca0b42 | subham-paul/Python-Programming | /N_27(d).py | 168 | 4.03125 | 4 | n=int (input("Enter number of term= "))
a=5
b=7
for i in range(1,n+1):
print(a)
a=a+b
b=b*2
"""
Enter number of term= 5
5
12
26
54
110
"""
|
41ffd54d227e0e6ccfa31cf3f4bc878c3a7060e4 | subham-paul/Python-Programming | /MaxNo_30.py | 403 | 3.625 | 4 | list=[10,20,30,40,50,60]
print("Max no in the list = ", max(list))
print("Min no in the list = ", min(list))
x = max(list)
y = min(list)
list.remove(x)
list.remove(y)
print()
print("2nd max no in the list = ", max(list))
print("2nd min no in the list = ", min(list))
"""
Max no in the list = 60
Min no in the list = 10
2nd max no in the list = 50
2nd min no in the list = 20
"""
|
772795bb1447e113ef80b22c40d4c35dc38b426b | Alfredo-Diaz-Gomez-2015090154/Compiladores2021B | /Prácticas/P3_AFN_a_AFD_Subconjuntos/AFD.py | 1,429 | 3.609375 | 4 | import copy
class AFD:
def __init__(self, alfabeto):
self.alfabeto = copy.copy(alfabeto)
self.transiciones = {}
def copiar_estados(self, estados_generados):
self.estados = estados_generados.copy()
def copiar_estado_inicial(self, estado_inicial):
self.estado_inicial = estado_inicial
def copiar_estados_finales(self, estados_finales):
self.estados_finales = estados_finales
def agregar_estado(self, estado_actual, entrada, estado_siguiente):
self.transiciones[(estado_actual, entrada)] = estado_siguiente
def determinar_estado_pozo(self, estado_pozo):
self.estado_pozo = estado_pozo
def mostrar_elementos(self):
print(f'Alfabeto: {self.alfabeto}')
print(f'Estados: {self.estados}')
print(f'Estado inicial: {self.estado_inicial}')
print(f'Estados finales: {self.estados_finales}')
print("Transiciones (Sin estado pozo): ")
for llave in self.transiciones.keys():
if not self.transiciones[llave] == self.estado_pozo:
print(f"{llave} -> {self.transiciones[llave]}")
mostrar_pozo = input("¿Mostrar pozo? (1 = Sí): ")
if mostrar_pozo == '1':
for llave in self.transiciones.keys():
if self.transiciones[llave] == self.estado_pozo:
print(f"{llave} -> {self.transiciones[llave]}")
|
6a357090cf6171ce46b4c2fdfc871e731335449a | Alfredo-Diaz-Gomez-2015090154/Compiladores2021B | /Prácticas/P7_Descenso_recursivo/descenso_recursivo_3.py | 971 | 3.609375 | 4 | #cadena = input('Ingresa la cadena a probar: ')
#cadena = "afdea"
#cadena = "bcafdeadfdea"
#cadena = "acafdeadea"
cadena = "afcafdeadea"
longitud_cadena = len(cadena)
indice_actual = 0
def consumir(caracter):
global indice_actual
if indice_actual < longitud_cadena:
if cadena[indice_actual] == caracter:
indice_actual += 1
return True
return False
def A():
if B():
if C():
if D():
if E():
return consumir('a')
return False
def B():
if consumir('b'):
if C():
return D()
return consumir('a')
def C():
if consumir('c'):
return A()
return consumir('f')
def D():
return consumir('d')
def E():
return consumir('e')
def main():
if A() and indice_actual == longitud_cadena:
print("Cadena aceptada.")
else:
print("Cadena NO aceptada.")
if __name__ == "__main__":
main()
|
a83aa31e172236de84390d0031488085aac50120 | JT-Wong/course_homework | /高等数理逻辑/大作业1/code/python/pro_logic.py | 16,604 | 3.5625 | 4 | # -*- coding: utf-8 -*-
import math
import traceback
import sys
def arg_check(pro_logic, i):
temp = ''
while i < len(pro_logic):
if pro_logic[i].isalpha() or pro_logic[i].isdigit():
temp += pro_logic[i]
i += 1
else:
break
return [i - 1, temp]
def syntax_check(pro_logic, custom_logic_list, zero_ele_custom_logic_list):
num_logic_word = ['0', '1']
basic_logic_word = ['¬', '∧', '∨', '⊕']
derivation_word = ['→', '↔']
# 语法检测结果 错误说明 变元列表
result = [True, 'no error', []]
# 检测推导符两边情况
temp_num = pro_logic.count('→')
temp_str = pro_logic.split('→', temp_num)
for s in temp_str:
if s.strip() == '':
result = [False, "→ left or right cnt't be null", []]
return result
temp_num = pro_logic.count('↔')
temp_str = pro_logic.split('↔', temp_num)
for s in temp_str:
if s.strip() == '':
result = [False, " ↔ left or right cnt't be null", []]
return result
i = 0
# 状态
state = 0
'''
0 : begin ( → ↔
1 : 0 1
2 : 命题变元 ) custome_end
3 : ¬
4 : ∧ ∨ ⊕
5 : custome_begin
'''
# 括号栈
bracket_stack = []
# 判断是否还在custom内,括号全匹配上
custom_stack = 0
try:
while i < len(pro_logic):
if state == 0 or state == 3 or state == 4:
if pro_logic[i] == ' ':
pass
elif pro_logic[i] == '0' or pro_logic[i] == '1':
state = 1
elif pro_logic[i].isalpha():
arg_result = arg_check(pro_logic, i)
# 更新下标
i = arg_result[0]
# 添加变元
arg_name = arg_result[1]
# 普通命题变元
if arg_name not in custom_logic_list:
if arg_name not in result[2] and arg_name not in zero_ele_custom_logic_list:
result[2].append(arg_name)
state = 2
# 自定义逻辑联结词
else:
state = 5
elif pro_logic[i] == '¬':
state = 3
elif pro_logic[i] == '(':
# 记录当且状态
bracket_stack.append(state)
state = 0
if custom_stack > 0 :
custom_stack += 1
else:
result = [False, 'error in ' + pro_logic[i - 1:i + 1], []]
break
i += 1
elif state == 1 or state == 2:
if pro_logic[i] == ' ':
pass
elif pro_logic[i] == '∧' or pro_logic[i] == '∨' or pro_logic[i] == '⊕':
state = 4
elif pro_logic[i] == '→' or pro_logic[i] == '↔':
state = 0
elif pro_logic[i] == ')':
bracket_stack.pop()
if custom_stack > 0 :
custom_stack -= 1
elif pro_logic[i] == ',' and custom_stack > 0:
state = 0
else:
result = [False, 'error in ' + pro_logic[i - 1:i + 1], []]
break
i += 1
elif state == 5:
if pro_logic[i] == '(':
bracket_stack.append(state)
custom_stack += 1
state = 0
else:
result = [False, 'error in ' + pro_logic[i - 1:i + 1], []]
break
i += 1
else:
print('error state')
result = [False, 'error in ' + pro_logic[i-1:i+1], []]
break
except:
result = [False, 'error in ' + pro_logic[i - 1:i + 1], []]
if result[0] == True :
if len(bracket_stack) != 0:
result = [False, 'lost )', []]
if state == 0 or state == 1 or state == 2 :
pass
else:
result = [False, 'proposition not complete', []]
return result
# 基本逻辑联结词的计算
def basic_logic_calculate(arg1, arg2, op):
result = 0
if op == '∧':
result = int(arg1) and int(arg2)
elif op == '∨':
result = int(arg1) or int(arg2)
elif op == '⊕':
result = int(arg1) ^ int(arg2)
elif op == '→':
if int(arg1) == 1 and int(arg2) == 0:
result = 0
else:
result = 1
elif op == '↔':
if int(arg1) == int(arg2):
result = 1
else:
result = 0
return result
# 自定义逻辑联结词的计算
def custom_logic_calculate(custom_logic_word, pro_logic, custom_logic_list, zero_ele_custom_logic_list, true_table, true_table_id, begin_index):
end_index = len(pro_logic) - 1
result = [0, end_index]
arg_value_list = []
# 括号栈
bracket_stack = 0
i = begin_index
if pro_logic[i] == '(':
bracket_stack += 1
i += 1
else:
print('lost ( after ' + str(custom_logic_word))
sys.exit(0)
element_num = 0
element = ''
while i < len(pro_logic):
if pro_logic[i] == ' ':
pass
elif pro_logic[i] == '(':
bracket_stack += 1
element += pro_logic[i]
elif pro_logic[i] == ')':
bracket_stack -= 1
element += pro_logic[i]
# 收集到自定义逻辑联结词的一个完整命题变元
elif pro_logic[i] == ',' and bracket_stack == 1:
temp_result = formula_calculate(element, custom_logic_list, zero_ele_custom_logic_list, true_table, true_table_id, 0, False)
if temp_result[0] == 0 or temp_result[0] == 1:
arg_value_list.append(temp_result[0])
else:
arg_value_list.append(0)
element = ''
element_num += 1
else:
element += pro_logic[i]
# 整个自定义的逻辑联结词结束
if bracket_stack <= 0:
if element[-1] == ')':
element = element[:-1]
temp_result = formula_calculate(element, custom_logic_list, zero_ele_custom_logic_list, true_table, true_table_id, 0, False)
if temp_result[0] == 0 or temp_result[0] == 1:
arg_value_list.append(temp_result[0])
else:
arg_value_list.append(0)
element = ''
element_num += 1
result[1] = i
break
i += 1
if element_num != int(custom_logic_list[custom_logic_word][0]):
print(custom_logic_word + ' element num is not right')
sys.exit(0)
arg_value_str = ''
for arg_value in arg_value_list:
arg_value_str += str(arg_value)
result[0] = int(custom_logic_list[custom_logic_word][1][int(arg_value_str,2)])
return result
# 对左右两侧的命题进行计算
# 出现¬和(时进行递归运算
def formula_calculate(pro_logic, custom_logic_list, zero_ele_custom_logic_list, true_table, true_table_id, begin_index, not_mark):
end_index = len(pro_logic) - 1
result = [0, end_index] #end_index 已分析的下标
arg_1 = -1
arg_2 = -1
if not_mark:
op = '¬'
else:
op = ''
i = begin_index
try:
while i < len(pro_logic):
if pro_logic[i] == ' ':
pass
elif pro_logic[i] == '0' or pro_logic[i] == '1':
if op == '':
if arg_1 == -1:
arg_1 = int(pro_logic[i])
else:
print('error in ' + pro_logic[i-1:i+1])
sys.exit(0)
# 正确处理后要返回
elif op == '¬':
if arg_1 == -1:
arg_1 = 1 ^ int(pro_logic[i])
result[0] = arg_1
result[1] = i
return result
else:
print('error in ' + pro_logic[i - 1:i + 1])
sys.exit(0)
else:
if arg_1 == -1:
print('error in ' + pro_logic[i - 1:i + 1])
sys.exit(0)
else:
arg_1 = basic_logic_calculate(arg_1, pro_logic[i], op)
op = ''
elif pro_logic[i].isalpha():
arg_result = arg_check(pro_logic, i)
i = arg_result[0]
arg_name = arg_result[1]
# 自定义逻辑联结词
if arg_name in custom_logic_list:
temp_result = custom_logic_calculate(arg_name, pro_logic, custom_logic_list, zero_ele_custom_logic_list, true_table, true_table_id, i + 1)
arg_value = temp_result[0]
i = temp_result[1]
elif arg_name in zero_ele_custom_logic_list:
arg_value = zero_ele_custom_logic_list[arg_name]
else:
arg_value = true_table[arg_name][true_table_id]
if op == '':
if arg_1 == -1:
arg_1 = int(arg_value)
else:
print('error in ' + pro_logic[i - 1:i + 1])
sys.exit(0)
elif op == '¬':
if arg_1 == -1:
arg_1 = 1 ^ int(arg_value)
result[0] = arg_1
result[1] = i
return result
else:
print('error in ' + pro_logic[i - 1:i + 1])
sys.exit(0)
else:
if arg_1 == -1:
print('error in ' + pro_logic[i - 1:i + 1])
sys.exit(0)
else:
arg_1 = basic_logic_calculate(arg_1, arg_value, op)
op = ''
elif pro_logic[i] == '∧' or pro_logic[i] == '∨' or pro_logic[i] == '⊕':
if op == '' :
op = pro_logic[i]
else:
result[0] = -1
return result
elif pro_logic[i] == '→' or pro_logic[i] == '↔':
if op == '' :
op = pro_logic[i]
else:
print('error in ' + pro_logic[i - 1:i + 1])
sys.exit(0)
elif pro_logic[i] == '¬':
temp_result = formula_calculate(pro_logic, custom_logic_list, zero_ele_custom_logic_list, true_table, true_table_id, i+1, True)
arg_value = int(temp_result[0])
i = temp_result[1]
if op == '':
if arg_1 == -1:
arg_1 = int(arg_value)
else:
print('error in ' + pro_logic[i - 1:i + 1])
sys.exit(0)
elif op == '¬':
if arg_1 == -1:
arg_1 = 1 ^ int(arg_value)
result[0] = arg_1
result[1] = i
return result
else:
print('error in ' + pro_logic[i - 1:i + 1])
sys.exit(0)
else:
if arg_1 == -1:
print('error in ' + pro_logic[i - 1:i + 1])
sys.exit(0)
else:
arg_1 = basic_logic_calculate(arg_1, arg_value, op)
op = ''
elif pro_logic[i] == '(':
temp_result = formula_calculate(pro_logic, custom_logic_list, zero_ele_custom_logic_list, true_table, true_table_id, i+1, False)
arg_value = temp_result[0]
i = temp_result[1]
if op == '':
if arg_1 == -1:
arg_1 = int(arg_value)
else:
print('error in ' + pro_logic[i - 1:i + 1])
sys.exit(0)
elif op == '¬':
if arg_1 == -1:
arg_1 = 1 ^ int(arg_value)
result[0] = arg_1
result[1] = i
return result
else:
print('error in ' + pro_logic[i - 1:i + 1])
sys.exit(0)
else:
if arg_1 == -1:
print('error in ' + pro_logic[i - 1:i + 1])
sys.exit(0)
else:
arg_1 = basic_logic_calculate(arg_1, arg_value, op)
op = ''
elif pro_logic[i] == ')':
if arg_1 == -1:
print('error in ' + pro_logic[i - 1:i + 1])
sys.exit(0)
else:
result[0] = arg_1
result[1] = i
return result
else:
print('error in ' + pro_logic[i - 1:i + 1])
sys.exit(0)
i += 1
except Exception as e:
traceback.print_exc()
result[0] = arg_1
return result
def pro_logic_check(pro_logic, custom_logic_list, zero_ele_custom_logic_list, var_list):
result = 'always true / always false / true status : '
# 命题逻辑成立时的真值表列数
true_states = []
true_table = {}
for var in var_list:
true_table[var] = []
# 生成真值表
var_num = len(var_list)
for i in range(int(math.pow(2, var_num))):
true_table_str = bin(i)[2:]
while len(true_table_str) < var_num:
true_table_str = '0' + true_table_str
for j in range(var_num):
true_table[var_list[j]].append(int(true_table_str[j]))
# 以→和↔切分命题公式
temp = '(' + pro_logic + ')'
i = 0
while i < len(temp):
if temp[i] == '→' or temp[i] == '↔':
# 填充右边的括号
j = i + 1
bracket_stack = 0
while j < len(temp):
if temp[j] == '(':
bracket_stack += 1
elif temp[j] == ')':
bracket_stack -= 1
if bracket_stack < 0:
temp = temp[:j] + ')' + temp[j:]
break
elif temp[j] == '→' or temp[j] == '↔':
temp = temp[:j] + ')' + temp[j:]
break
else:
pass
j += 1
temp = temp[:i+1] + '(' + temp[i+1:]
# 填充左边的括号
j = i - 1
bracket_stack = 0
while j >= 0:
if temp[j] == ')':
bracket_stack += 1
elif temp[j] == '(':
bracket_stack -= 1
if bracket_stack < 0:
temp = temp[:j+1] + '(' + temp[j+1:]
i += 1
break
else:
pass
j -= 1
temp = temp[:i] + ')' + temp[i:]
i += 1
i += 1
pro_logic = temp
# 根据真值表进行计算
for true_table_id in range(int(math.pow(2, var_num))):
logic_result = formula_calculate(pro_logic, custom_logic_list, zero_ele_custom_logic_list, true_table, true_table_id, 0, False)
if logic_result[0] == 1:
true_states.append(true_table_id)
if len(true_states) == 0:
result = 'always false'
elif len(true_states) == int(math.pow(2, var_num)):
result = 'always true'
else:
result = 'true states: ' + '\n'
temp_str = ''
for true_table_id in true_states:
for var in var_list:
temp_str += var + ' : ' + str(true_table[var][true_table_id]) + ' , '
temp_str = temp_str.strip().strip(',') + '\n'
result += temp_str
temp_str = ''
print(pro_logic)
return result |
9b25d5790a8f26477bf55a453a0fced4653a74a8 | EoinDavey/Competitive | /Codeforces/NCPC2018/b.py | 215 | 3.609375 | 4 | N = input()
xs = raw_input().split()
ind = 1
b = False
for x in xs:
if x != "mumble" and int(x)!=ind:
b = True
break
ind+=1
if b:
print "something is fishy"
else:
print "makes sense"
|
fd011effa4b26145b463eeff422ff932f2fe4a8a | EoinDavey/Competitive | /ProjectEuler/p57.py | 495 | 3.5 | 4 | two = (2,1)
one = (1,1)
half = (1,2)
def oneover((x,y)):
return (y,x)
def red((t,b)):
g = gcd(t,b)
return (t/g,b/g)
def gcd(a,b):
while b!=0:
a,b = b,a%b
return a
def add((x1,y1),(x2,y2)):
t = x1*y2 + x2*y1
b = y1*y2
return (t,b)
def check((t,b)):
return len(str(t)) > len(str(b))
cnt = 0
for n in range(1000):
t = half
for x in range(n):
t = oneover(add(two,t))
t = red(add(one,t))
if check(t):
cnt+=1
print cnt
|
0e4afa54ef2d958f9cd1536f46d2fcef75e606ee | EoinDavey/Competitive | /IrlCPC_2019/8.py | 418 | 3.578125 | 4 | def bsub(n):
if n[0] != 'B':
return "bo-b"+n[1:]
return "bo-"+n[1:]
def fsub(n):
if n[0] != 'F':
return "fo-f"+n[1:]
return "fo-"+n[1:]
def msub(n):
if n[0] != 'M':
return "mo-m"+n[1:]
return "mo-"+n[1:]
name = input()
print(', '.join([name, name, bsub(name)]))
print(', '.join(["bo-na-na fanna", fsub(name)]))
print(', '.join([("fee fi %s" % msub(name)), name+"!"]))
|
dd4bbc6f0daf8c6dcb588595d7cfd1644e6d54b0 | EoinDavey/Competitive | /IrlCPC_2019/3.py | 736 | 3.671875 | 4 | def anagram(s):
freqs = {}
for i in s:
if i not in freqs:
freqs[i] = 1
else:
freqs[i] += 1
odd = 0
for k, v in freqs.items():
if v % 2 != 0:
odd += 1
if odd > 1:
return False
return True
def tolower(i):
if (i >= 'A' and i <= 'Z') :
return chr(ord('a') + (ord(i) - ord('A')))
return i
N = int(input())
ans = []
for i in range(N):
stripped = []
s = input()
for j in s:
if (j >= 'A' and j <= 'Z') or (j >= 'a' and j <= 'z'):
stripped.append(tolower(j))
if anagram(stripped):
ans.append(1)
else:
ans.append(0)
print(" ".join(list(map(str, ans))))
|
8edf258a0f792d00fd8ee454206b27eb28e7c9fb | EoinDavey/Competitive | /AdventOfCode2020/d3.py | 593 | 3.515625 | 4 | import sys
from functools import reduce
def lines():
return [line.strip() for line in sys.stdin]
board = lines()
assert(all(map(lambda x: len(x) == len(board[0]), board)))
def get(x, y):
return board[x][y % len(board[0])]
def slopeHits(dx, dy):
x, y = 0, 0
cnt = 0
while x < len(board):
if get(x, y) == '#':
cnt += 1
x, y = x + dx, y + dy
return cnt
def partA():
print(slopeHits(1, 3))
def partB():
slopes = [(1, 1), (1, 3), (1, 5), (1, 7), (2, 1)]
hits = [slopeHits(x, y) for (x, y) in slopes]
print(reduce(lambda x, y: x * y, hits))
partA()
partB()
|
306114d6906e93e154cf9179154ff76dc95ef316 | EoinDavey/Competitive | /IEEEPractice/Food_Truck.py | 1,040 | 3.515625 | 4 | import sys
from math import asin, sqrt
import math
def sin(x):
return math.sin(math.radians(x))
def cos(x):
return math.cos(math.radians(x))
R = 6378.137
def toD(inp):
d = inp[0]
date, time = d.split(' ')
MM, dd, yy = date.split('/')
hh, mm = time.split(':')
return ':'.join([yy,MM,dd,hh,mm])
def sqr(x):
return x*x
def hav(lat1, lon1, lat2, lon2):
ans = 2 * R * asin(sqrt(sqr(sin((lat1 - lat2)/2)) + cos(lat1) * cos(lat2) * sqr(sin((lon1 - lon2)/2))))
return ans
def solve():
lines = [x.rstrip() for x in sys.stdin.readlines()]
lat1, lon1 = [float(x) for x in lines[0].split(',')]
r = float(lines[1])
splits = [x.split(',') for x in lines[3:]]
splits.sort(key=toD)
phoneMap = {}
for entry in splits:
phoneMap[entry[-1]] = (entry[1], entry[2])
out = []
for phone, (lat, lon) in phoneMap.items():
if hav(lat1, lon1, float(lat), float(lon)) <= r:
out.append(phone)
out.sort()
print(','.join(map(str, out)))
solve()
|
5397d98bcd790bfdb458805e8a65ef7ef5e1412f | EoinDavey/Competitive | /Kattis/Ascii_Figure.py | 493 | 3.640625 | 4 | def rep(x):
if x=='-':
return '|'
if x=='|':
return '-'
return x
def rotate(lines):
mxlen = max(map(len,lines))
lines = map(lambda x: x+"".join([" "]*(mxlen-len(x))),lines)
rot = map(lambda x: map(rep,list(x)[::-1]),zip(*lines))
print "\n".join(map(lambda x:"".join(x).rstrip(),rot))
b = False
while 1:
n = input()
if n==0:
break
if b:
print ""
b=True
lines = [raw_input() for _ in xrange(n)]
rotate(lines)
|
972ffdb7d618ea6487bbb12255efead9da55b5e0 | gr4yh4t-0/XRF-dev | /XRF-dev/play-using-import/importASCII_shrink.py | 1,434 | 3.671875 | 4 | import pandas as pd
path_to_ASCIIs = input("Enter path to ASCIIs here: ")
#notes:
# local file does not have global list EOI = [Cd_L, Cu, ...]. prompt for input?
#MAPS saves column headers with whitespace, this function is used to remove that whitespace
def noColNameSpaces(pd_csv_df):
old_colnames = pd_csv_df.columns.values
new_colnames = []
for name in old_colnames:
new_colnames.append(name.strip())
pd_csv_df.rename(columns = {i:j for i,j in zip(old_colnames,new_colnames)}, inplace=True)
return pd_csv_df
def shrinkASCII(large_ASCII_files):
smaller_dfs = []
for scan in large_ASCII_files:
csvIn = pd.read_csv(path_to_ASCIIs + r'/combined_ASCII_2idd_0{n}.h5.csv'.format(n = scan['Scan #']), skiprows = 1)
noColNameSpaces(csvIn) #removes whitspaces from column headers, for easy access
shrink1 = csvIn[['x pixel no', 'y pixel no', 'ds_ic']] #isolates x,y,and electrical columns
shrink2 = csvIn[EOI] #isolates element of interest columns
shrink = pd.concat([shrink1, shrink2], axis=1, sort=False) #combines these columns into one matrix while maintaining indices
smaller_dfs.append(shrink) #add smaller matrices to list so they may be iterated over...
return smaller_dfs
|
718b0686abd46dcdb548c456635035929c52d355 | rheehot/baekjoon-4 | /5397 키로거.py | 451 | 3.53125 | 4 | n = int(input())
for i in range(n):
L=input()
stack1 = []
stack2 = []
for x in L:
if x=='<':
if stack1:
stack2.append(stack1.pop())
elif x=='>':
if stack2:
stack1.append(stack2.pop())
elif x=='-':
if stack1:
stack1.pop()
else:
stack1.append(x)
stack1.extend(stack2[::-1])
print("".join(stack1))
|
dc85f7b9c68a142939a54c207665a87fab4947f3 | mzaira/brightNetwork | /python/src/video_player.py | 14,258 | 3.703125 | 4 | """A video player class."""
import random
from .video_library import VideoLibrary
class VideoPlayer:
"""A class used to represent a Video Player."""
cnt_video = None
state = None
playlist = {}
flagged = {}
def __init__(self):
self._video_library = VideoLibrary()
def number_of_videos(self):
"""Counting the number of videos in the library."""
num_videos = len(self._video_library.get_all_videos())
print(f"{num_videos} videos in the library")
def show_all_videos(self):
"""Showing all videos from the library"""
list_videos = self._video_library.get_all_videos()
for row_videos in list_videos:
id = row_videos.video_id
if row_videos.video_id in self.flagged:
print(f"{row_videos._title} ({id}) [{row_videos._tags}] - FLAGGED "
f"(reason: {self.flagged.get(id)})")
else:
print(f"{row_videos._title} ({id}) [{row_videos._tags}]")
def play_video(self, video_id):
"""Plays the respective video.
Args:
video_id: The video_id to be played.
"""
video = self._video_library.get_video(video_id)
if video == None:
print("Cannot play video: Video does not exist")
else:
if video_id in self.flagged:
print(f"Cannot play video: Video is currently flagged "
f"(reason: {self.flagged.get(video_id)})")
else:
"""If a video is currently playing, display a note that this video will be stopped."""
if self.cnt_video != None:
self.stop_video()
print(f"Playing video: {video.title}")
self.cnt_video = video_id
self.state = "Play"
else:
print(f"Playing video: {video.title}")
self.cnt_video = video_id
self.state = "Play"
def stop_video(self):
"""Stops the current video."""
video = self._video_library.get_video(self.cnt_video)
if self.cnt_video == None:
print("Cannot stop video: No video is currently playing")
else:
print(f"Stopping video: {video.title}")
self.cnt_video = None
self.state = None
def play_random_video(self):
"""Plays a random video from the video library."""
list_videos = self._video_library.get_all_videos()
video = random.choice(list_videos)
video_id = video.video_id
"""For the random play will not play a same video as the currently playing video."""
if video_id in self.flagged or self.cnt_video == video_id:
self.play_random_video()
else:
self.play_video(video_id)
def pause_video(self):
"""Pauses the current video."""
video = self._video_library.get_video(self.cnt_video)
if self.cnt_video == None:
print("Cannot pause video: No video is currently playing")
else:
if self.state == "Pause":
print(f"Video already paused: {video.title}")
self.stop_video()
self.state = None
else:
print(f"Pausing video: {video.title}")
self.state = "Pause"
def continue_video(self):
"""Resumes playing the current video."""
video = self._video_library.get_video(self.cnt_video)
if self.cnt_video == None:
print("Cannot continue video: No video is currently playing")
else:
if self.state == "Play":
print("Cannot continue video: Video is not paused")
else:
print(f"Continuing video: {video.title}")
self.state = "Play"
def show_playing(self):
"""Displays video currently playing."""
video = self._video_library.get_video(self.cnt_video)
if self.cnt_video == None:
print("No video is currently playing")
else:
"""Display if the current video is paused."""
if self.state == "Pause":
print(f"Currently playing: {video.title} {video.video_id} {video.tags} - PAUSED")
else:
print(f"Currently playing: {video.title} {video.video_id} {video.tags}")
def create_playlist(self, playlist_name):
"""Creates a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
if playlist_name not in self.playlist:
self.playlist.update({playlist_name: []})
print(f"Successfully created new playlist: {playlist_name}")
else:
print("Cannot create playlist: A playlist with the same name already exists")
def add_to_playlist(self, playlist_name, video_id):
"""Adds a video to a playlist with a given name.
Args:
playlist_name: The playlist name.
video_id: The video_id to be added.
"""
video = self._video_library.get_video(video_id)
id = video.video_id
if playlist_name not in self.playlist:
print(f"Cannot add video to {playlist_name}: Playlist does not exist")
else:
if video == None:
print(f"Cannot add video to {playlist_name}: Video does not exist")
else:
if id in self.flagged:
print(f"Cannot add video to {playlist_name}: Video is currently flagged "
f"(reason: {self.flagged.get(id)})")
else:
if video_id in self.playlist[playlist_name]:
print(f"Cannot add video to {playlist_name}: Video already added")
else:
self.playlist[playlist_name].append(video_id)
print(f"Added video to {playlist_name}: {video.title}")
def show_all_playlists(self):
"""Display all playlists."""
if len(self.playlist) == 0:
print("No playlists exist yet")
else:
print("Showing all playlists: ")
for key, value in self.playlist.items():
"""Count the number of values in the specific key (dictionary)."""
count = len([item for item in value if item])
string = "videos"
if count <= 1:
string = "video"
print(f" {key} ({count} {string})")
def show_playlist(self, playlist_name):
"""Display all videos in a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
if playlist_name in self.playlist:
if len(self.playlist[playlist_name]) != 0:
for values in self.playlist[playlist_name]:
video = self._video_library.get_video(values)
video_id = video.video_id
if video.video_id in self.flagged:
print(f" {video.title} ({video_id}) [{video.tags}] - FLAGGED "
f"(reason: {self.flagged.get(video_id)})")
else:
print(f" {video.title} ({video_id}) [{video.tags}]")
else:
print(" No videos are here yet")
else:
print(f"Cannot show playlist {playlist_name}: Playlist does not exist")
def remove_from_playlist(self, playlist_name, video_id):
"""Removes a video to a playlist with a given name.
Args:
playlist_name: The playlist name.
video_id: The video_id to be removed.
"""
video = self._video_library.get_video(video_id)
if playlist_name not in self.playlist:
print(f"Cannot remove video from {playlist_name}: Playlist does not exist")
else:
if video == None:
print(f"Cannot remove video from {playlist_name}: Video does not exist")
else:
if video_id not in self.playlist[playlist_name]:
print(f"Cannot remove video from {playlist_name}: Video is not in playlist")
else:
self.playlist[playlist_name].remove(video_id)
print(f"Removed video from {playlist_name}: {video.title}")
def clear_playlist(self, playlist_name):
"""Removes all videos from a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
if playlist_name not in self.playlist:
print(f"Cannot clear playlist {playlist_name}: Playlist does not exist")
else:
self.playlist[playlist_name].clear()
print(f"Successfully removed all videos from {playlist_name}")
self.show_playlist(playlist_name)
def delete_playlist(self, playlist_name):
"""Deletes a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
if playlist_name not in self.playlist:
print(f"Cannot delete playlist {playlist_name}: Playlist does not exist")
else:
del self.playlist[playlist_name]
print(f"Deleted playlist: {playlist_name}")
def play_input(self, video):
"""Input the corresponding number of a video to be able to play it."""
new_input = input("Would you like to play any of the above? If yes, specify the number of the video. "
"If your answer is not a valid number, we will assumes it's a no. \n")
if new_input in video:
self.play_video(video.get(new_input))
def search_videos(self, search_term):
"""Display all the videos whose titles contain the search_term.
Args:
search_term: The query to be used in search.
"""
list_videos = self._video_library.get_all_videos()
search_set = set()
search = []
count = 0
play_video = {}
for row_videos in list_videos:
video_id = row_videos._video_id
search_set.add(video_id)
"""Filtering out videos that doesn't match the search_term."""
search = [s for s in search_set if search_term.lower() in s]
"""Removing videos that are 'flagged'."""
for each in search:
if each in self.flagged:
search.remove(each)
if search == []:
print(f"No search results for {search_term}")
else:
for each in search:
video = self._video_library.get_video(each)
count += 1
print(f"{count}) {video.title} ({video.video_id}) [{video.tags}]")
play_video.update({str(count): video.video_id})
self.play_input(play_video)
def search_videos_tag(self, video_tag):
"""Display all videos whose tags contains the provided tag.
Args:
video_tag: The video tag to be used in search.
"""
list_videos = self._video_library.get_all_videos()
search_dict = dict()
search = []
count = 0
play_video = {}
for row_videos in list_videos:
tags = row_videos._tags
video_id = row_videos._video_id
search_dict.update({video_id: list(tags)})
"""Filter the videos with tags that matches the video_tag."""
for key, value in search_dict.items():
if video_tag in value:
search.append(key)
"""Removing the 'flagged' videos."""
for each in search:
if each in self.flagged:
search.remove(each)
if search == []:
print(f"No search results for {video_tag}")
else:
for each in search:
video = self._video_library.get_video(each)
count += 1
print(f"{count}) {video.title} ({video.video_id}) [{video.tags}]")
play_video.update({str(count): video.video_id})
self.play_input(play_video)
def flag_video(self, video_id, flag_reason=""):
"""Mark a video as flagged.
Args:
video_id: The video_id to be flagged.
flag_reason: Reason for flagging the video.
"""
video = self._video_library.get_video(video_id)
if flag_reason == "":
flag_reason = "Not supplied"
if video == None:
print("Cannot flag video: Video does not exist")
else:
if video_id in self.flagged:
print("Cannot flag video: Video is already flagged")
else:
if self.cnt_video != None:
self.stop_video()
print(f"Successfully flagged video: {video.title} (reason: {flag_reason})")
self.flagged.update({video_id: flag_reason})
else:
print(f"Successfully flagged video: {video.title} (reason: {flag_reason})")
self.flagged.update({video_id: flag_reason})
def allow_video(self, video_id):
"""Removes a flag from a video.
Args:
video_id: The video_id to be allowed again.
"""
video = self._video_library.get_video(video_id)
if video == None:
print("Cannot remove flag from video: Video does not exist")
else:
if video_id not in self.flagged:
print("Cannot remove flag from video: Video is not flagged")
else:
print(f"Successfully removed flag from video: {video.title}")
del self.flagged[video_id]
|
fa6d1b896e49611c68e011d7caebebffafac604e | Gressia/T07_ChambergoG.VilchezA | /Chambergo/Ejercicio_para3.py | 109 | 3.765625 | 4 | #Ejercicio_03
a=5
max=450
while(a <= max):
print("a",a)
a=a+5
#fin_while
print("programa culminado")
|
35b1ebc683ad9eef39240550cbd39033afd69168 | Gressia/T07_ChambergoG.VilchezA | /Vilchez/ejercicio.mientras05.py | 254 | 3.796875 | 4 | # Programa 05
rpta=""
rpta_invalida=(rpta!="gano" and rpta!="sigue intentando")
while(rpta_invalida):
rpta=input("Ingrese rpta(gano o sigue intentando):")
rpta_invalida=(rpta!="gano" and rpta!="sigue intentando")
#fin_while
print("rpta:",rpta)
|
eafda40ba1154d3f8d02c01d9b827f93f3d7edc6 | audflexbutok/Python-Lab-Source-Codes | /audrey_cooper_501_2.py | 1,788 | 4.3125 | 4 | # Programmer: Audrey Cooper
# Lab Section: 502
# Lab 3, assignment 2
# Purpose: To create a menu driven calculator
# set calc equal to true so it runs continuously
calc = True
while calc == True:
# adds two numbers
def add(x, y):
return x + y
# subtracts two numbers
def subtract(x, y):
return x - y
# multiplies two numbers
def multiply(x, y):
return x * y
# divides two numbers
def divide(x, y):
return x / y
# menu driven portion that allows user to select operation
print("Select operation.")
print("1. Add ")
print("2. Subtract ")
print("3. Multiply ")
print("4. Divide ")
print("5. Exit ")
# user input for operation choice
choice = input("Enter choice(1/2/3/4/5):")
# user input for number choice to perform operation
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
# statements to perform the correct operations and print their results
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
elif choice == '5':
break
else:
# input validation
print("Invalid input")
'''
IDLE Output
Select operation.
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter choice(1/2/3/4/5):4
Enter first number: 2
Enter second number: 2
2 / 2 = 1.0
Select operation.
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter choice(1/2/3/4/5):
'''
|
71c813eeaea12d9f0b3791bbbf7c2c92fcaf391f | dedx/PHYS200 | /Ch7-Ex7.4.py | 797 | 4.46875 | 4 | #################################
#
# ThinkPython Exercise 7.4
#
# J.L. Klay
# 30-Apr-2012
#
# Exercise 7.4 The built-in function eval takes a string and evaluates
# it using the Python interpreter. For example:
# >>> eval('1 + 2 * 3')
# 7
# >>> import math
# >>> eval('math.sqrt(5)')
# 2.2360679774997898
# >>> eval('type(math.pi)')
# <type 'float'>
# Write a function called eval_loop that iteratively prompts the user,
# takes the resulting input and evaluates it using eval, and prints the
# result.
# It should continue until the user enters 'done', and then return the
# value of the last expression it evaluated.
#
#
import math
def eval_loop():
while True:
line = raw_input('> ')
if line == 'done':
break
last = eval(line)
print last
print last
eval_loop()
|
1610e07843f5ea10192ceaf02101e9667c5bb934 | stuffyUdaya/Python | /1-9-17/looping.py | 392 | 3.78125 | 4 | # for x in range(1,20):
# print "I am good at coding",x
# my_list = [2,5,9,['carrot','lettuce'],78,90]
# for element in my_list:
# print element
# WHILE LOOP
# count = 0
# while(count<10):
# print "I love to code", count
# count= count+1
# BREAK AND CONTINUE
for val in "Hello":
if val == "l":
break
# continue
print val
|
d91dcff8fa9263c1c31e2b755001808fe041caa3 | stuffyUdaya/Python | /1-9-17/getandprintavg.py | 120 | 3.59375 | 4 | arr = [5,7,9,65,45]
sum =0
for x in range(0,len(arr)):
sum = sum+arr[x]
avg = sum/len(arr)
print sum
print avg
|
e5ed52cb751dad2071aa88dee39ee68fa02b4f44 | stuffyUdaya/Python | /1-9-17/swapstringfornegval.py | 115 | 3.5 | 4 | arr = [35,40,2,1,-8,7,-30]
for x in range(0,len(arr)):
if(arr[x]<0):
arr[x] = "Dojo"
print arr
|
2f319d09ef1183f75623fdc10fe226c371eba85f | stuffyUdaya/Python | /1-9-17/strings.py | 305 | 4.15625 | 4 | name = "hello world!"
lname = "This is Udaya"
print "Welcome",lname
print "Welcome"+lname
print "Hi {} {}".format(name,lname)
print name.capitalize()
print name.lower()
print name.upper()
print name.swapcase()
print name.find("l")
print lname.replace("Udaya","UdayaTummala")
print name.replace("o","0",1)
|
81e67608971d0d9f305a8fc15791880534e92891 | harshmalani007/python | /vowels.py | 224 | 4.0625 | 4 | ha = input ("Enter a char: ")
if(ha=='A' or ha=='a' or ha=='E' or ha =='e' or ha=='I'
or ha=='i' or ha=='O' or ha=='o' or ha=='U' or ha=='u'):
print(ha, "is a Vowels")
else:
print(ha, "is a Consonants")
|
f1ddf4f31c1f8a99a6a0d81dd68c9bd050a03f49 | ParkJH1/ML-Example | /lab-09.py | 690 | 3.6875 | 4 | import numpy as np
import matplotlib.pyplot as plt
def minumum_mean_square_error(y_predict, y_data):
ret = 0
for i in range(len(y_predict)):
ret += (y_data[i] - y_predict[i]) ** 2
ret /= len(y_predict)
return ret
x_data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y_data = np.array([8, 24, 28, 46, 44, 55, 79, 80, 99, 105])
mse_x = np.arange(-10, 30)
mse_y = []
for slope in mse_x:
y_predict = slope * x_data
error = minumum_mean_square_error(y_predict, y_data)
mse_y.append(error)
mse_y = np.array(mse_y)
plt.figure(0)
plt.plot(mse_x, mse_y, 'r-', label='minumum mean square error')
plt.xlabel('slope')
plt.ylabel('mse')
plt.legend()
plt.show()
|
1889f8c01638353f958f9e7c838ca30d30148c4d | eshu-bade/Data-Structures-and-Algorithms | /BinarySearchTree.py | 3,384 | 4.34375 | 4 | """
Binary search tree has left and right subtrees.
If the new child is smaller than node, it must go left side
If the new child is greater than node, it must go right side
It has 3 types of sortings
- In-order traversal method: returns list of elements in a binary tree in a specific order(first visits leftsubtree
- Out-order traversal method
"""
class BinarySearchTreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def addChild(self, data):
if data == self.data: # To check if the new value already exists
return
if data < self.data: # add data to left subtree
if self.left: # If tree is not empty
self.left.addChild(data)
else: # If tree is empty
self.left = BinarySearchTreeNode(data)
else: # add data to right subtree
if self.right: # If tree is not empty
self.right.addChild(data)
else: # If tree is not empty
self.right = BinarySearchTreeNode(data)
def inOrderTraversal(self):
listElements = []
if self.left:
listElements += self.left.inOrderTraversal()
listElements.append(self.data)
if self.right:
listElements += self.right.inOrderTraversal()
return listElements
def post_order_traversal(self):
listElements = []
if self.left:
listElements += self.left.post_order_traversal()
if self.right:
listElements += self.right.post_order_traversal()
listElements.append(self.data)
return listElements
def pre_order_traversal(self):
listElements = [self.data]
if self.left:
listElements += self.left.pre_order_traversal()
if self.right:
listElements += self.right.pre_order_traversal()
return listElements
def searchValue(self, value):
if self.data == value:
return "Value exists"
if value < self.data:
if self.left:
return self.left.searchValue(value)
else:
return "Value doesn't exist"
if value > self.data:
if self.right:
return self.right.searchValue(value)
else:
return "Value doesn't exists"
def findMini(self):
if self.left is None:
return self.data
return self.left.findMini()
def findMax(self):
if self.right is None:
return self.data
return self.right.findMax()
def calculateSum(self):
left_sum = self.left.calculate_sum() if self.left else 0
right_sum = self.right.calculate_sum() if self.right else 0
return self.data + left_sum + right_sum
def buildTree(listElements):
root = BinarySearchTreeNode(listElements[0])
for i in range(1, len(listElements)):
root.addChild(listElements[i])
return root
if __name__ == '__main__':
numbers = [17, 4, 1, 20, 9, 23, 18, 34]
numbersTree = buildTree(numbers)
# print(numbersTree.searchValue(23))
print(numbersTree.findMini())
print(numbersTree.findMax())
print(numbersTree.searchValue(30))
|
3c563a9a759b7c3fabf6df0a58e7d55ccd34c23f | lhc0506/leetcode | /210323_leetcode.py | 450 | 3.546875 | 4 | class Solution:
def threeSumMulti(self, arr: List[int], target: int) -> int:
n = len(arr)
count = 0
for i in range(n-2):
for j in range(i+1,n-1):
if arr[i] + arr[j] > target:
continue
else:
for k in range(j+1,n):
if arr[i] + arr[j] + arr[k] == target:
count += 1
return count
|
80fcbc62352da0272aa57cba930766812939e861 | sathishmepco/Python-Basics | /basic-programs/prime_nos.py | 428 | 3.671875 | 4 | def main():
start = int(input('Enter the start value : '))
end = int(input('Enter the end value : '))
primeNos = []
for value in range(start,end+1):
flag = True
for j in range(2,int(value/2)):
if value % j == 0:
flag = False
break
if flag is True:
primeNos.append(value)
for i in range(len(primeNos)):
if i is len(primeNos)-1:
print(primeNos[i],end="")
else:
print(primeNos[i],end=",")
main() |
1b3694daf743bcdb5e7c9835a5f8caa28e30c132 | sathishmepco/Python-Basics | /techgig/average_score.py | 410 | 3.515625 | 4 | def main():
n = int(input().strip())
names = {}
for i in range(n):
s = input().strip().split()
a = int(s[1])
b = int(s[2])
c = int(s[3])
avg = (a+b+c)/3
names[s[0]] = avg
name = input().strip()
print('{0:.2f}'.format(names[name]))
main()
'''
Test Case Input
3
Warner 150 100 120
Kohli 10 30 20
Rohit 60 80 40
Kohli
Test Case Output
20.00
''' |
e4a205127460b9e4f0688049e723dd8fb16ea8d9 | sathishmepco/Python-Basics | /basic-concepts/modules/calculator.py | 122 | 3.609375 | 4 | def add(a,b):
return a+b
def sub(a,b):
return a-b
def isEven(a):
if a % 2 == 0:
return True
else:
return False
|
676895da9e1eff2fc1b778059b14741eac5a1d55 | sathishmepco/Python-Basics | /basic-concepts/del_statement.py | 540 | 3.953125 | 4 | a = [-1, 1, 66.25, 333, 333, 1234.5]
print('The elements in the list are :',a)
del a[0]
print('After deleting 0th index element :',a)
del a[2:4]
print('Deleting elements from index 2 to 4th element')
print('After deletion :',a)
del a[:]
print('Deleting entire list :',a)
'''
OUTPUT
------
The elements in the list are : [-1, 1, 66.25, 333, 333, 1234.5]
After deleting 0th index element : [1, 66.25, 333, 333, 1234.5]
Deleting elements from index 2 to 4th element
After deletion : [1, 66.25, 1234.5]
Deleting entire list : []
''' |
690805257154a3d610f72d0fa777a0196b9e07fb | sathishmepco/Python-Basics | /basic-concepts/for_loop.py | 1,005 | 4.28125 | 4 | #for loop
print('------Looping through string list')
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x,len(x))
print('------Looping through String')
str = 'Python'
for x in str:
print(x)
print('-----Range() function')
for x in range(10):
print(x)
print('-----Range() function with start and end value')
for x in range(2,5):
print(x)
print('-----Range() function with start, end, step')
for x in range(1,10,2):
print(x)
print('-----Range() with negative numbers')
for x in range(-10, -100, -30):
print(x)
print('-----for with else block')
for x in range(5):
print(x)
else:
print('For block is over')
print('-----nested for loops')
for i in range(3):
for j in range(3):
print(i,j)
print('-----print list items using range()')
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(i,fruits[i])
print('-----print(range(5))')
print(range(5))
print('-----sum(print(range(5)))')
print(sum(range(5)))
print('-----list(range(5))')
print(list(range(5))) |
551f096fdf03040494cd2ef3d1df329a81766c86 | sathishmepco/Python-Basics | /basic-concepts/collections/counter.py | 217 | 3.703125 | 4 | from collections import Counter
def main():
s = input()
common = Counter(s).most_common(2)
if len(common) is 1:
print(common[0],end="")
else:
print(common[0],common[1],end="")
main() |
c2740cb3c6b4f838d3b8ff8bd7c54dade977cbe4 | sathishmepco/Python-Basics | /basic-programs/array/intersection.py | 763 | 4.09375 | 4 | def main():
a = int(input('Enter the length of array1 : ').strip())
s1 = input('Enter the values of array1 : ').strip()
b = int(input('Enter the length of array2 : ').strip())
s2 = input('Enter the values of array2 : ').strip()
array1 = s1.split()
array2 = s2.split()
list1 = []
list2 = []
for i in range(a):
value = int(array1[i])
list1.append(value)
for i in range(b):
value = int(array2[i])
list2.append(value)
list3 = list(set(list1) & set(list2))
print('intersection of both arrays : ',list3)
main()
'''
Enter the length of array1 : 3
Enter the values of array1 : 1 2 3
Enter the length of array2 : 3
Enter the values of array2 : 2 3 4
intersection of both arrays : [2, 3]
''' |
8617d6b008e47ed734b1ecaf568ae94dfc7db835 | sathishmepco/Python-Basics | /basic-concepts/collections/dequeue_demo.py | 1,329 | 4.34375 | 4 | from collections import deque
def main():
d = deque('abcd')
print('Queue of : abcd')
for e in d:
print(e)
print('Add a new entry to the right side')
d.append('e')
print(d)
print('Add a new entry to the left side')
d.appendleft('z')
print(d)
print('Return and remove the right side elt')
print(d.pop())
print('Return and remove the left side elt')
print(d.popleft())
print('Peek of leftmost item')
print(d[0])
print('Peek of rightmost item')
print(d[-1])
print('Reverse of deque')
l = list(reversed(d))
print(l)
print('Search in the deque')
bool = 'c' in d
print(bool)
print('Add multiple elements at once')
d.extend('xyz')
print(d)
print('Right rotation')
d.rotate(1)
print(d)
print('Left rotation')
d.rotate(-1)
print(d)
main()
'''
Queue of : abcd
a
b
c
d
Add a new entry to the right side
deque(['a', 'b', 'c', 'd', 'e'])
Add a new entry to the left side
deque(['z', 'a', 'b', 'c', 'd', 'e'])
Return and remove the right side elt
e
Return and remove the left side elt
z
Peek of leftmost item
a
Peek of rightmost item
d
Reverse of deque
['d', 'c', 'b', 'a']
Search in the deque
True
Add multiple elements at once
deque(['a', 'b', 'c', 'd', 'x', 'y', 'z'])
Right rotation
deque(['z', 'a', 'b', 'c', 'd', 'x', 'y'])
Left rotation
deque(['a', 'b', 'c', 'd', 'x', 'y', 'z'])
''' |
0000c11753a4882f5e1bf9675a714533b6551259 | sathishmepco/Python-Basics | /basic-programs/array/unique_set.py | 209 | 3.8125 | 4 | #Find unique elements
def main():
s1 = input().strip()
array1 = s1.split()
uniqueset = set(array1)
print(uniqueset)
main()
'''
Input
1 2 3 2 3 1 4 5 3 4 5
Output
{'1', '2', '5', '3', '4'}
''' |
45fba01c9f2649279f241e196e773dff5394f81c | sathishmepco/Python-Basics | /patterns/pattern21.py | 393 | 3.546875 | 4 | def main():
n = int(input().strip())
for i in range(n):
for j in range(i):
print(end=' ')
for j in range(i,n,1):
if j == i:
print(str(n-i),end='')
else:
print(' '+str(n-i),end='')
if i < n-1:
print()
main()
'''
Input
5
Output
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1
''' |
d7b198ce22ade78373e81feea7f1d34547ac686c | sathishmepco/Python-Basics | /techgig/itertools/groupby_demo2.py | 346 | 3.5 | 4 | from itertools import groupby
def main():
s = input().strip()
s = sorted(s)
groups = groupby(s)
result = [(sum(1 for _ in group),label) for label, group in groups]
output = " ".join("({}, \'{}\')".format(label, count) for label, count in result)
print(output)
main()
'''
Input
aabbccc
Output
(2, 'a') (2, 'b') (3, 'c')
''' |
b101c2a2a741512026b4829e570923eb3d45267d | duplamatyi/ads | /python/sorting/sorting.py | 4,777 | 4.1875 | 4 | """Sorting algorithms in Python"""
import copy
class Sorter:
@staticmethod
def bubble_sort(lst):
"""The greatest item bubbles to the top in each iteration"""
lst = copy.deepcopy(lst)
for i in range(len(lst) - 1, 0, -1):
ordered = True
for j in range(i):
if lst[j] > lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]
ordered = False
if ordered is True:
break
return lst
@staticmethod
def selection_sort(lst):
"""The greatest element is always paced to the right location"""
lst = copy.deepcopy(lst)
for i in range(len(lst) - 1, 0, -1):
pos_max = 0
for j in range(1, i + 1):
if lst[pos_max] < lst[j]:
pos_max = j
lst[pos_max], lst[i] = lst[i], lst[pos_max]
return lst
@staticmethod
def insertion_sort(lst):
r"""The current element gets always inserted in it's
position in an already sorted sub list.
"""
lst = copy.deepcopy(lst)
for i in range(1, len(lst)):
pos = i
current = lst[i]
while pos > 0 and lst[pos - 1] > current:
lst[pos - 1], lst[pos] = lst[pos], lst[pos - 1]
pos -= 1
lst[pos] = current
return lst
@classmethod
def shell_sort(cls, lst):
"""Sorts sub lists with a gap using insertion sort, until gap is 1.
This version uses a gap sequence len(list) // 2
"""
lst = copy.deepcopy(lst)
gap = len(lst) // 2
while gap > 0:
for start_pos in range(gap):
cls._gap_insertion_sort(lst, start_pos, gap)
gap //= 2
return lst
@staticmethod
def _gap_insertion_sort(lst, start_pos, gap):
for i in range(start_pos + gap, len(lst), gap):
pos = i
current = lst[i]
while pos > 0 and lst[pos - gap] > current:
lst[pos - gap], lst[pos] = lst[pos], lst[pos - gap]
pos -= gap
lst[pos] = current
@classmethod
def merge_sort(cls, lst):
"""Uses divide et impera: sorts parts and than merges them together"""
lst = copy.deepcopy(lst)
return cls._merge_sort_helper(lst)
@classmethod
def _merge_sort_helper(cls, lst):
if len(lst) > 1:
mid = len(lst) // 2
left_half = lst[:mid]
right_half = lst[mid:]
cls._merge_sort_helper(left_half)
cls._merge_sort_helper(right_half)
i = 0
j = 0
k = 0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
lst[k] = left_half[i]
i += 1
else:
lst[k] = right_half[j]
j += 1
k += 1
while i < len(left_half):
lst[k] = left_half[i]
i += 1
k += 1
while j < len(right_half):
lst[k] = right_half[j]
j += 1
k += 1
return lst
@classmethod
def quick_sort(cls, lst):
"""Selects a pivot element, places in place. Sorts the two sub lists."""
lst = copy.deepcopy(lst)
cls._quick_sort_helper(lst, 0, len(lst) - 1)
return lst
@classmethod
def _quick_sort_helper(cls, lst, first, last):
if first < last:
split_point = cls._partition(lst, first, last)
cls._quick_sort_helper(lst, first, split_point - 1)
cls._quick_sort_helper(lst, split_point + 1, last)
@staticmethod
def _partition(lst, first, last):
pivot = lst[first]
left_mark = first + 1
right_mark = last
done = False
while not done:
while left_mark <= right_mark and lst[left_mark] <= pivot:
left_mark += 1
while left_mark <= right_mark and lst[right_mark] >= pivot:
right_mark -= 1
if right_mark < left_mark:
done = True
else:
lst[left_mark], lst[right_mark] = lst[right_mark], lst[left_mark]
lst[first], lst[right_mark] = lst[right_mark], lst[first]
return right_mark
if __name__ == '__main__':
a = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print(a)
print(sorted(a))
print(Sorter.bubble_sort(a))
print(Sorter.selection_sort(a))
print(Sorter.insertion_sort(a))
print(Sorter.shell_sort(a))
print(Sorter.merge_sort(a))
print(Sorter.quick_sort(a))
|
b27991d36c39d6506daf2c4566203496798cc770 | domoritz/informaticup-2012 | /data/dataDistances.py | 2,895 | 3.875 | 4 | from data.dataMatrix import DataMatrix
class DataDistances(DataMatrix):
"""Data structure containing distances between stores."""
def getDistance(self, i1, i2):
"""Returns the minimum distance between i1 and i2."""
return self.getValue(i1, i2)
def prepare(self):
"""Prepares the data structure for the next steps (algorithms, ...) and makes optimizations."""
return self.generateFullGraph()
def generateFullGraph(self):
"""Floyd-Warshall alorithm used for finding the shortest paths"""
self.shortestDistances = []
self.shortestPaths = []
addNumbersNone = lambda x, y: x + y if x != None and y != None else None
# Creating data structure for floyd-warshall
for i in range(0, len(self.data)):
self.shortestDistances.append(list(self.data[i]))
self.shortestPaths.append([None for i in range(0, len(self.data))])
# For all pairs of cities set shortestPath[a][b] = b, i.e. b is reachable from a via b
for i in range(0, len(self.data)):
for j in range(0, len(self.data)):
self.shortestPaths[i][j] = j
# Try to find shorter routes via k ...
for k in range(0, len(self.data)):
# ... for all pairs of cities (i, j)
for i in range(0, len(self.data)):
for j in range(0, len(self.data)):
# compositePathLength = distance from i to j via k
# compositePathLength == None <=> no such path
compositePathLength = addNumbersNone(self.shortestDistances[i][k], self.shortestDistances[k][j])
if compositePathLength != None:
if self.shortestDistances[i][j] == None:
# There was no direct edge between (i,j) in the original graph, let's fill the gap
self.shortestDistances[i][j] = compositePathLength
self.shortestPaths[i][j] = k
elif compositePathLength < self.shortestDistances[i][j]:
# We found a shorter path from i to j
self.shortestPaths[i][j] = k
self.shortestDistances[i][j] = compositePathLength
# Modify actual data structure such that it doesn't contain None anymore
for i in range(0, len(self.data)):
for j in range(0, len(self.data)):
if self.data[i][j] == None:
self.data[i][j] = self.shortestDistances[i][j]
return self
def getRealPath(self, solution):
"""Retrieves an actual path from a given path without taking edges that don't exist in the original graph. The neccessary information was saved during Floyd-Warhshall."""
# Start with the first city
shortestPath = [solution[0]]
# Traverse all cities in the correct order
for city in range(0, len(solution) - 1):
currentCity = solution[city]
destinationCity = solution[city + 1]
# Use shortestPaths to get the real path from currentCity to destinationCity
while currentCity != destinationCity:
nextCity = self.shortestPaths[currentCity][destinationCity]
shortestPath.append(nextCity)
currentCity = nextCity
return shortestPath
|
fb367242ca13764800e441b677d24563b5ecf109 | stevenhankin/Entertainment_Center | /fresh_tomatoes.py | 2,576 | 3.53125 | 4 | import webbrowser
import os
import re
def get_template_data(template_name):
"""Retrieves specified template
The templates for the Header, content and tiles are
stored in HTML "template" files within a resources
subdirectory and are returned using this helper function
:return: String of the template stored in file
"""
return "".join(open('resources/' + template_name + '.html').readlines())
class Browser:
"""A Browser with a Fresh-Tomatoes-Style content
"""
_movies = []
_main_page_head = "" # Styles and scripting for the page
_main_page_content = ""
_movie_tile_content = ""
def __init__(self, movies):
self._movies = movies
self._main_page_head = get_template_data('main_page_head')
self._main_page_content = get_template_data('main_page_content')
self._movie_tile_content = get_template_data('movie_tile_content')
def __create_movie_tiles_content(self):
"""The HTML content for each film in this section of the page"""
content = ''
for movie in self._movies:
# Extract the youtube ID from the url
youtube_id_match = re.search(
r'(?<=v=)[^&#]+', movie.trailer_youtube_url)
youtube_id_match = youtube_id_match or re.search(
r'(?<=be/)[^&#]+', movie.trailer_youtube_url)
trailer_youtube_id = (youtube_id_match.group(0) if youtube_id_match
else None)
# Append the tile for the movie with its content filled in
content += self._movie_tile_content.format(
movie_title=movie.title,
storyline=movie.storyline,
poster_image_url=movie.poster_image_url,
trailer_youtube_id=trailer_youtube_id
)
return content
def open_movies_page(self):
"""Generates a new HTML File for Fresh Tomatoes contents
and opens in the default webbrowser"""
# Create or overwrite the output file
output_file = open('fresh_tomatoes.html', 'w')
# Replace the movie tiles placeholder generated content
rendered_content = self._main_page_content.format(
movie_tiles=self.__create_movie_tiles_content())
# Output the file
output_file.write(self._main_page_head + rendered_content)
output_file.close()
# open the output file in the browser (in a new tab, if possible)
url = os.path.abspath(output_file.name)
webbrowser.open('file://' + url, new=2)
|
5ffa633ffb47b5c83d71b2e17bf016d3f49cfa97 | Pavankalyan0105/Dynamic-Programming | /minCoinsChange.py | 993 | 3.71875 | 4 |
#function that gives the mimimum noof coins required
def minCoins(coins , sum):
rows = len(coins)
cols = sum+1
table = [[0 for j in range(cols)] for i in range(rows)]
for i in range(0 , rows):
table[i][0] = 0
for i in range(1, cols):
table[0][i] = i//coins[0]
for i in range(1 , rows):
for j in range(1 , cols):
if(coins[i]>j):
table[i][j] = table[i-1][j]
else:
table[i][j] = min(table[i-1][j],1+table[i][j-coins[i]])
for i in table:
print(i)
print("Hence the minimum no:of coins required are ::: " , table[rows-1][cols-1])
res_coins = []
i = rows-1
j = cols-1
while i>0 and j>0:
if (table[i][j] == table[i-1][j]):
i = i-1
else:
res_coins.append(coins[i])
j = j - coins[i]
print("And the coins are " , res_coins)
coins = [1,5,6,9]
sum = 10
minCoins(coins , sum) |
c5e31c20a1a55cec683250a8d64ebc8836c3f5b6 | JKodner/median | /median.py | 528 | 4.1875 | 4 | def median(lst):
"""Finds the median of a sequence of numbers."""
status = True
for i in lst:
if type(i) != int:
status = False
if status:
lst.sort()
if len(lst) % 2 == 0:
num = len(lst) / 2
num2 = (len(lst) / 2) + 1
avg = float(lst[num - 1] + lst[num2 - 1]) / 2
median = {"median": avg, "positions": [lst[num - 1], lst[num2 - 1]]}
elif len(lst) % 2 != 0:
num = (len(lst) + 1) / 2
median = {"median": lst[num - 1], "position": num}
return median
else:
raise ValueError("Inappropriate List") |
d42020a99ba634ce329ec2498d60f5f3594c198c | BramKineman/331-cc-queue | /CC6/solution.py | 2,688 | 3.859375 | 4 | """
CC6 - It's As Easy As 01-10-11
Name:
"""
from typing import Generator, Any
class Node:
"""
Node Class
:value: stored value
:next: reference to next node
"""
def __init__(self, value) -> None:
"""
Initializes the Node class
"""
self.value: str = value
self.next: Node = None
def __str__(self) -> str:
"""
Returns string representation of a Node
"""
return self.value
class Queue:
"""
Queue Class
:first: reference to first node in the queue
:last: reference to last node in the queue
"""
def __init__(self):
"""Create an empty queue."""
self._size = 0
self.first: Node = None
self.last: Node = None
def __len__(self):
"""Return the number of elements in the queue."""
return self._size
def is_empty(self):
"""Return True if the queue is empty."""
return self._size == 0
def pop(self):
"""
Remove and return the first element of the queue (i.e., FIFO).
:return: Value of Node removed from queue.
"""
if self.first is None:
return ""
answer = self.first.value
self.first = self.first.next
self._size -= 1
return answer
def insert(self, value: str):
"""
Add an element to the back of queue.
:param value: String value to be added to queue.
:return: None
"""
# check q size: if empty, assign self.first and self.last -> same thing
if self.first is None:
initial_node = Node(value)
self.first = initial_node
self.last = initial_node
else:
new_node = Node(value)
self.last.next = new_node
self.last = new_node
self._size += 1
def alien_communicator(n: Any) -> Generator[str, None, None]:
"""
Creates a generator object of strings representing binary numbers of 0 to n inclusive.
:param n: any built-in type in python.
:return: Generator object of strings representing binary numbers of 0 to n inclusive
if n is an int, None otherwise.
"""
is_int = isinstance(n, int)
# special case with bools
if is_int and not isinstance(n, bool) and n >= 0:
yield "0"
my_q = Queue()
my_q.insert("1")
while n > 0:
first = my_q.pop()
second = first
my_q.insert(first + "0")
my_q.insert(second + "1")
yield first
n -= 1
|
33487b5cd6e069e72cbe686724143ba1eb16979e | Tayuba/AI_Engineering | /AI Study Note/List.py | 1,895 | 4.21875 | 4 | # original list
a = [1, 2, 3, 4, "m", 6]
b = ["a", "b", "c", "d", 2, 9, 10]
# append(), add an item to the end of already existing list
c = 8
a.append(c) # interger append
print(a) # [1, 2, 3, 4, 'm', 6, 8]
d = "Ayuba"
b.append(d)
print(b) # ['a', 'b', 'c', 'd', 2, 9, 10, 'Ayuba']
# extend(), add all items to the to end of already existing list
a.extend(b)
print(a) # [1, 2, 3, 4, 'm', 6, 8, 'a', 'b', 'c', 'd', 2, 9, 10, 'Ayuba']
# insert(), insert an item at the a given position, first argument is the index and second argument is what is what to be inserted
first_names = ["ayuba", "zsuzsanna"]
first_names.insert(1, "tahiru")
first_names.insert(2, "imri")
print(first_names) # ['ayuba', 'tahiru', 'imri', 'zsuzsanna']
# remove(x), removes the first item from the list whose values is equal to the "x". raise ValueError if no such item
first_names.remove("ayuba")
print(first_names) # ['tahiru', 'imri', 'zsuzsanna']
# pop([i]), removes the item at the given position in the list, if no position is given, it removes and return the last item
index_zero_pop = first_names.pop(0)
print(index_zero_pop) # tahiru
no_index_pop = first_names.pop()
print(no_index_pop) # zsuzsanna
# clear(), remove all item from the list. equivalent to del a[:]
a.clear()
print(a) # []
del b[:]
print(b) # []
# index(x[,start[,end]]), return zero_base index in the list of the first item whose value is equal to x, Raise a ValueError if there is no such item
b = ["w", "a", "b", "c", "d","d", 2, 9, 10, 10]
indexed_value = b.index(2)
print(indexed_value) # 6
# count(x), returns the number of times x appears in a list
count_value = b.count("d")
print(count_value) # 2
c = ["w", "a", "b", "c", "d","d", "z", "q", "l"]
c.sort()
print(c) # ['a', 'b', 'c', 'd', 'd', 'l', 'q', 'w', 'z']
# reverse(), reverse the element of the list
c.reverse()
print(c) # ['z', 'w', 'q', 'l', 'd', 'd', 'c', 'b', 'a'] |
9793d0c61424787630040790531af6f165f99e5d | Tayuba/AI_Engineering | /Solutions_of_Exercises/Nump_Ex_Solutions/ex_34_42.py | 1,993 | 3.65625 | 4 | import numpy as np
import time
# How to get all the dates corresponding to the month of July 2016?
print(np.arange('2016-07', '2016-08', dtype='datetime64[D]'))
# How to compute ((A+B)*(-A/2)) in place (without copy)?
A = np.ones(3) * 1
B = np.ones(3) * 2
np.add(A, B, out=B)
np.divide(A, 2, out=A)
np.negative(A, out=A)
print(np.multiply(A, B, out=A))
print("\n")
#Extract the integer part of a random array using 5 different methods
int_of_five = np.random.uniform(5,-5,5)
print(int_of_five.astype(np.int64))
print(np.trunc(int_of_five))
print(np.ceil(int_of_five))
print("\n")
#Create a 5x5 matrix with row values ranging from 0 to 4
five_by_five = np.zeros((5, 5))
five_by_five += np.arange(5)
print(five_by_five)
print("\n")
# Consider a generator function that generates 10 integers and use it to build an array
def func_generator():
for x in range(10):
yield x
array_func = np.fromiter(func_generator(), dtype=float, count=-1)
print(array_func)
print("\n")
# Create a vector of size 10 with values ranging from 0 to 1, both excluded
exluded_0_1 = np.linspace(0, 1, 12, endpoint=True)[1:-1]
print(exluded_0_1)
print("\n")
# Create a random vector of size 10 and sort it
sorted_rand = np.random.random(10)
sorted_rand.sort()
print(sorted_rand)
print("\n")
# How to sum a small array faster than np.sum?
# Not recommended for small data
# L = [1,2,3,4,5]
# start_time1 = time.time()
# x = np.arange(L)
# np.sum(x)
# finish_time1 = time.time()
# print((finish_time1 - start_time1))
#
# # Fast method for small data
# start_time2 = time.time()
# for x in [1,2,3,4,5]:
# x += x
# finish_time2 = time.time()
# print(finish_time2 - start_time2)
# print("\n")
# Consider two random array A and B, check if they are equal
# Note this code only runs if the code for checking fast method is commented out
A = np.random.randint(0, 2, 5)
print(A)
B = np.random.randint(0, 2, 5)
print(B)
equal_or_not = np.allclose(A, B)
# equal_or_not = np.allclose(A, B)
print(equal_or_not) |
4f340717ec34d4d1ee5dc79b1bcac29c8be02600 | OliverMathias/University_Class_Assignments | /Python-Projects-master/Assignments/Celsius.py | 367 | 4.3125 | 4 | '''
A script that converts a user's celsius input into farenheight by using
the formula and prints out an temp in farenheight
'''
#gets user's temp Input
temp_c = float(input("Please enter the current temperature in celsius: "))
# turns it into farenheight
temp_f = temp_c*(9/5) + 32
#prints out farenheight
print("The current temp in farenheight is "+str(temp_f))
|
6bef25b006ecf686bb576d382cbdd711ff7faa11 | N02994498/ELSpring2015 | /code/logTemperature.py | 822 | 3.625 | 4 | #!/usr/bin/python
import sqlite3 as myDataBase
import sys
import time
import os
date = " "
tempC = 0
tempF = 0
""" Log Current Time, Temperature in Celsius and Fahrenheit
Returns a list [time, tempC, tempF] """
def readTemp():
tempfile = open("/sys/bus/w1/devices/28-0000069743ce/w1_slave")
tempfile_text = tempfile.read()
date=time.strftime("%x %X %Z")
tempfile.close()
tempC=float(tempfile_text.split("\n")[1].split("t=")[1])/1000
tempF=tempC*9.0/5.0+32.0
con = myDataBase.connect('/home/pi/ELSpring2015/misc/temperature.db')
with con:
cur = con.cursor()
cur.execute("Insert into TempData(date, tempC, tempF) Values(?,?,?)",
(date, tempC, tempF))
con.commit()
return "Current Temperature is: " + str(tempF) + "\nTemperature Logged"
print readTemp()
|
dd0b8328fbb3617d8f083904fe3d812230f35208 | pajakpawel/AdventOfCode_2020 | /Day_4/Puzzle_1.py | 641 | 3.90625 | 4 | def count_valid_passports(filepath: str) -> int:
valid_passports_number = 0
required_passport_fields = {"byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"}
with open(filepath) as bach_file:
passports_list = bach_file.read().split('\n\n')
for passport in passports_list:
if all(field in passport for field in required_passport_fields):
valid_passports_number += 1
return valid_passports_number
if __name__ == "__main__":
solution = count_valid_passports('puzzle_input.txt')
print("Solution for dataset included in 'puzzle_input.txt' is equal to {solution}".format(solution=solution))
|
33084ea3b0540cb423e7f4f546ca0c9a0a6a656f | pajakpawel/AdventOfCode_2020 | /Day_6/Puzzle_1.py | 857 | 3.953125 | 4 | def count_positive_answers(group_answers: str) -> int:
positive_answers = 0
counted_questions = set()
group_answers = ''.join(group_answers.split())
for answer in group_answers:
if answer not in counted_questions:
counted_questions.add(answer)
positive_answers += 1
return positive_answers
def count_positive_answers_sum(filepath: str) -> int:
with open(filepath) as collected_groups_answers:
answers_per_group = collected_groups_answers.read().split('\n\n')
positive_answers_per_group = map(count_positive_answers, answers_per_group)
return sum(positive_answers_per_group)
if __name__ == '__main__':
solution = count_positive_answers_sum('puzzle_input.txt')
print("Solution for dataset included in 'puzzle_input.txt' is equal to {solution}".format(solution=solution))
|
dfedefb05689f6278d9504e14f701cec7eae7a3b | camilocruz07/esport | /sport.py | 511 | 3.859375 | 4 | numero1= 45
numero2= 34
operacion = input("ELIJA UNA OPCIION: ")
if operacion =="a":
suma = numero1 + numero2
print ("el resultado es: ", suma)
elif operacion =="b":
suma = numero1 + numero2
print ("el resultado es: ", suma)
elif operacion =="c":
suma = numero1 + numero2
print ("el resultado es: ", suma)
elif operacion =="d":
suma = numero1 + numero2
print ("el resultado es: ", suma)
elif operacion =="e":
suma = numero1 + numero2
print ("el resultado es: ", suma) |
a0393bda25d0b27316eecbac32387507c079ad26 | zih123/assignment-1-zih123-master | /assignment1.py | 9,098 | 3.515625 | 4 | # This is the file you will need to edit in order to complete assignment 1
# You may create additional functions, but all code must be contained within this file
# Some starting imports are provided, these will be accessible by all functions.
# You may need to import additional items
import math
import os
import re
import nltk
nltk.download('punkt')
import numpy as np
from numpy.linalg import norm
import pandas as pd
from matplotlib import pyplot as plt
import json
import seaborn as sns
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
# You should use these two variable to refer the location of the JSON data file and the folder containing the news articles.
# Under no circumstances should you hardcode a path to the folder on your computer (e.g. C:\Chris\Assignment\data\data.json) as this path will not exist on any machine but yours.
datafilepath = 'data/data.json'
articlespath = 'data/football'
def task1():
#Complete task 1 here
teams_codes = []
with open(datafilepath,'r') as fp:
data = json.load(fp)
teams_codes = data['teams_codes']
teams_codes.sort()
return teams_codes
def task2():
#Complete task 2 here
# read the file and get corresponding information
scores = []
with open(datafilepath,'r') as fp:
data = json.load(fp)
clubs = data['clubs']
for club in clubs:
scores.append([club['club_code'],club['goals_scored'],club['goals_conceded']])
scores.sort(key=lambda item:item[0])
# store the data in the file
with open('task2.csv','w') as fp:
fp.write('team code, goals scored by team, goals scored against team\n')
for tt in scores:
fp.write('{0},{1},{2}\n'.format(tt[0],tt[1],tt[2]))
return scores
def task3():
#Complete task 3 here
paths = os.listdir(articlespath)
paths.sort()
reg = re.compile(r'\d+-\d+')
scores = []
for path in paths:
with open(articlespath+'/'+path, 'r') as fp:
text = ' '.join(fp.read().splitlines())
# match the score
ll = reg.findall(text)
max_score = 0
if len(ll) == 0:
scores.append([path,max_score])
continue
# find the maximum score and add it to the list
for tt in ll:
ss = tt.split('-')
s1 = int(ss[0])
s2 = int(ss[1])
if s1 < 0 or s1 > 99 or s2 < 0 or s2 > 99:
continue
value = s1 + s2
if value > max_score:
max_score = value
scores.append([path, max_score])
# write the data to the file
with open('task3.csv','w') as fp:
fp.write('filename, total goals\n')
for tt in scores:
fp.write('{0},{1}\n'.format(tt[0], tt[1]))
return
def task4():
#Complete task 4 here
x = pd.read_csv('task3.csv').values[:,1].tolist()
plt.boxplot(x,labels=[''],whis=1.5)
plt.title('Task4: boxplot of total scores')
plt.xlabel(u'total_scores')
plt.ylabel(u'values')
plt.savefig('task4.png')
return
def task5():
#Complete task 5 here
mentions = {}
# read names of clubs
with open(datafilepath) as fp:
data = json.load(fp)
name_clubs = data['participating_clubs']
for tt in name_clubs:
mentions[tt] = 0
# traverse the files and calculate the number of mentions
paths = os.listdir(articlespath)
paths.sort()
for path in paths:
with open(articlespath + '/' + path, 'r') as fp:
text = ' '.join(fp.read().splitlines())
for club in name_clubs:
if text.find(club) != -1:
mentions[club] += 1
# put the data in the list
list_mentions = []
for key in mentions.keys():
list_mentions.append([key, mentions[key]])
# sort the list in ascending alphabetic order
list_mentions.sort(key=lambda item: item[0])
# write the data to the file
with open('task5.csv','w') as fp:
fp.write('club name, number of mentions\n')
for tt in list_mentions:
fp.write('{0},{1}\n'.format(tt[0], tt[1]))
# plot a bar chart and save it to a image file
x = []
y = []
for tt in list_mentions:
x.append(tt[0])
y.append(tt[1])
plt.bar(x, y)
plt.title('Task5: number of mentions for each club name')
plt.xticks(rotation=-90)
plt.xlabel(u'club name')
plt.ylabel(u'number of mentions')
plt.tight_layout()
plt.savefig('task5.png')
return
def task6():
#Complete task 6 here
# get mentioned articles of each club
mentions = {}
# read names of clubs
with open(datafilepath) as fp:
data = json.load(fp)
name_clubs = data['participating_clubs']
for tt in name_clubs:
mentions[tt] = {'number_mentions':0,'articles':[]}
# traverse the files ,calculate the number of mentions
# and record mentioned articles of each club
paths = os.listdir(articlespath)
paths.sort()
for path in paths:
with open(articlespath + '/' + path, 'r') as fp:
text = ' '.join(fp.read().splitlines())
for club in name_clubs:
if text.find(club) != -1:
mentions[club]['number_mentions'] += 1
mentions[club]['articles'].append(path)
# calculate the similarity
arr = np.zeros((len(name_clubs),len(name_clubs)))
for i in range(len(name_clubs)):
for j in range(len(name_clubs)):
value = len(set(mentions[name_clubs[i]]['articles']).intersection(set(mentions[name_clubs[j]]['articles'])))
sum_mentions = mentions[name_clubs[i]]['number_mentions']+mentions[name_clubs[j]]['number_mentions']
if sum_mentions == 0:
continue
arr[i][j] = (2*value)/sum_mentions
# draw the heatmap
fig = plt.figure()
sns.heatmap(arr,cmap="OrRd")
plt.xlabel(u'clubs')
plt.ylabel(u'clubs')
plt.xticks(range(len(name_clubs)),name_clubs,rotation=-90)
plt.yticks(range(len(name_clubs)),name_clubs,rotation=0)
plt.title('Task6: heatmap of similarity')
plt.tight_layout()
fig.savefig("task6.png")
return
def task7():
#Complete task 7 here
scores = pd.read_csv('task2.csv').values[:,1]
number_mentions = pd.read_csv('task5.csv').values[:,1]
plt.scatter(number_mentions,scores)
plt.xlabel('number of mentions')
plt.ylabel('scores of clubs')
plt.title('Task7: scatterplot of number of mentions and scores')
plt.savefig('task7.png')
return
def task8(filename):
#Complete task 8 here
# read stop words
stop_words = set()
with open('stopwords_english','r') as fp:
stop_words = fp.read().splitlines()
# read all characters in the file
with open(filename, 'r') as fp:
text = ' '.join(fp.read().splitlines())
# preprocess the text
# change all uppercase characters to lower case
filtered_text = text.lower()
# remove all non-alphabetic characters exception for spacing characters
filtered_text = re.sub('[^a-z]',' ',filtered_text)
# tokenize the resulting string into words
words = nltk.word_tokenize(filtered_text)
# remove all stopwords and words which are a single character long
filtered_words = [word for word in words if word not in stop_words and len(word) > 1]
return filtered_words
def task9():
#Complete task 9 here
# get words of all files
paths = os.listdir(articlespath)
paths.sort()
number_articles = len(paths)
words_article = []
for path in paths:
filename = articlespath + '/' + path
words_article.append(task8(filename))
# calculate TF-IDF
vectorize = CountVectorizer()
transformer = TfidfTransformer()
txtList = []
for tt in words_article:
val = ' '.join(tt)
txtList.append(val)
tf = vectorize.fit_transform(txtList)
# calculate cosine similarity measure
sim = {}
tf_idf_array = transformer.fit_transform(tf).toarray()
rows = tf_idf_array.shape[0]
for i in range(rows):
for j in range(rows):
if i == j:
continue
if paths[j]+','+paths[i] in sim.keys():
continue
vec1 = tf_idf_array[i,:]
vec2 = tf_idf_array[j,:]
v1 = np.linalg.norm(vec1)
v2 = np.linalg.norm(vec2)
v3 = np.dot(vec1,vec2)
value = v3/(v1*v2)
sim[paths[i]+','+paths[j]] = value
# get the top 10
ll = []
for tt in sim:
ll.append([tt, sim[tt]])
ll.sort(key=lambda item:item[1],reverse=True)
sim_top10 = ll[:10]
# store the top 10 to the file
with open('task9.csv','w') as fp:
fp.write('article1,article2, similarity\n')
for tt in sim_top10:
fp.write('{0},{1}\n'.format(tt[0],tt[1]))
return |
53f51d2d0bcf61dd52f1a1eaa09d5a16f4a0edfc | shun-999/studey_04.kadai | /pos-system.py | 3,571 | 4.15625 | 4 | ### 商品クラス
import pandas as pd
import datetime
class Item:
def __init__(self,item_code,item_name,price):
self.item_code=item_code
self.item_name=item_name
self.price=price
def get_price(self):
return self.price
### オーダークラス
class Order:
def __init__(self,item_master):
self.item_order_list=[]
self.item_order_name=[]
self.item_order_price=[]
self.item_number = []
self.item_master=item_master
def add_item_order(self,item_code, item_number):
#self.item_order_list.append(item_code)
for i in self.item_master:
if item_code == i.item_code:
self.item_order_list.append(item_code)
self.item_order_name.append(i.item_name)
self.item_order_price.append(i.price)
self.item_number.append(item_number)
def payment(self, payment):
self.deposit = payment
def view_item_list(self):
sum_price = 0
sum_num = 0
for item,name,price,num in zip(self.item_order_list, self.item_order_name, self.item_order_price, self.item_number):
print("商品コード:{},商品名:{},価格:{}".format(item,name,price))
print("注文:{},{}個".format(name,num))
self.txt_out("商品コード:{},商品名:{},価格:{}".format(item,name,price))
self.txt_out("注文:{},{}個".format(name,num))
sum_price += price*num
sum_num += num
print("合計金額:{},合計個数:{}".format(sum_price,sum_num))
print("お預かり金:{},お釣り:{}".format(int(self.deposit),int(self.deposit)-sum_price))
self.txt_out("合計金額:{},合計個数:{}".format(sum_price,sum_num))
self.txt_out("お預かり金:{},お釣り:{}".format(int(self.deposit),int(self.deposit)-sum_price))
def txt_out(self, content):
dt_now = datetime.datetime.today()
dt_time = dt_now.strftime("%Y.%m.%d_%H.%M.%S")
text_name = "./{}.txt".format(dt_time)
with open(text_name, mode="a", encoding="utf-8")as f:
f.write(content + "\n")
def master_recog(file):
item_master=[]
df = pd.read_csv(file)
for item,name,price in zip(list(df["商品コード"]),list(df["商品名"]),list(df["価格"])):
item_master.append(Item(str(item),name,price))
return item_master
def order_buy():
item_list = []
sum_number = []
while True:
x = input("商品コードを入力してください>>")
y = input("個数を入力してください>>")
if x == "":
break
else:
item_list.append(x)
sum_number.append(y)
return item_list, sum_number
### メイン処理
def main():
# マスタ登録
item_master = master_recog("./master.csv")
#item_master = []
#item_master.append(Item("001","りんご",100))
#item_master.append(Item("002","なし",120))
#item_master.append(Item("003","みかん",150))
# オーダー登録
order = Order(item_master)
#order.add_item_order("001")
#order.add_item_order("002")
#order.add_item_order("003")
item_list, sum_number= order_buy()
for item_code,item_number in zip(item_list,sum_number):
order.add_item_order(item_code, int(item_number))
pay_out = input("お金を入れてください>>")
order.payment(pay_out)
# オーダー表示
order.view_item_list()
if __name__ == "__main__":
main() |
7a1ec8cc30caf9b4fd0f586c53bc4189999c3cf4 | ChandanB/Tweet-Generator | /Before Template/bf_stoch_samp.py | 1,488 | 3.703125 | 4 | import sys
import string
import re
import random
outcome_for = {}
user_input = sys.argv[1]
sentence = []
dict = open('Bible.txt', 'r')
text = dict.read()
dict.close()
def histogram(source_text):
histogram = {}
for word in source_text.split():
word = word.translate(None, string.punctuation)
if word in histogram:
histogram[word] += 1
else:
histogram[word] = 1
print (histogram)
return histogram
def random_word(histogram):
probability = 0
random_index = random.randint(1, sum(histogram.values()))
for word in histogram:
probability += histogram[word]
if probability >= random_index:
if word in outcome_for:
outcome_for[word] += 1
else:
outcome_for[word] = 1
return word
def return_random():
random_word = random_word(hist_dict)
def get_sentence(count):
count = str(user_input)
hist_dict = histogram(text)
for i in range(count):
random_word(hist_dict)
new_word = random_word(hist_dict)
word = new_word.strip()
sentence.append(word)
full_sentence = ' '.join(sentence)
return full_sentence
if __name__ == "__main__":
count = str(user_input)
get_sentence(count)
random_sentence = get_sentence(count)
hist_dict = histogram(text)
print("VALUE: " + str(outcome_for[word]))
print("ERROR: " + str(abs(outcome_for[word] - 50000.0) / 500.0) + "%")
|
e6e42e07e0a08a8fa3c6e3b7ce67a14fcc97eb21 | GateNLP/python-gatenlp | /gatenlp/processing/pipeline.py | 9,529 | 3.5 | 4 | """
Module that provides the Pipeline class. A Pipeline is an annotator which is configured to contain several annotators
which get executed in sequence. The result of each annotator is passed on to the next anotator.
Each annotator can return a single document, None, or list of documents. If no document is returned, subsequent
annotators are not called and None is returned from the pipeline. If several documents are areturned, subsequent
annotators are invoked for each of those documents and the list of final return documents is returned by the pipeline.
Whenever a single document is returned it is returned as the document and NOT as a list with a single document as
the only element.
"""
from collections.abc import Iterable
import inspect
from gatenlp.processing.annotator import Annotator
from gatenlp.utils import init_logger
def _check_and_ret_callable(a, **kwargs):
"""
Make sure a is either a callable or a class that can be instatiated to a callable.
Args:
a: a class or instantiated callable
kwargs: arguments to pass on to the initializer
**kwargs:
Returns:
an instantiated callable or throws an exception if not a callable
"""
if inspect.isclass(a):
a = a(**kwargs)
if not callable(a):
raise Exception(f"Not a callable: {a}")
return a
def _has_method(obj, name):
"""
Check if the object has a method with that name
Args:
obj: the object
name: the name of the method
Returns:
True if the object has a callable method with that name, otherwise False
"""
mth = getattr(obj, name, None)
if mth is None:
return False
elif callable(mth):
return True
else:
return False
class Pipeline(Annotator):
"""
A pipeline is an annotator which runs several other annotators in sequence on a document
and returns the result. Since annotators can return no or more than one result document
in a list, the pipeline can return no or more than one document for each input document
as well.
When the start/finish/reduce method of the pipeline is invoked, all start/finish/reduce methods of
all annotators are invoked in sequence. The finish method returns the list of all return values of
all the finish methods of the annotators (if a finish method returns None, this is added to the list).
The reduce method expects a list with as many return value lists as there are annotators and returns
the overall result for each annotator (again, including None if there is none).
"""
def __init__(self, *annotators, **kwargs):
"""
Creates a pipeline annotator. Individual annotators can be added at a later time to the front or back
using the add method.
Note: each annotator can be assigned a name in a pipeline, either when using the add method or
by passing a tuple (annotator, name) instead of just the annotator.
Args:
annotators: each parameter can be an annotator, a callable, a tuple where the first item is
an annotator or callable and the second a string(name), or a list of these things.
An annotator can be given as an instance or class, if it is a class, the kwargs are used
to construct an instance. If no annotators are specified at construction, they can still
be added later and incrementally using the `add` method.
**kwargs: these arguments are passed to the constructor of any class in the annotators list
"""
self.annotators = []
self.names = []
self.names2annotators = dict()
self.logger = init_logger("Pipeline")
for ann in annotators:
if not isinstance(ann, list):
anns = [ann]
for a in anns:
if isinstance(a, tuple) and len(a) == 2:
a, name = a
else:
name = f"{len(self.annotators)}"
a = _check_and_ret_callable(a)
if name in self.names2annotators:
raise Exception(f"Duplicate name: {name}")
self.names2annotators[name] = a
self.annotators.append(a)
self.names.append(name)
# if len(self.annotators) == 0:
# self.logger.warning("Pipeline is a do-nothing pipeline: no annotators")
def copy(self):
"""
Return a shallow copy of the pipeline: the annotators and the annotator data is identical, but
the pipeline data itself is copied, so that an existing pipeline can be modified or extendet.
Returns:
a shallow copy of this pipeline
"""
new = Pipeline([(name, ann) for name, ann in self.names2annotators.items()])
return new
def add(self, annotator, name=None, tofront=False):
"""
Add an annotator to list of annotators for this pipeline. The annotator must be an initialized instance,
not a class.
Args:
annotator: the annotator to add
name: an optional name of the annotator, if None, uses a string representation of the
number of the annotator as added (not the index in the pipeline!)
tofront: if True adds to the front of the list instead of appending to the end
"""
a = _check_and_ret_callable(annotator)
if name is None:
name = f"{len(self.annotators)}"
if name in self.names2annotators:
raise Exception(f"Duplicate name: {name}")
if tofront:
self.annotators.insert(0, a)
self.names.insert(0, name)
else:
self.annotators.append(a)
self.names.append(name)
self.names2annotators[name] = a
def __getitem__(self, item):
if isinstance(item, str):
return self.names2annotators[item]
else:
return self.annotators[item]
def __call__(self, doc, **kwargs):
"""
Calls each annotator in sequence and passes the result or results to the next.
Args:
doc: the document to process
**kwargs: any kwargs will be passed to all annotators
Returns:
a document or a list of documents
"""
toprocess = [doc]
results = []
for annotator in self.annotators:
results = []
for d in toprocess:
ret = annotator(doc, **kwargs)
if isinstance(ret, list):
results.extend(ret)
else:
if ret is not None:
results.append(ret)
toprocess = results
if len(results) == 1:
return results[0]
else:
return results
def pipe(self, documents, **kwargs):
"""
Iterate over each of the documents process them by all the annotators in the pipeline
and yield all the final non-None result documents. Documents are processed by in turn
invoking their `pipe` method on the generator created by the previous step.
Args:
documents: an iterable of documents or None (None values are ignored)
**kwargs: arguments to be passed to each of the annotators
Yields:
documents for which processing did not return None
"""
gen = documents
for antr in self.annotators:
gen = antr.pipe(gen, **kwargs)
return gen
def start(self):
"""
Invokes start on all annotators.
"""
for annotator in self.annotators:
if _has_method(annotator, "start"):
annotator.start()
def finish(self):
"""
Invokes finish on all annotators and return their results as a list with as many
elements as there are annotators (annotators which did not return anything have None).
Returns:
list of annotator results
"""
results = []
for annotator in self.annotators:
if _has_method(annotator, "finish"):
results.append(annotator.finish())
else:
results.append(None)
return results
def reduce(self, results):
"""
Invokes reduce on all annotators using the list of result lists. `results` is a list with
as many elements as there are annotators. Each element is a list of results from different
processes or different batches.
Returns a list with as many elements as there are annotators, each element the combined result.
Args:
results: a list of result lists
Returns:
a list of combined results
"""
results = []
assert len(results) == len(self.annotators)
for reslist, annotator in zip(results, self.annotators):
if _has_method(annotator, "reduce"):
results.append(annotator.reduce(reslist))
else:
results.append(reslist)
return results
def __repr__(self):
reprs = []
for name, ann in zip(self.names, self.annotators):
if hasattr(ann, "__name__"):
arepr = ann.__name__
else:
arepr = ann.__class__.__name__
repr = name + ":" + arepr
reprs.append(repr)
reprs = ",".join(reprs)
return f"Pipeline({reprs})"
|
33e2d191343b8e41cb60a3f79d2742e408e13f7f | jwalters006/blackjack | /handsplit.py | 843 | 3.984375 | 4 | # Start by placing the player_hand in a container interable, then put all of the
# ensuing logic in a "for x in container", so that either one or multiple hands
# can be processed by the ensuing logic. If the initial hand is split,
# additional hands are put into additional places in the container, and a
# continue command brings things back to the beginning of the logic.
# Upon the choice to split a hand, check to see the name of the hand, and create
# two new names that adds an integer to the hand (e.g., player_hand gets split
# and the names player_hand_1 and player_hand_2 are created). Create these
# names at the global level.
# Pass those new hand into a splitter function to change it.
def handSplit(hand):
player_hand1 = []
player_hand2 = []
player_hand1.append(hand.pop(0))
player_hand2.append(hand.pop(0)) |
31dfc6f78ac61e9cd4e39d33175a825542535592 | bpruitt63/python-and-flask | /python-ds-practice/27_titleize/titleize.py | 364 | 3.921875 | 4 | def titleize(phrase):
"""Return phrase in title case (each word capitalized).
>>> titleize('this is awesome')
'This Is Awesome'
>>> titleize('oNLy cAPITALIZe fIRSt')
'Only Capitalize First'
"""
lst = phrase.split(' ')
nlst = []
for word in lst:
nlst.append(word.capitalize())
return ' '.join(nlst)
|
ca21870eede88503c013ed741eac2d1581d68554 | SachinSPawar/wordmatch-backend | /checkword.py | 1,206 | 3.84375 | 4 | import string
import random
from random import seed
from random import randint
vowels="aeiou"
consonants="abcdefghijklmnopqrstuvwxyz"
def checkword(word,characters):
word= word.upper()
characters=characters.upper()
letters = {}
for c in word:
letters[c]=1
for c in characters:
if c in letters:
del letters[c]
if not letters:
return checkIfEnglishWord(word)
else:
return False
def checkIfEnglishWord(word):
f = open('words.txt', 'r')
x = f.readlines()
f.close()
x = map(lambda s: s.strip(), x)
if word.upper() in x:
return True
else:
return False
def getRandomLetters(numberOfCharacters):
global vowels
global consonants
characters=""
for _ in range(numberOfCharacters/3):
value = randint(0, len(vowels)-1)
characters = characters+vowels[value]
for _ in range(2*numberOfCharacters/3):
value = randint(0, len(consonants)-1)
characters = characters+consonants[value]
print "characters : "+characters
return characters
def calculateScore(words,chars):
if words:
return len(words)
else:
return 0 |
10ea306fedbee3cff2ce63c97add2561c9f2b54a | mbkhan721/PycharmProjects | /RecursionFolder/Practice6.py | 2,445 | 4.40625 | 4 | """ Muhammad Khan
1. Write a program that recursively counts down from n.
a) Create a recursive function named countdown that accepts an
integer n, and progressively decrements and outputs the value of n.
b) Test your function with a few values for n."""
def countdown(n): # def recursive_function(parameters)
if n <= 0: # countdown stops at 1 since the parameter is 0
return n # return base_case_value
else:
print(n)
countdown(n - 1) # countdown decrements by 1
countdown(5)
print()
""" 2. Write a function called numEven that returns the number of even
digits in a positive integer parameter.
For example, a program that uses the function numEven follows.
print(numEven(23)) # prints 1
print(numEven(1212)) # prints 2
print(numEven(777)) # prints 0 """
def numEven(n): # defining numEven Function
even_count = 0 # making initial count=0
while (n > 0): # checking input number greater than 0 or not
rem = n % 10 #slashing up inputted number into digits
if (rem % 2 == 0): #verifing digit is even or odd by dividing with 2.if remainder=0 then digit is even
even_count += 1 #counting the even digits
n = int(n / 10)
print(even_count) #printing the even number count
if (even_count % 2 == 0): #exits the function
return 1
else:
return 0
numEven(23)
numEven(1212)
numEven(777)
print()
""" 3. Write a function called lastEven that returns the last even digit
in a positive integer parameter. It should return 0 if there are no
even digits.
For example, a program that uses the function lastEven follows.
print(lastEven(23)) # prints 2
print(lastEven(1214)) # prints 4
print(lastEven(777)) # prints 0 """
def lastEven(x):
if x == 0:
return 0
remainder = x % 10
if remainder % 2 == 1:
return lastEven(x // 10)
if remainder % 2 == 0:
return remainder + lastEven(x // 10)
print(lastEven(23))
print(lastEven(1212))
print(lastEven(777))
print()
class Vehicle:
def __init__(self, t ="unknown"):
self.type = t
def print(self):
print("type =", self.type)
x1 = Vehicle()
x1.print()
x2 = Vehicle("abcde")
x2.print()
print()
class Car(Vehicle):
def __init__(self, name="Unknown"):
#super().__init__()
self.name = name
self.type = "Car"
def print(self):
print(self.type, self.name)
x1 = Car()
x1.print()
x2 = Car("Audi")
x2.print()
print()
|
b4649ad4164529beddc033f4e141fce74d56b637 | mbkhan721/PycharmProjects | /pythonProject/Functions.py | 3,765 | 4.125 | 4 | # star* means unlimited args
def my_function(*kids):
#for name in kids:
#print(name)
#print(kids)
print("The youngest child is " + kids[4])
my_function("Emil", "Tobias", "Linus", "John", "Khan")
print()
print("------------- Exercise 12 -------------")
print()
import random
from random import randrange
n = 10
a = [randrange(1, 7) for i in range(n)]
print("Roll of dice this time is:", a)
print()
print("------------- Exercise 13 -------------")
print()
def sum(numbers):
total = 0
for x in numbers:
total += x
return total
print("The sum of all number is:", sum((1, 2, 3, 4, 5)))
print()
print("------------- Exercise 14 -------------")
print()
def smFact(n):
if (n % 2 == 0):
return 2;
i = 3;
while(i * i <= n):
if (n % i == 0):
return i;
i += 2;
return n;
n = 81; # Enter a number here to find its smallest factor
print("Smallest factorial of the given number is: ", smFact(n));
print()
print("------------- Exercise 15 -------------")
print()
def Reverse_int(val):
rev = 0
while val > 0:
digit = val % 10
rev = (rev*10) + digit
val = val//10
return rev
#val = int(input("Enter upto 10 numbers to reverse: "))
rev = Reverse_int(123)
print("Reversed numbers are: %d" %rev)
print()
"""
def is_divisible(x, y):
if x % y == 0:
return True
else:
return False
if is_divisible(10, 2):
print("yes")
else:
print("no")
def printHello():
print("Hello")
#end function
# main
printHello()
pi = 3.14159
def circleArea(radius):
area = pi * radius * radius
return area
#end function
# main
ans = circleArea(1) # add 2 or 3 or any number
print(ans)
import random
print(random.random())
print(random.uniform(1, 10))
print(random.randint(1, 10))
print(random.randrange(0, 101, 2))
def dice ():
return random.randrange(1, 7)
for i in range(10):
ans = dice()
print (ans, end = " ")
def factorial(val):
res = 1
while val > 1:
res *= val
print(val, res)
val -= 1
print()
ans = factorial(4)
def displayReverse(val):
while val > 0:
digit = val % 10
print (digit, end = " ")
val = val//10
#end while
# end of function
displayReverse(123)
birthday = "05/20/1986"
print(birthday)
print()
mylist = birthday.split("/")
print(mylist)
print()
def num_year(birthdaylist):
birthyear = int(birthdaylist[2])
targetyear = 2020
yearsalive = targetyear - birthyear
return yearsalive
print("I am", num_year(mylist),"years old")
print()
student1 = {
'Name': 'Khan',
'ET574': 'B',
'ET710': 'A',
}
student2 = {
'Name': 'Azeem',
'ET574': 'A',
'ET710': 'C',
}
student1["age"] = 34
student2["age"] = 2
studentlist = [student1, student2]
studentlist = []
studentlist.append(student1)
studentlist.append(student2)
print(studentlist)
print()
for dict in studentlist:
print("Name:", dict["Name"], "Age:", dict["age"])
print( "\tET574:", dict["ET574"] )
print( "\tET710:", dict["ET710"] )
print()
def my_function(fname):
print(fname + " Khan")
my_function("Muhammad")
my_function("Fatima")
my_function("Azeem")
print()
def my_list(*kids):
print("The youngest cild is " + kids[2])
my_list("Fatima", "Refsnes", "Azeem")
print()
def my_count(country = "Pakistan"):
print("I am from " + country)
my_count("Sweden")
my_count("India")
my_count()
my_count()
my_count("Brazil")
print()
def my_kitchen(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_kitchen(fruits)
print()
def my_multi(x):
return 5 * x
print(my_multi(3))
print(my_multi(5))
print(my_multi(9))
print()
def myexample():
pass
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.