blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
545k
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
545k
|
---|---|---|---|---|---|---|
e27c1d39c34b9dcb5391eb9ec24497ee34412e95 | rizkisadewa/MachineLearningA-Z | /Part 2 - Regression/Section 6 - Polynomial Regression/polynomial_regression.py | 2,302 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 22 10:28:44 2019
@author: rizky
"""
# Polynomial Regression
# Import the Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Import the dataset
dataset = pd.read_csv('Position_Salaries.csv')
# Make a matrix feature of the three independent variables
X = dataset.iloc[:,1:2].values
# Create the dependent variable vector
Y = dataset.iloc[:,2].values
# Splitting the dataset into Trainning set and Testing set
from sklearn.model_selection import train_test_split # a library for splitting a dataset
X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size = 0.2, random_state = 0)
'''
the remark will be updated soon
'''
# Feature Scaling
"""
from sklearn.preprocessing import StandardScaler # import class from library
sc_X = StandardScaler() # an object from the class above
X_train = sc_X.fit_transform(X_train) # fit the object and transform it
X_test = sc_X.transform(X_test) # we only transfer the object as it's already fitted in train set
""""
'''
for the dependent variable vector do not have to be scalled due to the the value represent
as category with 2 value "yes" or "no"
'''
# Fitting Linear Regression to the dataset
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, Y)
# Fitting Polynomial Regression to the dataset
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 4)
X_poly = poly_reg.fit_transform(X)
lin_reg2 = LinearRegression()
lin_reg2.fit(X_poly, Y)
# Visualising the Linear Regression
plt.scatter(X, Y, color='red')
plt.plot(X, lin_reg.predict(X), color='blue')
plt.title('Truth or Bluff (Linear Regression)')
plt.xlabel('Position Level')
plt.ylabel('Salary')
plt.show()
# Visualising the Polynomial Regression
X_grid = np.arange(min(X), max(X), 0.1)
X_grid = X_grid.reshape((len(X_grid), 1))
plt.scatter(X, Y, color='red')
plt.plot(X_grid, lin_reg2.predict(poly_reg.fit_transform(X_grid)), color='blue')
plt.title('Truth or Bluff (Polynomial Regression)')
plt.xlabel('Position Level')
plt.ylabel('Salary')
plt.show()
# Predict a new result with Linear Regression
lin_reg.predict(6.5)
# Predict a new result with Polynomial Regression
lin_reg2.predict(poly_reg.fit_transform(6.5))
|
58c58dbaf3ad230ec20eded8beed69a34cb0d5bf | PawelKapusta/Python-University_Classes | /Lab10/queue_lib.py | 544 | 3.75 | 4 | class Queue:
def __init__(self, elems=None):
if elems is None:
elems = []
self.items = elems
def __str__(self):
return str(self.items)
def __eq__(self, other):
return self.items == other.items
def is_empty(self):
return not self.items
def is_full(self):
return False
def put(self, data):
if self.is_full():
raise OverflowError("Queue is full!")
self.items.append(data)
def get(self):
if self.is_empty():
raise ValueError("Queue is empty!")
return self.items.pop(0)
|
4f52547a0a15a57c72290bf61d21eb11a18668f2 | PawelKapusta/Python-University_Classes | /Lab8/task1.py | 590 | 3.8125 | 4 | def solve1(a, b, c):
if a == 0:
if b == 0:
if c == 0:
print("identity equation")
else:
print("No solutions")
else:
if c == 0:
print("Solution: y = 0")
else:
print("Solution: y =", -c / b)
else:
if b == 0:
if c == 0:
print("Solution: x = 0")
else:
print("Solution: x =", -c / a)
else:
if c == 0:
print("Solution: y =", -a / b, "* x")
else:
print("Solution: y =", -a / b, "* x +", -c / b)
print("Solution for equation 5x + 10y + 50 = 0: ")
solve1(5, 10, 50)
|
2d3272a23f8cb49bc5dfa00f5fb27286adff493e | PawelKapusta/Python-University_Classes | /Lab2/task14.py | 624 | 3.921875 | 4 | def replaceChar(word):
return str(word).replace('.', '').replace(',', '')
def theLongest(words):
return max(words,key=len)
line = "Python is a high-level programming language designed to be easy to read and simple to implement.\n" \
"It is open source, which means it is free to use, even for commercial applications.\n" \
"Python can run on Mac, Windows, and Unix systems and has also been ported to Java and .NET virtual machines."
words = line.split()
results = list(map(replaceChar, words))
long = theLongest(results)
print("The longest string in line is:",long,"and its length equals:",len(long)) |
51a2e174e5c69fb89bdb07708a86c774c972a659 | PawelKapusta/Python-University_Classes | /Lab3/task6.py | 581 | 4.03125 | 4 | output = ""
try:
firstSide = int(input("Write first side of rectangle: "))
secondSide = int(input("Write second side of rectangle: "))
except ValueError:
print("Check your input, maybe you do not write a number")
else:
for index in range(2 * firstSide + 1):
if index % 2 == 0:
output += "+"
for i in range(secondSide):
output += "---+"
output += "\n"
else:
output += "|"
for j in range(secondSide):
output += " |"
output += "\n"
print(output)
|
490b309f4fed53ab48b914a9a1b8c6fa8934e45f | PawelKapusta/Python-University_Classes | /Lab4/task7.py | 259 | 3.875 | 4 | returned = []
def flatten(seq):
for item in seq:
if isinstance(item, (list, tuple)):
flatten(item)
else:
returned.append(item)
return returned
seq = [1, (2, 3), [], [4, (5, 6, 7)], 8, [9]]
print(flatten(seq))
|
52fc107624d46f57e2b99394196053e444eb7136 | PawelKapusta/Python-University_Classes | /Lab8/task4.py | 387 | 4.15625 | 4 | import math
def area(a, b, c):
if not a + b >= c and a + c >= b and b + c >= a:
raise ValueError('Not valid triangle check lengths of the sides')
d = (a + b + c) / 2
return math.sqrt(d * (d - a) * (d - b) * (d - c))
print("Area of triangle with a = 3, b = 4, c = 5 equals = ", area(3, 4, 5))
print("Area of triangle with a = 15, b = 4, c = 50 equals = ", area(15, 4, 50))
|
8f8253c2114c5029661eb2660d200314bb7eacff | lucasrcz/Python-Exercises | /Python-01/exercicio 20.py | 742 | 4.09375 | 4 | # O mesmo professor do desafio anterior quer sortear a ordem
#de apresentaรงรฃo do trabalho dos alunos. Faรงa um programa que
#leia o nome dos quatro alunos e mostre a ordem sorteada
import random
from random import shuffle
print('Bem vindo ao gerador de Listas Randรดmicas 1.0.')
a1 = str(input('Digite o nome do segundo Aluno: '))
a2 = str(input('Digite o nome do segundo Aluno: '))
a3 = str(input('Digite o nome do terceiro Aluno: '))
a4 = str(input('Digite o nome do quarto Aluno: '))
lista=[a1,a2,a3,a4]
random.shuffle(lista)
#Cria-se a lista e logo apรณs embaralha a mesma para que a lista saia de forma aleatรณria no print
print('A ordem da lista gerada randรดmicamente รฉ a seguinte: {}'.format(lista))
#Se vocรช para selecionar |
5614aa22786c0c72c3e4ec96a77904a54b67de3e | lucasrcz/Python-Exercises | /Python-01/exercicio 17.py | 251 | 3.84375 | 4 | from math import hypot
oposto = float(input('Digite o comprimento do cateto oposto em M: '))
adj = float(input('Digite o comprimento do cateto adjacente em M: '))
print('O comprimento da hipotenusa รฉ igual รก {:.2f} M '.format(hypot(oposto, adj)))
|
023229ca86719b66aa7d8e1834631f284db9a88f | lucasrcz/Python-Exercises | /Python-01/Exercicio 28.py | 259 | 3.984375 | 4 | from random import randint
print('Bem vindo ao jogo de adivinhaรงรฃo')
n = int(input('Digite um nรบmero de 0 a 5: '))
m = randint(0, 5)
if m == n:
print('Vocรช adivinhou o nรบmero, parabรฉns!')
else:
print('Vocรช perdeu :(, tente novamente')
|
788b70df4320be219682ba0abd8697be77f8e3a6 | Adinaytalalantbekova/pythonProject1 | /homework_3.py | 599 | 3.953125 | 4 | letters = []
numbers = []
data_tuple = ('h', 6.13, 'C', 'e', 'T', True, 'K', 'e', 3, 'e', 1, 'G')
for element in data_tuple:
if(type(element)==str):
letters.append(element)
else:
numbers.append(element)
print(letters)
print(numbers)
numbers.remove(6.13)
true = numbers.pop(0)
letters.append(true)
print(letters)
print(numbers)
numbers.insert(1, 2)
print(numbers)
numbers = sorted(numbers)
print(numbers)
letters.reverse()
print(letters)
letters[4] = 'k'
letters[7] = 'c'
print(letters)
numbers = tuple(numbers)
letters = tuple(letters)
print(letters)
print(numbers)
|
c2f0c2eb520f18c5235b3bef3ff87ca289723eb5 | Adinaytalalantbekova/pythonProject1 | /homework_2.py | 773 | 4.03125 | 4 | while True:
number = int(input("ะะฐะทะฐะฒะธัะต ะบะพะด ัะตะณะธะพะฝะฐ: "))
if number == 1:
print('ะะธัะบะตะบ')
elif number == 2:
print('ะั')
elif number == 3:
print('ะะฐัะบะตะฝ')
elif number == 4:
print('ะะฐะปะฐะป-ะะฑะฐะด')
elif number == 5:
print('ะะฐััะฝ')
elif number == 6:
print('ะััะบะฐั ะพะฑะปะฐััั')
elif number == 7:
print('ะขะฐะปะฐััะบะฐั ะพะฑะปะฐััั')
elif number == 8:
print('ะงัะนัะบะฐั ะพะฑะปะฐััั')
elif number == 9:
print('ะัััะบ-ะัะปััะบะฐั ะพะฑะปะฐััั')
elif number == 0:
print('ะฒัะนัะธ ะธะท ัะธะบะปะฐ')
break
else:
print("ะขะฐะบะพะณะพ ัะตะณะธะพะฝะฐ ะฝะตั")
|
fa1200aaf3d92da9b51a6c124967ab88c94378e5 | Adinaytalalantbekova/pythonProject1 | /lesson_2..py | 922 | 3.765625 | 4 | # ะฃัะปะพะฒะฝัะต ะบะพะฝััััะบัะธะธ ะธ ะะฟะตัะฐัะพัั ััะฐะฒะฝะตะฝะธั, ะัะปะตะฐะฝั, ะฆะธะบะปั
# !=, <,>, <=, >=, not, and, or
count = 0
rounds = 12
while not count == rounds:
count += 1
if count == 6:
print('knock down, finish')
continue
print(count)
# bool()
# zero = False
# one = True
# number = 5
# user = int(input('Enter the number: '))
# if number > user:
# print('greater')
# if number < user:
# print('less')
# if number == user:
# print('equal')
# else:
# print('finish')
# while True:
# signal = input('Enter signal: ')
# if signal == 'green' or signal == 'ะทะตะปะตะฝัะน':
# print('Go!')
# elif signal == 'yellow' or signal == 'ะถะตะปััะน':
# print('ready')
# elif signal == 'red' or signal == 'ะบัะฐัะฝัะน':
# print('stop')
# else:
# print('look at the situation')
# break |
cfa1a3bd23631be1d067659f5d8ebf674341cad5 | soon-h/BaekJoon | /BaekJoonBasic/5622.py | 234 | 3.890625 | 4 | dial = ['ABC','DEF','GHI','JKL','MNO','PQRS','TUV','WXYZ']
word = input()
time = 0
for unit in dial :
for i in unit:
for x in word :
if i == x :
time += dial.index(unit) +3
print(time) |
f81eb55666cfbe6f99b59ddca4df58f3dfe04140 | soon-h/BaekJoon | /BaekJoonBasic/2884.py | 284 | 3.75 | 4 | Hour,Min = input().split()
Hour = int(Hour)
Min = int(Min)
if Min < 45:
if Hour == 0:
Hour = 23
Min = 60 - (45 - Min)
print(Hour,Min)
else:
Hour -= 1
Min = 60 - (45 - Min)
print(Hour,Min)
else:
Min -= 45
print(Hour,Min) |
849402be8f503d46883dc5e8238821566b33598b | Rajatku301999mar/Rock_Paper_Scissor_Game-Python | /Rock_paper_scissor.py | 2,350 | 4.21875 | 4 | import random
comp_wins=0
player_wins=0
def Choose_Option():
playerinput = input("What will you choose Rock, Paper or Scissor: ")
if playerinput in ["Rock","rock", "r","R","ROCK"]:
playerinput="r"
elif playerinput in ["Paper","paper", "p","P","PAPER"]:
playerinput="p"
elif playerinput in ["Scissor","scissor", "s","S","SCISSOR"]:
playerinput="s"
else:
print("I dont understand, try again.")
Choose_Option()
return playerinput
def Computer_Option():
computerinput=random.randint(1,3)
if computerinput==1:
computerinput="r"
elif computerinput==2:
computerinput="p"
else:
computerinput="s"
return computerinput
while True:
print("")
playerinput=Choose_Option()
computerinput=Computer_Option()
print("")
if playerinput=="r":
if computerinput=="r":
print("You choose Rock, Computer choose Rock, Match Tied...")
elif computerinput=="p":
print("You choose Rock, Computer choose Paper, You Lose...")
comp_wins+=1
elif computerinput=="s":
print("You choose Rock, Computer choose Scissor, You Win...")
player_wins+=1
elif playerinput=="p":
if computerinput=="r":
print("You choose Paper, Computer choose Rock, You Win...")
player_wins+=1
elif computerinput=="p":
print("You choose Paper, Computer choose Paper, Match Tied...")
elif computerinput=="s":
print("You choose Paper, Computer choose Scissor, You Lose...")
comp_wins+=1
elif playerinput=="s":
if computerinput=="r":
print("You choose Scissor, Computer choose Rock, You Lose...")
comp_wins+=1
elif computerinput=="p":
print("You choose Scissor, Computer choose Paper, You Win...")
player_wins+=1
elif computerinput=="s":
print("You choose Scissor, Computer choose Scissor, Match Tied...")
print("")
print("Player wins: "+ str(player_wins))
print("Computer wins: " + str(comp_wins))
print("")
playerinput=input("Do you want to play again? (y,n)")
if playerinput in ["Y","y","Yes","yes"]:
pass
elif playerinput in ["N","n","No","no"]:
break
else:
break
|
f9ac9c75d756a1548225c139265206ffb70e3bfc | manzeelaferdows/week3_homework | /data_types.py | 1,481 | 4.1875 | 4 | str = 'Norwegian Blue', "Mr Khan's Bike"
list = ['cheddar', ['Camembert', 'Brie'], 'Stilton', 'Brie', 'Brie']
tuples = (47, 'spam', 'Major', 638, 'Ovine Aviation')
tuples2 = (36, 29, 63)
set = {'cheeseburger', 'icecream', 'chicken nuggets'}
dict = {'Totness': 'Barber', 'BritishColumbia': 'Lumberjack'}
print(len(list))
print(min(tuples2))
print(max(tuples2))
print(sum(tuples2))
a = 'Mash Potato'
b = 'Gravy'
print(a, b)
a, b = b, a
print(a, b)
Gouda, Edam, Caithness = range(3)
print(range)
Belgium = 'Belgium,10445852,Brussels,737966,Europe,1830,Euro,Catholicism,Dutch,French,German'
Belgium2 = Belgium*2
print(Belgium2)
thing = 'Hello'
print(type(thing))
thing = ('Hello',)
print(type(thing))
list[:0] = ['Newham', 'Hackney']
print(list)
list += ['Southwark', 'Barking']
print(list)
list.extend(['Dagenham', 'Croydon'])
print(list)
list.insert(5, 'Tottenham')
print(list)
list[5:5] = ['Edmonton']
print(list)
list2 = list.pop(1)
print(list2)
list3 = list.pop(3)
print('the two items we removed:', list2, 'and', list3, "Now the list is shorter:", list)
list.remove('Edmonton')
print(list)
print(list.count('Brie'))
print(list.index('Brie'))
list.reverse()
print(list)
set1 = {5, 6, 7, 8, 9}
set2 = {10, 11, 12, 13}
print(set1)
print(set2)
set1.remove(9)
print(set1)
set2.add(9)
print(set2)
print(len(set2))
list4 = [1, 1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5]
list4b = ["cat", "dog", "cat", "dog"]
list4_set = set(list4)
list4 = list(list4_set)
print(list4)
|
e36f1118cfbfd8ac36951fe666b499717c5a22b5 | manzeelaferdows/week3_homework | /lotto.py | 685 | 3.984375 | 4 | import random
#print(help(random))
lucky_numbers = input('please type in your 6 lucky numbers')
lotto_numbers = []
for i in range(0, 6):
number = random.randint(1, 50)
while number in lotto_numbers:
number = random.randint(1, 50)
lotto_numbers.append(number)
print(lotto_numbers)
if lotto_numbers == lucky_numbers:
print("You win as the lottery numbers {} matches your lucky numbers{}".format(lotto_numbers, lucky_numbers))
else:
print("Better luck next time. The lottery numbers {} didn't match your lucky numbers{}".format(lotto_numbers,
lucky_numbers))
|
f4222eae8a9be74bd2a743bbb7ab0bb8c4300887 | Gabyluu/Python-Proyectos | /#clasesObjetos.py | 867 | 3.515625 | 4 | #clasesObjetos.py
class MixinsData(object);
def__init__(self,
user="anonimo",
password="patito",
port="1234",
ost="localhost",
db="sqlite3");
self.user = user
self.password = password
self.port = port
self.ost = host
self.db = db
#metodos para recuperar datos
def get_username(self):
return self.user
def get_password(self):
return self.password
def get_port(self):
return self.port
def get_host(self):
return self.host
def get_db(self):
return self.db
#atributos
usuario= str(input("Nombre del usuario? :_____"))
password = str(input("Password?:___ "))
obj = MixinsData(password= password, user=usuario)
print(obj.user)
print(obj.password)
print(obj.get_username())
user = obj.get_username()
print(user*10)
|
446c481634d6cf1cebf897533cfe9baaacce2c3e | plaetzaw/htx-immersive-01-20 | /01-week/4-Thursday/lectureNotes/class.py | 3,142 | 4.125 | 4 |
# Hello
# Hello
# Hello
# count = 0
# while count < 3:
# print('Hello')
# count += 1
# alphabet = [1, 2, 3, 4, 5, 6, 7]
# new_list = alphabet[2:5]
# myVar = 1
# mvVar2 = 2
# def greeting():
# print("hello world")
# if (myVar == 1):
# print('Hello')
# greeting()
# def print_students():
# print("Shu Pei")
# print("Thomas")
# print("Gustavo Fette")
# print("Alim")
# print("Day 1: Students in SRE class")
# print("lecture: git 101")
# print_students()
# print("Day 2: Students in SRE class")
# print("lecture: git 102")
# print_students()
# print("Day 3: Students in SRE class")
# print("lecture: python 101")
# print_students()
# def myFunction():
# for i in range(10):
# print(i)
# def greeting():
# print('hello')
# for i in range(10):
# greeting()
# def separateRuns():
# print('******************')
# print()
# def getGroceries():
# print('milk')
# print('flour')
# print('sugar')
# print('butter')
# separateRuns()
# for i in range(3):
# getGroceries()
# def greeting(person):
# print(f'hello {person}')
# greeting('Kazim')
# def add(num1, num2):
# sum = num1 + num2
# return sum
# result = add(4, 5)
# # print(result)
# def concat_lists(list1, list2):
# concat = list1 + list2
# return concat
# c_result = concat_lists([1, 4, 6], [7, 9, 0])
# print(c_result)
# def cal_avg(param1, param2, param3, parm4):
# sum = param1 + param2 + param3 + parm4
# avg = sum / 4
# return avg
# result = cal_avg(4, 6, 9, 0)
# print(result)
# print(cal_avg(6, 8, 22, 11))
# def myFunction(num1, num2, num3):
# return num1*2, num2*3, num3*4
# c1, c2, c3 = myFunction(4, 7, 9)
# print(c1)
# print(c2)
# print(c3)
# def addTwo(startingValue):
# endingValue = startingValue + 2
# print('The sum of', startingValue, 'and 2 is:', endingValue)
# return endingValue
# result = addTwo(5)
# print(result)
# print("hello")
# def greeting(name):
# print(f'hello {name}')
# students = ['Kazim', "Matt", "Alina", "Mary", "Alex"]
# for name in students:
# greeting(name)
# print("bye")
# TAX_RATE = .09 # 9 percent tax
# COST_PER_SMALL_WIDGET = 5.00
# COST_PER_LARGE_WIDGET = 8.00
# def calculateCost(nSmallWidgets, nLargeWidgets):
# TAX_RATE = 7
# subTotal = (nSmallWidgets * COST_PER_SMALL_WIDGET) + (nLargeWidgets * COST_PER_LARGE_WIDGET)
# taxAmount = subTotal * TAX_RATE
# totalCost = subTotal + taxAmount
# return totalCost
# total1 = calculateCost(4, 8) # 4 small and 8 large widgets
# print('Total for first order is', total1)
# total2 = calculateCost(12, 15)
# def dance2():
# print("I want to do a %s dance" % kind)
# def dance():
# kind = "silly"
# print("I am doing a %s dance" % kind)
# dance2()
# dance()
# def dance(kind="silly"):
# print("I am doing a %s dance" % kind)
# dance("funky") # Totally OK.
# print(kind) # Error!
def dance(kind="silly"):
print(f'I am doing a {kind} dance')
dance("funky") # Totally OK.
|
866df365ca6ec790f67224b2208e90eca5eeb811 | vaamarnath/amarnath.github.io | /content/2011/10/multiple.py | 665 | 4.125 | 4 | #!/usr/bin/python
import sys
def checkMultiple(number) :
digits = {"0":0, "1":0, "2":0, "3":0, "4":0, "5":0, "6":0, "7":0, "8":0, "9":0}
while number != 0 :
digit = number % 10
number = number / 10
digits[str(digit)] += 1
distinct = 0
for i in range(0, 10) :
if digits[str(i)] != 0 :
distinct += 1
return distinct
number = int(sys.argv[1])
counter = 1
while True :
multiple = number * counter
if checkMultiple(multiple) == 1 :
print "Found the multiple with least number of distinct digits"
print multiple, counter
break
counter += 1
print multiple,
|
96961f632167a62d1a4dfd8b6928b0a21f86cfc2 | dengking/TheAlgorithms-Python | /recursion/Euclidean_algorithm.py | 962 | 3.921875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/10/6 11:21
# @File : Euclidean_algorithm
def recursive_gcd(a, b):
"""
gcd(a, b) = gcd(b, a mode b)
:param a:
:param b:
:return:
"""
if b == 0:
return a
remainder = a % b
if remainder == 0:
return b
return recursive_gcd(b, remainder)
def iterative_gcd(a, b):
"""
:param a:
:param b:
:return:
"""
while True:
if b == 0:
return a
remainder = a % b
if remainder == 0:
return b
a, b = b, remainder
if __name__ == '__main__':
print(recursive_gcd(2, 4))
print(iterative_gcd(2, 4))
assert recursive_gcd(2, 4) == recursive_gcd(4, 2) == iterative_gcd(2, 4) == iterative_gcd(4, 2)
print(recursive_gcd(1997, 615))
print(iterative_gcd(1997, 615))
assert recursive_gcd(1997, 615) == recursive_gcd(615, 1997) == iterative_gcd(1997, 615) == iterative_gcd(615, 1997)
|
3a29452ad6baf1d89fc522842a7657ea54bc2e16 | ViswanathanMukundan/AutoSummarizer_Python | /Summarizer.py | 1,810 | 3.90625 | 4 | '''PY PROGRAM TO GENERATE A SUMMARY FOR A GIVEN PIECE OF TEXT'''
'''FURTHER TASKS:
1. REPLACE MORE CASES LIKE i.e., AND e.g. IN ORDER TO AVOID CONFUSIONS WHILE TOKENIZING.
2. FIND A WAY TO GET THE TEXT FROM PARSING THE SOURCE CODE OF A WEBSITE.
3. MODULARIZE THE CODE.
4. EXPAND STOPWORD LIST.
5. CONVERT THE SUMMARY FROM LIST TO STRING.'''
import nltk
from nltk.corpus import stopwords
from string import punctuation
from nltk.tokenize import word_tokenize, sent_tokenize
from heapq import nlargest
from nltk.probability import FreqDist
from collections import defaultdict
t = input("Enter text: ")
t = t.replace("i.e.","that is, ")
t = t.replace("e.g.","for example, ") #FIND MORE SUCH CASES LIKE THESE TWO
def summarize(text, n):
sents = sent_tokenize(text)
assert n <= len(sents)
word_sent = word_tokenize(text.lower())
_stopwords = set(stopwords.words('english') + list(punctuation)) #Create a custom list of all stopwords to be removed from the text. The list consists of all stopwords from nltk.corpus as well as punctuation marks from string module.
word_sent = [word for word in word_sent if word not in _stopwords] #Create a list of all words in the text with the stopwords removed.
freq = FreqDist(word_sent) #The freq distribution of the words in the text is constructed as a dictionary with the key as the word and the value as its frequency.
ranking = defaultdict(int) #Create a new dictionary to store the word frequencies.
for i, sent in enumerate(sents):
for w in word_tokenize(sent.lower()):
if w in freq:
ranking[i] += freq[w]
sents_index = nlargest(n, ranking, key=ranking.get) #Get the top n frequencies of words in the text
return [sents[j] for j in sorted(sents_index)]
print("\nSummary: ", summarize(t,10))
|
2cac53c06247c2326e847d77a9c3f402e5ec59c0 | Aarif123456/prisonerDilemmaSimulator | /pavlov.py | 987 | 3.65625 | 4 | # COMP-3710 Final project Prisoner Dilemma simulator
# the pavlov bot cooperates on the first move and defect if the players had two different previous move
# this strategy is also called win-stay-lose-shift
from botBase import baseBot
class pavlovBot(baseBot):
def __init__(self):
# bot inherits from base class and sets it's name
super().__init__("pavlov")
def getMove(self,opponentMoves) -> bool:
if(len(opponentMoves)==0): #for first move cooperate
self.lastMove = baseBot.cooperate
else:
# If both defected it will try to forgive.
# So, it see see-saws between tit-for-tat and forgiving. We could make this strategy
# more advanced by remembering more
if self.lastMove == opponentMoves[-1]:
self.lastMove = baseBot.cooperate
# lastly if it cooperated and other defected switch to defect or if other cooperated and it defected then keep defecting
else:
self.lastMove = baseBot.defect
return self.lastMove
|
080025aa8dea5b5a00709e17964d026f03c60d0e | MKRNaqeebi/CodePractice | /Past/amma/4442.py | 1,716 | 3.984375 | 4 | import collections
def solution(S):
"""
Calculate smallest sub-array length from an array in which all integer exists from the original array
Sample Input ==> Sample Output
[7, 3, 7, 3, 1, 3, 4, 1] ==> 5
[2, 1, 1, 3, 2, 1, 1, 3] ==> 3
[7, 5, 2, 7, 2, 7, 4, 7] ==> 6
[1, 1, 2, 3, 4, 5, 1, 1, 1] ==> 5
:param [] S: orignal array
:return int: length of smallest subarray
"""
alphabet = set(S) # get all unique numbers
var_count = collections.defaultdict(int) # make dict to hold count of all number in sub array
start = 0
for end in range(len(S)):
var_count[S[end]] += 1 # Count all number
if len(var_count) == len(alphabet): # Get possible best end if 0 is best start for subarray
break
best_start = start
best_end = end
while end < len(S):
while var_count[S[start]] > 1: # Check if starting element is more than once so we can remove
var_count[S[start]] -= 1
start += 1
if end - start < best_end - best_start: # Check if we have better subarray than previous
best_start = start
best_end = end
var_count[S[end]] += 1 # Move end forward for we can check we have best array here or ahead
end += 1
return 1 + best_end - best_start # len of best array; +1 cause we incluse both end in smallest array
print(solution([7, 3, 7, 3, 1, 3, 4, 1]))
print(solution([2, 1, 1, 3, 2, 1, 1, 3]))
print(solution([7, 5, 2, 7, 2, 7, 4, 7]))
print(solution([1, 1, 2, 3, 4, 5, 1, 1, 1]))
|
c50e993970f4bc347da833816541caa978c68642 | BobcatsII/brush_leetcode | /tree/Nๅๆ ็ๅฑๅบ้ๅ.py | 930 | 3.703125 | 4 | ##dfs
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
res = []
def dfs(root, depth):
if not root: return
if len(res) <= depth:
res.append([])
res[depth].append(root.val)
for ch in root.children:
dfs(ch, depth+1)
dfs(root, 0)
return res
##BFS
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if not root: return []
res = []
queue = [root] #ๅๅงๅไธไธชroot
while queue:
cur = []
res.append([])
for node in queue: #ๅ ไธบๆฏNๅๆ ,ๆไปฅ้่ฆ้ๅ
res[-1].append(node.val)
cur.extend(node.children)
queue = cur ##้่ฆ!
return res |
6ec390b3fd5f838db120c42991b17d59ef289ce0 | BobcatsII/brush_leetcode | /stack_and_queue/ๆๆ็ๆฌๅท.py | 1,297 | 3.78125 | 4 | # ่ฏฆ็ปๅๆณ
from collection import deque
class Stack:
def __init__(self):
self.items = deque()
def push(self, val):
return self.items.append(val)
def pop(self):
return self.items.pop()
def empty(self):
return len(self.items) == 0
def top(self):
return self.items[-1]
class Solution:
def isValid(self, s: str) -> bool:
if not s:
return True
stack = Stack()
for char in s:
if stack.empty():
stack.push(char)
else:
top = stack.top()
if is_pair(char) == top:
stack.pop()
else:
stack.push(char)
return stack.empty()
def is_pair(char):
if char == ")":
return "("
elif char == "]":
return "["
elif char == "}":
return "{"
# ็ฎๅๅๆณ
class Solution:
def isValid(self, s: str) -> bool:
dic = {")":"(", "]":"[","}":"{"}
stack = []
for i in s:
if stack and i in dic:
if stack[-1] == dic[i]:
stack.pop()
else:
return False
else:
stack.append(i)
return not stack
|
7655aca2a56f81d9b23a40f4e83e4b18389c2355 | BobcatsII/brush_leetcode | /array_linkedlist/ๅๅนถไธคไธชๆๅบๆฐ็ป.py | 1,312 | 3.546875 | 4 | # ๆนๆณไธ
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
if 0 == n:
pass
elif 0 == m:
nums1[:n] = nums2[:n]
else:
a, b = m-1, n-1
k = m+n-1
while (a >= 0) and (b >= 0):
if nums1[a] <= nums2[b]: #nums1 ็ๅ
็ด ๅฐฝ้ๅฐๅจ
nums1[k] = nums2[b]
k -= 1
b -= 1
else:
nums1[k] = nums1[a]
k -= 1
a -= 1
if (a >= 0):
pass
if (b >= 0):
nums1[k-b:k+1] = nums2[:b+1] #ๅฟ
็ถๆ k-b == 0๏ผๅ ไธบๅฉไธ็ๆฏๆๅฐ็๏ผๅฟ
็ถๆฏcopyๅฐๆๅ้ข
#็ฎๅๆนๆณ
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
while n:
if m and nums1[m - 1] >= nums2[n - 1]:
nums1[m + n - 1] = nums1[m - 1]
m -= 1
else:
nums1[m + n - 1] = nums2[n - 1]
n -= 1
#ๆ็นๅๅทงๅง๏ผไธ็ฅ้ๅฅฝไธๅฅฝ
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
nums1[m:] = nums2[:n]
nums1.sort()
|
95623ba15a7de048ac4527d053acbe8a3eeb6ccc | artem1205/shipengine-python | /shipengine/util/__init__.py | 481 | 3.640625 | 4 | """Testing a string manipulation helper function."""
from .sdk_assertions import * # noqa
def snake_to_camel(snake_case_string: str) -> str:
"""
Takes in a `snake_case` string and returns a `camelCase` string.
:params str snake_case_string: The snake_case string to be converted
into camelCase.
:returns: camelCase string
:rtype: str
"""
initial, *temp = snake_case_string.split("_")
return "".join([initial.lower(), *map(str.title, temp)])
|
68be2823bda994f4bdebb5c508bf80e9a0ad4a44 | jasper-lu/LNYF-Matching | /matching.py | 4,383 | 3.625 | 4 | from dancer import Dancer, Dancers
from dance import Dance
import random
# Our matching algorithm is basically just the hospital resident matching algorithm.
# https://en.wikipedia.org/wiki/Stable_marriage_problem
# Classes are named as such to reflect that.
class Player:
def __init__(self, name):
self.name = name
self.prefs = None
self.matching = None
# Get the player's favorite in prefs that they are not currently matched with, or None
def get_favorite(self):
return self.prefs and self.prefs[0] or None
def match(self, other):
self.matching = other
def unmatch(self, other):
self.matching = None
def set_preferences(self, prefs):
self.prefs = prefs
self.pref_names = [x.name for x in prefs]
def forget(self, other):
prefs = self.prefs[:]
if other in prefs:
prefs.remove(other)
self.prefs = prefs
class Hospital(Player):
def __init__(self, name, capacity):
super().__init__(name)
self.capacity = capacity
self.matching = []
def match(self, other):
self.matching.append(other)
self.matching.sort(key=self.prefs.index)
def unmatch(self, other):
matching = self.matching
matching.remove(other)
self.matching = matching
def match_pair(a, b):
a.match(b)
b.match(a)
def unmatch_pair(a, b):
a.unmatch(b)
b.unmatch(a)
def delete_pair(a, b):
a.forget(b)
b.forget(a)
def match_dancers(dancers, dances, shuffle=True):
# The algorithm here biases toward dancer preferences
# i.e. a dancer who ranks urban dance first, but gets a purple in
# kpop and a green in urban dance will more likely be placed in
# urban dance.
dancer_players = [Player(x.email) for x in dancers]
dance_players = [Hospital(x.name, x.quota) for x in dances]
# Add in a little more randomness.
if shuffle:
random.shuffle(dancer_players)
def set_prefs():
dancer_players_dict = {x.name: x for x in dancer_players}
dance_players_dict = {x.name: x for x in dance_players}
for dancer_name, dancer in dancer_players_dict.items():
dancer_obj = dancers[dancer_name]
prefs = [dance_players_dict[x] for x in dancer_obj.preferences]
dancer.set_preferences(prefs)
for dance_name, dance in dance_players_dict.items():
dance_obj = dances[dance_name]
prefs = [dancer_players_dict[x.email] for x in dance_obj.rankings]
dance.set_preferences(prefs)
set_prefs()
# Run the algorithm until the matching is stable.
while dancer_players:
dancer = dancer_players.pop()
dance = dancer.get_favorite()
# If the dancer is in the reds of the dance, or wasn't ranked, then remove them because
# they will never be matched to that dance.
# Keep going until we get a dance that the dancer can actually be ranked with.
# This is to incentivize people to be true to their dance preferences, instead
# of playing the game of "I didn't do well in soran auditions, so I should
# rank it lower."
while dance and dancer not in dance.prefs:
dancer.forget(dance)
dance = dancer.get_favorite()
# Too bad lol. The dancer ran out of dances to be matched to.
if not dance:
continue
match_pair(dance, dancer)
# The dance is over capacity now, so kick out the person with the worst ranking
if len(dance.matching) > dance.capacity:
worst_match = dance.matching[-1]
unmatch_pair(dance, worst_match)
# Put the player back in consideration for other dances.
dancer_players.append(worst_match)
# Once a dance has reached capacity, it won't consider any dancers
# ranked lower than the dancer with the current worst ranking.
# So, delete those pairs.
if len(dance.matching) == dance.capacity:
worst_match = dance.matching[-1]
to_forget = dance.prefs[dance.prefs.index(worst_match) + 1:]
for dancer_to_forget in to_forget:
delete_pair(dance, dancer_to_forget)
# Algorithm has finished running. Return the matchings.
return {d: d.matching for d in dance_players}
|
e1289e9769ad313bc415a66d5e5600e5007fec90 | dhansolo/R-P-S | /main.py | 684 | 4.21875 | 4 | from random import randint
player = raw_input('rock (r), paper (p), or scissors (s)? ')
while player != 'r' and player != 'p' and player != 's':
player = raw_input('Must choose rock (r), paper (p), or scissors (s) ')
# end='' tells print to print an extra space instead of a line in python 3 and above
computer = randint(1, 3)
if computer == 1:
computer = 'r'
elif computer == 2:
computer = 'p'
else:
computer = 's'
print(player, 'vs', computer)
if(player == computer):
print('TIE!')
elif(player == 'r' and computer == 's' or player == 's' and computer == 'p' or player == 'p' and computer == 'r'):
print('PLAYER WINS!')
else:
print('COMPUTER WINS!')
|
8ade0d93f3f875e777b57d39c90326247da41860 | Wallart/gluon-tacotron2 | /initializer/custom_xavier.py | 2,164 | 3.59375 | 4 | from mxnet import nd
from mxnet.initializer import Xavier, register
import math
def calculate_gain(nonlinearity, param=None):
r"""Return the recommended gain value for the given nonlinearity function.
The values are as follows:
================= ====================================================
nonlinearity gain
================= ====================================================
Linear / Identity :math:`1`
Conv{1,2,3}D :math:`1`
Sigmoid :math:`1`
Tanh :math:`\frac{5}{3}`
ReLU :math:`\sqrt{2}`
Leaky Relu :math:`\sqrt{\frac{2}{1 + \text{negative\_slope}^2}}`
================= ====================================================
Args:
nonlinearity: the non-linear function (`nn.functional` name)
param: optional parameter for the non-linear function
Examples:
>>> gain = nn.init.calculate_gain('leaky_relu')
"""
linear_fns = ['linear', 'conv1d', 'conv2d', 'conv3d', 'conv_transpose1d', 'conv_transpose2d', 'conv_transpose3d']
if nonlinearity in linear_fns or nonlinearity == 'sigmoid':
return 1
elif nonlinearity == 'tanh':
return 5.0 / 3
elif nonlinearity == 'relu':
return math.sqrt(2.0)
elif nonlinearity == 'leaky_relu':
if param is None:
negative_slope = 0.01
elif not isinstance(param, bool) and isinstance(param, int) or isinstance(param, float):
# True/False are instances of int, hence check above
negative_slope = param
else:
raise ValueError('negative_slope {} not a valid number'.format(param))
return math.sqrt(2.0 / (1 + negative_slope ** 2))
else:
raise ValueError('Unsupported nonlinearity {}'.format(nonlinearity))
@register
class CustomXavier(Xavier):
def __init__(self, gain):
super(CustomXavier, self).__init__(rnd_type='uniform', factor_type='out', magnitude=3)
self._gain = nd.array(calculate_gain(gain))
def _init_weight(self, _, arr):
super()._init_weight(_, arr)
nd.elemwise_mul(arr, self._gain, out=arr)
|
7cee4713aa67c45851d8ac66e6900c25c95ccef1 | UCMHSProgramming16-17/final-project-shefalidahiya | /day05/ifstatement2.py | 366 | 4.375 | 4 | # Create a program that prints whether a name
# is long
name = "Shefali"
# See if the length of the name counts as long
if len(name) > 8:
# If the name is long, say so
print("That's a long name")
# If the name is moderate
elif len(name) < 8:
print("That's a moderate name")
# If the name is short
else len(name) < 5:
print("That's a short name") |
c0e649a267a181a377f4f3651c6467908cd6789c | UCMHSProgramming16-17/final-project-shefalidahiya | /day14/rps.py | 3,138 | 4.46875 | 4 | # import random module
import random
# run function while count is less than/equal to 3
while count >= 3:
# set count to zero at start
count = 0
# set number of computer wins to 0
computer = 0
# set number of human wins to 0
human = 0
# allow user to choose rock, paper, or scissors
a = input("rock, paper, or scissors? ")
# allow computer to randomly chose rock, paper or scissors
options = ["rock", "paper", "scissors"]
b = random.choice(options)
# print what the computer and you chose
print("you chose", a, "and computer choses", b)
# define function
def rockpaperscissors():
# if user = rock and computer = rock
if a == "rock":
if b == "rock":
# print "tie"
print("tie!")
# reduce count bc a tie should not count as a round
count -= 1
# if user = rock and computer = paper
elif b == "paper":
# print "computer wins"
print("computer wins")
# add to computer victories
computer +=1
# if user = rock and computer = scissors
elif b == "scissors":
# print "you win"
print("you win!")
# add to human victories
human += 1
# if user = paper and computer = paper
if a == "paper":
if b == "paper":
# print tie
print("tie!")
# reduce count bc a tie should not count as a round
count -= 1
# if user = paper and computer = scissors
elif b == "scissors":
# print "computer wins"
print("computer wins")
# add to computer victories
computer +=1
# if user = paper and computer = rock
elif b == "rock":
# print "you win"
print("you win!")
# add to human victories
human += 1
# if user = scissors and computer = scissors
if a == "scissors":
if b == "scissors":
# print tie
print("tie!")
# reduce count bc a tie should not count as a round
count -= 1
# if user = scissors and computer = rock
elif b == "rock":
# print "computer wins"
print("computer wins")
# add to computer victories
computer +=1
# if user = scissors and computer = paper
elif b == "paper":
# print "you win"
print("you win!")
# add to human victories
human += 1
# call function
rockpaperscissors()
# increase count for each time run through function
count += 1
# if human has won twice
if human == 2:
print("you win!" )
# print "you win game"
# if computer has won twice
if computer == 2:
# print "computer wins game"
print("computer wins game" ) |
97650c893ca11f33314f88708d54257d5f6ccbf6 | Mini-Pingu/studious-giggle | /past_apps/app6.py | 235 | 3.8125 | 4 | # values = [item * 2 for item in range(5) if item > 2]
# print(values)
try:
age = int(input("Age: "))
x = 10 / age
except (ValueError, ZeroDivisionError):
print("You entered the wrong type value.")
else:
print("hihi")
|
b362396efd75e55fea862695e2592ab8e50a1f59 | tommy85/test | /python/test8.py | 806 | 4.09375 | 4 | #!/usr/local/bin/python
import exceptions
#print dir(exceptions)
#raise ZeroDivisionError("zero exception")
class CustomException(Exception):
str = "caonima"
def hehe(self):
print self.str
while True:
try:
x = input('first number:')
y = input('second number:')
raise CustomException("zhangteng exception")
print x/y
#except ZeroDivisionError,e:
# print e
# print "The second number can't be zero!"
#except TypeError:
# print "That wasn't a number."
#except (ValueError,NameError),e:
# print e
except CustomException,e:
e.hehe()
except Exception,e:
e.hehe()
print 'Invalid input',e
print 'try again'
else:
break
finally:
print "clean up"
|
524f63f9f4d75d2da2259550b912a473a4673b96 | elu267/python-challenge | /PyPoll/main.py | 4,503 | 3.828125 | 4 | # Read the csv file
import os
import csv
# getting the csv file (data set)
csvFile = os.path.join('election_data.csv')
# creating a variable to store the entire dataset
csvDataset = []
# creating a variable to store the candidate names
csvDataset_Candidate = []
# creating a variable to store the voter IDs
csvDataset_VoterID = []
# creating a variable to hold the candidate, percentage of votes and total votes
summary_votes = []
# creating formatting for print
lines = "-" * 25
# another way to call in a file without importing os is using pandas - holy cow, that is so much simpler
with open(csvFile,'r') as electionFile:
csvRead = csv.reader(electionFile,delimiter=',')
#print(csvRead)
csv_header = next(csvRead) #skips the header
#print(f"CSV Header: {csv_header}")
for row in csvRead:
# print(row)
# this creates a list of dictionaries (i.e. one dictionary for each voter ID)
# you missed a great white boarding session as I figured this out
# adds the keys for the header and selects each value by its index
csvDataset.append({
'voterID': row[0], \
'county': row[1], \
'candidate': row[2]
})
csvDataset_Candidate.append(row[2]) # giving myself list options for later
csvDataset_VoterID.append(row[0]) # same
# the total number of votes cast
total_votes = len(csvDataset_VoterID)
# a complete list of candidates who received votes
unique_candidate = []
def unique():
# global allows write access to the list variable, unique_candidate
global unique_candidate
#loop through all elements in list
for x in csvDataset_Candidate:
# check if candidate exists in the unique list or not
if x not in unique_candidate:
unique_candidate.append(x)
#for x in unique_candidate:
#print(x)
# calling the function because if you don't then nothing happens
unique()
# the percentage of votes each candidate won
# the total number of votes each candidate won
def sumVotes():
for z in unique_candidate: # z becomes the candidate name
votes = 0 # variable resets to zero each loop
#print(z)
for c in csvDataset: # c is the counter that loops through the dictionary
if z == c["candidate"]: # because z always equals c (duh) - see vba homework
votes += 1 # tally of votes per candidate
#print(votes)
pctVotes = round(((votes/total_votes) * 100), 3) # calculating the percentage of votes with three decimals
# adding each key and value to a dictionary
summary_votes.append({'candidate': z,'pctVotes': pctVotes, 'totVotes': votes})
sumVotes() # calling the function
#print(summary_votes)
# the winner of the election based on popular vote
winnerChickenDinner = None # setting variable to no one
def winner():
rockTheVote = 0 # setting variable to zero
global winnerChickenDinner # made this global b/c it wouldn't print otherwise
for x in summary_votes: # looping through total votes in the dictionary
if x['totVotes'] > rockTheVote: # if the value is the maximum then that is the winner
rockTheVote = x['totVotes'] # getting and storing max votes
winnerChickenDinner = x['candidate'] # the name of the winner if they have the max votes
winner()
print("Election Results\n")
print(f"{lines}\n")
print(f"Total Votes: {total_votes}\n")
print(f"{lines}\n")
for x in summary_votes:
print("{0}: {1:.3f}% ({2:.0f})\n".format(x['candidate'], x['pctVotes'], x['totVotes']))
print(f"{lines}\n")
print(f"Winner: {winnerChickenDinner}\n")
print(f"{lines}")
# Write to a text file
target = open("pyPoll.txt", 'w')
target.write("Election Results\n")
target.write(f"{lines}\n")
target.write(f"Total Votes: {total_votes}\n")
target.write(f"{lines}\n")
for x in summary_votes:
target.write("{0}: {1:.3f}% ({2:.0f})\n".format(x['candidate'], x['pctVotes'], x['totVotes']))
target.write(f"{lines}\n")
target.write(f"Winner: {winnerChickenDinner}\n")
target.write(f"{lines}") |
9a9ce98f6276d68c81f501b3815f71ec11dce377 | danebulat/py-image-manip-demo | /imgmanip/manipulator.py | 6,824 | 3.75 | 4 | """ manipulator.py
Implements the ImageManipulator class which caches a loaded image in
memory. The class operations process this image, and the image can be
saved to a new file by called ImageManipulator.save_image().
"""
import os
import copy
from PIL import Image, ImageEnhance, ImageFilter
# -------------------------------------------------------------------------
# MODULE: ImageManipulator Class
# -------------------------------------------------------------------------
class ImageManipulator:
"""A class that caches an input image and performs a number of operations
on it using PIL (Python Imaging Library).
"""
def __init__(self, image, index):
self.image = image
self.original_filename = image.filename
self.save_flag = False
self.index = index
def output_information(self):
"""Sends image properties to standard output."""
print("{0:<9}: {1}".format("Filename", self.image.filename))
print("{0:<9}: {1}".format("Size", self.image.size))
print("{0:<9}: {1}".format("Format", self.image.format))
print("{0:<9}: {1}\n".format("Bands", self.image.getbands()))
def _apply_filter(self, filter_string):
"""Apply a PIL filter to an image and return it."""
return {
'BLUR': self.image.filter(ImageFilter.BLUR),
'CONTOUR': self.image.filter(ImageFilter.CONTOUR),
'DETAIL': self.image.filter(ImageFilter.DETAIL),
'EDGE_ENHANCE': self.image.filter(ImageFilter.EDGE_ENHANCE),
'EMBOSS': self.image.filter(ImageFilter.EMBOSS),
'FIND_EDGES': self.image.filter(ImageFilter.FIND_EDGES),
'SHARPEN': self.image.filter(ImageFilter.SHARPEN),
'SMOOTH': self.image.filter(ImageFilter.SMOOTH),
'SMOOTH_MORE': self.image.filter(ImageFilter.SMOOTH_MORE),
'EDGE_ENHANCE_MORE':
self.image.filter(ImageFilter.EDGE_ENHANCE_MORE)
}[filter_string]
def apply_filter_and_save(self, filter_string):
"""Apply a filter to a loaded image and save the new version."""
self.save_flag = True
self.image = self._apply_filter(filter_string)
print(f"{filter_string} filter applied to {self.original_filename}")
def _apply_enhancer(self, enhancer, enhancer_string, factor):
"""Enhances an image and saves a new file."""
self.image = enhancer.enhance(factor)
print("{0} enhancer applied to {1} [factor = {2}]"
.format(enhancer_string, self.original_filename, factor))
def apply_enhancer_and_save(self, enhancer_string, factor):
"""Enhances an image and calls apply_enhancer() to save a new file."""
# Set save flag
self.save_flag = True
if enhancer_string == 'BRIGHTNESS':
enh = ImageEnhance.Brightness(self.image)
self._apply_enhancer(enh, enhancer_string, factor)
elif enhancer_string in ['COLOR', 'COLOUR']:
enh = ImageEnhance.Color(self.image)
self._apply_enhancer(enh, enhancer_string, factor)
elif enhancer_string == 'CONTRAST':
enh = ImageEnhance.Contrast(self.image)
self._apply_enhancer(enh, enhancer_string, factor)
elif enhancer_string == 'SHARPNESS':
enh = ImageEnhance.Sharpness(self.image)
self._apply_enhancer(enh, enhancer_string, factor)
elif enhancer_string == 'GREYSCALE':
self.image = self.image.convert('L')
print("{0} enhancer applied to {1}".format(
enhancer_string, self.original_filename))
elif enhancer_string in ['GAUSSIANBLUR', 'BOXBLUR']:
if enhancer_string == 'GAUSSIANBLUR':
self.image = self.image.filter(
ImageFilter.GaussianBlur(factor))
else:
self.image = self.image.filter(
ImageFilter.BoxBlur(factor))
print("{0} filter applied to {1} [radius = {2}]".format(
enhancer_string, self.original_filename, factor))
def generate_thumbnail(self, width):
"""Saves a thumbnail version of the cached image."""
# Make a deep copy of the image before generating thumbnial
thumb_image = copy.deepcopy(self.image)
# Calculate heigt dynamically based on the received width
size = (width,
int(((width / self.image.size[0]) * self.image.size[1])))
# Calculate the output name - name-widthxheight.thumb
name = os.path.splitext(self.image.filename)[0]
out_filename = name + '-' + \
str(size[0]) + 'x' + str(size[1]) + '-' + str(self.index) \
+ '.thumb'
# Generate thumbnail and save
thumb_image.thumbnail(size)
thumb_image.save(out_filename, thumb_image.format)
print("Thumbnail of {0} generated: {1}".format(
self.original_filename, out_filename))
def apply_flips(self, flips):
"""Flips the image horizontally or vertically."""
# Flip internal image
for flip in flips:
if flip.upper() == 'HORZ':
self.image = self.image.transpose(Image.FLIP_LEFT_RIGHT)
print(f"{self.original_filename} flipped horizontally.")
elif flip.upper() == 'VERT':
self.image = self.image.transpose(Image.FLIP_TOP_BOTTOM)
print(f"{self.original_filename} flipped vertically.")
# Save file
self.save_flag = True
def resize_image(self, size):
"""Resizes cached image to the X and Y values in the passed tuple.
"""
self.image = self.image.resize(size)
print(f"{self.original_filename} resized to: {size}")
# Save file
self.save_flag = True
def rotate_image(self, increment):
"""Rotates the cached image counter-clockwise in a 90 degree
increment.
"""
if increment == 90:
self.image = self.image.transpose(Image.ROTATE_90)
elif increment == 180:
self.image = self.image.transpose(Image.ROTATE_180)
else:
self.image = self.image.transpose(Image.ROTATE_270)
print(f"{self.original_filename} rotated {increment} degrees CCW.")
# Save file
self.save_flag = True
def save_image(self):
"""Saves the image to a new file if save flag is set."""
if self.save_flag is True:
name, ext = os.path.splitext(self.original_filename)
out_filename = name + '-manip-' + str(self.index) + ext
self.image.save(out_filename)
print(f"New file saved as: {out_filename}")
|
808727432b9d4db61b4c6b6dfc497ce9302e0a76 | core-harshit/core-harshit | /Coding/alternatesorting.py | 715 | 3.921875 | 4 | def alternatingSort(a):
b=[]
c=0
if len(a)%2==0:
for c in range(len(a)//2):
b.append(a[c])
b.append(a[-c-1])
if len(b)!=len(set(b)):
return False
else:
if b==sorted(b):
return True
else:
return False
else:
for c in range(len(a)):
b.append(a[c])
b.append(a[-c-1])
del b[len(a)::]
if len(b)!=len(set(b)):
return False
else:
if b==sorted(b):
return True
else:
return False
a=[-92, -23, 0, 45, 89, 96, 99, 95, 89, 41, -17, -48]
p=alternatingSort(a)
print(p)
|
1a9dea57415668bf56fd5e0b0193952a1af49e27 | freaking2012/coding_recipes | /Python/LearnBasics/HashPattern2.py | 365 | 4.3125 | 4 | '''
This program takes input a even number n. Then it prints n line in the following pattern
For n = 8
##
####
######
########
########
######
####
##
'''
n=input("Enter number of lines in patter (should be even): ")
for i in range(1,n/2+1):
print (' ' * (n/2-i)) + ('##' * i)
for i in range(1,n/2+1):
print (' ' * (i-1)) + ('##' * (n/2-i+1))
|
f55cc1e9874d4173e4ee8f3e6b0451753a048c70 | Jan-Zeiseweis/pycriteo | /pycriteo/util.py | 1,742 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
class CurrencyConverter(object):
"""
Converts currencies (ISO 4217 format).
Arguments:
from_currency -- currency to convert from (i.e 'EUR')
to_currency -- currency to convert to (i.e 'USD')
Example:
Convert from USD to EUR
>>> currency_converter = CurrencyConverter('USD', 'EUR')
>>> currency_converter.convert(45.15)
33.34
"""
def __init__(self, from_currency, to_currency):
_from = from_currency.upper()
_to = to_currency.upper()
if len(_from) != 3 or len(_to) != 3:
raise Exception("Currency has wrong length (should have length 3)")
self.from_currency = _from
self.to_currency = _to
self.exchange_rate = None
def convert(self, amount):
return round(float(amount) * float(self._exchange_rate()), 2)
def _exchange_rate(self):
if not self.exchange_rate:
self.exchange_rate = self._get_exchange_rate()
return self.exchange_rate
def _get_exchange_rate(self):
request_url = ("http://rate-exchange.appspot.com/currency?"
"from={0}&to={1}".format(self.from_currency,
self.to_currency))
response = urllib2.urlopen(request_url)
exchange_info = json.loads(response.read())
if 'err' in exchange_info:
raise Exception(exchange_info['err'] +
" Check if your currencies are in ISO 4217")
assert(exchange_info['to'] == self.to_currency)
assert(exchange_info['from'] == self.from_currency)
return exchange_info['rate']
|
f1ee0a14505213b22191a31d3e9ce1c3446828ea | smoloney/CS415 | /project1/project.py | 7,674 | 4.03125 | 4 | #Authors: Sean Moloney and Jon Killinger
#Class : CS 415
#Assignment: Project 1
#In order to run this program, compile it wil python2 project.py
# all the computations for HW 1 shall be done using binary arithmetic
# only the user input and the final output will be in decimal.
# the two functions dec2bin and bin2dec provide I/O conversion between
# binary and decimal.
# functions provided: Add, Mult, divide and many supporting functions such as
# Compare to compare two unbounded integers, bin2dec and dec2bin etc.
# missing functions: sub which performs subtraction and Divide which is the decimal version
# of divide, and also a solution to Problem 3.
########################################################
### SAMPLE INPUT/OUTPUT ###
########################################################
##########################################################
import random
import sys
import time
sys.setrecursionlimit(10000000)
from random import *
def shift(A, n):
if n == 0:
return A
return [0]+shift(A, n-1)
def mult(X, Y):
# mutiplies two arrays of binary numbers
# with LSB stored in index 0
if zero(Y):
return [0]
Z = mult(X, div2(Y))
if even(Y):
return add(Z, Z)
else:
return add(X, add(Z, Z))
def Mult(X, Y):
X1 = dec2bin(X)
Y1 = dec2bin(Y)
return bin2dec(mult(X1,Y1))
def zero(X):
# test if the input binary number is 0
# we use both [] and [0, 0, ..., 0] to represent 0
if len(X) == 0:
return True
else:
for j in range(len(X)):
if X[j] == 1:
return False
return True
def div2(Y):
if len(Y) == 0:
return Y
else:
return Y[1:]
def even(X):
if ((len(X) == 0) or (X[0] == 0)):
return True
else:
return False
def add(A, B):
A1 = A[:]
B1 = B[:]
n = len(A1)
m = len(B1)
if n < m:
for j in range(len(B1)-len(A1)):
A1.append(0)
else:
for j in range(len(A1)-len(B1)):
B1.append(0)
N = max(m, n)
C = []
carry = 0
for j in range(N):
C.append(exc_or(A1[j], B1[j], carry))
carry = nextcarry(carry, A1[j], B1[j])
if carry == 1:
C.append(carry)
return C
def Add(A,B):
return bin2dec(add(dec2bin(A), dec2bin(B)))
def exc_or(a, b, c):
return (a ^ (b ^ c))
def nextcarry(a, b, c):
if ((a & b) | (b & c) | (c & a)):
return 1
else:
return 0
def bin2dec(A):
if len(A) == 0:
return 0
val = A[0]
pow = 2
for j in range(1, len(A)):
val = val + pow * A[j]
pow = pow * 2
return val
def reverse(A):
B = A[::-1]
return B
def trim(A):
if len(A) == 0:
return A
A1 = reverse(A)
while ((not (len(A1) == 0)) and (A1[0] == 0)):
A1.pop(0)
return reverse(A1)
def compare(A, B):
# compares A and B outputs 1 if A > B, 2 if B > A and 0 if A == B
A1 = reverse(trim(A))
A2 = reverse(trim(B))
if len(A1) > len(A2):
return 1
elif len(A1) < len(A2):
return 2
else:
for j in range(len(A1)):
if A1[j] > A2[j]:
return 1
elif A1[j] < A2[j]:
return 2
return 0
def Compare(A, B):
return bin2dec(compare(dec2bin(A), dec2bin(B)))
def dec2bin(n):
if n == 0:
return []
m = n/2
A = dec2bin(m)
fbit = n % 2
return [fbit] + A
def divide(X, Y):
# finds quotient and remainder when A is divided by B
if zero(X):
return ([],[])
(q,r) = divide(div2(X), Y)
q = add(q, q)
r = add(r, r)
if (not even(X)):
r = add(r,[1])
if (not compare(r,Y)== 2):
r = sub(r, Y)
q = add(q, [1])
return (q,r)
def map(v):
if v==[]:
return '0'
elif v ==[0]:
return '0'
elif v == [1]:
return '1'
elif v == [0,1]:
return '2'
elif v == [1,1]:
return '3'
elif v == [0,0,1]:
return '4'
elif v == [1,0,1]:
return '5'
elif v == [0,1,1]:
return '6'
elif v == [1,1,1]:
return '7'
elif v == [0,0,0,1]:
return '8'
elif v == [1,0,0,1]:
return '9'
def bin2dec1(n):
if len(n) <= 3:
return map(n)
else:
temp1, temp2 = divide(n, [0,1,0,1])
return bin2dec1(trim(temp1)) + map(trim(temp2))
def sub(A, B):
A1 = A[:]
B1 = B[:]
n = len(A1)
m = len(B1)
if n < m:
for j in range(len(B1)-len(A1)):
A1.append(0)
else:
for j in range(len(A1)-len(B1)):
B1.append(0)
B1 = twoComplement(B1)
B1 = add(B1,[1])
N = max(m, n)
C = []
carry = 0
for j in range(N):
C.append(exc_or(A1[j], B1[j], carry))
carry = nextcarry(carry, A1[j], B1[j])
return C
def twoComplement(a):
for i in range (len(a)):
if a[i] & 1 == 1:
a[i] = 0
else:
a[i] = 1
return a
def problem1a(a,b,c,d):
aRaisedb = expo(a, b)
cRaisedd = expo(c, d)
if compare(aRaisedb, cRaisedd) == 2:
remainder = sub(cRaisedd, aRaisedb)
r = "-" + str(bin2dec(remainder))
print(r)
else:
remainder = sub(aRaisedb, cRaisedd)
print(bin2dec(remainder))
def problem1b(a, b, c, d):
aRaisedb = expo(a, b)
cRaisedd = expo(c, d)
if compare(aRaisedb, cRaisedd) == 2:
print("Q: 1", "R: ", bin2dec(sub(cRaisedd, aRaisedb)))
return None
quotient, remainder = divide(aRaisedb, cRaisedd)
print("Q:", bin2dec(quotient), "R:", bin2dec(remainder))
def fractAdd(p,q,r,s):
num = add(mult(p,s), mult(q,r))
den = mult(q,s)
return (num,den)
def gcd(a, b):
if( zero(b) or (compare(a,b)==0)):
return a
if(compare(a,b)==2):
return gcd(b,a)
else:
quotient, remainder = divide(a,b)
return gcd(b, remainder)
def problem1c(a):
summedNum = [1]
summedDenom = [1]
for i in range(2,bin2dec(a)+1):
summedNum, summedDenom = fractAdd([1],dec2bin(i),summedNum,summedDenom)
g = gcd(summedNum,summedDenom)
(p1, q1) = divide(summedNum, g)
(p2, q2) = divide(summedDenom, g)
print(bin2dec(p1),bin2dec(p2))
def expo(a, b):
if b == dec2bin(1):
return a
if b == dec2bin(2):
return mult(a, a)
if(even(b)):
return expo(expo(a, div2(b)), [0,1])
else:
return mult(a,(expo(expo(a,div2(sub(b, [1]))),dec2bin(2))))
def main():
end = 1
while(end != 0):
num = int(input("Press 1 for subtraction. \n Press 2 for division. \n Press 3 for problem1c.\n Press 0 to quit."))
if num == 1 or num == 2:
a = dec2bin(int(input("First number: ")))
b = dec2bin(int(input("To the power of: ")))
c = dec2bin(int(input ("Second number: ")))
d = dec2bin(int(input("To the power of: ")))
if num == 1:
problem1a(a, b, c, d)
else:
problem1b(a, b, c ,d)
elif num == 3:
a = dec2bin(int(input("Enter a number: ")))
problem1c(a)
else:
sys.exit()
main()
|
4ca634a62c46930073c67fbb01bea13796de8edb | leoP0/OS1 | /Small Python/mypython.py | 1,376 | 4.1875 | 4 | #Python Exploration
#CS344
#Edgar Perez
#TO RUN IT JUST DO: 'python mypython.py' (whitout the ' ')
#Modules
import random
import string
import os
import io
#function that generates random lowercase leters given a range
def random_char(y):
return ''.join(random.choice(string.ascii_lowercase) for x in range(y))
#create files if they dont exist
file1 = open("uno", "w+") #uno means one lol
file2 = open("dos", "w+") #dos means two
file3 = open("tres", "w+")#tres means three
#after creat the files write the random letters plus "\n" character at the end
# There is probaly a better way but this is what I did:
file1.write((random_char(10)) + "\n")
file2.write((random_char(10)) + "\n")
file3.write((random_char(10)) + "\n")
#close files after being read
file1.close()
file2.close()
file3.close()
# Read files created
file1 = open("uno", "r") #uno means one lol
file2 = open("dos", "r") #dos means two
file3 = open("tres", "r")#tres means three
#Display to stdout only 10 characters
print file1.read(10)
print file2.read(10)
print file3.read(10)
#close files after being read
file1.close()
file2.close()
file3.close()
# Generate first integer from 1 to 42
randomN1 = random.randint(1,42)
print randomN1
# Generate first integer from 1 to 42
randomN2 = random.randint(1,42)
print randomN2
# Display the result of (random number1 * random number2)
print (randomN1*randomN2)
|
12c8fb82cfd7dba46e3f27b5b61e061c6b78c927 | starlightromero/flower-garden | /Flower.py | 843 | 4.09375 | 4 | """Import Turtle Graphics and Plant."""
import turtle as jerry
from Plant import Plant
class Flower(Plant):
"""Class to make a flower which inherits from Plant."""
def __init__(self, x, y, size, color):
"""Initialize Flower and parent Plant."""
super().__init__(x, y, size, color)
self._num_petals = size
self._petal_length = size * 4
def _get_turn_degrees(self):
return 360 / self._num_petals
def draw(self):
"""Draw Flower."""
self._goto()
jerry.pencolor(self._color)
jerry.pensize(self._size)
for _ in range(self._num_petals):
jerry.forward(self._petal_length)
jerry.backward(self._petal_length)
jerry.right(self._get_turn_degrees())
jerry.pencolor("orange")
jerry.dot(self._size * 2)
|
affb49e789f1a8a2222310b5912ab01119618677 | cyancirrus/datastructures | /datastructures/MinHeap.py | 1,240 | 3.890625 | 4 | class min_heap:
def __init__(self,array:list):
self.array = array
self.heap_size = len(self.array)
self.length = len(self.array)
def left(self,i):
return 2*i+1
def right(self,i):
return 2*i+2
def parent(self,i):
return int((i-1)/2)
def build_min_heap(self):
for i in range(int((self.length-1)/2),-1,-1):
self.min_heapify(i)
def min_heapify(self,i):
l = self.left(i)
r = self.right(i)
if l < self.heap_size and self.array[i] > self.array[l]:
smallest = l
else:
smallest = i
if r < self.heap_size and self.array[smallest] > self.array[r]:
smallest = r
if smallest != i:
self.array[i],self.array[smallest] = \
self.array[smallest],self.array[i]
self.min_heapify(smallest)
def heap_sort(self):
self.build_min_heap()
for i in range(self.length-1,0,-1):
self.array[i],self.array[0] = \
self.array[0],self.array[i]
self.heap_size -= 1
self.min_heapify(0)
def insert(self,x):
self.array = [x] + self.array
self.heap_size += 1
self.length +=1
self.min_heapify(0)
def extract_min(self):
minimum = self.array[0]
self.array[0],self.array[self.heap_size-1] = \
self.array[self.heap_size -1],self.array[0]
self.heap_size -= 1
self.min_heapify(0)
return minimum
|
493e7bcfcd6648b9aca1bd25d3c7bb5ec4d79090 | IllinoisWCS/python-start | /intermediate.py | 5,431 | 4.65625 | 5 | import csv
import sys
class Intermediate:
'''
This exercise should get you warmed up on how the data structure `dictionary` can be used
Dictionaries, or hashmaps, allow for a way to associate a 'key' with a 'value'. Imagine it like an index of a textbook. You know what topic you want to look for (the key), and you want a list of where it can be found (the value).
For this exercise, I want you to take the idea of a book index and check to find what pages two different topics are both on. For example, if our book index looked like:
apples: [2, 5, 64, 66, 70]
oranges: [3, 6, 63, 64, 70]
grapes: [3, 4, 5, 50, 64]
and we called the function with 'apples' and 'oranges' as our topics, the function should return
[64, 70].
If one of the topics queried is not in the book_index, you should return [], indicating that there doesn't exist any shared indices because, well, one of the topics is missing!
You may find some help from these docs:
- https://docs.python.org/2/tutorial/datastructures.html#dictionaries
- for element in array - looping through array elements instead of array indices
- key in dictionary - true or false of whether or not a key exists in the dictionary
- element in dictionary - true or false of whether or not a certain element is in the array
'''
def dictionary_exercise(self, book_index, topic1, topic2):
return []
'''
.CSV exercise
(CSV files are like raw versions of Excel files, they are tabulated using commas and new lines)
One awesome part about Python and many other languages is that it can import in files to parse data and return information.
For example, if we had a file that contained your grades history from high school, you would be able to calculate metrics such as your GPA by just specifying what file to use.
In this case, I want you to calculate the GPA of files that are in the format
[ClassName, Grade]
Our parameter, csvfile, is a string that has the file name. In order to access its contents, you'll have to open the file to expose a file object. Then, you'll have to create a csv reader object and read the file line-by-line.
Our tests use the following scale. Assume all classes are 1 credit hour.
- A/A+ - 4.0
- A- - 3.7
- B+ - 3.3
- B - 3.0
- B- - 2.7
- C+ - 2.3
- C - 2.0
- C- - 1.7
- D+ - 1.3
- D - 1.0
- F - 0.0
You may find some help from these docs:
- with open('filename', 'r') as f
- csv reader objects and their available functions - https://docs.python.org/2/library/csv.html
'''
def calculate_GPA_CSV(self, csvfile):
# This is a default return value for this function. You'll want to change this!
return 0
'''
In data science, we not only want to know the average, the median, the maximum and the minimum of a set of numbers that we're given, but also, how much those numbers vary.
For this exercise, I'll refer to the array of numbers as our data. Each number in that array is called a data point.
We use the concept of variance and standard deviation. Variance, intuitively, gives us a sense of how far apart data points are from the average. If variance is small, then we can say that our data is mostly centered around the average and our average actually is very representative of all data points. However, if variance is quite large, then we cannot say that. Our data varies way too much for our average to be representative.
You can calculate the variance via 3 steps.
1. Find the mean (or average).
2. For each data point, calculate its difference from the mean. Square this difference.
3. Sum all of the differences you find.
Taking the square root of variance yields a measure called standard deviation. Standard deviation is also a measure of how spread out our data points are. It is more often used by statisticians and data scientists to describe the spread of data points.
In this case, we give a csvfile that has the following format:
[Country, GDP]
You'll need to use similar techniques above to read this file and it's values.
Using the CSV parsing techniques you've learned above, fill in the functions below that calculate the following statistics about countries and their GDP values
- Average GDP
- Max GDP and which country has that GDP
- Min GDP and which country has that GDP
- Variance
- Standard Deviation
Hints:
- More reading on standard deviation and variance: http://www.mathsisfun.com/data/standard-deviation.html
- If you're interested in where this data came from: http://data.worldbank.org/indicator/NY.GDP.MKTP.CD
- sys.float_info.max (sys is already imported for you)
- You'll want to store the GDP values you encounter while reading the CSV file into an array to calculate the variance - array.append
'''
def calculate_statistics(self, gdpfile):
# Default values are set for you
average = 0
max_gdp = 0
min_gdp = sys.float_info.max
country_with_highest_gdp = 'USA'
country_with_lowest_gdp = 'USA'
variance = 0
standard_deviation = 0
# Insert your code here!
return average, max_gdp, min_gdp, country_with_highest_gdp, country_with_lowest_gdp, variance, standard_deviation |
5548df9c3f3e31ffce2cdb3e0f6fda197bf7ab72 | tazdaboss/python_basic | /datatype_learn/number_operation.py | 226 | 4.1875 | 4 | num1=int(input("enter num1:\t"))
num2=int(input("enter num2:\t"))
print("add",num1+num2)
print("subtract",num1*num2)
print("divide",num1/num2)
print("remainder",num1%num2)
print("quotient",num1//num2)
print("power",num1**num2) |
a599c583af200aa0365d49cc22f0903842c12ccc | kclaka/HackerRank | /HackerRank/Mutations.py | 303 | 3.609375 | 4 | '''
Created on Dec 29, 2018
@author: K3NN!
url : https://www.hackerrank.com/challenges/python-mutations/problem
'''
def mutate_string(string, position, character):
string = string[:position] + character + string[position+1:]
return string
if __name__ == '__main__':
pass
|
b87c87815df4281b6c6046136515cda3896b8ea7 | CanonMukai/Qiskit-2048 | /display.py | 6,988 | 3.75 | 4 |
import numpy as np
import sys
import copy
ROW = 4
COLUMN = 4
def Display(board):
print ("\n - - - - - - - - -")
n = len(board)
for i in range(n):
for j in range(n):
if board[i][j] == '*':
num = ' '
else:
num = board[i][j]
if j == 0:
print (" | %s" % num, end="")
elif j%4 == 3:
print (" | %s |" % num)
else:
print (" | %s" % num, end="")
print (" - - - - - - - - -")
def Addition(a, b):
return a + b
def Up(board):
print ('up')
for column in range(COLUMN):
target = 0
for row in range(1, ROW):
if board[row][column] == '*':
continue
if board[target][column] == '*':
board[target][column], board[row][column] = board[row][column], board[target][column]
elif board[target][column] == board[row][column]:
board[target][column] = Addition(board[target][column], board[row][column])
board[row][column] = '*'
target += 1
if target == ROW - 1:
break
continue
else:
target += 1
if target == ROW - 1:
break
target2 = target
while target2 < row and board[target2][column] == '*':
if target2 == row - 1:
board[target][column], board[row][column] = board[row][column], board[target][column]
break
target2 += 1
def Down(board):
print ('down')
for column in range(COLUMN):
target = ROW - 1
for row in range(ROW - 2, -1, -1):
if board[row][column] == '*':
continue
if board[target][column] == '*':
board[target][column], board[row][column] = board[row][column], board[target][column]
elif board[target][column] == board[row][column]:
board[target][column] = Addition(board[target][column], board[row][column])
board[row][column] = '*'
target -= 1
if target == 0:
break
continue
else:
target -= 1
if target == 0:
break
target2 = target
while target2 > row and board[target2][column] == '*':
if target2 == row + 1:
board[target][column], board[row][column] = board[row][column], board[target][column]
break
target2 -= 1
def Left(board):
print ('left')
for row in range(ROW):
target = 0
for column in range(1, COLUMN):
if board[row][column] == '*':
continue
if board[row][target] == '*':
board[row][target], board[row][column] = board[row][column], board[row][target]
elif board[row][target] == board[row][column]:
board[row][target] = Addition(board[row][target], board[row][column])
board[row][column] = '*'
target += 1
if target == COLUMN - 1:
break
continue
#
else:
target += 1
if target == COLUMN - 1:
break
target2 = target
while target2 < column and board[row][target2] == '*':
if target2 == column - 1:
board[row][target], board[row][column] = board[row][column], board[row][target]
break
target2 += 1
def Right(board):
print ('right')
for row in range(ROW):
target = COLUMN - 1
for column in range(COLUMN - 2, -1, -1):
if board[row][column] == '*':
continue
if board[row][target] == '*':
board[row][target], board[row][column] = board[row][column], board[row][target]
elif board[row][target] == board[row][column]:
board[row][target] = Addition(board[row][target], board[row][column])
board[row][column] = '*'
target -= 1
if target == 0:
break
continue
else:
target -= 1
if target == 0:
break
target2 = target
while target2 > column and board[row][target2] == '*':
if target2 == column + 1:
board[row][target], board[row][column] = board[row][column], board[row][target]
break
target2 -= 1
def Blank(board):
blank_list = []
for row in range(ROW):
for column in range(COLUMN):
if board[row][column] == '*':
blank_list.append([row, column])
return blank_list
def IsValid(board):
for row in range(ROW):
for column in range(COLUMN - 1):
if board[row][column] == board[row][column + 1]:
return True
for column in range(COLUMN):
for row in range(ROW - 1):
if board[row][column] == board[row + 1][column]:
return True
return False
def OneStep(board, operation):
old_board = copy.deepcopy(board)
if operation == 'up':
Up(board)
elif operation == 'down':
Down(board)
elif operation == 'left':
Left(board)
elif operation == 'right':
Right(board)
if old_board == board:
return 'Operation Error', board
return Random2or4(board)
def Random2or4(board):
blank_list = Blank(board)
prob = np.random.random()
if prob < 0.8:
new_tile = 2
else:
new_tile = 4
if len(blank_list) == 1:
board[blank_list[0][0]][blank_list[0][1]] = new_tile
if not IsValid(board):
return 'Game Over', board
else:
random = np.random.randint(len(blank_list))
blank = blank_list[random]
board[blank[0]][blank[1]] = new_tile
return 'Continue', board
board = [['*', '*', '*', '*'],
['*', '*', '*', 4 ],
['*', '*', '*', '*'],
['*', 2 , '*', '*']]
Display(board)
operation_list = ['up', 'down', 'left', 'right', 'q']
operation = ''
while operation != 'q':
operation = input()
if operation == 'q':
print ('Quit')
break
if operation not in operation_list:
print ('invalid operation')
continue
status, board = OneStep(board, operation)
if status == 'Game Over':
print (status)
sys.exit()
elif status == 'Operation Error':
print ('`%s` is not available' % operation)
Display(board)
else:
Display(board)
|
4873da408f7e0eef3c60e2a734d018d5d81b15ba | TheConstructRIT/Machine-Swipe-System | /tests/Model/UserTest.py | 1,062 | 3.703125 | 4 | """
Zachary Cook
Unit tests for the User module.
"""
import unittest
from Model import User
"""
Test the User class.
"""
class TestUserClass(unittest.TestCase):
"""
Tests the constructor.
"""
def test_constructor(self):
User.User("000000000",100)
"""
Tests the getId method.
"""
def test_getId(self):
CuT = User.User("000000000",100)
self.assertEqual(CuT.getId(),"000000000","Incorrect id stored.")
"""
Tests the getAccessType method.
"""
def test_getAccessType(self):
CuT1 = User.User("000000000",100,"AUTHORIZED")
CuT2 = User.User("000000000",100)
self.assertEqual(CuT1.getAccessType(),"AUTHORIZED","Incorrect access type stored.")
self.assertEqual(CuT2.getAccessType(),"UNAUTHORIZED","Incorrect default access type stored.")
"""
Tests the getSessionTime method.
"""
def test_getSessionTime(self):
CuT = User.User("000000000",100)
self.assertEqual(CuT.getSessionTime(),100,"Incorrect max session time stored.")
"""
Runs the unit tests.
"""
def main():
unittest.main()
# Run the tests.
if __name__ == '__main__':
main() |
10b80bbf124cc3b1bcd8a0b2c9a2424fcbc1e786 | aarozhentsev/HH-tasks | /hh 2_1.py | 1,340 | 3.53125 | 4 | def DigitAndX(s,var):
i = 0
while i<len(s)-1:
if s[i].isdigit():
if s[i+1]==var:
s = s.replace(s[i]+s[i+1],s[i]+'*'+s[i+1])
if s[i].isdigit() or s[i]==var:
if s[i+1]=='(':
s = s.replace(s[i]+s[i+1],s[i]+'*'+s[i+1])
i+=1
return s
def FindVar(s):
i=0
while i<len(s):
if s[i].isalpha():
x = s[i]
break
i+=1
return(x)
z = str(input()) #ะะฒะพะดะธะผ ะฝะฐัั ัััะพะบั
import sympy #ะัะฟะพะปัะทัะตะผ ะฑะธะฑะปะตะพัะตะบั sympy
x = FindVar(z) #ะัะตะผ ะฝะฐัั ะฟะตัะตะผะตะฝะฝัั
z = z.replace('^','**') #ะัะตะพะฑัะฐะทัะตะผ ะฒ ะฝัะถะฝัะน ะดะปั sympy ะฒะธะด
z = z.replace(')(',')*(') #ะัะตะพะฑัะฐะทัะตะผ ะฒ ะฝัะถะฝัะน ะดะปั sympy ะฒะธะด
z = DigitAndX(z,x) #ะัะตะพะฑัะฐะทัะตะผ ะฒ ะฝัะถะฝัะน ะดะปั sympy ะฒะธะด
x = sympy.Symbol(x) #ะะฒะพะดะธะผ ะฟะตัะตะผะตะฝะฝัั ะฒ sympy
z = sympy.sympify(z) #ะัะตะพะฑัะฐะทัะตะผ ะฝะฐัั ัััะพะบั ะฒ ะฒะธะด sympy
z = str(z.expand()) #ะ ะฐัะบััะฒะฐะตะผ ัะบะพะฑะบะธ ะธ ะฒัะฟะพะปะฝัะตะผ ะฐัะธัะผะตัะธัะตัะบะธะต ะพะฟะตัะฐัะธะธ
z = z.replace('**','^') #ะัะตะพะฑัะฐะทัั ะพะฑัะฐัะฝะพ ะฒ ะฝะฐั ะฒะธะด
z = z.replace('*','') #ะัะตะพะฑัะฐะทัั ะพะฑัะฐัะฝะพ ะฒ ะฝะฐั ะฒะธะด
print(z) #ะัะฒะพะดะธะผ ะพัะฒะตั
|
8c3835e2d19f46231c6982724c4680e54228c7d7 | SanjayMarreddi/Open-CV | /Object_Detection/4.Contour_Object_Detection.py | 3,283 | 4.15625 | 4 | # Once We have segmented out the key areas of an image, the next step is typically to identify the individual objects.
# One powerful way is to use OpenCV's implementation of contours. The goal of contours is to take a binary image and create a tightly fitting closed perimeter around all individual objects in the scene. Each perimeter is called a contour.
# From a mathematical point of view, it is called an iterative energy reduction algorithm. But conceptually, we can think of it as an elastic film that starts on the edges of an image and squeezes in around all the objects and shapes. It creates the boundary around all these objects.
# One thing to be aware of is the idea of neighborhoods and connectedness. Contours will consider any pixel value above zero as part of the foreground, and any other pixels touching or connected to this pixel will be made to be part of the same object.
# As the algorithm runs, it tries to reduce the energy or the bounding box around all these objects until it comes to a converged result. It's important to understand that while this may be an iterative algorithm, we know contours will always converge, so it'll never be stuck in an infinite loop.
# At the end, you have a list of contours, and each contour is simply a linear list of points which describe the perimeter of a single object. They are always enclosed, a technical term meaning there are no gaps. This means they can be safely drawn back onto an image and completely filled with a new color.
# Contours is one of the gateways to determine many other useful properties about a single object within an image, making it a very powerful algorithm at our image processing disposal. It moves from the step of object segmentation, often done by thresholding, into the step of object detection.
import numpy as np
import cv2
img = cv2.imread('detect_blob.png',1)
# Converting to GRAY
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)
cv2.imshow("Binary", thresh)
# It actually Outputs 2 Values. 1st one is contours, which is the actually list of individual contours and recall that each contour is a list of points which describe a parameter of an object.
# Followed by hierarchy. Hierarchy is, essentially, a parent-child relationship of all the contours. A child, for example, would be if one contour is enclosed by another
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
img2 = img.copy() # Make a Deep Copy of Original IMAGE
index = -1 # This'll be the index of the contour we want to draw and in this case, using an index value of minus one, we'll draw all the contours.
thickness = 4
color = (255, 0, 255) # Color of Contours being drawn : Here PINK
cv2.drawContours(img2, contours, index, color, thickness)
cv2.imshow("Contours",img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
# A common secondary step after running contour is to filter through and only look at a contour you need to use. To do this, it's often useful to look at various parameters and information that you can get from a single contour. Nonetheless, we can already see that contours is a very easy-to-use and powerful algorithm in open OpenCV. |
b6f5c5dc5b1c4703650b0e12ba82517d237c92ea | SanjayMarreddi/Open-CV | /Object_Detection/1.Simple_Thresholding.py | 2,452 | 4.375 | 4 | # Now we are focused on extracting features and objects from images. An object is the focus of our processing. It's the thing that we actually want to get, to do further work. In order to get the object out of an image, we need to go through a process called segmentation.
# Segmentation can be done through a variety of different ways but the typical output is a binary image. A binary image is something that has values of zero or one. Essentially, a one indicates the piece of the image that we want to use and a zero is everything else.
# Binary images are a key component of many image processing algorithms. These are pure, non alias black and white images, the results of extracting out only what you need. They act as a mask for the area of the sourced image. After creating a binary image from the source, you do a lot when it comes to image processing.
# One of the typical ways to get a binary image, is to use what's called the thresholding algorithm. This is a type of segmentation that does a look at the values of the sourced image and a comparison against one's central value to decide whether a single pixel or group of pixels should have values zero or one.
import numpy as np
import cv2
# "0" tells opencv to load the GRAY IMAGE
bw = cv2.imread('detect_blob.png', 0)
height, width = bw.shape[0:2]
cv2.imshow("Original BW",bw)
# Now the goal is to ample a straightforward thresholding method to extract the objects from an image. We can do that by assigning all the objects a value of 1 and everything else a value of 0.
binary = np.zeros([height,width,1],'uint8') # One channel binary Image
thresh = 85 # Every pixel is compared against this
for row in range(0,height):
for col in range(0, width):
if bw[row][col]>thresh:
binary[row][col]=255 # I just said that a binary image is consisting of either 0s or 1s, but in this case we want to display the image in the user interface, and because of OpenCV's GUI requirements, we want to actually show a 255 or 0 value-based image. That way, the binary image will appear white where we actually want our objects.
cv2.imshow("Slow Binary",binary) # Slower method due to two for Loops
# Faster Method using OPENCV builtins.
# Refer Documentation to explore More
ret, thresh = cv2.threshold(bw,thresh,255,cv2.THRESH_BINARY)
cv2.imshow("CV Threshold",thresh)
# This is a Simple example of IMAGE SEGMENTATION using Thresholding !
cv2.waitKey(0)
cv2.destroyAllWindows() |
ada6baf778bbc2c8092e91aba6bdda306d217a99 | SanjayMarreddi/Open-CV | /Object_Detection/6.Canny_Edge_Detection.py | 1,626 | 4.03125 | 4 | # Often we need to pre-process images in order to improve our final result, and in the case of extracting contours from individual objects in an image it is often handy to first detect and accentuate the edges within an image.
# Canny Edges is one type of edge detection algorithm that works quite well to help create better separation of objects within the image. Generally speaking, edge detection algorithms look at the rate or speed at which color changes across the image.
# Canny Edges is a specific form of that algorithm that creates a single pixel wide line at key high gradient areas in the image. This can help break up the object if there was an overlap in our segmentation process.
# Let's take a look at how we can use Canny Edges. Imagine the goal here is to try and segment out each individual tomato. If we're running a threshold, we may run into an issue where the different tomatoes get blobbed together as one single object.
import numpy as np
import cv2
img = cv2.imread("tomatoes.jpg",1)
# Conversion
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Thresholding
res,thresh = cv2.threshold(hsv[:,:,0], 25, 255, cv2.THRESH_BINARY_INV) # Essentially this line of code is saying that we want to extract all of the pixels that have a hue of value 25 or less as We have INV
cv2.imshow("Thresh",thresh)
# There's two threshold values we want to give. We can play with these values if we want, but for this purpose, let's just type in 100 and 70 for the lower and upper limit of the threshold of the edges
edges = cv2.Canny(img, 100, 70)
cv2.imshow("Canny",edges)
cv2.waitKey(0)
cv2.destroyAllWindows() |
a2277f1bd4c2522d4199a1c960a4bff9751cbc62 | MOOC-Learner-Project/MOOC-Learner-Visualized | /config/config.py | 2,305 | 3.53125 | 4 | #!/usr/bin/env python
'''
This is the parser of YAML configuration file.
Parse the YAML config file and store all configuration variables as constants.
'''
import yaml
import getpass
class ConfigParser(object):
'''
Handles parsing and processing the config YAML file and
act as an interface for other modules to read config information.
'''
CONFIG_STRUCTURE = {
"mysql": {
"query_user": None,
"database": None,
"query_password": None,
"host": None,
"user": None,
"query_database": None,
"password": None,
"port": None
},
"redis": {
"host": None,
"port": None,
"db": None
}
}
def __init__(self, path='./config/config.yml'):
# Parse YAML file and check validity
self.cfg = yaml.safe_load(open(path))
self.validity = self.check()
if self.validity:
self.pre_process()
def check(self):
# Check whether the structure of cfg is valid
return self.dict_structure(self.cfg) == self.CONFIG_STRUCTURE
def dict_structure(self, d):
# Extract out the structure of dict cfg to
# compare with the legal structure
if isinstance(d, dict):
return {k: self.dict_structure(d[k]) for k in d}
else:
# Replace all non-dict values with None.
return None
def is_valid(self):
return self.validity
def pre_process(self):
pass
def get_or_query_mysql(self):
cfg_mysql = self.cfg['mysql']
if cfg_mysql['query_user']:
cfg_mysql['user'] = raw_input('Enter your username for MySQL: ')
if cfg_mysql['query_password']:
cfg_mysql['password'] = getpass.getpass('Enter corresponding password of user %s: ' % cfg_mysql['user'])
if cfg_mysql['query_database']:
cfg_mysql['database'] = raw_input('Enter the database get_redis_key: ')
credential_list = [
'host',
'port',
'user',
'password',
'database'
]
return {k: cfg_mysql[k] for k in credential_list if k in cfg_mysql}
def get_redis(self):
return self.cfg['redis']
|
1e13d93a10f306025b94c070c9f972ab48e87093 | Mpumelelo-Change/Project_Euler | /sum_sqr_diff.py | 292 | 3.671875 | 4 | def sqr_of_sum(num):
tot = 0
for i in range(1, num + 1) :
tot += i
return (tot**2)
def sum_of_sqr(num):
tot = 0
for i in range(1, num + 1) :
tot += i**2
return (tot)
spec = 100
print(sqr_of_sum(spec) - sum_of_sqr(spec))
|
f8c5b89b5c26a8fb389d24d3e2dbd56194b03c9a | gatij/python_fun_projects | /flower.py | 511 | 3.859375 | 4 | import turtle
def DrawFlower():
window=turtle.Screen()
window.bgcolor("white")
some_turtle=turtle.Turtle()
some_turtle.shape("arrow")
some_turtle.speed(1000000000)
some_turtle.color("blue")
for j in range(0,36):
DrawTriangle(some_turtle,2)
DrawTriangle(some_turtle,3)
some_turtle.right(10)
#some_turtle.right(90)
#some_turtle.forward(200)
window.exitonclick()
def DrawTriangle(brad,num):
for i in range(0,num):
brad.forward(100)
brad.right(120)
DrawFlower() |
7e9ec36b9950de705ceddea727d9597998ed75f4 | namitasurana96/dataEngineering | /Set2.py | 71 | 3.765625 | 4 | set = {"a", "b", "c", "d", "a", "e", "d", "f"}
for x in set:
print(x) |
2e3dfc66b1a26f06c86ab484ca405430c6cb1d72 | namitasurana96/dataEngineering | /Array4.py | 77 | 3.6875 | 4 | vowels = ['a', 'e', 'i', 'o', 'a', 'u', 'a']
vowels.remove("a")
print(vowels) |
869c397c85225c688fe51d389a56e09da8987a45 | Mohan110594/Design-4 | /Design_Twitter.py | 3,664 | 4.125 | 4 | // Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : None
from collections import OrderedDict
#created a class tweet which contains tweetid and created time.
class Tweet:
def __init__(self,tweetid,createdAt):
self.tweetid=tweetid
self.createdAt=createdAt
class Twitter(object):
def __init__(self):
"""
Initialize your data structure here.
"""
# feedsize to get the number of recent tweets when getNewsFeed() is called.
self.feedsize=10
self.timestamp=0
self.userTweetsMap=dict()
self.userFollowsMap=dict()
#O(1) operation
#checks if the user is new .If yes create a key for that user in both the dictionaries.
def isFirstTime(self,userId):
if userId not in self.userTweetsMap.keys():
self.userTweetsMap[userId]=[]
t=set()
t.add(userId)
self.userFollowsMap[userId]=t
#check if user is present or not.If yes add the tweet to his key_value else create a new one.
def postTweet(self, userId, tweetId):
"""
Compose a new tweet.
:type userId: int
:type tweetId: int
:rtype: None
"""
# print(self.userTweetsMap)
self.isFirstTime(userId)
self.timestamp=self.timestamp+1
tweet=Tweet(tweetId,self.timestamp)
self.userTweetsMap[userId].append(tweet)
# we can get the top tweets posted by a user and his followers.
def getNewsFeed(self, userId):
"""
Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
:type userId: int
:rtype: List[int]
"""
self.isFirstTime(userId)
followees=self.userFollowsMap[userId]
totusertweets=dict()
for j in followees:
usertweet=self.userTweetsMap[j]
for k in usertweet:
totusertweets[k.tweetid]=k.createdAt
#used for ordering the tweets as per the timeframe created.
tweets=OrderedDict(sorted(totusertweets.items(), key=lambda t: t[1],reverse=True))
count=self.feedsize
result=[]
for k in tweets:
if count!=0:
result.append(k)
else:
break
count=count-1
return result
#user to follow another user
def follow(self, followerId, followeeId):
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: None
"""
self.isFirstTime(followerId)
self.isFirstTime(followeeId)
self.userFollowsMap[followerId].add(followeeId)
#user to unfollow another user.
def unfollow(self, followerId, followeeId):
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: None
"""
self.isFirstTime(followerId)
self.isFirstTime(followeeId)
if followerId!=followeeId:
if followeeId in self.userFollowsMap[followerId]:
self.userFollowsMap[followerId].remove(followeeId)
# Your Twitter object will be instantiated and called as such:
# obj = Twitter()
# obj.postTweet(userId,tweetId)
# param_2 = obj.getNewsFeed(userId)
# obj.follow(followerId,followeeId)
# obj.unfollow(followerId,followeeId) |
bd1997c9427f2f364e60fccc86e04d39c628f979 | walidA1/programmingnew | /Pe5_1/functie met if.py | 227 | 3.515625 | 4 | def lang_genoeg(lengte):
if lengte >= 120:
print('Je bent lang genoeg voor de attractie!')
else:
print('Je bent te klein!')
lengte = input('Hoelang ben jij in centimeters?')
(lang_genoeg(int(lengte)))
|
0fbfdc83757f9153365c06b1f9e86950d8d46e99 | walidA1/programmingnew | /Final assignment bagagekluizen/functions.py | 3,868 | 3.828125 | 4 | def printmenu():
print('1: Ik wil weten hoeveel kluizen nog vrij zijn')
print('2: Ik wil een nieuwe kluis')
print('3: ik wil even iets uit mijn kluis halen')
print('4: ik geef mijn kluis terug\n')
select()
def select():
selected_number = 0
while selected_number > 4 or selected_number < 1:
try:
selected_number = int(input("invoer: "))
except:
print("Voer een getal in!\n")
selected_number = 0
printmenu()
if selected_number < 1 or selected_number > 4:
print("voer een geldige waarde in!\n")
printmenu()
if selected_number == 1:
hoeveelkluizen()
elif selected_number == 2:
nieuwekluis()
elif selected_number == 3:
openKluis()
elif selected_number == 4:
verwijderKluis()
def hoeveelkluizen():
try:
file = open("kluizen.txt" , 'r')
temp = file.readlines()
count = 0
for temp in temp:
count += 1
if count < 13:
print("\ner zijn nog {} kluisjes vrij\n".format(12-count))
else: print('alle kluisjes zitten vol')
file.close()
printmenu()
except:
print("\nalle kluizen zijn nog vrij\n")
printmenu()
def nieuwekluis():
kluizen = []
for i in range(1,13):
kluizen.append(i)
try:
file = open("kluizen.txt" , 'r')
temp = file.readlines()
for x in temp:
a = x.split(sep=';')
kluizen.remove(eval(a[0]))
file.close()
except:
pass
if len(kluizen) != 0:
print("u krijgt kluis {}".format(kluizen[0]))
try:
file = open("kluizen.txt",'a')
except:
file = open('kluizen.txt', 'w')
ww = ''
while len(ww) < 4:
print('Wachtwoord moet minimaal 4 tekens lang zijn!')
ww = input('typ uw wachtwoord: ')
file.write("{};{}\n".format(kluizen[0],ww))
file.close()
print('Succesvol!\n')
printmenu()
else:
print("alle kluizen zijn bezet\n")
printmenu()
def openKluis():
try:
kluisnmr = int(input('uw kluis nummer: '))
if kluisnmr > 12:
kluisnmr = int("haha noob")
try:
file = open("kluizen.txt", 'r')
ww = input("Wachtwoord: ")
temp = file.readlines()
succes = 0
for x in temp:
a = x.split(sep=';')
if kluisnmr == int(a[0]) and ww == a[1].strip('\n'):
print('Succes, kluis {} wordt nu open gemaakt\n'.format(int(a[0])))
succes = 1
if succes == 0:
print('De gegevens zijn incorect\n')
file.close()
printmenu()
except:
print("Je hebt helemaal geen kluis!\n")
printmenu()
except:
print('ongeldig nummer!\n')
printmenu()
def verwijderKluis():
try:
kluisnmr = int(input('Wat is uw kluis nummer: '))
ww = input('wat is uw wachtwoord: ')
try:
file = open("kluizen.txt", "r")
lines = file.readlines()
file.close()
file = open('kluizen.txt', 'w')
succes = 0
for x in lines:
a = "{};{}\n".format(kluisnmr,ww)
if x != a:
file.write(x)
else: succes = 1
if succes == 1:
print("De kluis wordt vrijgegeven\n")
else: print('De gegevens zijn incorect\n')
file.close()
printmenu()
except:
print('Jij hebt helemaal geen kluis\n')
printmenu()
except:
print('voer een getal in\n')
printmenu()
|
dddf7daa3fd9569dbeb61fdba7f39f070aa4be39 | Ironkey/ex-python-automatic | /Chapter 01-02/Hello World.py | 597 | 4.21875 | 4 | # This program says hello and asks for my name.
print('Hello wolrd!')
print ('What is your name?') # ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The Length of your name is:')
print(len(myName))
print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) +1) + ' in a year.')
print('ํธ๊ตฌ์ผ ์ค์๊ฐ์ข ์
๋ ฅํด๋ผ: ')
myround = float(input())
if str(type(myround)) == "<class 'float'>" :
print('๋๊ฐ ์
๋ ฅํ ๊ฐ์ ๋ฐ์ฌ๋ฆผํด์ฃผ๋ง :' + str(round(myround)))
else:
print('์ค์๊ฐ ๋ชจ๋ฅด๋')
|
aac96403d55aedefb8f4c550b3aa2681e8359db2 | willcl-ark/boltstore | /database.py | 2,545 | 3.71875 | 4 | import sqlite3
from utilities import sha256_of_hex_to_hex
# data types #
# INTEGER: A signed integer up to 8 bytes depending on the magnitude of the value.
# REAL: An 8-byte floating point value.
# TEXT: A text string, typically UTF-8 encoded (depending on the database encoding).
# BLOB: A blob of data (binary large object) for storing binary data.
# NULL: A NULL value, represents missing data or an empty cell.
##############
class Database:
def __init__(self, sqlite_file):
self.db = sqlite_file
self.conn = sqlite3.connect(self.db)
self.cursor = self.conn.cursor()
# helper function to create sha256 hash of hex item. returns hex
self.conn.create_function("sha256_hex_hex", 1, sha256_of_hex_to_hex)
def reconnect(self):
try:
self.conn.close()
except sqlite3.Error:
pass
self.conn = sqlite3.connect(self.db)
self.cursor = self.conn.cursor()
def close_connection(self):
self.conn.close()
def create_table(self, table_name, column_name, column_type):
"""
Create table with a primary column
"""
query = f"""
CREATE TABLE
{table_name} ({column_name} {column_type} PRIMARY KEY)
"""
self.cursor.execute(query)
self.conn.commit()
def add_column(self, table_name, column_name, column_type):
query = f"""
ALTER TABLE
{table_name}
ADD COLUMN
'{column_name}' {column_type}
"""
self.cursor.execute(query)
self.conn.commit()
def insert_row(self, table_name, *args):
# if you add more columns, add more question marks after VALUES
query = f"""
INSERT OR IGNORE INTO
{table_name}
VALUES
(?, ?, ?, ?)
"""
self.cursor.execute(query, tuple(args))
self.conn.commit()
def update_row(self, table_name, id_col, id, column, new_val):
query = f"""
UPDATE
{table_name}
SET
{column} = ?
WHERE
{id_col} = ?
"""
self.cursor.execute(query, (new_val, id))
self.conn.commit()
def get_row(self, table_name, id_col, id):
"""
returns a tuple of values
"""
query = f"""
SELECT
*
FROM
{table_name}
WHERE
{id_col} = ?
"""
self.cursor.execute(query, id)
return self.cursor.fetchone()
|
4c69bf913b87c5c3373368d83464ecd9e49e9184 | mennonite/Python-Automation | /Chapter 8 -- Reading and Writing Files/Practice Projects/madlibs_Regex.py | 920 | 4.25 | 4 | #! python3
# madlibs_Regex.py - opens and reads a text file and lets the user input their own words (solved using REGEX)
import re
# open text file
madlibFile = open('.\\Chapter 8 -- Reading and Writing Files\\Practice Projects\\test.txt')
# save the content of the file into a variable
content = madlibFile.read()
madlibFile.close()
# build a regex to identify replaceable words
madlibsRegex = re.compile(r'(ADJECTIVE|NOUN|ADVERB|VERB)')
matches = madlibsRegex.findall(content)
# for each match, prompt the user to replace it
for match in matches:
userWord = input('Gimme %s %s:\n' % ('an' if match.startswith('A') else 'a', match.lower()))
content = content.replace(match, userWord, 1)
print(content)
# the resulting text is saved to a new file
madlibAnswers = open('.\\Chapter 8 -- Reading and Writing Files\\Practice Projects\\test-answer.txt', 'w')
madlibAnswers.write(content)
madlibAnswers.close() |
94e4db9080e79ac124178be55ab9cf86896e2153 | Y1B0/Artificial-Intelligence-for-Robotics | /expansion grid.py | 3,340 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 13 11:36:16 2017
@author: huyibo
"""
# ----------
# User Instructions:
#
# Define a function, search() that returns a list
# in the form of [optimal path length, row, col]. For
# the grid shown below, your function should output
# [11, 4, 5].
#
# If there is no valid path from the start point
# to the goal, your function should return the string
# 'fail'
# ----------
# Grid format:
# 0 = Navigable space
# 1 = Occupied space
from operator import add
import numpy as np
import copy
grid = [[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0],
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 0]]
init = [0, 0]
goal = [len(grid)-1, len(grid[0])-1]
cost = 1
footprint = [init]
delta = [[-1, 0], # go up
[ 0,-1], # go left
[ 1, 0], # go down
[ 0, 1]] # go right
delta_name = ['^', '<', 'v', '>']
def search():
# ----------------------------------------
# insert code here
# ----------------------------------------
path = [0,init[0],init[1]]
archive = copy.deepcopy(grid)
grid[init[0]][init[1]] = 1
expand = [[-1 for i in range(len(grid[0]))]for j in range(len(grid))]
expand[init[0]][init[1]] = 0
track = [[' ' for i in range(len(grid[0]))]for j in range(len(grid))]
track[goal[0]][goal[1]] = "*"
def is_valid(maze,curr):
if curr[0]>=len(maze) or curr[0]<0 or curr[1]>=len(maze[0]) or curr[1]<0:
return False
elif maze[curr[0]][curr[1]] == 1:
return False
else:
return True
stack = [path]
next_level = []
step_record = 0
found = False
while stack or next_level:
if not stack:
stack = next_level
next_level = []
curr_path = stack.pop(0)
# print curr_path
curr_position = [curr_path[1],curr_path[2]]
if curr_position == goal:
# print np.matrix(expand)
found = True
break
for i,step in enumerate(delta):
next_step = map(add,step,curr_position)
if is_valid(grid,next_step):
grid[next_step[0]][next_step[1]] = 1
step_record += 1
expand[next_step[0]][next_step[1]] = step_record
next_level.append([curr_path[0]+cost,next_step[0],next_step[1],delta_name[i]])
tracked = False
def minimal_prev(curr):
record = []
fake_delta_name = ['v', '>', '^', '<']
for i,step in enumerate(delta):
prev_step = map(add,step,curr)
if (is_valid(archive,prev_step)) and (expand[prev_step[0]][prev_step[1]] > -1):
record.append([prev_step[0],prev_step[1],fake_delta_name[i]])
mini = record[0]
for i in record:
if expand[i[0]][i[1]]<expand[mini[0]][mini[1]]:
mini = i
return mini
if found:
curr = goal
while not tracked:
# print curr
if curr == init:
tracked = True
break
prev_step = minimal_prev(curr)
curr = [prev_step[0],prev_step[1]]
track[prev_step[0]][prev_step[1]] = prev_step[2]
print np.matrix(expand)
print np.matrix(track)
return track
return "fail"
search() |
319b50bba1445e6aeb1d7282c61a8a5c583b80b5 | vadim-kravtsov/skyCam | /libs/guiLibs.py | 3,693 | 3.65625 | 4 | #! /usr/bin/env python2
from os import path
import pygame
class TextLabel(object):
def __init__(self, screen, xStart, yStart):
self.font = pygame.font.SysFont(u'ubuntumono', 22)
self.xStart = xStart
self.yStart = yStart
self.fontColor = (119,153,51)#pygame.Color("green")
self.black = pygame.Color("black")
self.fontSurface = None
self.screen = screen
def set_text(self, newText):
# At first we want to fill the area to
# remove the previous text
if self.fontSurface is not None:
self.fontSurface.fill(self.black)
self.screen.blit(self.fontSurface, (self.xStart, self.yStart))
self.fontSurface = self.font.render(newText, True, self.fontColor)
self.screen.blit(self.fontSurface, (self.xStart, self.yStart))
pygame.display.update()
class MeteoLabel(object):
def __init__(self, screen, xStart, yStart):
self.font = pygame.font.SysFont(u'ubuntumono', 20)
self.xStart = xStart
self.yStart = yStart
self.fontColor = (251,51,51)#pygame.Color("red")
self.black = pygame.Color("black")
self.fontSurface = None
self.screen = screen
def set_text(self, newText):
# At first we want to fill the area to
# remove the previous text
if self.fontSurface is not None:
self.fontSurface.fill(self.black)
self.screen.blit(self.fontSurface, (self.xStart, self.yStart))
self.fontSurface = self.font.render(newText, True, self.fontColor)
self.screen.blit(self.fontSurface, (self.xStart, self.yStart))
pygame.display.update()
class FieldRect(object):
def __init__(self, screen):
self.screen = screen
self.xSize = 40
self.ySize = 26
self.pathToFile = path.join("libs", "fieldCoords.dat")
# Parameters of the rectangle are stored in the
# fieldCoords.dat file. Let's check if the file exists
if path.exists(self.pathToFile):
# if so, just read the data from it
dataFile = open(self.pathToFile)
data = dataFile.readline()
dataFile.close()
self.xCen = int(data.split()[0])
self.yCen = int(data.split()[1])
else:
# if file doesn't exists we set the coordinates to
# the center of the image and create the file with
# such values
self.xCen = 360
self.yCen = 288
self.store_coords()
def store_coords(self):
fout = open(self.pathToFile, "w")
fout.truncate(0)
fout.write("%i %i" % (self.xCen, self.yCen))
fout.close()
def draw(self):
coordParams = (self.xCen-self.xSize/2,
self.yCen-self.ySize/2,
self.xSize,
self.ySize)
# draw rectangle
pygame.draw.rect(self.screen, pygame.Color("red"), coordParams, 2)
# draw cross. Cross is made of two lines: the vertical and the horizonthal
pygame.draw.line(self.screen, pygame.Color("red"),
(self.xCen, self.yCen-5), (self.xCen, self.yCen+5), 1)
pygame.draw.line(self.screen, pygame.Color("red"),
(self.xCen-5, self.yCen), (self.xCen+5, self.yCen), 1)
def move(self, direction):
if direction == "up":
self.yCen -= 2
elif direction == "down":
self.yCen += 2
elif direction == "left":
self.xCen -= 2
elif direction == "right":
self.xCen += 2
self.store_coords()
|
797c941cf15e8010a432aa770feb313e93d4f124 | pantherman594/countermachine | /countermachine_copy_macros.py | 8,636 | 3.78125 | 4 | #counter machine
#The low level code is a list of instructions.
#Each instruction is a string.
#The strings have the following format:
#I<let> (where <let> denotes any lower-case letter)
#D<let>
#B<let><n> where <n> denotes an integer constant--note that this is written
#without spaces
#B<n>
#H#
#The function below interprets the low-level code. The second argument is
#a tuple of integers originally assigned to 'a','b',....
import string
import sys
letters='abcdefghijklmnopqrstuvwxyz'
Letters='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digits='0123456789'
alphanum=letters+Letters+digits+'_'
def allin(s,charset):
for c in s:
if not (c in charset):
return False
return True
def interpret(program,*args,**kwargs):
counters=[0]*26
for j in range(len(args)):
counters[j]=args[j]
if 'verbose' in kwargs:
verbose=kwargs['verbose']
else:
verbose=False
ip=0
while program[ip]!='H':
current_instruction = program[ip]
if ip>len(program):
sys.exit('instruction pointer out of range')
if current_instruction[0] == 'I':
variable=ord(current_instruction[1])-ord('a')
counters[variable]+=1
if verbose:
print (str(ip)+': '+'inc '+current_instruction[1])
ip+=1
elif current_instruction[0]=='D':
variable=ord(current_instruction[1])-ord('a')
counters[variable]=max(0,counters[variable]-1)
if verbose:
print (str(ip)+': '+'dec '+current_instruction[1])
ip+=1
elif current_instruction[0]=='B' and (current_instruction[1] in letters):
variable=ord(current_instruction[1])-ord('a')
#print ip,variable
target=int(current_instruction[2:])
if verbose:
print (str(ip)+': '+'goto ' + str(target) + ' if '+current_instruction[1]+'=0')
if counters[variable]==0:
ip=target
else:
ip+=1
elif current_instruction[0]=='B':
target=int(current_instruction[1:])
if verbose:
print (str(ip)+': '+'goto '+str(target))
ip=target
return counters
######################################################
# changing the references to counters in program, to match those of counters, and append those to obj
def integrate(program,counters, obj, current):
# create a new variable to keep track of current since we need the original current to offset goto calls
final_current = current
for line in program:
# create the new translated line beginning with the first character (is typically H, I, D, or B)
newline = ''+line[0]
# for I and D, simply translate the counter values and concatenate it with newline
if line[0] == 'I' or line[0] == 'D':
found_var = False
for i in range(len(counters)):
if (ord('a')+i) == ord(line[1]):
newline += counters[i][0]
found_var = True
if not found_var:
sys.exit('MACRO: counter assignment not found')
# for B with conditions, we convert both counter value and the goto line
elif line[0] == 'B' and (line[1] in letters):
found_var = False
for i in range(len(counters)):
if (ord('a')+i) == ord(line[1]):
newline += counters[i][0]
found_var = True
if not found_var:
sys.exit('MACRO: counter assignment not found')
newline+=str(int(line[2:])+current)
# for unconditional B, we simply convert the goto line
elif line[0] == 'B':
newline += str(int(line[1:])+current)
obj.append(newline)
final_current+=1
# we check our converted code for any H, and change those to goto whatever comes after our translated code
for index in range(len(obj)):
if obj[index] == 'H':
newline='B'
newline+=str(final_current)
obj[index] = newline
return obj, final_current
######################################################
#A source program is here represented as a sequence of lines, each
#line a list of strings. Assemble the source program into the lower-level
#code used above, and return the low-level program.
def assemble(source):
symbol_table={}
obj=[]
already_assembled=[]
current=0
for line in source:
#is it a label?
#These have the form alphanum*:
if (len(line)==1) and (line[0][-1]==':') and allin(line[0][:-1],alphanum):
#print 'label'
label=line[0][:-1]
if label in symbol_table:
sys.exit('redefinition of label '+label)
else:
symbol_table[label]=current
#is it a conditional branch instruction?
#These have the form goto label if x=0 but the parser
#accepts anything of form goto label if lower-case letter followd by anything.
elif (len(line)>=4) and (line[0]=='goto') and allin(line[1],alphanum) and (line[2]=='if') and (line[3][0] in letters):
#print 'conditional branch'
label=line[1]
variable=line[3][0]
obj.append('B'+variable+'#'+label)
current+=1
#is it an unconditional branch instruction?
#These have the form goto label
elif (len(line)==2) and (line[0]=='goto') and allin(line[1],alphanum):
#print 'unconditional branch'
label=line[1]
obj.append('B'+'#'+label)
current+=1
#is it a decrement instruction?
#these have the form dec variable
elif (len(line)==2) and (line[0]=='dec') and (len(line[1])==1) and (line[1][0] in letters):
#print 'decrement'
obj.append('D'+line[1][0])
current+=1
#is is an increment instruction?
elif (len(line)==2) and (line[0]=='inc') and (len(line[1])==1) and (line[1][0] in letters):
#print 'increment'
obj.append('I'+line[1][0])
current+=1
#is it a halt instruction?
elif (len(line)==1) and (line[0]=='halt'):
#print 'halt'
obj.append('H')
current+=1
#############################################
#is it a MACRO call?
elif (len(line)>=3) and (line[0] == 'MACRO'):
#we would essentially insert the counter machine code from the macro call into the assembled language.
pair = [0]*2
pair[0] = current
obj, current = integrate(assemble_from_file(line[1],macro=True), line[2:], obj, current)
pair[1] = current
already_assembled.append(pair)
############################################# modifications also made to below code where we resolve table references
#resolve symbol table references
for j in range(len(obj)):
instruction=obj[j]
if instruction[0]=='B':
# if j is not in the range of any of the pairs of already_assembled, then we do below code
not_yet_assembled = True
for pair in already_assembled:
for checking in range(pair[0],pair[1]):
if j == checking:
not_yet_assembled = False
if not_yet_assembled:
place=instruction.index('#')
label=instruction[place+1:]
if not label in symbol_table:
sys.exit('undefined label '+label)
else:
instruction=instruction[:place]+str(symbol_table[label])
obj[j]=instruction
return obj
#Now produce object code from source file. Skip comments and blank lines.
def assemble_from_file(filename,macro=False):
# if this is assembled as a macro call, then we need to append '.cp' to find the file
if macro:
filename+='.cp'
f=open(filename,'r')
source=[]
for line in f:
if (line[0]!='#') and not allin(line,string.whitespace):
source.append(line.split())
#print source
return assemble(source)
#run a program from a file on a sequence of inputs
def runcp(filename,*args,**kwargs):
obj = assemble_from_file(filename)
return interpret(obj,*args,**kwargs)
|
2cc34c8802dcc2d6973903960182889adbfb31f2 | Noopuragr/Python-Assignment | /Python_Assignment/Sample 1/Sample1_soln/que24.py | 188 | 3.671875 | 4 | def cumulative_list(lists):
list_var=[]
length=len(lists)
list_var=[sum(lists[0:x+1]) for x in range (0,length)]
return list_var
lists = [10,20,30,40,50]
print(cumulative_list(lists)) |
ad60442beb74e0d4e6b1048a86425641b2760577 | Noopuragr/Python-Assignment | /Python_Assignment/Sample 1/Sample1_soln/que4.py | 158 | 4.1875 | 4 | num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
print("Quotient is :" ,num2/num1)
print("REmainder is :" ,num2%num1)
|
ebb53ab79760bfa0d6d0c33cb5a08a0423922f9b | Noopuragr/Python-Assignment | /Python_Assignment/Sample 1/Sample1_soln/que20.py | 294 | 3.96875 | 4 | str1 = str(input("Enter the first string"))
str2 = str(input("Enter the second string"))
count1 = 0
count2 = 0
for ch in str1:
count1 = count1+1
for ch in str2:
count2 = count2+1
if(count1>count2):
print(str1)
elif(count2>count1):
print(str2)
else:
print("Both string are of same length")
|
9301ec25d5d7cd6e0e80a64d05b799cd987cb5dc | Noopuragr/Python-Assignment | /Python_Assignment/Sample 1/Sample1_soln/que16.py | 178 | 4.09375 | 4 | str1 = str(input("Enter the string"))
new_str=''
for ch in str1:
if ch == 'a':
new_str += '$'
else:
new_str += ch
print(new_str)
#str1=str1.replace('a','$')
#print(str1) |
bea1ddcc6371381ee84f4588c24bb97c290ece8b | Noopuragr/Python-Assignment | /Python_Assignment/Sample 1/Sample1_soln/que22.py | 217 | 3.921875 | 4 | str1 = str(input("Enter the string"))
count = 0
count2 = 0
for ch in str1:
if ch.isdigit():
count = count+1
else:
count2=count2+1
print("The number of digit is", count)
print("THe number of alphabet is", count2) |
7ff9e2b37bded88fbd494d9679821004d05025f3 | dcandrade/python_para_zumbis | /palindromo.py | 189 | 3.96875 | 4 | #verifica se a palavra lida รฉ palรญdromo, supondo que nรฃo tem acentos
palavra = input("Digite a palavra:").lower()
print("E palidrome" if palavra==palavra[::-1] else "Nao e palindrome")
|
3959cf84ecea19519ef31a462a07a6127e44d0b0 | rohitprofessional/test | /StringPractice/SP02.py | 649 | 4.0625 | 4 | # ---------Write a program to count vowels and consonants in a string.----------
S = input("Enter a STRING: ")
print("You entered the string:",S)
print("Length of the string you entered:",len(S))
vow = 0
con = 0
space = 0
for i in range(len(S)):
if (S[i]==" "):
space = space + 1
print("THIS IS A SPACE.",space)
elif S[i] in ['a','e','i','o','u']:
vow = vow + 1
print("VOWEL count:",vow,"char:",S[i])
else:
con = con + 1
print("CONSONANT:",con,"char:",S[i])
print("Total vowels are:", vow)
print("Total conconants are:", con)
print("Total space :",space)
|
cb5a0fa4c5e15ece58b25f8a0fedb9fb56f26c5f | rohitprofessional/test | /f_string.py | 386 | 4.4375 | 4 | letter = "Hey my name is {1} and I am from {0}"
country = "India"
name = "Rohit"
print(letter.format(country, name))
print(f"Hey my name is {name} and I am from {country}")
print(f"We use f-strings like this: Hey my name is {{name}} and I am from {{country}}")
price = 49.09999
txt = f"For only {price:.2f} dollars!"
print(txt)
# print(txt.format())
print(type(f"{2 * 30}")) |
db834ca3d26f8d0901498cc48d2219ea940b38f3 | rohitprofessional/test | /CLASS AND OBJECTS/Introduction to oops/class_attributes.py | 669 | 4.09375 | 4 | # How to create a class:
class Item:
def calculate_total_price(self, x, y):
return x * y
# How to create an instance of a class
item1 = Item()
# Assign attributes:
item1.name = "Phone"
item1.price = 100
item1.quantity = 5
# Calling methods from instances of a class:
print(item1.calculate_total_price(item1.price, item1.quantity))
# How to create an instance of a class (We could create as much as instances we'd like to)
item2 = Item()
# Assign attributes
item2.name = "Laptop"
item2.price = 1000
item2.quantity = 3
# Calling methods from instances of a class:
print(item2.calculate_total_price(item2.price, item2.quantity)) |
3b5e88fd60e1fcc969536b9a995d53b4ab14e563 | rohitprofessional/test | /OUTPUT PROG/output_07.py | 119 | 3.53125 | 4 | x = 'one'
y = 'two'
counter = 0
while counter < len(x):
print(x[counter],y[counter])
counter = counter + 1 |
f9d5c0e1ab4ec959bb7988e185c83b2ba49a23a5 | rohitprofessional/test | /PRACTICE/stop_watch.py | 534 | 4.125 | 4 | #---------------STOP WATCH--------
import time
time_limit = int(input("Enter the stopwatch time.: "))
# hours = int(time_limit/3600)
# minutes = int(time_limit/60) % 60
# seconds = (time_limit) % 60
# print(hours,minutes,seconds)
for x in range(time_limit,0,-1):
seconds = (x) % 60
minutes = int(x/60) % 60
hours = int(x/3600)
time.sleep(1) # it'll delay o/p by given sec
print(f"{hours:02}:{minutes:02}:{seconds:02}")
# print(minutes,"minutes left",":",seconds,"seconds left")
|
3677635246e0838d7d9ce919e40713bcd2c2a2b0 | rohitprofessional/test | /StringPractice/SP05.py | 442 | 3.859375 | 4 | n = '@pyThOnlobb!Y34'
numeric = 0
lower = 0
upper = 0
special = 0
for i in range(len(n)):
if n[i].isnumeric():
numeric = numeric + 1
elif n[i].islower():
lower = lower+1
elif n[i].isupper():
upper = upper+1
else:
special = special + 1
# printing result
print("Numeric counts",numeric)
print("Lower counts",lower)
print("Upper counts",upper)
print("Special counts",special) |
608257fd5528026be5797f7ca712d9328ca7382b | rohitprofessional/test | /CHAPTER 01/localVSglobal_variable.py | 1,353 | 4.5 | 4 | # It is not advisable to update or change the global variable value within in a local block of code. As it can lead to complexity
# in the program. But python provides a global keyword to do so if you want to.
# Although it is also not advisable to use global variable into a local function. It is a maintainable programming practice.
def local(m,n):
# global x # changing global variable value by accessing it
# x = 30 # using the word 'global'
m = 5 # local variable and can be accessible within the block only
n = 8 # after the block ends variable scope/use out of block also ends
print("\ninside the function:")
print(f"\n\t3.local to func variable x: {m}, address{id(m)}")
print(f"\n\t2.local to func variable y: {n}, address{id(n)}")
# print(f"2. local variable x: {x}, address{id(x)}") # local variable
# print(f"2. local variable y: {y}, address{id(y)}")
return
print("\t\tmain-->>")
x = 10 # global variable and can be use anywhere in prog
y = 20 # global variable and can be use anywhere in prog
print("Variables before func call:")
print(f"\n1.global variabel x: {x}, address{id(x)}")
print(f"\n2.global variabel y: {y}, address{id(y)}")
local(x,y)
print(f"\n5.global variable x: {x}, address{id(x)}")
print(f"\n6.global variable : {y}, address{id(y)}")
|
e49eb95627c1f9262aad83447236cc085a6f5afd | rohitprofessional/test | /CHAPTER 07/intro to for loops.py | 1,151 | 4.375 | 4 | # -------------------- FOR LOOP UNDERSTANDING -------------------------------
'''So here we range is a function w/c helps compiler to run the for loop.
Return an object that produces a sequence of integers from start (inclusive)
to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.
These are exactly the valid indices for a list of 4 elements. When step is given,
it specifies the increment (or decrement).'''
print("-----------------------------FOR LOOP-------------------------------")
print("Table of 2")
# By default 0 , n , 1 -->> If we pass only one value, ie., n.
for n in range(1,11,1): # (Initialization, Condition, Increament)
print("1 *", n ," = ", n*2)
#------------------------- REVERSE FOR LOOP ------------------------------
print("---------------------------REVERSE FOR LOOP---------------------------------")
print("Revrse table of 2")
for n in range(10,0,-1):
print("1 *", n ," = ", n*2)
print("------------------------------------------------------------") |
ba5c344d4431c6f434b1bd7f2f9bcff98f9ef1ba | chaitanyakush/PythonLearning | /Date Detection.py | 980 | 4 | 4 | import re
def dateValidate(date):
# 31/02/2020
dateRegex = re.compile(r'(\d\d)/([0-1]\d)/([1-2]\d\d\d)')
mo = dateRegex.search(date).groups()
day = int(mo[0])
month = int(mo[1])
year = int(mo[2])
if month in (4, 6, 9, 11) and day > 30:
print("Wrong date")
return False
elif month in (1, 3, 5, 7, 8, 10, 12) and day > 31:
print("Wrong date")
return False
elif month == 2:
if year % 4 == 0:
if day > 29:
print("wrong days for February.....")
return False
elif year % 100 == 0 and year % 400 == 0:
if day > 29:
print("wrong days for February.....")
return False
else:
if day > 28:
print("wrong days for February.....")
return False
else:
print("Incorrect month")
return False
return "Success"
print(dateValidate('30/02/2016'))
|
6af71e11738ca1f1a56d20c477462ebc0e48602d | seohae2/python_algorithm_day | /์๊ณ ๋ฆฌ์ฆ๊ตฌํ/04_BFS/bfs.py | 1,233 | 3.75 | 4 | # BFS
from collections import deque
def bfs(graph, start, visited):
# ํ ๊ตฌํ์ ์ํด deque ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ฌ์ฉ
queue = deque([start])
# ํ์ฌ ๋
ธ๋๋ฅผ ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ
visited[start] = True
while queue:
v = queue.popleft()
print(v, end=' ')
for value in graph[v]:
if not visited[value]:
queue.append(value)
visited[value] = True
# ๊ฐ ๋
ธ๋๊ฐ ์ฐ๊ฒฐ๋ ์ ๋ณด๋ฅผ ๋ฆฌ์คํธ ์๋ฃํ์ผ๋ก ํํ
graph = [
[],
[2, 3, 8], # 1๋ฒ ๋
ธ๋์ ์ธ์ ๋
ธ๋๋ 2, 3, 8 ์ด๋ค.
[1, 7], # 2๋ฒ ๋
ธ๋์ ์ธ์ ๋
ธ๋๋ 1, 7 ์ด๋ค.
[1, 4, 5], # 3๋ฒ ๋
ธ๋์ ์ธ์ ๋
ธ๋๋ 1, 4, 5 ์ด๋ค.
[3, 5], # 4๋ฒ ๋
ธ๋์ ์ธ์ ๋
ธ๋๋ 4, 5 ์ด๋ค.
[3, 4], # 5๋ฒ ๋
ธ๋์ ์ธ์ ๋
ธ๋๋ 3, 4 ์ด๋ค.
[7], # 6๋ฒ ๋
ธ๋์ ์ธ์ ๋
ธ๋๋ 7 ์ด๋ค.
[2, 6, 8], # 7๋ฒ ๋
ธ๋์ ์ธ์ ๋
ธ๋๋ 2, 6, 8 ์ด๋ค.
[1, 7] # 8๋ฒ ๋
ธ๋์ ์ธ์ ๋
ธ๋๋ 1, 7 ์ด๋ค.
]
# ๊ฐ ๋
ธ๋๊ฐ ๋ฐฉ๋ฌธ๋ ์ ๋ณด๋ฅผ ๋ฆฌ์คํธ ์๋ฃํ์ผ๋ก ํํ
visited = [False] * 9 # [False, False, False, False, False, False, False, False, False]
# BFS ํจ์ ํธ์ถ
bfs(graph, 1, visited) |
8d49d90011858c4fba6724068786e20d7f9254e6 | seohae2/python_algorithm_day | /์ฝ๋ฉ์ธํฐ๋ทฐ/chapter11_ํด์_ํ
์ด๋ธ/03_์ค๋ณต๋ฌธ์_์๋_๊ฐ์ฅ๊ธด_๋ถ๋ถ๋ฌธ์์ด/exam2.py | 656 | 3.65625 | 4 | """
์ค๋ณต ๋ฌธ์๊ฐ ์๋ ๊ฐ์ฅ ๊ธด ๋ถ๋ถ ๋ฌธ์์ด (substring)์ ๊ธธ์ด๋ฅผ ๋ฆฌํดํ๋ผ.
์
๋ ฅ
"abcabcbb"
์ถ๋ ฅ
3
= ์ ๋ต์ "abc"๋ก ๊ธธ์ด๋ 3์ด๋ค.
"""
def lengthOfLongesSubstring(self, s: str) -> int:
used = {}
max_length = start = 0
for index, char in enumerate(s):
# ์ด๋ฏธ ๋ฑ์ฅํ๋ ๋ฌธ์๋ผ๋ฉด 'start' ์์น ๊ฐฑ์
if char in used and start <= used[char]:
start = used[char] + 1
else: # ์ต๋ ๋ถ๋ถ ๋ฌธ์์ด ๊ธธ์ด ๊ฐฑ์
max_length = max(max_length, index - start + 1)
# ํ์ฌ ๋ฌธ์์ ์์น ์ฝ์
used[char] = index
return max_length
|
a57a4b323d90a1390bacf3cd59393f4846099bb2 | seohae2/python_algorithm_day | /์ฝ๋ฉ์ธํฐ๋ทฐ/chapter07_๋ฐฐ์ด/D0120/04_์ธ์์_ํฉ/exam/9-2.py | 2,111 | 3.5625 | 4 | from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
results = []
# ์ ๋ ฌ
nums.sort()
for i in range(len(nums) - 2):
# ์ค๋ณต๋ ๊ฐ ๊ฑด๋๋ฐ๊ธฐ
if i > 0 and nums[i] == nums[i - 1]:
continue
# ๊ฐ๊ฒฉ์ ์ขํ๊ฐ๋ฉฐ ํฉ `sum` ๊ณ์ฐ
# left ๋ i + 1๋ฒ์งธ๋ก, right ๋ ๋งจ๋ง์ง๋ง ์์๋ก
left, right = i + 1, len(nums) - 1
# ๋ฐ๋ณต๋ฌธ ์คํ (left ๊ฐ right ๋ณด๋ค ๊ฐ๊ฑฐ๋ ์ปค์ง๋ค๋ ๊ฒ์ ๋ฆฌ์คํธ๋ฅผ ๋ชจ๋ ํ์ํ๋ค๋ ์๋ฏธ)
while left < right:
sum = nums[i] + nums[left] + nums[right]
if sum < 0: # sum ์ด 0 ๋ณด๋ค ์์ผ๋ฉด left + 1 ์ ํด์ค์ผ๋ก์จ ๋ ํฐ ๊ฐ์ ๋ํ๋ค.
left += 1
elif sum > 0: # sum ์ด 0 ๋ณด๋ค ๋ฉด right - 1 ์ ํด์ค์ผ๋ก์จ ๋ ์์ ๊ฐ์ ๋ํ๋ค.
right -= 1
else:
# `sum = 0`์ธ ๊ฒฝ์ฐ์ด๋ฏ๋ก ์ ๋ต ๋ฐ ์คํต ์ฒ๋ฆฌ
results.append([nums[i], nums[left], nums[right]])
# ์๋ ๋ก์ง์ ์ค๋ณต ์ ๊ฑฐ๋ฅผ ์ํ ๋ก์ง์ด๋ค.
# left ๊ฐ right ๋ณด๋ค ์์๋
# nums[left] ๊ฐ ๋ค์ ์์์ ๊ฐ์๋ ๋ค์ ์์ ์ฐจ๋ก๋ก left ๋ฅผ ๋ฐ๊ฟ์ค๋ค.
while left < right and nums[left] == nums[left + 1]:
left += 1
# left ๊ฐ right ๋ณด๋ค ์์๋
# nums[right] ๊ฐ right ์ ๋ค์ ์์(์ผ์ชฝ)์ ๊ฐ์๋ ๋ค์(์ผ์ชฝ) ์์ ์ฐจ๋ก๋ก right ๋ฅผ ๋ฐ๊ฟ์ค๋ค.
while left < right and nums[right] == nums[right - 1]:
right -= 1
# ๋ค์ for ๋ฌธ์ left, right ๋ฅผ ์ง์ ํด์ฃผ๊ธฐ ์ํจ์ด๋ค.
left += 1
right -= 1
return results
f = Solution()
# [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
print(Solution.threeSum(f, [-1, 0, 1, 2, -1, -4])) |
c55faee6657fbb7d1a938f6f07b8e64896c0c680 | seohae2/python_algorithm_day | /01_ํ์ด์ฌ_์ฒซ๊ฑธ์/18_ํจ์.py | 2,718 | 3.71875 | 4 | # coding=utf-8
# ๊ฒฐ๊ณผ๊ฐ์ด ์๋ ํจ
def add(a, b):
return a + b
# ๊ฒฐ๊ณผ๊ฐ์ด ์๋ ํจ์
def voidAdd(a, b):
print("%d, %d์ ํฉ์ %d์
๋๋ค." % (a, b, a+b))
a = 3
b = 4
c = add(a, b)
print(c)
print(add(3, 4)) # 3, 4๋ ์ธ์
print(voidAdd(1,2))
a1 = add(3, 4)
print(a1)
a2 = voidAdd(3, 4)
print(a2) # None
# ๋งค๊ฐ๋ณ์ ์ง์ ํ์ฌ ํธ์ถ
result = add(a=3, b=7) # a์ 3, b์ 7์ ์ ๋ฌ
print(result)
result = add(b=5, a=3) # b์ 5, a์ 3์ ์ ๋ฌ (์์ ์๊ด์์ด ๋ณ์์ ์ ๋ฌ ๊ฐ๋ฅ)
print(result) # 8
# ์
๋ ฅ๊ฐ ์ ํ ์๋ ํจ์
def add_many(*args):
result = 0
for i in args:
result = result + i
return result
result = add_many(1,2,3)
print(result) # 6
result = add_many(1,2,3,4,5,6,7,8,9,10)
print(result) # 55
# ํค์๋ ํ๋ผ๋ฏธํฐ kwargs (๋์
๋๋ฆฌ๋ก ์ฒ๋ฆฌ)
def print_kwargs(**kwargs):
print(kwargs)
print_kwargs(a=1) # {'a': 1}
print_kwargs(name='foo', age=3) # {'age': 3, 'name': 'foo'}
# return
def add_and_mul(a,b):
return a+b, a*b # ์๋ฌ ๋ฐ์ํ์ง ์์
result = add_and_mul(3,4) # ํํ์ ๊ฐ๊ฒ๋จ
print result # (7, 12)
# return (ํจ์ ํ์ถ)
def say_nick(nick):
if nick == "๋ฐ๋ณด":
return
print("๋์ ๋ณ๋ช
์ %s ์
๋๋ค." % nick)
say_nick('์ผํธ') # ๋์ ๋ณ๋ช
์ ์ผํธ์
๋๋ค.
say_nick('๋ฐ๋ณด') # ''
# ํจ์ ์ด๊น๊ฐ ์ค์
def say_myself(name, old, man=True):
print("๋์ ์ด๋ฆ์ %s ์
๋๋ค." % name)
print("๋์ด๋ %d์ด์
๋๋ค." % old)
if man:
print("๋จ์์
๋๋ค.")
else:
print("์ฌ์์
๋๋ค.")
say_myself("๋ฐ์์ฉ", 27)
say_myself("๋ฐ์์ฉ", 27, True)
# ๋งค๊ฐ๋ณ์ ์์ ์ฃผ์
"""
def say_myself2(name, man=True, old):
print("๋์ ์ด๋ฆ์ %s ์
๋๋ค." % name)
print("๋์ด๋ %d์ด์
๋๋ค." % old)
if man:
print("๋จ์์
๋๋ค.")
else:
print("์ฌ์์
๋๋ค.")
say_myself2("๋ฐ์์ฉ", 27) # 27์ man ๋ณ์์ old ๋ณ์ ์ค ์ด๋ ๊ณณ์ ๋์
ํด์ผ ํ ์ง ์ ์ ์๋ค.
"""
# ๋ณ์์ ํจ๋ ฅ ๋ฒ์
a = 1
def vartest(a):
a = a +1
print(a) # ์ฌ๊ธฐ์ a๋ vertest ํจ์๋ง์ ๋ณ์์ด๋ค.
vartest(a) # 2
print(a) # 1
# ํจ์ ์์์ ํจ์ ๋ฐ์ ๋ณ์ ๋ณ๊ฒฝํ๊ธฐ
a = 1
def vartest(a):
a = a +1
return a
a = vartest(a)
print(a)
# global
a = 1
def vartest():
global a # ์ ์ญ๋ณ์ a๋ฅผ ๋ปํจ
a = a+1
print(a)
vartest() # 2
print(a) # 2
# lambda
# lambda๋ ํจ์๋ฅผ ์์ฑํ ๋ ์ฌ์ฉํ๋ ์์ฝ์ด๋ก def์ ๋์ผํ ์ญํ
add = lambda a, b: a+b # ๋งค๊ฐ๋ณ์ a,b ๊ฒฐ๊ณผ a+b
result = add(3, 4)
print(result) # 7
def add(a, b):
return a+b
result = add(3, 4) # 7
print(result) # 7
|
8e104c272b50a9ea7c1b16b200b2a4b42a6a0914 | seohae2/python_algorithm_day | /์ด๊ฒ์ด์ฝ๋ฉํ
์คํธ๋ค/01_๊ธฐ๋ณธ_๊ฐ๋
/02_๋ฆฌ์คํธ_์๋ฃํ.py | 3,218 | 3.796875 | 4 | # ๋ฆฌ์คํธ ์๋ฃํ
# ์ฌ๋ฌ๊ฐ์ ๋ฐ์ดํฐ๋ฅผ ์ฐ์์ ์ผ๋ก ๋ด์ ์ฒ๋ฆฌํ๊ธฐ์ํด ์ฌ์ฉํ๋ ์๋ฃํ
# ํ์ด์ฌ์ ๋ฐฐ์ด ์ ์ฌ์ฉํ ๋ ๋ฆฌ์คํธ๋ฅผ ์ฌ์ฉํ๋ค. (๋ฆฌ์คํธ๋ฅผ ๋ฐฐ์ด ๋๋ ํ
์ด๋ธ์ด๋ผ๊ณ ๋ ํ๋ค.)
# ์ธ๋ฑ์ค๋ 0 ๋ถํฐ ์์ํ๋ค
# ์ง์ ๋ฐ์ดํฐ๋ฅผ ๋ฃ์ด ์ด๊ธฐํ
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a)
# ๋ค๋ฒ์งธ ์์ ์ถ๋ ฅ
print(a[3])
# ํฌํค๊ฐ N์ด๊ณ , ๋ชจ๋ ๊ฐ์ด 0์ธ 1์ฐจ์ ๋ฆฌ์คํธ ์ด๊ธฐํ
n = 10
a = [0] * n
print(a) # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a[4] = 0
print(a) # [1, 2, 3, 4, 0, 6, 7, 8, 9]
# ๋ฆฌ์คํธ์ ํน์ ํ ์์์ ์ ๊ทผํ๋ ๊ฒ์ ์ธ๋ฑ์ฑ(Indexing)์ด๋ผ๊ณ ํ๋ค.
# ๋ค์ชฝ์์ ์์์ ์์
print(a[7]) # 8๋ฒ์งธ ์์
print(a[-1]) # ๋ค์์ 1๋ฒ์งธ ์์
# ๋ฆฌ์คํธ์์ ์ฐ์์ ์ธ ์์น๋ฅผ ๊ฐ๋ ์์๋ค์ ๊ฐ์ ธ์์ผํ ๋๋ ์ฌ๋ผ์ด์ฑ(Slicing)์ ์ด์ฉํ๋ค. (:์ ๊ธฐ์ค์ผ๋ก ์์ ์ธ๋ฑ์ค์ ๋ ์ธ๋ฑ์ค๋ฅผ ์ค์ ํ๋ค)
# ๋ ์ธ๋ฑ์ค๋ ์ค์ ์ธ๋ฑ์ค๋ณด๋ค 1 ํฌ๊ฒ ์ค์ ํ๋ค.
print(a[3]) # ๋ค๋ฒ์งธ ์์๋ง ์ถ
print(a[1:4]) # ๋๋ฒ์งธ ์์๋ถํฐ ๋ค๋ฒ์ฌ ์์๊น์ง
# ๋ฆฌ์คํธ ์ปดํ๋ฆฌํจ์
: ๋ฆฌ์คํธ๋ฅผ ์ด๊ธฐํํ๋ ๋ฐฉ๋ฒ ์ค ํ๋์ด๋ค. (๋๊ดํธ ์์ ์กฐ๊ฑด๋ฌธ๊ณผ ๋ฐ๋ณต๋ฌธ์ ์ ์ฉํ์ฌ ๋ฆฌ์คํธ๋ฅผ ์ด๊ธฐํํ ์ ์๋ค.)
array = [i for i in range(10)] # i๊ฐ 0๋ถํฐ 9๊น์ง
print(array)
array = [i for i in range(20) if i % 2 == 1] # 0๋ถํฐ 19๊น์ง์ ์ซ์ ์ค if ์กฐ๊ฑด์ ํด๋น
# ์ ํ์ค์ ๋ก์ง์ ์๋์ ๊ฐ๋ค.
array = []
for i in range(20):
if i % 2 == 1:
array.append(i)
array = [i * i for i in range(1, 10)] # 1, 9๊น์ง
# ๋ฆฌ์คํธ ์ปดํ๋ฆฌํจ์
์ 2์ฐจ์ ๋ฆฌ์คํธ๋ฅผ ์ด๊ธฐํํ ๋ ํจ๊ณผ์ ์ผ๋ก ์ฌ์ฉ์ด ๊ฐ๋ฅํ๋ค.
# ex) array = [[0] * m for _ in range(n)] # m ๋ฒ ๋ฐ๋ณต์ ํ ๋๋ง๋ค ๊ธธ์ด๊ฐ n์ธ ๋ฆฌ์คํธ๋ฅผ ๋ง๋ ๋ค.
n = 4
m = 3
array = [[0] * m for _ in range(n)] # [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
print(array)
array[1][1] = 5
print(array) # [[0, 0, 0], [0, 5, 0], [0, 0, 0], [0, 0, 0]]
# ์๋ชป๋ ์์
n = 4
m = 3
array2 = [[0] * m] * n # ๊ฐ์ฒด ์์ฒด๋ฅผ ๊ฐ์ ๊ฐ์ฒด๋ก ํ๋จํ๋ค.
array2[1][1] = 5
print(array2) # [[0, 5, 0], [0, 5, 0], [0, 5, 0], [0, 5, 0]]
# ์ธ๋๋ฐ(_)์ ์ฌ์ฉ
# ๋ฐ๋ณต์ ์ํ ๋ณ์์ ๊ฐ์ ๋ฌด์ํ ๊ฒฝ์ฐ ์ฌ์ฉํ๋ค.
for _ in range(5):
print("hi")
# ๋ฆฌ์คํธ ๊ด๋ จ ํจ์
"""
* append() : ๋ฆฌ์คํธ์ ์์ ํ๋ ์ฝ์
* sort() : ์ค๋ฆ์ฐจ์ ์ ๋ ฌ (๋ด๋ฆผ์ฐจ์; sort(reverse=True))
* reverse() : ์์์ ์์ ๋ค์ง๊ธฐ
* insert() : ํน์ ํ ์์น์ ์์ ์ฝ์
(insert(์ฝ์
ํ ์์น ์ธ๋ฑ์ค, ๊ฐ))
* count() : ๋ฐ์ดํฐ ๊ฐ์
* remove() : ํน์ ํ ๊ฐ์ ์ ๊ฑฐ (๊ฐ์ ๊ฐ์ด ์ฌ๋ฌ๊ฐ์ผ ๊ฒฝ์ฐ 1๊ฐ๋ง ์ญ์ ํ๋ค)
"""
# remove ํจ์๋ฅผ ์ฌ์ฉํด์ ํน์ ์์๋ฅผ ๋ชจ๋ ์ ๊ฑฐํด์ผํ ๊ฒฝ์ฐ
a = [1, 2, 3, 4, 5, 5, 5]
remove_set = {3, 5} # ์งํฉ ์๋ฃํ
result = [i for i in a if i not in remove_set] # remove_set ์ ํฌํจ๋์ด์์ง ์์ ์์๋ฅผ ๋ด์ ๋ฆฌ์คํธ๋ฅผ ์์ฑํ๋ค
print(result) # [1, 2, 4] => 3, 5๊ฐ ์ญ์ ๋์๋ค. 5๋ ์ด 3๊ฐ์ธ๋ฐ ๋ชจ๋ ์ญ์ ๋์์์ ์ ์ ์๋ค.
|
44c04f70f03915db09630c870952a87f87f9afab | seohae2/python_algorithm_day | /์ด๊ฒ์ด์ฝ๋ฉํ
์คํธ๋ค/00_์๊ณ ๋ฆฌ์ฆ_๊ตฌํ/09_๊ณ์์ ๋ ฌ.py | 650 | 3.515625 | 4 | # ๋ชจ๋ ์์์ ๊ฐ์ด 0๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ๋ค๊ณ ๊ฐ์ ํ๋ค
array = [7, 5, 9, 0, 3, 1, 6, 2, 9, 1, 4, 8, 0, 5, 2]
# ๋ชจ๋ ๋ฒ์๋ฅผ ํฌํจํ๋ ๋ฆฌ์คํธ ์ ์ธ (๋ชจ๋ ๊ฐ์ 0์ผ๋ก ์ด๊ธฐํ)
count = [0] * (max(array) + 1) # max(array)=9, 0 ๋ถํฐ ์ด๋ฏ๋ก + 1 ์ฒ๋ฆฌ
print(count) # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for i in range(len(array)):
# array[i] : value ๋ฅผ ์ธ๋ฑ์ค๋ก ์ง์ ํ๋ค
count[array[i]] += 1 # ๊ฐ ๋ฐ์ดํฐ์ ํด๋นํ๋ ์ธ๋ฑ์ค์ ๊ฐ ์ฆ๊ฐ
for i in range(len(count)): # ๋ฆฌ์คํธ์ ๊ธฐ๋ก๋ ์ ๋ ฌ ์ ๋ณด ํ์ธ
for j in range(count[i]): # ๊ฐ์๋งํผ ์ถ๋ ฅ
print(i, end=' ')
|
b83e800b14ee1bcaff0c3d5a3e6da8b0cd787bc1 | seohae2/python_algorithm_day | /์ฝ๋ฉ์ธํฐ๋ทฐ/chapter06_๋ฌธ์์ด์กฐ์/D0119/05_๊ทธ๋ฃน_์ ๋๊ทธ๋จ/seohae.py | 674 | 3.875 | 4 | # https://leetcode.com/problems/group-anagrams/
# ๋ฆฌ์คํธ ์์๋๋ก ๋จ์ด ๊บผ๋ด๊ธฐ
# ๊บผ๋ธ ๋จ์ด๋ฅผ ์ํ๋ฒณ ์์ผ๋ก ์ ๋ ฌํ๊ธฐ (์ด๋ ๊ฒ๋๋ฉด ๊ฐ์ ์ํ๋ฒณ์ ๋จ์ด๋ ๋์ผํ ๊ฐ์ผ๋ก ๋น๊ต ๊ฐ๋ฅํ๋ค)
test_list = ["eat", "tea", "tan", "ate", "nat", "bat"]
test_dict = {}
for text in test_list:
alpha_list = list(text)
alpha_list.sort()
print(alpha_list)
sort_text = "".join(alpha_list)
if sort_text in test_dict:
# test_dict[sort_text] = test_dict[sort_text].append(text) -> ๊ฒฐ๊ณผ๊ฐ์ None ์ด๋ค.
test_dict[sort_text].append(text)
else:
test_dict[sort_text] = [text]
print(test_dict)
|
06bcfa5043b7daed8c40ecb3d513a0bfd5ddb2d8 | seohae2/python_algorithm_day | /์ฝ๋ฉ์ธํฐ๋ทฐ/1_๊ธฐ๋ณธ_๋ฌธ๋ฒ/4_๋์
๋๋ฆฌ_๋ชจ๋.py | 1,313 | 3.71875 | 4 | """
defaultdict ๊ฐ์ฒด : ์กด์ฌํ์ง ์๋ ํค๋ฅผ ์กฐํํ ๊ฒฝ์ฐ, ์๋ฌ ๋ฉ์์ง๋ฅผ ์ถ๋ ฅํ๋ ๋์ ๋ํดํธ ๊ฐ์ ๊ธฐ์ค์ผ๋ก ํด๋น ํค์ ๋ํ ๋์
๋๋ฆฌ ์์ดํ
์ ์์ฑํ๋ค.
"""
import collections
a = collections.defaultdict(int)
a['A'] = 5
a['B'] = 4
print(a) # defaultdict(<class 'int'>, {'A': 5, 'B': 4})
a['C'] += 1 # ์กด์ฌํ์ง์๋ key ์ฌ์ฉ
print(a) # defaultdict(<class 'int'>, {'A': 5, 'B': 4, 'C': 1})
# default(0) ์ ๊ธฐ์ค์ผ๋ก ์๋์ผ๋ก ์์ฑํ ํ 1์ ๋ํด key 'C'๊ฐ ์์ฑ๋์๋ค.
"""
Counter ๊ฐ์ฒด : ์์ดํ
์ ๋ํ ๊ฐ์๋ฅผ ๊ณ์ฐํ์ฌ ๋์
๋๋ฆฌ๋ก ๋ฆฌํดํ๋ค.
"""
a = [1, 2, 3, 4, 5, 5]
b = collections.Counter(a)
print(b) # Counter({5: 2, 1: 1, 2: 1, 3: 1, 4: 1})
# ํด๋น ์์ดํ
์ ๊ฐ์๊ฐ ๋ค์ด๊ฐ ๋์
๋๋ฆฌ๋ฅผ ์์ฑํด์ค๋ค.
# ํ๋ฒ ๋ ๋์
๋๋ฆฌ๋ฅผ ๋ํํ collections.Counter ํด๋์ค๋ฅผ ๊ฐ๋๋ค.
print(type(b)) # <class 'collections.Counter'>
print(b.most_common(2)) # ๊ฐ์ฅ ๋น๋์๊ฐ ๋์ ์์๋ฅผ ์ถ์ถ (2๊ฐ์ ์์๋ฅผ ์ถ์ถ) ; [(5, 2), (1, 1)]
"""
OrderedDict ๊ฐ์ฒด : ํด์ ํ
์ด๋ธ์ ์ด์ฉํ ์๋ฃํ์ ์์๊ฐ ์ ์ง๋์ง ์๊ธฐ ๋๋ฌธ์, ์
๋ ฅ ์์๊ฐ ์ ์ง๋๋ ๋ณ๋์ ๊ฐ์ฒด๋ฅผ ์ฌ์ฉํ๋ค.
"""
collections.OrderedDict({'key1': 1, 'key2': 2, 'key3': 3})
|
f4131a488c76f6bc1938b6a214b91125cf3ff0bd | seohae2/python_algorithm_day | /์ฝ๋ฉ์ธํฐ๋ทฐ/chapter08_์ฐ๊ฒฐ๋ฆฌ์คํธ [๋ค์ํ๊ธฐ]/01_๋_์ ๋ ฌ_๋ฆฌ์คํธ์_๋ณํฉ/seohae.py | 1,198 | 3.671875 | 4 | # ์ ๋ ฌ๋์ด์๋ ๋ ์ฐ๊ฒฐ ๋ฆฌ์คํธ๋ฅผ ํฉ์ณ๋ผ
# ์
๋ ฅ 1->2->4, 1->3->4
# ์ถ๋ ฅ 1->1->2->3->4->4
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# ๋ฆฌ์คํธ ๋ณํ
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
while l1 is not None:
prev = l1.val
while l2 is not None:
if prev >= l2.val:
# l1์ด ๊ธฐ์กด์ ๊ฐ๋ฅดํค๊ณ ์๋ ๋
ธ๋ ์ ์ฅ
prevL1 = l1.next
# l1์ด ๊ฐ๋ฆฌํค๋ ๋
ธ๋๋ฅผ l2๋ก ๋ณ๊ฒฝ
l1.next = l2
# ๊ธฐ์กด์ l2๊ฐ ๊ฐ๋ฆฌํค๋ ๋
ธ๋๋ฅผ ์ ์ฅ
prevL2 = l2.next
# l2๊ฐ ๊ฐ๋ฆฌํค๋ ๋
ธ๋๋ฅผ l1 ๋ค์ ๋
ธ๋๋ก ๋ณ๊ฒฝ
l1.next.next = prevL1
# l2๋ ๊ธฐ์กด l2๊ฐ ๊ฐ๋ฆฌํค๋ ๋
ธ๋๋ก ๋ณ๊ฒฝ
l2 = prevL2
else:
# l2 ๋ค์ ๋
ธ๋๋ก ๋ณ๊ฒฝ
l2 = l2.next
l1 = l1.next
return l1
l1 = ListNode(1)
l1.next = ListNode(2)
l1.next.next = ListNode(4)
l2 = ListNode(1)
l2.next = ListNode(3)
l2.next.next = ListNode(4)
answer = mergeTwoLists(l1, l2)
|
849a3fe2b8dc3cf6d78c3f738bb8835b77b2bc11 | seohae2/python_algorithm_day | /02_ํ์ด์ฌ_300์ /M071~M080_ํํ.py | 1,338 | 3.578125 | 4 | # 071. ํํ์ ๋ง๋ค์ด๋ผ
my_variable = ()
print(type(my_variable))
# 072. ์์ 3๊ฐ์ธ ํํ์ ๋ง๋์ธ์
movies = ("๋ฅํฐ ์คํธ๋ ์ธ์ง", "์คํ๋ฆฟ", "๋ญํค")
print(movies)
# 073. ์ซ์ 1์ด ์ ์ฅ๋ ํํ์ ์์ฑํ์ธ์
my_tuple = (1)
print(type(my_tuple)) # <class 'int'> (ํํ์ด ์๋ ์ ์ํ์ผ๋ก ์ธ์ํ๋ค)
my_tuple = (1, )
print(type(my_tuple)) # <class 'tuple'> ์ผํ๋ฅผ ํจ๊ป ์
๋ ฅํ์.
# 074. ์๋ฌ ๋ฐ์์ ์ด์ ๋?
t = (1, 2, 3)
# t[0] = 'a' > ํํ์ ์์์ ๊ฐ์ ๋ณ๊ฒฝํ ์ ์๋ค.
# 075. t = 1, 2, 3, 4 ์ ํ์
์? ํํ
t = 1, 2, 3
print(type(t)) # <class 'tuple'> (๊ดํธ ์๋ต์ด ๊ฐ๋ฅํ๋ค)
# 076. ํํ์ ์
๋ฐ์ดํธ ํ์ธ์
t = ('a', 'b', 'c')
t = ('A', 'b', 'c')
print(t) # ๊ธฐ์กด์ ํํ์ ์ญ์ ํ๊ณ ๋ง์ง๋ง์ผ๋ก ์ ์ฅ๋ ํํ์ด ์ถ๋ ฅ๋๋ค
# 077. ํํ์ ๋ฆฌ์คํธ๋ก ๋ณํํ์ธ์
interest = ('์ผ์ฑ์ ์', 'LG์ ์', 'ํํ')
list_a = list(interest)
print(list_a)
# 078. ๋ฆฌ์คํธ๋ฅผ ํํ๋ก ๋ณํํ์ธ์
list_a = ['์ผ์ฑ์ ์', 'LG์ ์', 'ํํ']
tuple_b = tuple(list_a)
print(tuple_b)
# 079. ํํ ์ธํฉ
temp = ('apple', 'banana', 'cake')
a, b, c = temp
print(a, b, c) # apple banana cake
# 080. 1~99 ์ ์ ์ค ์ง์๋ง ์ ์ฅ๋ ํํ์ ์์ฑํ๋ผ
data = tuple(range(2, 100, 2))
print(data)
|
5cdca923cabb019f8b64f8e4098cc02179a030ba | seohae2/python_algorithm_day | /์๊ณ ๋ฆฌ์ฆ๊ตฌํ/05_์ฐ๊ฒฐ๋ฆฌ์คํธ/node.py | 1,056 | 3.59375 | 4 | # ์ฐ๊ฒฐ๋ฆฌ์คํธ
class Node:
def __init__(self, data):
self.data = data
self.next = None
def add(self, node):
# ๋ค์ ๋
ธ๋๊ฐ None ์ด๋ผ๋ฉด,
if self.next is None:
self.next = node
# ๋ค์ ๋
ธ๋๊ฐ None์ด ์๋๋ผ๋ฉด,
else:
n = self.next
# ๋ง์ง๋ง ๋
ธ๋๋ฅผ ์ฐพ์๋๊น์ง ๋ฐ๋ณต๋ฌธ ์คํ
while True:
# ๋ง์ง๋ง ๋
ธ๋๋ฅผ ์ฐพ์๋ค๋ฉด, ํด๋น ๋
ธ๋์ ๋ค์ ๋
ธ๋๋ None ์ผ ๊ฒ
if n.next is None:
n.next = node
break
else: # ๋ง์ง๋ง ๋
ธ๋๊ฐ ์๋๋ผ๋ฉด ๊ณ์ํด์ ๋ค์ ๋
ธ๋ ํ์
n = n.next
def select(self, idx):
n = self.next
for i in range(idx - 1):
n = n.next
return n.data
def delete(self, idx):
# ๋ค์ ๋
ธ๋๋ฅผ ์ ์ฅ
n = self.next # ๋ง์ง๋ง ๋
ธ๋๋ผ๋ฉด None
# ๋ง์ง๋ง ๋
ธ๋๋ ์ ์ธ (๋ค์ ๋
ธ๋๊ฐ ์์ผ๋ฏ๋ก)
for i in range(idx - 2):
n = n.next
t = n.next
n.next = t.next
del t
|
57bb333497c4da8133ea63bcba7a06eaceef7a3f | seohae2/python_algorithm_day | /01_ํ์ด์ฌ_์ฒซ๊ฑธ์/16_while๋ฌธ.py | 1,258 | 3.6875 | 4 | # coding=utf-8
# while๋ฌธ ์ฌ์ฉ
treeHit = 0
while treeHit < 10:
treeHit = treeHit +1
print("๋๋ฌด๋ฅผ %d๋ฒ ์ฐ์์ต๋๋ค." % treeHit)
if treeHit == 10:
print("๋๋ฌด ๋์ด๊ฐ๋๋ค.")
# while๋ฌธ ๋น ์ ธ๋๊ฐ๊ธฐ (break)
coffee = 10
money = 300
while money:
print("๋์ ๋ฐ์์ผ๋ ์ปคํผ๋ฅผ ์ค๋๋ค.")
coffee = coffee -1
print("๋จ์ ์ปคํผ์ ์์ %d๊ฐ์
๋๋ค." % coffee)
if coffee == 0:
print("์ปคํผ๊ฐ ๋ค ๋จ์ด์ก์ต๋๋ค. ํ๋งค๋ฅผ ์ค์งํฉ๋๋ค.")
break # ๋ฐ๋ณต๋ฌธ ํ์ถ
# ์์
coffee = 10
while True:
money = int(input("๋์ ๋ฃ์ด ์ฃผ์ธ์: "))
if money == 300:
print("์ปคํผ๋ฅผ ์ค๋๋ค.")
coffee = coffee -1
elif money > 300:
print("๊ฑฐ์ค๋ฆ๋ %d๋ฅผ ์ฃผ๊ณ ์ปคํผ๋ฅผ ์ค๋๋ค." % (money -300))
coffee = coffee -1
else:
print("๋์ ๋ค์ ๋๋ ค์ฃผ๊ณ ์ปคํผ๋ฅผ ์ฃผ์ง ์์ต๋๋ค.")
print("๋จ์ ์ปคํผ์ ์์ %d๊ฐ ์
๋๋ค." % coffee)
if coffee == 0:
print("์ปคํผ๊ฐ ๋ค ๋จ์ด์ก์ต๋๋ค. ํ๋งค๋ฅผ ์ค์ง ํฉ๋๋ค.")
break
# while๋ฌธ ๋งจ ์ฒ์์ผ๋ก ๋์๊ฐ๊ธฐ (continue)
a = 0
while a < 10:
a = a + 1
if a % 2 == 0:
continue
print(a)
|
176d1ff7a48509e3095cdfc3372d1460efbf9609 | CurtisNewbie/Learning-Notes | /PyTutorial/w3schools/examples/PythonVariables.py | 702 | 4.0625 | 4 | x, y, z = "X", "Y", "Z"
print(x, y, z)
x = y = z = "XYZ"
print(x, y, z)
x = y + "ABC"
print("XYZ + ABC =", x)
print("XYZ + ABC = " + x)
# this will cause exception
# print("1 + 1 = " + 2)
"""
Traceback (most recent call last):
File "PythonVariables.py", line 12, in <module>
print("1 + 1 = " + 2)
TypeError: can only concatenate str (not "int") to str
"""
print("1 + 1 = " + str(2))
print("1 + 1 =", 1+1)
text = "Some Text"
def showText():
print(text)
showText()
def showInnerText():
text = "Nah"
print(text)
showInnerText()
def createGlobalVar():
global globalVar
globalVar = "I am global variable created within a func"
createGlobalVar()
print(globalVar)
|
6cde4e6620a5d5e13d310615cb7b6527bff6da89 | iotarepeat/sms-spam-detector | /main.py | 594 | 3.515625 | 4 | import pickle
from train import messageFunction
def predict(message):
message = messageFunction(message)
with open('probab.pickle', 'rb') as f:
probablity = pickle.load(f)
with open('word_count.pickle', 'rb') as f:
word_counter = pickle.load(f)
for word in message:
for label, counter in word_counter.items():
if counter.get(word, False):
probablity[label] *= counter.get(word)
return max(probablity, key=lambda x: probablity[x])
message = input("Enter txt message:")
print("Message is most likely: ", predict(message))
|
c726cb7f310a7f4bccc8dc03e93f1def136d89a9 | JohnHuiWB/leetcode | /22. Generate Parentheses/22.py | 555 | 3.609375 | 4 | class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
def gen(cur, l, r):
if not l and not r:
out.append(cur)
return
if r and r > l:
gen(cur + ')', l, r - 1)
if l:
gen(cur + '(', l - 1, r)
out = []
gen('', n, n)
return out
if __name__ == '__main__':
s = Solution()
print(s.generateParenthesis(3))
print(s.generateParenthesis(4))
|
62a5040efaa5a7702cc952e0e8399f2cfc8aeac0 | luifrancgom/mintic_retos_2021 | /004_reto4_luis_francisco.py | 7,968 | 3.9375 | 4 | # Aplicar la estrategia divide y venceras
# Primero se requiere obtener informaciรณn del nรบmero de zonas
# Ingresar el nรบmero de zonas
zonas = int(input())
# Segundo se requiere guardar los datos en una matriz
# de la variable materia orgรกnica
matriz_materia_organica = []
for i in range(0, zonas, 1):
# En esta parte se utiliza lo seรฑalado en
# https://www.w3schools.com/python/ref_string_split.asp
# Ingresar los valores de la zona {i + 1} de materia organica
materia_organica = input().split(" ")
fila_materia_organica = []
# Luego debemos convertir cada elemento de la lista
# de caracteres a tipo float
for i in range(0, len(materia_organica), 1):
fila_materia_organica.append(float(materia_organica[i]))
# Luego debemos agregar la fila a la matriz
matriz_materia_organica.append(fila_materia_organica)
# Tercero se requiere guardar los datos en una matriz
# de la variable รณxido de fosforo
matriz_oxido_fosforo = []
for i in range(0, zonas, 1):
# En esta parte se utiliza lo seรฑalado en
# https://www.w3schools.com/python/ref_string_split.asp
# Ingresar los valores de la zona {i + 1} de materia organica
oxido_fosforo = input().split(" ")
fila_oxido_fosforo = []
# Luego debemos convertir cada elemento de la lista
# de caracteres a tipo float
for i in range(0, len(materia_organica), 1):
fila_oxido_fosforo.append(float(oxido_fosforo[i]))
# Luego debemos agregar la fila a la matriz
matriz_oxido_fosforo.append(fila_oxido_fosforo)
# Cuarto se requiere realizar el conteo de cada
# categoria para cada zona en base a la informaciรณn
# de las matrices matriz_materia_organica y
# matriz_oxido_fosforo
# Para realizar este proceso y mantener los datos
# consolidados se construye una matriz donde las
# columnas corresponden a las categorias (no_apto,
# marginalmente_apto, moderadamente_apto, sumamente_apto)
# y las filas a cada zona
matriz_categorias_zonas = []
for i in range(0, len(matriz_materia_organica), 1):
# Fijar las varibles de conteo
n_sumamente_apto = 0
n_moderadamente_apto = 0
n_marginalmente_apto = 0
n_no_apto = 0
# Generar el conteo para cada zona
for j in range(0, len(matriz_materia_organica[0]), 1):
# sumamente apto
if (matriz_materia_organica[i][j] > 5 and matriz_oxido_fosforo[i][j] > 69):
n_sumamente_apto = n_sumamente_apto + 1
# moderadamente apto
elif (matriz_materia_organica[i][j] > 4 and matriz_oxido_fosforo[i][j] > 57):
n_moderadamente_apto = n_moderadamente_apto + 1
# marginalmente apto
elif (matriz_materia_organica[i][j] >= 3 and matriz_oxido_fosforo[i][j] >= 46):
n_marginalmente_apto = n_marginalmente_apto + 1
# no apto
else:
n_no_apto = n_no_apto + 1
# Guardar el conteo por categorias para cada zona
matriz_categorias_zonas.append(
[n_no_apto, n_marginalmente_apto, n_moderadamente_apto, n_sumamente_apto])
# Quinto se realiza el conteo de cada categoria
# (no_apto, marginalmente_apto, moderadamente_apto,
# sumamente_apto)
conteo_categorias = []
for j in range(0, len(matriz_categorias_zonas[0]), 1):
suma = 0
for i in range(0, len(matriz_categorias_zonas), 1):
suma = suma + matriz_categorias_zonas[i][j]
conteo_categorias.append(suma)
# Sexto se selecciona la categorรญa que mรกs se
# presenta por zona donde si existe un empate
# se escoje la mejor categorรญa
categoria_mas_se_presenta = []
for i in range(0, len(matriz_categorias_zonas), 1):
# Especificar el mรกximo
maximo = max(matriz_categorias_zonas[i])
# sumamente apto
if matriz_categorias_zonas[i][3] == maximo:
categoria_mas_se_presenta.append("sumamente apto")
# moderadamente apto
elif matriz_categorias_zonas[i][2] == maximo:
categoria_mas_se_presenta.append("moderadamente apto")
# marginalmente apto
elif matriz_categorias_zonas[i][1] == maximo:
categoria_mas_se_presenta.append("marginalmente apto")
# no apto
else:
categoria_mas_se_presenta.append("no apto")
# Septimo se selecciona la categorรญa que menos se
# presenta por zona donde si existe un empate
# se escoje la mejor categorรญa
# Ademรกs si no se presenta una categorรญa, no debe
# ser tenida en cuenta. Es decir, si el conteo por zona
# de una categoria es cero, esa categorรญa no serรก considerada
# como la que menos se presentรณ.
# Septimo a: Construimos una funciรณn auxiliar que encuentre el
# segundo elemento mรกs pequeรฑo. Para el caso del reto4 esta funciรณn
# no tendrรก problemas dado que el segundo elemento mรกs pequeรฑo
# siempre existe
def segundo_min(lista):
minimo = min(lista)
segundo_min = lista[0]
for i in range(0, len(lista), 1):
# Esta parte se incluye dado que
# el mรญnimo podrรญa estar en una
# posiciรณn anterior a cualquier otro
# nรบmero y la parte del elif no
# funcionarรญa. Por ejemplo [1,5] o [1,1,5]
if minimo == segundo_min:
segundo_min = lista[i+1]
elif minimo < lista[i] and segundo_min > lista[i]:
segundo_min = lista[i]
return segundo_min
# Septimo b: se selecciona la categorรญa que menos se
# presenta por zona donde si existe un empate
# se escoje la mejor categorรญa y se tiene en cuenta el
# caso cuando el mรญnimo es cero
categoria_menos_se_presenta = []
for i in range(0, len(matriz_categorias_zonas), 1):
# Calcular el mรญnimo
minimo = min(matriz_categorias_zonas[i])
# Caso en el que el mรญnimo sea diferente de cero
if minimo != 0:
# sumamente apto
if matriz_categorias_zonas[i][3] == minimo:
categoria_menos_se_presenta.append("sumamente apto")
# moderadamente apto
elif matriz_categorias_zonas[i][2] == minimo:
categoria_menos_se_presenta.append("moderadamente apto")
# marginalmente apto
elif matriz_categorias_zonas[i][1] == minimo:
categoria_menos_se_presenta.append("marginalmente apto")
# no apto
else:
categoria_menos_se_presenta.append("no apto")
# Caso en el que el mรญnimo sea igual a cero
else:
# Calcular el segundo elemento mรกs pequeรฑo
segundo_minimo = segundo_min(matriz_categorias_zonas[i])
# sumamente apto
if matriz_categorias_zonas[i][3] == segundo_minimo:
categoria_menos_se_presenta.append("sumamente apto")
# moderadamente apto
elif matriz_categorias_zonas[i][2] == segundo_minimo:
categoria_menos_se_presenta.append("moderadamente apto")
# marginalmente apto
elif matriz_categorias_zonas[i][1] == segundo_minimo:
categoria_menos_se_presenta.append("marginalmente apto")
# no apto
else:
categoria_menos_se_presenta.append("no apto")
# Octavo se realiza la impresiรณn de los resultados
# en base al formato solicitado
# Conteo de categorias
for i in range(0, len(conteo_categorias), 1):
if i != len(conteo_categorias) - 1:
print(f"{conteo_categorias[i]}", end=" ")
else:
print(f"{conteo_categorias[i]}", end="\n")
# Categorias que mas se presentan
for i in range(0, len(categoria_mas_se_presenta), 1):
if i != len(categoria_mas_se_presenta) - 1:
print(f"{categoria_mas_se_presenta[i]}", end=",")
else:
print(f"{categoria_mas_se_presenta[i]}", end="\n")
# Categorias que menos se presentan
for i in range(0, len(categoria_menos_se_presenta), 1):
if i != len(categoria_menos_se_presenta) - 1:
print(f"{categoria_menos_se_presenta[i]}", end=",")
else:
print(f"{categoria_menos_se_presenta[i]}", end="\n")
# Valores de prueba
# 3
# 5.62 2.33 1.97 4.78 4.21 1.64 4.26
# 2.09 7.12 7.13 3.62 1.87 4.11 2.14
# 5.09 3.19 5.17 4.5 4.99 3.21 5.24
# 63 58 42 64 46 45 62
# 72 42 53 77 77 43 56
# 59 56 58 67 48 79 49
|
2062912d0fdc908793112866c857b605a457d998 | luifrancgom/mintic_retos_2021 | /002_reto2_luis_francisco.py | 2,043 | 3.59375 | 4 | # no incluir mensajes en los inputs
# tambien se incluye int dado que las muestras deben
# ser nรบmeros enteros
muestras = int(input())
# indicadores de la variable de conteo
# muestras
i = 0
# categorias
n_sumamente_apto = 0
n_moderadamente_apto = 0
n_marginalmente_apto = 0
n_no_apto = 0
# suma variables
suma_materia_organica = 0
suma_oxido_fosforo = 0
while (i < muestras):
# no incluir mensajes en los inputs
materia_organica = float(input())
oxido_fosforo = float(input())
# conteo de muestras
i = i + 1
# acumulacion suma de variables
suma_materia_organica = suma_materia_organica + materia_organica
suma_oxido_fosforo = suma_oxido_fosforo + oxido_fosforo
# En esta parte utilice el cรณdigo de Kariett Justine Pinto Pinto,
# estudiante del curso, para mejorar esta secciรณn relacionada con
# el reto 1 para que fuera mรกs compacta y corta la ejecuciรณn
# sumamente apto
if (materia_organica > 5 and oxido_fosforo > 69):
n_sumamente_apto = n_sumamente_apto + 1
# moderadamente apto
elif (materia_organica > 4 and oxido_fosforo >= 58):
n_moderadamente_apto = n_moderadamente_apto + 1
# marginalmente apto
elif (materia_organica >= 3 and oxido_fosforo >= 46):
n_marginalmente_apto = n_marginalmente_apto + 1
# no apto
else:
n_no_apto = n_no_apto + 1
# Esta parte la realice de esta forma para obtener exactamente
# las salidas esperadas donde seguรญ las indicaciones de
# Sebastian Joao Racedo Valbuena respecto a lo seรฑalado en
# https://www.w3schools.com/python/ref_string_format.asp
# De esa manera por ejemplo obtengo 55.00 y no 55 si lo hiciera con
# round(x,2)
# promedio de la materia organica a 2 decimales
print(f"{suma_materia_organica/muestras:.2f}")
# promedio del oxido de fosforo a 2 decimales
print(f"{suma_oxido_fosforo/muestras:.2f}")
# conteo de categorias resultantes
print(f"sumamente apto {n_sumamente_apto}")
print(f"moderadamente apto {n_moderadamente_apto}")
print(f"marginalmente apto {n_marginalmente_apto}")
print(f"no apto {n_no_apto}")
|
Subsets and Splits