blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
3bd68486e51753134cef0461c41bc1f01fa9d68c | NicholasTancredi/python_examples | /examples/simple.py | 6,812 | 3.703125 | 4 | """
File with simple examples of most common use cases for:
- unittest
- pytypes
- pydantic
- typing
- enum
"""
from unittest import TextTestRunner, TestLoader, TestCase
from argparse import ArgumentParser
from typing import NamedTuple, Tuple, Union
from enum import Enum
from math import hypot
from pytypes import typechecked
from pydantic import validator, BaseModel, PydanticValueError
@typechecked
class Point(NamedTuple):
y: int
x: int
@typechecked
class Line(NamedTuple):
start: Point
end: Point
@typechecked
def get_line_distance(line: Line) -> float:
"""
# NOTE: a NamedTuple can still be accessed by index like a regular tuple, for example:
return hypot(
line[1][1] - line[0][1],
line[1][0] - line[0][0]
)
"""
return hypot(
line.end.x - line.start.x,
line.end.y - line.start.y
)
@typechecked
def WARNING_DONT_WRITE_LIKE_THIS_get_line_distance(line: Tuple[Tuple[int, int], Tuple[int, int]]) -> float:
"""
NOTE: using the raw type 'get_line_distance' would be written like this.
Looking at the type for line:
"Tuple[Tuple[int, int], Tuple[int, int]]"
you can see how opaque the input becomes.
"""
return hypot(
line[1][1] - line[0][1],
line[1][0] - line[0][0]
)
# NOTE: In edge cases you may want to accept all types of input
@typechecked
def get_line_distance_polytype(line: Union[Line, Tuple[Point, Point], Tuple[Tuple[int, int], Tuple[int, int]]]) -> float:
return hypot(
line[1][1] - line[0][1],
line[1][0] - line[0][0]
)
# NOTE Reference material for enums - https://docs.python.org/3/library/enum.html#creating-an-enum
# It is important to note that enums are functional constants. The importance of that is we should endure to use the functional constant whenever possible, and reserve the `value`
# for the rare moment where we actually want to use the value (primarily for storage). This will have consequences for how we store and use data inside of data classes.
# Note Nomenclature
# The class TextAlign is an enumeration (or enum)
# The attributes TextAlign.left, TextAlign.center, etc., are enumeration members (or enum members) and are functionally constants.
# The enum members have names and values (the name of TextAlign.left is left, the value of TextAlign.hidden is 0, etc.)
class TextAlign(str, Enum):
LEFT = 'LEFT'
RIGHT = 'RIGHT'
CENTER = 'CENTER'
# NOTE: Here to highlight the difference between name and value in enums
HIDDEN = 'ANYTHING'
@typechecked
def pad_text(text: str, text_align: TextAlign = TextAlign.LEFT, width: int = 20, fillchar: str = '-') -> str:
"""
This also has an example of a "python" switch statement equivalent using a dict
"""
psuedo_switch_statement = {
TextAlign.LEFT: text.ljust(width, fillchar),
TextAlign.RIGHT: text.rjust(width, fillchar),
TextAlign.CENTER: text.center(width, fillchar),
}
return psuedo_switch_statement[text_align]
class AuthorizationError(PydanticValueError):
code = 'AuthorizationError'
msg_template = 'AuthorizationError: the Bearer token provided was invalid. value={value}'
# NOTE: Doesn't need @typechecked for type checking
class Header(BaseModel):
Authorization: str
@validator('Authorization')
def validate_auth(cls, value: str) -> str:
if value != 'Bearer {}'.format('SECRET_KEY'):
raise AuthorizationError(value=value)
return value
class AssessmentType(str, Enum):
GAIT = 'GAIT'
class PoseJob(BaseModel):
assessment_type: AssessmentType
if __name__ == '__main__':
parse = ArgumentParser()
parse.add_argument(
'--unittest',
action='store_true'
)
args = parse.parse_args()
if args.unittest:
class Test(TestCase):
def test_get_line_distance(self):
distance_a = get_line_distance(
line=Line(
start=Point(
y=1,
x=2
),
end=Point(
y=3,
x=4
)
)
)
# Less verbose example of calling get_line_distance
distance_b = get_line_distance(Line(Point(1, 2), Point(3, 4)))
print('distance_b: ', distance_b)
# NOTE: WARNING! This is not an example how I'd recommend writing this!
distance_c = get_line_distance_polytype(((1, 2), (3, 4)))
distance_d = WARNING_DONT_WRITE_LIKE_THIS_get_line_distance(((1, 2), (3, 4)))
self.assertEqual(
distance_a,
distance_b
)
self.assertEqual(
distance_a,
distance_c
)
self.assertEqual(
distance_a,
distance_d
)
def test_pad_text(self):
# NOTE: Simple validating enum has str in it.
self.assertTrue('CENTER' in TextAlign.__members__)
padded_text = pad_text('yolo', text_align = TextAlign.CENTER)
print('padded_text: ', padded_text)
self.assertEqual(
padded_text,
'--------yolo--------'
)
def test_header(self):
json_input = {
'Authorization': 'Bearer {}'.format('SECRET_KEY')
}
header = Header(**json_input)
print('header.json(): ', header.json())
self.assertDictEqual(
json_input,
header.dict()
)
# NOTE: Input does not have to be json, (i.e. is equivalent)
header = Header(
Authorization='Bearer {}'.format('SECRET_KEY')
)
self.assertDictEqual(
json_input,
header.dict()
)
def test_pose_job(self):
# NOTE incoming data from some external source
incoming_data = {
'assessment_type': 'GAIT'
}
job = PoseJob(**incoming_data)
self.assertEqual(
incoming_data['assessment_type'],
job.assessment_type.value
)
print('job.assessment_type: ', job.assessment_type)
TextTestRunner().run(TestLoader().loadTestsFromTestCase(Test))
|
d8eea6878b92a31589a7b58cc6a3cdbc5a7299db | Bawya1098/python-Beginner | /day_2_assignment/list_sum.py | 263 | 4.09375 | 4 | number = input("enter elements")
my_array = list()
sum = 0
print("Enter numbers in array: ")
for i in range(int(number)):
n = input("num :")
my_array.append(int(n))
print("ARRAY: ", my_array)
for num in my_array:
sum = sum + num
print("sum is:", sum)
|
44971d0672295eea12f2d5f3ad8dad4faea2c47f | Bawya1098/python-Beginner | /Day3/Day3_Assignments/hypen_separated_sequence.py | 273 | 4.15625 | 4 | word = str(input("words to be separated by hypen:"))
separated_word = word.split('-')
sorted_separated_word = ('-'.join(sorted(separated_word)))
print("word is: ", word)
print("separated_word is:", separated_word)
print("sorted_separated_word is: ", sorted_separated_word)
|
67a947661af531ea618cb15951041076cfaab19b | Bawya1098/python-Beginner | /Week2_day1/Multi_level_inheritance.py | 873 | 3.734375 | 4 | class Micro_Computers():
def __init__(self, size):
self.size = size
def display(self):
print("size is:", self.size)
class Desktop(Micro_Computers):
def __init__(self, size, cost):
Micro_Computers.__init__(self, size)
self.cost = cost
def display_desktop(self):
print("cost is: Rs.", self.cost)
class Laptop(Desktop):
def __init__(self, size, cost, battery):
Desktop.__init__(self, size, cost)
self.battery = battery
print('laptop are')
def display_laptop(self):
print("battery is:", self.battery)
l = Laptop('small', 20000, 'battery_supported')
l.display()
l.display_desktop()
l.display_laptop()
print('---------------------------------------------')
d = Desktop('large', 30000)
d.display_desktop()
d.display()
print('---------------------------------------------')
|
af0200ae519c67895fbb02c24de47233935b9b0b | Bawya1098/python-Beginner | /Day_1_Assignments/mystery_n.py | 762 | 3.8125 | 4 | def mystery(numbers):
sum = 1
for i in range(0, numbers):
if i < 6:
for k in range(1, numbers): #num1 to 5: sum=2^(numbers**2)
sum *= 2
print(sum)
else: #number6: sum=2^(5*number)*5
if i < 10: #number7: sum=2^(5*number)*5^2
sum *= 5 #number8: sum=2^(5*number)*5^3
print(sum) #number9: sum=2^(5*number)*5^4
else: #number10: sum=2^(5*number)*(5^4)*(3^1)
sum *= 3 #number11: sum=2^(5*number)*(5^4)*(3^2)
print(sum)
return sum
myserty(3) |
abde32d028db53073878822c4ab038eda0b5a507 | ranellegomez/Object-oriented-Python-calculator | /test/CalculatorTest.py | 3,317 | 3.5 | 4 | import unittest
import ModularCalculator
import RecursiveExponentCalculator
class MyTestCase(unittest.TestCase):
def test_add(self):
for a in range(-100, 100):
for b in range(-100, 100):
for c in range(-100, 100):
print(
'add_test', a, b, c, 'result: ',
ModularCalculator.ModularCalculator.add(
self, [a, b, c]))
self.assertAlmostEqual(
a + b + c,
ModularCalculator.ModularCalculator.add(
self, [a, b, c]))
def test_subtract(self):
for a in range(-100, 100):
for b in range(-100, 100):
for c in range(-100, 100):
print(
'subtract_test', a, b, c, 'result: ',
ModularCalculator.ModularCalculator.subtract(
self, [a, b, c]))
self.assertAlmostEqual(
a - b - c,
ModularCalculator.ModularCalculator.subtract(
self, [a, b, c]))
def test_multiply(self):
for x in range(-100, 100):
for y in range(-100, 100):
for z in range(-100, 100):
print(
'multiply_test', x, y, z, 'result: ',
ModularCalculator.ModularCalculator.multiply(
self, [x, y, z]))
self.assertAlmostEqual(
x * y * z,
ModularCalculator.ModularCalculator.multiply(
self, [x, y, z]))
def test_exponentiate(self):
for b in range(-10, 100):
for p in range(-10, 100):
self.assertEqual(
b**p,
RecursiveExponentCalculator.RecursiveExponentiation.
tail_recursive_exponentiate(self, b, p))
self.assertEqual(
b**p,
RecursiveExponentCalculator.RecursiveExponentiation.
recursive_exponentiate(self, b, p))
self.assertEqual(
b**p,
ModularCalculator.ModularCalculator.
two_integer_exponentiate(self, b, p))
def test_divide(self):
for a in range(-100, 100):
for b in range(-100, 100):
for c in range(-100, 100):
if b == 0 or c == 0:
self.assertEqual(
'Whoops. Cannot divide by zero. 😭',
ModularCalculator.ModularCalculator.divide(
self, [a, b, c]))
else:
print(
'divide_test', a, b, c, 'result: ',
ModularCalculator.ModularCalculator.divide(
self, [a, b, c]))
self.assertAlmostEqual(
a / b / c,
ModularCalculator.ModularCalculator.divide(
self, [a, b, c]))
if __name__ == '__main__':
unittest.main()
|
fcd96d8a74d9a565277a2ee8b44e9056943a3f30 | tonyfg/project_euler | /python/p04.py | 473 | 3.875 | 4 | #Q: Find the largest palindrome made from the product of two 3-digit numbers.
#A: 906609
def is_palindrome(t):
a = list(str(t))
b = list(a)
a.reverse()
if b == a:
return True
return False
a = 0
last_j = 0
for i in xrange(999, 99, -1):
if i == last_j:
break
for j in xrange(999, 99, -1):
temp = i*j
if is_palindrome(temp) and temp > a:
a = temp
last_j = j
break
print(str(a))
|
35d047c6d9377e87680dcc98b62182b49bf89a3e | tonyfg/project_euler | /python/p21.py | 424 | 3.546875 | 4 | #Q: Evaluate the sum of all the amicable numbers under 10000.
#A: 31626
def divisor_sum(n):
return sum([i for i in xrange (1, n//2+1) if not n%i])
def sum_amicable(start, end):
sum = 0
for i in xrange(start, end):
tmp = divisor_sum(i)
if i == divisor_sum(tmp) and i != tmp:
sum += i+tmp
return sum/2 #each pair is found twice, so divide by 2 ;)
print sum_amicable(1,10000)
|
8ea1a9399f7b7325159494391e648245e0e76179 | Danielkaas94/Any-Colour-You-Like | /code/python/PythonApplication1.py | 2,115 | 4.1875 | 4 | def NameFunction():
name = input("What is your name? ")
print("Aloha mahalo " + name)
return name
def Sum_func():
print("Just Testing")
x = input("First: ")
y = input("Second: ")
sum = float(x) + float(y)
print("Sum: " + str(sum))
def Weight_func():
weight = int(input("Weight: "))
unit_option = input("(K)g or (L)bs:")
if unit_option.upper() == "K":
converted_value = weight / 0.45
print("Weight in Lbs:" + str(converted_value))
else:
converted_value = weight * 0.45
print("Weight in Kg:" + str(converted_value))
NameFunction(); print("")
Sum_func(); print("")
birth_year = input("Enter your birth year: ")
age = 2020 - int(birth_year)
print(age)
course = 'Python for Beginners'
print(course.upper())
print(course.find('for'))
print(course.replace('for', '4'))
print('Python' in course) #True
print(10 / 3) # 3.3333333333333335
print(10 // 3) # 3
print(10 % 3) # 1
print(10 ** 3) # 1000
print(10 * 3) # 30
x = 10
x = x + 3
x += 3
x = 10 + 3 * 2
temperature = 35
if temperature > 30:
print("Hot night, in a cold town")
print("Drink infinite water")
elif temperature > 20:
print("It's a fine day")
elif temperature > 10:
print("It's a bit cold")
else:
print("It's cold")
print("LORT! ~ Snehaderen")
Weight_func(); print("")
i = 1
while i <= 1_1:
#print(i)
print(i * '*')
i += 1
names = ["Doktor Derp", "Jens Jensen", "John Smith", "Toni Bonde", "James Bond", "Isaac Clark", "DOOMGUY"]
print(names)
print(names[0])
print(names[-1]) # Last Element - DOOMGUY
print(names[0:3]) # ['Doktor Derp', 'Jens Jensen', 'John Smith']
numbers = [1,2,3,4,5]
numbers.append(6)
numbers.insert(0,-1)
numbers.remove(3)
#numbers.clear()
print(numbers)
print(1 in numbers)
print(len(numbers))
for item in numbers:
print(item)
i = 0
while i < len(numbers):
print(numbers[i])
i += 1
#range_numbers = range(5)
#range_numbers = range(5, 10)
range_numbers = range(5, 10, 2)
print(range_numbers)
for number in range_numbers:
print(number)
for number in range(7,45,5):
print(number)
numbers2 = (1,2,3) #Tuple |
7b1c346f4ef2097de68fbd0b2a4430765ee1d13e | TeknikhogskolanGothenburg/Docker_MySQL_Alembic_SQLAlchemy | /app/UI/customers_menu.py | 2,117 | 3.578125 | 4 | from Controllers.customers_controller import get_all_customers, get_customer_by_id, get_customer_by_name, store_changes, \
store_new_first_name
def customers_menu():
while True:
print("Customers Menu")
print("==============")
print("1. View All Customers")
print("2. View Customer by Id")
print("3. Find Customers by Name")
print("5. Quit Customers Menu")
selection = input("> ")
if selection == "1":
customers = get_all_customers()
for customer in customers:
print(customer)
elif selection == "2":
id = input("Enter Customer Id: ")
customer = get_customer_by_id(id)
if customer:
print(customer)
else:
print("Could not find customer with id ", id)
elif selection == "3":
pattern = input("Enter full or partial customer name: ")
customers = get_customer_by_name(pattern)
for key, customer in customers.items():
print(f'{key}. {customer}')
edit_selection = input("Enter number for customer to edit: ")
edit_selection = int(edit_selection)
customer = customers[edit_selection]
print(f'1. Customer Name: {customer.customerName}')
print(f'2. Contact First Name: {customer.contactFirstName}')
print(f'3. Contact Last Name: {customer.contactLastName}')
print(f'4. Phone: {customer.phone}')
print(f'5. Address Line 1: {customer.addressLine1}')
print(f'6. Address Line 2: {customer.addressLine2}')
print(f'7. City: {customer.city}')
print(f'8. State: {customer.state}')
print(f'9. Postal Code: {customer.postalCode}')
print(f'10. Country: {customer.country}')
line = input("Enter number for what line to edit: ")
if line == "2":
new_value = input("Enter new First Name: ")
store_new_first_name(customer, new_value)
else:
break |
b8d583b681f9579475e30829ac3a596c41406e94 | lsiddd/ml | /NeuralNets/ELM.py | 1,882 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
verbose = False
erro = lambda y, d: 1/2 * sum([np.sum (i **2) for i in np.nditer(y - d)])
def output(x, d, w1, w2=[]):
sh = list(x.shape)
sh[1] = sh[1] + 1
Xa = np.ones(sh)
Xa[:,:-1] = x
#ativação sigmoidal
S = np.tanh(np.matmul(Xa, w1.transpose()))
sh = list(S.shape)
sh[1] = sh[1] + 1
Ha = np.ones(sh)
Ha[:,:-1] = S
#se os pesos de saída não forem fornecidos
#calculamos eles aqui
if(w2 == []):
w2 = np.matmul(np.linalg.pinv(Ha), d).transpose()
#caso contrário, se faz propagação direta
Y = np.matmul(Ha, w2.transpose())
if (verbose):
print (f'pesos da camada oculta: \n{w1}')
print (f'pesos da camada de saída: \n{w2}')
print (f'resposta da camada oculta:\n {S}')
print (f'resposta da camada de saída:\n {Y}')
print (f' O erro RMS da rede é {erro(Y, d)}\n\n')
plt.style.use("ggplot")
plt.figure()
plt.title(f"Sen(x), erro RMS = {erro(Y, d)}")
plt.plot(x, Y, "+", color="green", label="resposta da Rede")
plt.plot(x, d, "-.", color="red", label="Função Original")
plt.ylabel("Saída")
plt.xlabel("Entrada")
plt.legend()
plt.show()
return w2, Y
def main():
x = []
d = []
linspace = np.arange(0, 10, 0.01)
for i in linspace:
x.append([i])
d.append([np.sin(i)])
#O conjunto de testes
testx = np.array(x[1::20])
testd = np.array(d[1::20])
#conjunto de treinamento
x = np.array(x[::30])
d = np.array(d[::30])
#número de neurônioa na camada oculta
P = 12000
M = 1
C = 1
#inicialiazação dos pesos
w1 = (np.random.rand(P,M+1) - 0.5) / 2
#obtenção dos pesos de saída
w2, response = output(x, d, w1)
#testes para valores não presentes no conjunto de treinamento
global verbose
verbose = True
output(testx, testd, w1, w2)
if __name__ == "__main__":
main()
|
f2540cf61a8935116b8ed9153e693541e3c91706 | fear-the-lord/Structural-Balance-Identificator | /manual_network.py | 4,432 | 3.625 | 4 | # Import all the necessary dependencies
import networkx as nx
import matplotlib.pyplot as plt
import random
import itertools
def checkStability(tris_list, G):
stable = []
unstable = []
for i in range(len(tris_list)):
temp = []
temp.append(G[tris_list[i][0]][tris_list[i][1]]['sign'])
temp.append(G[tris_list[i][1]][tris_list[i][2]]['sign'])
temp.append(G[tris_list[i][0]][tris_list[i][2]]['sign'])
if(temp.count('+') % 2 == 0):
unstable.append(tris_list[i])
else:
stable.append(tris_list[i])
stableNum = len(stable)
unstableNum = len(unstable)
balance_score = stableNum / (stableNum + unstableNum)
if balance_score == 1.0:
print('The network is STRUCTURALLY BALANCED')
elif balance_score >= 0.9:
print('The network is APPROXIMATELY STRUCTURALLY BALANCED')
else:
print('The network is Not STRUCTURALLY BALANCED')
print("Stable triangles: ", stableNum)
print("Unstable triangles: ", unstableNum)
print("Number of Triangles: ", stableNum + unstableNum)
return stable, unstable
if __name__ == "__main__":
G = nx.Graph()
# Number of nodes
n = 6
# G.add_nodes_from([i for i in range(1, n+1)])
# mapping = {1:'Alexandra',2:'Anterim', 3:'Bercy',4:'Bearland',5:'Eplex', 6:'Ron'}
# Hard Coding positions for better presentation
G.add_node(1,pos=(2,3))
G.add_node(2,pos=(1,2))
G.add_node(3,pos=(2,1))
G.add_node(4,pos=(4,3))
G.add_node(5,pos=(5,2))
G.add_node(6,pos=(4,1))
mapping = {}
for i in range(1,n+1):
mapping[i] = "Node" + str(i)
G = nx.relabel_nodes(G, mapping)
# Hard coding the signs
G.add_edge( 'Node1', 'Node2', sign ='+')
G.add_edge( 'Node1', 'Node3', sign ='+')
G.add_edge( 'Node1', 'Node4', sign ='-')
G.add_edge( 'Node1', 'Node5', sign ='-')
G.add_edge( 'Node1', 'Node6', sign ='-')
G.add_edge( 'Node2', 'Node3', sign ='+')
G.add_edge( 'Node2', 'Node4', sign ='-')
G.add_edge( 'Node2', 'Node5', sign ='-')
G.add_edge( 'Node2', 'Node6', sign ='-')
G.add_edge( 'Node3', 'Node4', sign ='-')
G.add_edge( 'Node3', 'Node5', sign ='-')
G.add_edge( 'Node3', 'Node6', sign ='-')
G.add_edge( 'Node4', 'Node5', sign ='+')
G.add_edge( 'Node4', 'Node6', sign ='+')
G.add_edge( 'Node5', 'Node6', sign ='+')
# # Random signs
# G = nx.relabel_nodes(G, mapping)
# signs = ['+', '-']
# for i in G.nodes():
# for j in G.nodes():
# if i != j:
# G.add_edge(i, j, sign = random.choice(signs))
edges = G.edges()
nodes = G.nodes()
tris_list = [list(x) for x in itertools.combinations(nodes, 3)]
stable, unstable = checkStability(tris_list, G)
edge_labels = nx.get_edge_attributes(G, 'sign')
# pos = nx.circular_layout(G)
pos = nx.spring_layout(G)
# Getting positions from the nodes
pos=nx.get_node_attributes(G,'pos')
nx.draw(G, pos, node_size = 2000, with_labels = True, font_size = 10)
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, font_size = 15)
Friends = [k for k, v in edge_labels.items() if v == '+']
Enemies = [k for k, v in edge_labels.items() if v == '-']
nx.draw_networkx_edges(G, pos, edgelist = Friends, edge_color="g")
nx.draw_networkx_edges(G, pos, edgelist = Enemies, edge_color="r")
# plt.savefig("network.png", format="PNG")
plt.show()
# # Uncomment this to see individual triangle states
# plt.pause(10)
# for i in range(len(stable)):
# temp = [tuple(x) for x in itertools.combinations(stable[i], 2)]
# plt.cla()
# nx.draw(G, pos, node_size = 2000, with_labels = True, font_size = 10)
# nx.draw_networkx_edges(G, pos, edgelist = temp, edge_color="g", width = 6 )
# # plt.savefig("stable{}.png".format(i), format="PNG")
# plt.pause(2)
# plt.show()
# for i in range(len(unstable)):
# temp = [tuple(x) for x in itertools.combinations(unstable[i], 2)]
# plt.cla()
# nx.draw(G, pos, node_size = 2000, with_labels = True, font_size = 10)
# nx.draw_networkx_edges(G, pos, edgelist = temp, edge_color="r", width = 6)
# plt.pause(2)
|
18f50b38f9ef8dfc927c8850927d6739bba3dac7 | Philthy-Phil/practice-python | /ex3-ListLessThanTen.py | 541 | 3.765625 | 4 | __author__ = 'phil.ezb'
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
x = []
ui = "\n*************************"
print("Given list of numbers: ", a)
print(ui)
for num in a:
if (num < 5):
print(num, end=", ")
print(ui)
for num in a:
if (num < 5):
x.append(num)
print("here are all the numbers < 5: ", x)
print(ui)
usrnum = int(input("what's your number? "))
ulist = []
for num in a:
if(num < usrnum):
ulist.append(num)
print("here are all the numbers from a, which are smaller than your input: ", ulist)
|
b698727d6dfa278ead4845b0b150dde2e8439b6e | stawary/LeetCode | /LeetCode/Median_of_Two_Sorted_Arrays.py | 796 | 3.96875 | 4 | #There are two sorted arrays nums1 and nums2 of size m and n respectively.
#两个排好序的数组,求这两个数组的中位数。
#Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
#Example 1:
#nums1 = [1, 3]
#nums2 = [2]
#The median is 2.0
#Example 2:
#nums1 = [1, 2]
#nums2 = [3, 4]
#The median is (2 + 3)/2 = 2.5
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
for i in range(len(nums2)):
nums1.append(nums2[i]) #合并nums1和nums2
nums = sorted(nums1) #排序
length = len(nums)
if length%2==1: #长度为奇数
median = nums[length//2]
else: #长度为偶数
median = (nums[length//2-1]+nums[length//2])/2
return float(median)
|
692a0421d4258a93f1a16759976a4a98c5f1af41 | Ejas12/pythoncursobasicoEstebanArtavia | /dia7/tarea6.py | 936 | 3.5 | 4 | import csv
input_file = csv.DictReader(open("C:\\Users\\Esteban Artavia\\Documents\\scripts\\\Pythoncourse\\dia7\\serverdatabase.csv"))
outputfile = open('C:\\Users\\Esteban Artavia\\Documents\\scripts\\\Pythoncourse\\dia7\\output.txt', 'w+')
outputfile.write('NEW RUN\n')
outputfile.close
outputfile = open('C:\\Users\\Esteban Artavia\\Documents\\scripts\\\Pythoncourse\\dia7\\output.txt', 'a+')
for lineausuario in input_file:
nombre = lineausuario['first_name']
apellido = lineausuario['last_name']
numero = lineausuario['phone1']
mail = lineausuario['email'].split('@')
login = mail[0]
proveedorurl = mail[1].split('.')[0]
pass
mensaje_print = "Hola me llamo {nombre} {apellido}. Mi teléfono es {numero} .Mi usuario de correo es: {login} usando una cuenta de {proveedorurl}\n".format(nombre = nombre, apellido = apellido, numero = numero, login = login, proveedorurl = proveedorurl)
outputfile.writelines(mensaje_print)
|
26b5cff2b5c9a9eca56befae9956bc895690c60e | sundusaijaz/pythonpractise | /calculator.py | 681 | 4.125 | 4 | num1 = int(input("Enter 1st number: "))
num2 = int(input("Enter 2nd number: "))
op = input("Enter operator to perform operation: ")
if op == '+':
print("The sum of " + str(num1) + " and " + str(num2) + " = " +str(num1+num2))
elif op == '-':
print("The subtraction of " + str(num1) + " and " + str(num2) + " = " +str(num1-num2))
elif op == '*':
print("The multiplication of " + str(num1) + " and " + str(num2) + " = " +str(num1*num2))
elif op == '/':
print("The division of " + str(num1) + " and " + str(num2) + " = " +str(num1/num2))
elif op == '%':
print("The mod of " + str(num1) + " and " + str(num2) + " = " +str(num1%num2))
else:
print("Invalid Input") |
1a301b5f2b834fb833f81fcb8060853474736c87 | pjjefferies/python_practice | /huffman_encoding.py | 6,229 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 13 21:10:34 2019
@author: PaulJ
"""
# import unittest
# takes: str; returns: [ (str, int) ] (Strings in return value are single
# characters)
def frequencies(s):
return [(char, s.count(char)) for char in set(s)]
# takes: [ (str, int) ], str; returns: String (with "0" and "1")
def encode(freqs, s):
if len(freqs) <= 1:
return None
if not s:
return ''
nodes_in_tree, root_node_key = create_node_tree(freqs)
result = ''
for a_char in s:
curr_node = nodes_in_tree[root_node_key]
while True:
new_char = True
for a_child_no in ['0', '1']:
a_child_node = 'child_' + a_child_no
if curr_node[a_child_node] is not None:
if a_char in curr_node[a_child_node]:
result += a_child_no
curr_node = nodes_in_tree[curr_node[a_child_node]]
new_char = False
continue
if not new_char:
continue
break
return result
def create_node_tree(freqs):
nodes_to_add = {}
for a_char, a_freq in freqs: # adding parent, lh_child, rh_child nodes
nodes_to_add[a_char] = {
'freq': a_freq,
'parent': None,
'child_0': None,
'child_1': None
} # adding l/r_child
nodes_in_tree = {}
while nodes_to_add:
node_freq = zip(nodes_to_add.keys(), [nodes_to_add[x]['freq']
for x in nodes_to_add])
min_key1 = min(node_freq, key=lambda x: x[1])[0]
node1_to_add = nodes_to_add.pop(min_key1)
node_freq = zip(nodes_to_add.keys(), [nodes_to_add[x]['freq']
for x in nodes_to_add])
min_key2 = min(node_freq, key=lambda x: x[1])[0]
node2_to_add = nodes_to_add.pop(min_key2)
new_node = { # node1_to_add[0] + node2_to_add[0],
'freq': node1_to_add['freq'] + node2_to_add['freq'],
'parent': None,
'child_0': min_key2,
'child_1': min_key1}
node1_to_add['parent'] = min_key1 + min_key2
node2_to_add['parent'] = min_key1 + min_key2
nodes_in_tree[min_key1] = node1_to_add
nodes_in_tree[min_key2] = node2_to_add
nodes_to_add[min_key1 + min_key2] = new_node
if len(nodes_to_add) == 1:
root_node_key = min_key1 + min_key2
root_node = nodes_to_add.pop(root_node_key)
nodes_in_tree[root_node_key] = root_node
return nodes_in_tree, root_node_key
# takes [ [str, int] ], str (with "0" and "1"); returns: str
# e.g. freqs = [['b', 1], ['c', 2], ['a', 4]]
# bits = '0000111010'
def decode(freqs, bits):
if len(freqs) <= 1:
return None
if len(bits) == 0:
return ''
nodes_in_tree, root_node_key = create_node_tree(freqs)
bits_list = bits[:]
result = ''
curr_node_key = root_node_key
while bits_list:
curr_node = nodes_in_tree[curr_node_key]
curr_bit = bits_list[0]
bits_list = bits_list[1:]
child_str = 'child_' + curr_bit
if nodes_in_tree[curr_node[child_str]][child_str] is None:
result += curr_node[child_str] # take letter
curr_node_key = root_node_key
else:
curr_node_key = curr_node[child_str] # no letter found yet, g-down
return result
s = 'aaaabcc'
fs = frequencies(s)
encoded = encode(fs, s)
decoded = decode(fs, encoded)
print('s:', s, ', fs:', fs, ', encoded:', encoded, ', decoded:', decoded)
fs1 = [('a', 1), ('b', 1)]
test1 = ["a", "b"]
for a_test in test1:
encoded = encode(fs1, a_test)
decoded = decode(fs1, encoded)
print('a_test:', a_test, ', fs1:', fs1, ', encoded:', encoded,
', decoded:', decoded)
"""
class InterpreterTestMethods(unittest.TestCase):
len_tests = [["aaaabcc", 10]] #,
"""
"""
['2 - 1', 1],
['2 * 3', 6],
['8 / 4', 2],
['7 % 4', 3],
['x = 1', 1],
['x', 1],
['x + 3', 4],
['y', ValueError],
['4 + 2 * 3', 10],
['4 / 2 * 3', 6],
['7 % 2 * 8', 8],
['(7 + 3) / (2 * 2 + 1)', 2]]
def test_basic(self):
interpreter = Interpreter()
for expression, answer in self.tests:
print('\n')
try:
result = interpreter.input(expression)
except ValueError:
result = ValueError
print('expression:', expression, ', answer:', answer,
', result:', result)
self.assertEqual(result, answer)
"""
"""
if __name__ == '__main__':
unittest.main()
test.describe("basic tests")
fs = frequencies("aaaabcc")
test.it("aaaabcc encoded should have length 10")
def test_len(res):
test.assert_not_equals(res, None)
test.assert_equals(len(res), 10)
test_len(encode(fs, "aaaabcc"))
test.it("empty list encode")
test.assert_equals(encode(fs, []), '')
test.it("empty list decode")
test.assert_equals(decode(fs, []), '')
def test_enc_len(fs, strs, lens):
def enc_len(s):
return len(encode(fs, s))
test.assert_equals(list(map(enc_len, strs)), lens)
test.describe("length")
test.it("equal lengths with same frequencies if alphabet size is a power of two")
test_enc_len([('a', 1), ('b', 1)], ["a", "b"], [1, 1])
test.it("smaller length for higher frequency, if size of alphabet is not power of two")
test_enc_len([('a', 1), ('b', 1), ('c', 2)], ["a", "b", "c"], [2, 2, 1])
test.describe("error handling")
s = "aaaabcc"
fs = frequencies(s)
test.assert_equals( sorted(fs), [ ("a",4), ("b",1), ("c",2) ] )
test_enc_len(fs, [s], [10])
test.assert_equals( encode( fs, "" ), "" )
test.assert_equals( decode( fs, "" ), "" )
test.assert_equals( encode( [], "" ), None );
test.assert_equals( decode( [], "" ), None );
test.assert_equals( encode( [('a', 1)], "" ), None );
test.assert_equals( decode( [('a', 1)], "" ), None );
""" |
10c1c00ec710a8a6e32c4e0f6f73df375f5a72d5 | pjjefferies/python_practice | /find_anagrams.py | 824 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 21:59:44 2019
@author: PaulJ
"""
def anagrams(word, words):
anagrams_found = []
for a_word in words:
a_word_remain = a_word
poss_anagram = True
for a_letter in word:
print('1: a_word_remain:', a_word_remain)
first_let_pos = a_word_remain.find(a_letter)
if first_let_pos == -1:
poss_anagram = False
continue
a_word_remain = (a_word_remain[:first_let_pos] +
a_word_remain[first_let_pos + 1:])
print('2: a_word_remain:', a_word_remain)
if not a_word_remain and poss_anagram:
anagrams_found.append(a_word)
return anagrams_found
print('result: ', anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada'])) |
e7eb877dfa1edc9e2f3e0c59c71338453ff9b964 | pjjefferies/python_practice | /censor_test.py | 545 | 3.75 | 4 | def censor(text, word):
word_replace = "*" * len(word)
for i in range(len(text)):
print (i, text[i], word[0])
if text[i] == word[0]:
for j in range(len(word)):
print (i, j, text[i+j], word[j])
if text[i+j] != word[j]:
break
else:
print (text, word, word_replace)
text = text.replace(word, word_replace)
return text
print (censor("Now is the time for all good men to come to the aid of their country", "to"))
|
07a627b0e4ab6bb12ec51db84fb72f56032649c4 | Skyorca/deeplearning_practice_code | /FC_tf.py | 3,607 | 4.03125 | 4 | import tensorflow as tf
import numpy as np
from numpy.random import RandomState
#Here is a built-in 3-layer FC with tf as practice
"""
how tf works?
1. create constant tensor(e.g.: use for hparam)
tensor looks like this: [[]](1D) [[],[]](2D)...
tf.constant(self-defined fixed tensor, and type(eg. tf.int16, should be defined following tensor))
tf.zeros/ones([shape])
tf.random... just like numpy
2. create variable tensor(e.g.: use for weight&bias)
tf.Variable(init_tensor, type), value could change but shape can not, initial could be any value
3. create placeholder(e.g.: use for feeding batch data, repeatedly use)
tf.placeholder(type, shape=())
before training(session begins), everything you do within functions are done by placeholders&constants, no variables
4. define operations(from basic operations to complicated functions)
tf.func_name(params) [some are like numpy]
sess.run(defined_operation, feed_dict)
5. everything starts with a graph
tf.Graph(), used in session. if there is only one graph, without defining a graph is allowed
if you like, use graph like this:
with graph.as_default():
define nodes&vects for Net
6. training starts with a session
after having defined NetStructure&operations, start a session to start training.
with tf.Session() as session: #if multiple graphs, tf.Session(graph=graph_x)
training...
sess.run(operation, feed_dict)
7. practical notes:
a. use None in shape=(), could alternatively change
b. use tf functions to build loss_function, and define train_step with optimizer(optimizing this loss)
c. how to use Class to make a Net???
d.
tf.reduce_mean: calculate average along whole tensor/appointed axis
a=[[1,1], [2,2]]
tf.reduce_mean(a) = 1.5 ,type=float32
tf.reduce_mean(a, 0) = [1.5, 1.5], do along each column (1+2)/2
tf.reduce_mean(a, 1) = [1, 2], do along each row 1+1/2, 2+2/2
"""
graph = tf.Graph()
#define Net Structure
with graph.as_default():
x = tf.placeholder(tf.float32, shape=(2, None)) #x=(a,b)
y = tf.placeholder(tf.float32, shape=(1, None))
W1 = tf.Variable(tf.random_normal([3,2], stddev=1, seed=1)) # auto. float32
W2 = tf.Variable(tf.random_normal([1,3], stddev=1, seed=1))
b1 = tf.Variable(tf.random_normal([1,1]))
b2 = tf.Variable(tf.random_normal([1,1]))
#1st layer is input a_0=x
#2nd layer
a_1 = tf.nn.relu(tf.matmul(W1, x)+b1) # a_1 is (3, none)
# output layer
y_pred = tf.nn.sigmoid(tf.matmul(W2, a_1)+b1) # a_2 is(1, none)
#define loss
cross_entropy_loss = -tf.reduce_mean(y*tf.log(tf.clip_by_value(y_pred, 1e-10,1.0)))
train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy_loss)
#define a simulated sample
rdm=RandomState(1)
data_size=512
X = []
for i in range(data_size):
X.append(rdm.rand(2,1))
X = np.array(X)
Y = []
for i in range(data_size):
Y.append([int((X[i][0]+X[i][1])<1)])
Y = np.array(Y)
#begin training
epoch = 100
batch_size = 10
with tf.Session(graph=graph) as sess:
sess.run(tf.initialize_all_variables())
for time in range(epoch):
for i in range(data_size/batch_size+1):
start = i*batch_size % data_size
end = min(start+batch_size, batch_size) # build batch
Y_u = Y.T
sess.run(train_step, feed_dict={x:X[start:end], y:Y_u[start:end]})
"""
here is a trick: in 1st batch, start=0, end=10, there are 11 samples;
However, in slice[start:end], get idx 0~9 actually
"""
loss = sess.run(cross_entropy_loss, feed_dict={x:X, y:Y})
print("at %d epoch, loss->%f" % (time, float(loss)))
|
26d288b468e8cf62b3d27a5ab20513e6889373bf | Wigrovski/Python3 | /SandwichApp/sandwich.py | 399 | 3.625 | 4 | import sys
if sys.version_info < (3, 0):
# Python 2
import Tkinter as tk
else:
# Python 3
import tkinter as tk
def eat(event):
print("Вкуснятина")
def make(event):
print ("Бутер с колбасой готов")
root = tk.Tk()
root.title("Sandwich")
tk.Button(root, text="Make me a Sandwich").pack()
tk.Button(root, text="Eat my Sandwich").pack()
tk.mainloop() |
9c013a6131b469a6d40a294243ec6b6f1c0da02d | JenniferHhj/UcBerkeley-IndustryEng135 | /Neural_Network/NN.py | 4,743 | 3.671875 | 4 |
import tensorflow as tf
import tensorflow_datasets as tfds
tfds.disable_progress_bar()
import math
import numpy as np
import matplotlib.pyplot as plt
import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.regularizers import l2
import os
from tensorflow.keras.layers import Conv2D
#print(tf.version.VERSION)
dataset, metadata = tfds.load('fashion_mnist', as_supervised=True, with_info=True)
train_dataset, test_dataset = dataset['train'], dataset['test']
num_train_examples = metadata.splits['train'].num_examples
num_test_examples = metadata.splits['test'].num_examples
print("Number of training examples: {}".format(num_train_examples))
print("Number of test examples: {}".format(num_test_examples))
def normalize(images, labels):
images = tf.cast(images, tf.float32)
images /= 255
return images, labels
# The map function applies the normalize function to each element in the train
# and test datasets
train_dataset = train_dataset.map(normalize)
test_dataset = test_dataset.map(normalize)
# The first time you use the dataset, the images will be loaded from disk
# Caching will keep them in memory, making training faster
train_dataset = train_dataset.cache()
test_dataset = test_dataset.cache()
'''
Build the model
Building the neural network requires configuring the layers of the model, then compiling the model.
Setup the layers
The basic building block of a neural network is the layer. A layer extracts a representation from the data fed into it. Hopefully, a series of connected layers results in a representation that is meaningful for the problem at hand.
Much of deep learning consists of chaining together simple layers. Most layers, like tf.keras.layers.Dense, have internal parameters which are adjusted ("learned") during training.
'''
# Initialize model constructor
model = Sequential()
'''
TO DO
# Add layers sequentially
Keras tutorial is helpful: https://www.tensorflow.org/guide/keras/sequential_model
The score you get depends on your testing data accuracy.
0.00 <= test_accuracy < 0.85: 0/18
0.85 <= test_accuracy < 0.86: 3/18
0.86 <= test_accuracy < 0.87: 6/18
0.87 <= test_accuracy < 0.88: 9/18
0.88 <= test_accuracy < 0.89: 12/18
0.89 <= test_accuracy < 0.90: 15/18
0.90 <= test_accuracy < 1.00: 18/18
'''
################# TO DO ###################
##reference: https://www.kaggle.com/saraei1pyr/classifying-images-of-clothing
##reference: https://www.programcreek.com/python/example/89658/keras.layers.Conv2D
##Using reference help from kaggle for the layer adding and analyzation of the moddel
model.add(Conv2D(28, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dense(units=20, activation='softmax'))
###########################################
'''
Compile the model
Before the model is ready for training, it needs a few more settings. These are added during the model's compile step:
Loss function — An algorithm for measuring how far the model's outputs are from the desired output. The goal of training is this measures loss.
Optimizer —An algorithm for adjusting the inner parameters of the model in order to minimize loss.
Metrics —Used to monitor the training and testing steps. The following example uses accuracy, the fraction of the images that are correctly classified.
'''
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(),
metrics=['accuracy'])
'''
### Training is performed by calling the `model.fit` method:
1. Feed the training data to the model using `train_dataset`.
2. The model learns to associate images and labels.
3. The `epochs=5` parameter limits training to 5 full iterations of the training dataset, so a total of 5 * 60000 = 300000 examples.
(Don't worry about `steps_per_epoch`, the requirement to have this flag will soon be removed.)
'''
BATCH_SIZE = 32
train_dataset = train_dataset.cache().repeat().shuffle(num_train_examples).batch(BATCH_SIZE)
test_dataset = test_dataset.cache().batch(BATCH_SIZE)
'''
TO DO
# Decide how mnay epochs you want
'''
model.fit(train_dataset, epochs=20, steps_per_epoch=math.ceil(num_train_examples/BATCH_SIZE))
'''
As the model trains, the loss and accuracy metrics are displayed. This model reaches an accuracy of about 0.88 (or 88%) on the training data.
'''
model.save('my_model')
test_loss, test_accuracy = model.evaluate(test_dataset, steps=math.ceil(num_test_examples/32))
print('Accuracy on test dataset:', test_accuracy)
|
ac62e611bd36e4117f7705720bf39692148835f5 | elvirich04/myOOP | /OOP/OOP2.PY | 724 | 3.796875 | 4 | class Person:
def __init__(self, Name, Sex, Age):
self.Name=Name
self.Sex=Sex
self.Age=Age
def Show(self):
if self.Sex=="Male":
pronoun="Mr."
else:
pronoun="Ms."
print("%s %s is %i years old."%(pronoun, self.Name, self.Age))
Person1=Person("John", "Male", 19)
Person2=Person("Sony", "Male", 27)
Person3=Person("Elvira","Female",22)
Person4=Person("Ondoy","Female",20)
Person5=Person("Jhane","Female",17)
Person6=Person("Joy","Female",19)
Person7=Person("Ferdinand","Male",17)
Person8=Person("Gabriel","Male",19)
Person1.Show()
Person2.Show()
Person3.Show()
Person4.Show()
Person5.Show()
Person6.Show()
Person7.Show()
Person8.Show()
|
ac79e5ed6bfa7b1d928aa2d6eb07f9fcab72d39f | elvirich04/myOOP | /OOP/OOP.PY | 473 | 3.8125 | 4 | class Person:
def __init__(self):
self.Name=""
self.Sex=""
self.Age=0
def Show(self):
if self.Sex=="Male":
pronoun="Mr."
else:
pronoun="Ms."
print("%s %s is %i years old."%(pronoun, self.Name, self.Age))
Person1=Person()
Person1.Name="John"
Person1.Sex="Male"
Person1.Age=19
Person2=Person()
Person2.Name="Elvira"
Person2.Sex="Female"
Person2.Age=22
Person1.Show()
Person2.Show()
|
4f2f5eb803fee7c8ba6e73a1a142864f6ae91660 | dmnjzl/jupyter | /class-and-object/maxHeap.py | 2,471 | 3.921875 | 4 | #MaxHeap class from Lab 3
class MaxHeap(object):
def __init__(self,data=[]):
# constructor - empty array
self.data = data
def isEmpty(self):
# return true if maxheaph has zero elements
return(len(self.data)==0)
def getSize(self):
# return number of elements in maxheap
return(len(self.data))
def clear(self):
# remove all elements of maxheap
self.data=[]
def printout(self):
# print elements of maxheap
print (self.data)
def getMax(self):
# return max element of maxHeap
# check that maxHeaph is non-empty
if (not self.isEmpty()):
return(max(self.data))
else:
return None
#helper method for add(newEntry) and removeMax()
#swap elements so parent node is greater than both its children
#if swap made, call heapify on swapped child
def heapify(self, parentIndex):
#given parentIndex, find left and right child indices
child1Index = parentIndex*2+1
child2Index = parentIndex*2+2
largest=parentIndex
# check if left child is larger than parent
if (child1Index < len(self.data)) and (self.data[child1Index] > self.data[parentIndex]):
largest = child1Index
# check if right child is larger than the max of left child
# and parent
if (child2Index < len(self.data)) and (self.data[child2Index] > self.data[largest]):
largest = child2Index
# if either child is greater than parent:
# swap child with parent
if (largest != parentIndex):
self.data[largest], self.data[parentIndex] = self.data[parentIndex], self.data[largest]
self.heapify(largest)
# call heapify() on subtree
def buildHeap(self, A):
# build maxheap, calling heapify() on each non-leaf node
self.data = A
for i in range((len(A)-1)//2, -1, -1):
self.heapify(i)
def removeMax(self):
# remove root node, call heapify() to recreate maxheap
if (not self.isEmpty()):
maxVal = self.data[0]
if (len(self.data)>1):
self.data[0] = self.data[len(self.data)-1]
# remove last element
self.data.pop()
self.heapify(0)
else:
self.data.pop()
return maxVal
else:
return None
|
8d048eb12a10e55edafe9d0e56ac4c4313eb0137 | srawlani22/LSystems-Genetic-Algorithms-with-Python3 | /Intro-to-L-Systems/recursionexamples/tutorial.py | 1,104 | 3.984375 | 4 | import turtle
import time
import math
#from turtleLS import randint
draw = turtle.Turtle()
# # drawing a square
# draw.forward(100)
# draw.right(90)
# draw.forward(100)
# draw.right(90)
# draw.forward(100)
# draw.right(90)
# draw.forward(100)
# # time.sleep(3)
# # draw.reset()
# draw.penup()
# draw.forward(100)
# draw.pendown()
# Another design- draws a fancy star graph using recursion in Python.
pickachu = turtle.Turtle()
screen = turtle.Screen()
pickachu.pencolor("white")
pickachu.getscreen().bgcolor("black")
# r = randint(0,255)
# g = randint(0,255)
# b = randint(0,255)
# screen.colormode(255)
# draw.pencolor(r,g,b)
# for i in range(5):
# pickachu.forward(200)
# pickachu.left(216)
pickachu.speed(0)
pickachu.penup()
pickachu.goto((-200,100))
pickachu.pendown()
def starGraph(turtle, size):
if size <= 10:
return
else:
turtle.begin_fill()
for i in range(5):
pickachu.forward(size)
starGraph(turtle, size/3)
pickachu.left(216)
turtle.end_fill()
starGraph(pickachu,360)
turtle.done() |
20821b277bb38285010d11b0bace9a4da4d539b5 | shreo-adh/Python | /PDF_rotator.py | 485 | 3.890625 | 4 | import PyPDF2
file_path = input("Input file path: ")
rotate = 0
with open(file_path, mode='rb') as my_file:
reader = PyPDF2.PdfFileReader(my_file)
page = reader.getPage(0)
rotate = int(input("Enter the degree of rotation(Clockwise): "))
page.rotateClockwise(rotate)
writer = PyPDF2.PdfFileWriter()
writer.addPage(page)
new_file_path = input("Enter path of new file: ")
with open(new_file_path, mode='wb') as new_file:
writer.write(new_file)
|
c03f949e619ad6bdec690bd942043a3bfca7d816 | acstibi02/4.ora | /hf4_4.py | 403 | 3.625 | 4 | bekert_szöveg = input("Írjon be egy szöveget: ")
i = 0
j = 1
lista=[]
a = 'False'
while i < (len(bekert_szöveg)//2):
if bekert_szöveg[i] == bekert_szöveg[len(bekert_szöveg)-j]:
lista.append('True')
i+=1
j+=1
else:
lista.append('False')
i+=1
j+=1
if a in lista:
print("Ez nem palindrom. ")
if a not in lista:
print("Ez palindrom. ") |
c0a4b3de94544033bfa95b7a208f58f2b5c0eedc | NBALAJI95/Python-programming | /inClass/Class - 2/inClass-charac-freq.py | 471 | 3.984375 | 4 | def findCharFreq(s, c):
if c not in s:
return 'Letter not in string'
else:
count = s.count(c)
return count
def main():
inp_str = input('Enter the string:')
distinct_letters = []
for i in inp_str:
if i not in distinct_letters:
distinct_letters.append(i)
for e in distinct_letters:
print('Character Frequency of %s is %s' % (e, findCharFreq(inp_str, e)))
if __name__ == '__main__':
main()
|
8a869f9cc02943a51c4d0ce03dafe50c15740dc3 | NBALAJI95/Python-programming | /inClass/Class - 4/inClass.py | 729 | 3.703125 | 4 | import requests
from bs4 import BeautifulSoup
import os
def main():
url = "https://en.wikipedia.org/wiki/Android_(operating_system)"
source_code = requests.get(url)
plain_text = source_code.text
# Parsing the html file
soup = BeautifulSoup(plain_text, "html.parser")
# Finding all div tags
result_list = soup.findAll('div')
# In the list of div tags, we are extracing h1
for div in result_list:
h1 = div.find('h1')
if h1 != None:
# Printing only text associated with h1
print(h1.text)
# Doing the same procedure for body
result_list1 = soup.findAll('body')
for b in result_list1:
print(b.text)
if __name__=='__main__':
main() |
10becb5b4a704625c66e56c5a66b975ab3c1628e | NBALAJI95/Python-programming | /inClass/Class - 3/inClass-1.py | 905 | 3.859375 | 4 |
def print_horiz_line():
return '---'
def print_vert_line():
return '|'
def main():
inp = input('Enter dimensions of the board separated by "x":')
inp = inp.split('x')
inp = list(map(lambda a: int(a), inp))
print(inp)
op =''
t = 0
case = ''
it = 0
if (inp[0] + inp[1]) % 2 == 0:
it = inp[0] + inp[1] + 1
else:
it = inp[0] + inp[1]
for i in range(it):
if i % 2 == 0:
t = inp[1]
case = 'even'
else:
t = inp[1] + 1
case = 'odd'
for j in range(t):
if j == 0 and case == 'even':
op += ' '
if case == 'even':
op += print_horiz_line() + ' '
elif case == 'odd':
op += print_vert_line()
op += ' '
op += '\n'
print(op)
if __name__ == '__main__':
main() |
fb213cb12399aa1b08a15d4040ef3ce15457e9e9 | NBALAJI95/Python-programming | /Assignments/Week - 3/Task-3.py | 1,624 | 3.953125 | 4 | # Getting input co-ordinates from the user
def getCoordinates(turn, tt):
player = ''
while True:
if turn % 2 == 0:
inp = input("Player 1, enter your move in r,c format:")
player = 'X'
else:
inp = input("Player 2, enter your move in r,c format:")
player = 'O'
inp = inp.split(',')
inp = list(map(lambda a: int(a), inp))
r = inp[0]-1
c = inp[1]-1
if tt[r][c] != -1:
print('INVALID MOVE, TRY AGAIN!')
else:
break
inp.append(player)
return inp
# Setting values
def setCoordinates(t, m):
m[0] -= 1
m[1] -= 1
t[m[0]][m[1]] = m[2]
return t
def print_horiz_line():
return '--- ' * 3
def print_vert_line():
return '|'
#function for printing the board
def gameBoard(tt):
ret = ''
for i in range(3):
for j in range(3):
if j == 0:
ret += print_horiz_line()
ret += '\n'
ret += print_vert_line()
if tt[i][j] != -1:
ret += tt[i][j]
else:
ret += ' '
ret += print_vert_line()
ret += ' '
ret += '\n'
ret += print_horiz_line()
return ret
print_horiz_line()
def main():
tic_tac = list()
for i in range(3):
t = []
for j in range(3):
t.append(-1)
tic_tac.append(t)
for i in range(9):
g = getCoordinates(i, tic_tac)
tic_tac = setCoordinates(tic_tac, g)
print(gameBoard(tic_tac))
if __name__ == "__main__":
main() |
9154ab03fa537db195606670fe318a1240ca20ba | djd1283/UndiagnosedDiseaseClassifier | /get_random_submissions.py | 2,058 | 3.5 | 4 | """Get random submissions from Reddit as negative examples for classifier."""
import os
import csv
import praw
from filter_reddit_data import load_credentials
from tqdm import tqdm
data_dir = 'data/'
negative_submissions_file = 'negative_submissions.tsv'
accepted_submissions_file = 'accepted_submissions.tsv'
def generate_negative_posts(reddit, n_posts):
# TODO find regular posts from popular subreddits as negative examples for training a classifier
negative_posts = []
bar = tqdm(total=n_posts)
while True:
random_submissions = reddit.subreddit('all').random_rising(limit=n_posts)
random_submissions = [submission for submission in random_submissions]
for submission in random_submissions:
title = submission.title
text = ' '.join(submission.selftext.split())
subreddit = submission.subreddit
if len(text) > 0:
negative_posts.append([title, text, subreddit])
bar.update()
if len(negative_posts) >= n_posts:
return negative_posts
def main():
n_posts = 2000
creds = load_credentials()
reddit = praw.Reddit(client_id=creds['client'],
client_secret=creds['secret'],
user_agent=creds['agent'])
# we generate the same number of negative examples as positive examples if n_posts is not specified
if n_posts is None:
n_posts = sum([1 for line in open(os.path.join(data_dir, accepted_submissions_file), 'r')])
print(f'Number of negative submissions: {n_posts}')
negative_submissions = generate_negative_posts(reddit, n_posts)
# random posts from common subreddit we use as negative examples and save to negative file
with open(os.path.join(data_dir, negative_submissions_file), 'w', newline='\n') as f_negative:
writer = csv.writer(f_negative, delimiter='\t')
for submission in negative_submissions:
writer.writerow(submission)
if __name__ == '__main__':
main()
|
775bc457736c4a7dd6c98a389e63432c814cd1a4 | custu2000/curs_python | /lab1/lab1.py | 843 | 3.8125 | 4 | #ex 1
for i in range(100):
print ("hello world")
# ex 2
s="hello world"*100
print (s)
#ex 3
#fizz %3, buzz %5, fizz buzz cu 3 si 5
#rest numarul
for i in range(100):
if i % 3 ==0 and i % 5 ==0:
print "fizz buzz for: ",i
if i % 3 ==0 :
print "fizz for: ",i
if i % 5 ==0 :
print "buzz for: ",i
#ex 4
n=input('introduceti numarul: ')
n1=(n%100)//10
print "cifra zecilor este :",n1
#ex 5
print "ex 5"
n=input('introduceti numarul de minute: ')
n1=n//60
n2=n-n1*60
print ("Minute : %d Secunde:%d "%(n1,n2))
print ("Minute : {} Secunde: {}".format(n1,n2))
#ex 6
#bisect %4 dar nu si cu 100
#bisect daca este diviz cu 400
an=input('introduceti anul: ')
if an % 400 ==0 or (an % 4==0 or an %100==0):
print("anul {} este bisect".format(an))
else:
print("anul nu este bisect");
#ex7
|
3da597b2bcdcdaf16bfa50bc86a060fa56173667 | ND13/zelle_python | /chapter_2/futval.py | 792 | 4.15625 | 4 | #!/usr/bin/python3.6
# File: futval.py
# A program that computes an investment carried 10 years into future
# 2.8 Exercises: 5, 9
def main():
print("This program calculates the future value of a 10-year investment.")
principal = float(input("Enter the principal amount: "))
apr = float(input("Enter the annualized interest rate: "))
length = int(input("Enter the length in years of investment: "))
inflation = float(input("Enter yearly rate of inflation: "))
apr = apr * .01
inflation = inflation * .01
for i in range(length):
principal = principal * (1 + apr)
principal = principal / (1 + inflation)
year = i + 1
print(f"Year {year}: {principal:.2f}")
print(f"The amount in {length} years is: {principal:.2f}")
main()
|
7482b65b788259f74c8719944618f9d856417780 | ND13/zelle_python | /chapter_3/pizza.py | 450 | 4.3125 | 4 | # sphere_2.py
# calculates the price per square inch of circular pizza using price and diameter
def main():
price = float(input("Enter the price for your pizza: $"))
diameter = float(input("Enter the diameter of the pizza: "))
radius = diameter / 2
area = 3.14159 * radius ** 2
price_per_sq_inch = price / area
print(f"The price per square inch of pizza is ${price_per_sq_inch:.2f}")
if __name__ == '__main__':
main()
|
bd85de544ae4984bddacf4f091f186fec0b8e3f4 | AmarJ/ieeeCodingChallenge | /2018-Fall/solutions/Q1.py | 484 | 3.671875 | 4 | def rot_1(A, d):
output_list = []
# Will add values from n to the new list
for item in range(len(A) - d, len(A)):
output_list.append(A[item])
# Will add the values before
# n to the end of new list
for item in range(0, len(A) - d):
output_list.append(A[item])
return output_list
def rot_2(A, d):
return (A[-d:] + A[:-d])
A = [1, 2, 3, 4, 5, 6, 7]
d = 2
print rot_1(A, d)
print rot_2(A, d) |
4e58aa912b1e41bf3fb42cfc8917909137174ea6 | jsy2906/Portfolio | /프로그래머스/실력 테스트/Q2.py | 198 | 3.53125 | 4 | # Q2) 입력된 숫자만큼 문자 밀기
def solution(s, n):
string = ''
for i in s:
result = ord(i) + n
string += chr(result)
return string
solution('eFg', 10)
|
f1a0cde50de74b36ff22705364f41fb62a26f56a | jsy2906/Portfolio | /파이썬/동명이인 찾기.py | 193 | 3.53125 | 4 | def find_same_name(a):
n = len(a)
result = set()
for i in range(n-1):
for j in range(i+1,n):
if a[i] == a[j]:
result.add(a[i])
return result
|
1e284588df9d0a43fde6af4e7358c1d1691c82c7 | nikdavis/poker_hand | /poker_hand/parsers/card_parser.py | 559 | 3.6875 | 4 | class CardParser(object):
RANK = {
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
"T": 10,
"J": 11,
"Q": 12,
"K": 13,
"A": 14
}
SUIT = {
"H": "heart",
"D": "diamond",
"C": "club",
"S": "spade"
}
def __init__(self, card_str):
"""Takes one hands string, returns dict"""
self.cards = card_str.split(" ")
def ranks(self):
return [self.RANK[card[0]] for card in self.cards]
def suits(self):
return [self.SUIT[card[-1]] for card in self.cards]
|
6cf792b36892e4c8372d95eb9857034bf939e378 | leogao/examples | /hackerrank/isFib.py | 763 | 3.734375 | 4 | #!/usr/bin/env python
# https://www.hackerrank.com/challenges/is-fibo
import sys
T = int(raw_input())
assert 1<=T<=10**5
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
X = 10
fibs = []
for i in xrange(X):
fibs.append(fib(i))
for i in xrange(T):
a = int(raw_input())
assert 1<=a<=10**10
if a in fibs:
print 'isFibo'
elif a > fibs[-1]:
for i in xrange(1000):
fibsv = fibs[X-2+i] + fibs[X-1+i]
fibs.append(fibsv)
if fibsv == a:
print 'isFibo'
break
elif fibsv > a:
print 'isNotFibo'
break
elif a < fibs[-1]:
print 'isNotFibo'
|
415ceea1e04a46bbab094f7abe18de80e487e0b5 | heartthrob227/kenstoolbox | /convfilecheckerV0.1.py | 2,049 | 3.5625 | 4 | import csv, re, pandas
from collections import defualtdict
print('=================================')
print('Welcome to the Conversion File Checker')
#Ask for file to parse
rawfile = input('What file do you want to test (without extension; must be csv)? ')
firstfile = rawfile + '.csv'
#Open file
fout=open(outputname,"w+", newline='')
def dateformat():
datecolumn = input('What is the name of the date column? ')
#Draw value for one key from one row
dateformat = #drawn value from key
def idcheckandcount():
# Determine profile/affcode or KClickID
idtype = input('Is this a Click ID (C) or Profile|Affcode (P) based file (case sensitive)? ')
if idtype == 'C':
#insert regex Check
#valid rows
validrows = #count of rows that meet criteria
#not valid rows (return an error file with row that had error)
invalidrows = #count of rows that do not meet criteria
elif idtype == 'P':
#insert regex Check
#valid rows
#not valid rows (return an error file with row that had error)
else:
print ('Not a valid Type')
def singleormulti():
# Determine if single column for conv type or multiple columns
singleormulti = input('Is this file based on single (S) or multiple (M) columns for conversions (case sensitive)? ')
if singleormulti == 'S'
# If single run this
## of conversions by Type
# $ by Type
elif singleormulti == 'M'
#if multiple run this
## of conversions by Type
# $ by Type
else:
print ('That is not a valid response')
dateformat()
idcheckandcount()
singleormulti()
def createreport():
print ('======================================')
print ('Date format is ' + dateformat)
print ('The number of valid rows is ' + validrows)
print ('The number of valid rows is ' + invalidrows)
print ('') #figure out a way to get the consolidated list of conv types and their aggregation
print ('') #same as above but with Rev
|
d95ad94be6d99173fbab10e23b772a94d8ed0cd8 | mclearning2/Algorithm_Practice | /math/204_Count_Primes.py | 508 | 3.953125 | 4 | '''
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
'''
class Solution:
def countPrimes(self, n: int) -> int:
answer = 0
memory = list(range(n))
memory[:2] = None, None
for i in range(2, n):
if memory[i]:
answer += 1
for j in range(i, n, i):
memory[j] = None
return answer |
61b71063cf7828bbb2806a7992b43da37d41a9a2 | Cathelion/Numerical-Approximation-Course | /Assignment4_Remez_algo.py | 3,736 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 3 20:16:53 2021
@author: florian
A short demonstration of the Remez algorithm to obtain the best
approximation of a function in the supremum norm on a compact interval.
The test function used is f(x) = x*sin(x) and we use 7 points
We also plot the sign-changing error a characteristic of the approximation in the supremum norm,
and its convergence. Furthermore we keep track of the set of extremal points.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
plt.style.use('seaborn')
plt.figure(1,figsize=(10,7))
plt.figure(2,figsize=(10,7))
plt.figure(1)
def coeff(xDat,func):
n = len(xDat)-2
powerM = np.tile( np.arange(n+1) ,(n+2,1))
dataM = np.tile(np.reshape(xDat, (-1, 1)) , n+1)
Mat= np.power(dataM,powerM)
eta_vec = np.array([-(-1)**i for i in range(n+2)])
Mat = np.hstack((Mat,np.reshape(eta_vec, (-1, 1))))
b = func(xDat)
a = np.linalg.solve(Mat, b)
return a
def evalPoly(coeff,x):
n = len(coeff)
powerV = np.array([x**i for i in range(n)])
return np.dot(powerV,coeff)
def findxhat(coeff,func,a,b):
xD = np.linspace(a,b,1000)
yD = np.array([evalPoly(coeff, x) for x in xD])
error = np.abs(yD-func(xD))
return xD[error.argmax()]
def exchange(xDat, xNew, coeff, func):
sgn_hat = np.sign(evalPoly(coeff, xNew)-func(xNew))
if xNew<xDat[0]:
sgn_x0 = np.sign(evalPoly(coeff, xDat[0])-func(xDat[0]))
if sgn_x0==sgn_hat:
xDat[0] = xNew
else:
xDat[-1] = xNew
return
elif xNew>xDat[-1]:
sgn_x0 = np.sign(evalPoly(coeff, xDat[-1])-func(xDat[-1]))
if sgn_x0==sgn_hat:
xDat[-1] = xNew
else:
xDat[0] = xNew
return
for k in range(len(xDat)-1):
if xDat[k]<=xNew<=xDat[k+1]:
sgn_xk = np.sign(evalPoly(coeff, xDat[k])-func(xDat[k]))
if sgn_xk==sgn_hat:
xDat[k] = xNew
else:
xDat[k+1] = xNew
return
xDat.sort() # sort data in case new value in start/end
def remez(xDat,f,a,b):
errors = []
maxErrorOld = 0
E_k_sets = [["%.4f" % x for x in xDat]]
for i in range(20):
coeff1 = coeff(xDat,f)
maxErrorNew = coeff1[-1]
coeff1=coeff1[:-1]
if i%2==0:
plt.figure(1)
xD = np.linspace(a,b,5000)
yD = [evalPoly(coeff1, x) for x in xD]
plt.plot(xD,yD,label="i = "+str(i),linewidth=0.8)
plt.xlabel("x")
plt.ylabel("f(x)")
plt.figure(2)
yD2 = [evalPoly(coeff1, x)-f(x) for x in xD]
plt.plot(xD,yD2, label="i = "+str(i),linewidth =1)
plt.xlabel("x")
plt.ylabel("error")
xHat = findxhat(coeff1, f,a,b)
exchange(xDat, xHat, coeff1, f)
E_k_sets.append(["%.4f" % x for x in xDat])
errors.append(np.abs(maxErrorNew-maxErrorOld))
if np.abs(maxErrorOld-maxErrorNew)<10**(-12):
plt.figure(3)
plt.scatter(list(range(len(errors))), errors)
plt.xlabel("number of iterations")
plt.ylabel("absolute change in error")
print("DONE! max error is ", np.abs(maxErrorNew))
print("Polynomial coeffs are ", coeff1 )
print("E_k: \n", E_k_sets)
break
else:
maxErrorOld = maxErrorNew
a,b=0,2*np.pi
test = np.linspace(a,b,7)
f = lambda x: x*np.sin(x)
xD = np.linspace(a,b,1000)
plt.plot(xD,f(xD))
remez(test,f,a,b)
plt.figure(2)
plt.legend()
plt.figure(1)
plt.legend()
|
5a8aef01cc4e4dd1ec33a423b4b7fe01134371be | kcarson097/Beginner-Projects | /Text-editor.py | 560 | 4.03125 | 4 | def read_text_file(file):
#file name is entered as 'file.txt'
with open(file) as f:
contents = f.read()
return contents
def edit_text_file(file, new_text):
#this function will overwrite the current txt file
with open(file, mode = 'w') as f:
#opens file as read and write option - any edits overwrites past files
edited_file = f.write(new_text)
def add_to_file(file,add_text):
#this function adds to text file
with open(file, mode = 'a') as f:
new_file = f.write(add_text)
|
c41a32b3bc188f45b33e89d1d4f9f8ada85abe84 | RikaIljina/PythonLearning | /word_count_script/count_words.py | 4,264 | 4.0625 | 4 | import os
import sys
from pathlib import Path
# Add your file name here
file_path = r"counttext.txt"
result_path = r"result.csv"
# Remember names of source and target files
f_name = Path(file_path)
r_name = Path(result_path)
print("#" * 86)
print(f"This script will read the file {f_name} that must be placed in the same folder\n"
f"and analyse the amount and distribution of words used in it. The result is saved\n"
f"in a csv file in the same directory and can be opened in Excel or a text editor.\n"
f"The file encoding is iso-8859-1, suitable for German language.")
print("#" * 86)
try:
my_file = open(file_path, "r", encoding="iso-8859-1")
except:
print("\nCouldn't open source file counttext.txt. Place it in the same directory as this script.\n")
input()
sys.exit("Aborting script...")
# Deleting old result file if it exists
if os.path.isfile(result_path):
print(f"\nThe existing file {r_name} will be deleted and recreated. Proceed? y/n ")
user_input = input()
if user_input == "y" or user_input == "Y":
os.remove(result_path)
else:
sys.exit("Aborting script...")
result_file = open(r"result.csv", "a+", encoding="iso-8859-1")
# This function reads the file, removes all unwanted characters, replaces line breaks with whitespace,
# converts all characters to lowercase and splits the string into a list containing all words.
def make_word_list(file):
file_contents = file.read()
file_contents_upd = "".join(
c for c in file_contents if c not in "\"\t\\/'_;{}“”‘’“”«»[]()?:!.,—-–=<>*123y4567890§$%&#+|")
file_contents_upd = file_contents_upd.replace("\n", " ")
# print(file_contents_upd)
file_contents_upd = file_contents_upd.lower()
file_contents_list = file_contents_upd.split()
# print(file_contents_list)
return file_contents_list, len(file_contents_list)
# This function creates a dictionary and reads the list word by word.
# Each word will be used as a unique key in the dict, and its value is a counter
# indicating how many times it was used throughout the text.
def count_words(w_list):
w_dict = {}
for el in w_list:
if el in w_dict:
w_dict[el] += 1
else:
w_dict[el] = 1
return w_dict
# This function sorts the dict by most used word and alphabetically, calculates the percentage for each word
# and appends an f-string formatted line to a comma separated csv file.
def show_result(w_dict, w_count):
sorted_list_by_usage = [(k, w_dict[k]) for k in sorted(w_dict, key=w_dict.get, reverse=True)]
sorted_list_alphab = [(k, w_dict[k]) for k in sorted(w_dict.keys())]
result_file.write(f"sep=,\n")
result_file.write(f"Analysed file: {f_name}\n")
result_file.write(f"Unique words: {len(sorted_list_alphab)}, Total words: {w_count}\n\n")
result_file.write(f"Words by usage,Percentage,Amount,Words alphabetically,Percentage,Amount\n")
plural_s = "s"
for el in range(0, len(sorted_list_by_usage)):
prc_1 = format(100 * int(sorted_list_by_usage[el][1]) / w_count, '.3f') \
if 100 * int(sorted_list_by_usage[el][1]) / w_count < 1 \
else format(100 * int(sorted_list_by_usage[el][1]) / w_count, '.2f')
prc_2 = format(100 * int(sorted_list_alphab[el][1]) / w_count, '.3f') \
if 100 * int(sorted_list_alphab[el][1]) / w_count < 1 \
else format(100 * int(sorted_list_alphab[el][1]) / w_count, '.2f')
# print(f"{sorted_list_by_usage[el][0]} : {prc_1:.2f}%")
result_file.write(f"{sorted_list_by_usage[el][0]},{prc_1}%,{sorted_list_by_usage[el][1]} "
f"usage{plural_s if sorted_list_by_usage[el][1] > 1 else ''},"
f"{sorted_list_alphab[el][0]},{prc_2}%,{sorted_list_alphab[el][1]} "
f"usage{plural_s if sorted_list_alphab[el][1] > 1 else ''}\n")
word_list, words_total = make_word_list(my_file)
# word_dict = count_words(make_word_list(my_file))
print(f"...Creating the result file {r_name} from {f_name}")
show_result(count_words(word_list), words_total)
print("...File created. Press enter to finish.")
input()
print("...Closing files...")
result_file.close()
my_file.close()
|
99add258003c36dcd2023264fd4af8c2e7045333 | RikaIljina/PythonLearning | /cypher_1/cypher_template.py | 6,030 | 4.5 | 4 | ##############################################
# This code is a template for encoding and
# decoding a string using a custom key that is
# layered on top of the string with ord() and
# chr(). The key can be any sequence of symbols,
# e.g. "This is my $uper-$ecret k3y!!"
# Optimally, this code would ask users to
# choose between encoding and decoding a
# string, read in a file with the secret
# content, take the key as input and overwrite
# the secret file with the encoded string.
# When decoding, it would take a key, apply
# it to the encoded file and show the result.
##############################################
# this import is just needed for a test
import random
# This function takes the string secret_content and
# the key. It turns every letter into its Unicode
# code point, adds the Unicode value of the key on top
# and returns the encoded string containing int values
# separated with '.'
def encode_string(secret_content, incr_key):
# this will count how many symbols from the key have been used
counter = 0
# this will be added to each letter to encode it
incr = 0
# this will be the Unicode code point of the letter
int_letter = 0
# this is the resulting string
safe_string = ''
# It is possible that the key is longer than the secret text.
# In that case, I want to encode the encoded string again with
# the remainder of the key by running additional encryption loops.
# If the key is shorter than the text, encryption_loops is 1.
encryption_loops = int(0 if incr_key == "" else (len(incr_key) / len(secret_content))) + 1
# Now let's go through each letter of our secret content
# and convert it:
for letter in secret_content:
int_letter = ord(letter)
# Let's find the value from the key that
# will be added to our secret letter:
incr = get_next_increment(incr_key, counter)
# If we have more than 1 encryption loop, this loop
# checks if there are characters in the key left that
# have not been used yet and adds them to the increment.
for loop in range(1, encryption_loops):
if counter + len(secret_content) * loop < len(incr_key):
incr += get_next_increment(incr_key, (counter + len(secret_content) * loop))
# Let's check if we used up the entire key and reset
# or set the counter to the next symbol in the key:
if (incr_key is not None or incr_key != "") and len(incr_key) - counter != 1:
counter += 1
else:
counter = 0
# Here, the letter is finally encoded and added to the safe string:
safe_string = safe_string + "." + str(int_letter + incr)
return safe_string
# This function is the same as encode_string,
# only backwards. It takes the safe string and
# a key and returns the decoded string.
def decode_string(safe_string, incr_key):
counter = 0
incr = 0
chr_letter = ''
int_letter = 0
decr_string = ''
# Let's parse the encoded string, create a list
# with all Unicode values and remove the first
# empty value:
encoded_list = safe_string.split('.')
del (encoded_list[0])
decryption_loops = int(0 if incr_key == "" else (len(incr_key) / len(encoded_list))) + 1
for el in encoded_list:
incr = get_next_increment(incr_key, counter)
for loop in range(1, decryption_loops):
if counter + len(encoded_list) * loop < len(incr_key):
incr = incr + get_next_increment(incr_key, (counter + len(encoded_list) * loop))
if (incr_key is not None or incr_key != "") and len(incr_key) - counter != 1:
counter += 1
else:
counter = 0
# Here, we decode the letter by subtracting the
# calculated increment value and turning it back
# into a character.
int_letter = int(el) - incr
chr_letter = chr(int_letter if 0 <= int_letter <= 1114111 else 0)
decr_string += chr_letter
return decr_string
# This function takes the increment key
# and the current counter as arguments and returns
# the Unicode value of the key at position [counter].
def get_next_increment(incr_key, counter):
return 0 if incr_key is None or incr_key == "" else int(ord(incr_key[counter]))
def main():
# This is your secret text. It should be replaced with
# a string read from a file.
secret_content = "This is the text I will encode. It is highly classified, of course.\nNo one is allowed to see it. Ever."
print(secret_content + "\n")
print("##########\nEnter your secret key (any characters, the longer, the better)\n##########:")
incr_key = input()
safe_string = encode_string(secret_content, incr_key)
print("\n##########\nThis is the encoded string. It should be stored in a file for future decoding:\n##########\n",
safe_string)
decoded_string = decode_string(safe_string, "")
print("\n##########\nThis is what you get if you decode the string without a key:\n##########\n", decoded_string)
# The following logic constructs a random key with 1-35 characters
# and tries to decode the string with it:
random.seed()
rnd_key = ''
for i in range(random.randrange(1, 35)):
random.seed()
rnd_key = rnd_key + chr(random.randint(33, 127))
decoded_string = decode_string(safe_string, str(rnd_key))
print("\n##########\nThis is what you get if you decode the string with the random key ", rnd_key,
":\n##########\n", decoded_string)
# Obviously, incr_key shouldn't be saved anywhere. Rather, the user
# should be prompted to enter the correct key now.
decoded_string = decode_string(safe_string, incr_key)
print("\n##########\nThis is what you get if you decode the string with the correct key:\n##########\n")
print(decoded_string)
print("\n##########\nI hope you enjoyed my first attempt at encryption! :)\n##########\n")
if __name__ == "__main__":
main()
|
f75081ff4aa02c2d226247c160a69e941149c980 | zhaokaiju/fluent_python | /c07_closure_deco/p05_closure.py | 728 | 4.34375 | 4 | """
闭包:
闭包指延伸了作用域的函数,其中包含函数定义体中引用、但是不在定义体中定义的非全局变量。
函数是不是匿名的没关系,关键是它能访问定义体之外定义的非全局变量。
"""
def make_averager():
"""
闭包
"""
# 局部变量(非全局变量)(自由变量)
series = []
def averager(new_value):
series.append(new_value)
total = sum(series)
return total / len(series)
return averager
def use_make_averager():
avg = make_averager()
print(avg(10))
print(avg(12))
# 输出结果:
"""
10.0
11.0
"""
if __name__ == '__main__':
use_make_averager()
|
77d5735d02e893939063d955f7e32ca4b64a1f48 | kescott027/PythonHacker | /ransomnote.py | 1,365 | 3.578125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def checkMagazine(magazine, note):
d = {}
result = 'Yes'
for word in magazine:
d.setdefault(word, 0)
d[word] +=1
for word in note:
if word in d and d[word] -1 >= 0:
d[word] -=1
else:
result = 'No'
print(result)
stillnotefficient = """
def checkMagazine(magazine, note):
d = {}
result = 'Yes'
for word in magazine:
d.setdefault(word, 0)
d[word] +=1
for word in note:
if word in d and d[word] -1 >= 0:
note[word] -=1
else:
result = 'No'
def checkMagazine(magazine, note):
result = 'Yes'
for i in range(len(note)):
try:
magazine.pop(magazine.index(i))
except ValueError:
result = 'No'
print(result)
"""
# Valid but too expensive at higher
# list counts
# def checkMagazine(magazine, note):
#
#
# result = 'Yes'
# for word in note:
# if word not in magazine:
# result = 'No'
# else:
# magazine.pop(magazine.index(word))
# print(result)
if __name__ == '__main__':
mn = input().split()
m = int(mn[0])
n = int(mn[1])
magazine = input().rstrip().split()
note = input().rstrip().split()
checkMagazine(magazine, note)
|
feb5d900ebb46fd80cfa86d8346b12c17e94ce0b | kescott027/PythonHacker | /maxmin.py | 2,527 | 4 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the maxMin function below.
def maxMin(k, arr):
"""
given a list of integers arr, and a single integer k, create an array of length k from elements arr such
as its unfairness is minimized. Call that array subarr. unfairness of an array is calculated as:
max(subarr) - min(subarr)
:param k: an integer - the number of elements in the array to create
:param arr: a list of integers
:return:
"""
debug = False
newarr = []
c = {}
arr = sorted(arr)
if debug:
print("array size: {0}".format(k))
print("starting array {0}".format(arr))
i=0
while i + k <= len(arr):
c[arr[i+(k - 1)] - arr[i]] = i
i+=1
print("ranges: {0}".format(c))
start_index = c[min(c.keys())]
if debug:
print("min key: {0}".format(min(c.keys())))
print("starting index: {0}".format(start_index))
newarr = arr[start_index:start_index+k]
final = max(newarr) - min(newarr)
if debug:
print("sorted array {0}".format(arr))
print("final array {0}".format(newarr))
print("min {0}".format(min(newarr)))
print("max {0}".format(max(newarr)))
print("result = {0} ".format(final))
return final
if __name__ == '__main__':
k = [3, 4, 2, 5, 3]
inputs = [[10, 100, 300, 200, 1000, 20, 30], [1, 2, 3, 4, 10, 20, 30, 40, 100, 200], [1, 2, 1, 2, 1],
[4504, 1520, 5857, 4094, 4157, 3902, 822, 6643, 2422, 7288, 8245, 9948, 2822, 1784, 7802, 3142, 9739,
5629, 5413, 7232], [100, 200, 300, 350, 400, 401, 402]]
expected = [20, 3, 0, 1335, 2]
case = range(0, len(inputs))
failures = 0
i = 0
while i < len(inputs):
print("Test Case {0} ({1})".format(case[i], i))
expect = expected[i]
print("inputs: {0}\nk: {1}".format(inputs[i], k[i]))
result = maxMin(k[i], inputs[i])
if result != expect:
print("Test Case {0}: FAIL\n\tinput:{1}\n\touput: {2}\n\texpected: {3}".format(case[i], inputs[i], result,
expect))
failures += 1
else:
print("Test Case {0}: PASS\n\tinput: {1}\n\toutput: {2}".format(i, inputs[i], result))
# pass
print(" ")
i += 1
if failures > 0:
print("Test cases failed.")
else:
print("All cases Pass successfully") |
162e451ee6116712ba11c38246234fd1ea324138 | suhyeok24/Programmers-For-Coding-Test | /Programmers Lv.1/lv1. 최소직사각형.py | 1,037 | 3.5 | 4 | # 내 풀이
import numpy as np
def solution(sizes):
sizes=np.array(sizes).T.tolist()
print(sizes) #[[가로],[세로]]
width=sizes[0]
height=sizes[1]
big=max(max(width),max(height))
#가장 big을 찾는다. > 나머지 가로(세로)를 최소화시켜야 함.
# index끼리 대소비교해서 smaller를 나머지 선분으로 몰빵
if big in width:
for i in range(len(width)):
if width[i] < height[i]:
width[i],height[i] = height[i],width[i]
return big*max(height)
else:
for i in range(len(height)):
if width[i] > height[i]:
width[i],height[i] = height[i],width[i]
return big*max(width)
#좋은 풀이 > 아 ㅋㅋ
def solution(sizes):
return max(max(x) for x in sizes) * max(min(x) for x in sizes)
#max(max(x) for x in sizes) : 내가 말한 가장 큰놈. big
#max(min(x) for x in sizes) : smaller ones 들중 가장 큰 놈..(나머지 선분의 최소화) |
ce89c9d119563e15bdf426ae3d6d18800802ffe0 | suhyeok24/Programmers-For-Coding-Test | /Programmers Lv.1/프로그래머스 lv1. 나누어 떨어지는 숫자 배열.py | 858 | 3.53125 | 4 | # 가장 흔한 for문
def solution(arr, divisor):
answer = []
for n in arr:
if n % divisor == 0:
answer.append(n)
if not answer:
return [-1]
else:
return sorted(answer)
# lIST COMPRHENSION 이용
def solution(arr, divisor):
return sorted([ num for num in arr if num % divisor == 0]) or [-1]
# sorted([]) = [] 은 boolean으로 FaLSE 이므로 [-1]이 대신 리턴된다.
# return에 관하여 한말씀 올리면
# return A or B 일때 A,B가 둘다 참이면, A가 return됨(가장 첫번쨰 값)
# but A 와 B 중에 none, empty 값(boolean이 False)이 있으면 그 값을 제외한 True 값이 리턴됨
# 즉, 하나만 참이면 그 참인 값이 리턴.
#파이썬에서는 괄호 없이 값을 콤마로 구분하면 튜플이 된다.
# ex) 1,2 = (1,2) |
3895cae859876b54b659f2b8a8b4edec12fddee3 | corneliag08/Rezolvarea-problemelor-IF-WHILE-FOR | /problema 9.py | 250 | 3.6875 | 4 | n=int(input("Dati un numar: "))
suma=0
if(n!=0) and (n!=1):
for i in range (1,n):
if n%i==0:
suma+=i
if suma==n:
print("Numarul", n,"este perfect.")
else:
print("Numarul", n,"nu este perfect.") |
eb8542490893d3b99e9a8cfd416e0f363182de13 | codeking-hub/Coding-Problems | /AlgoExpert/balanceBrackets.py | 585 | 3.90625 | 4 | def balancedBrackets(string):
# Write your code here.
stack = []
opening_brackets = "([{"
closing_brackets = "}])"
matching_brackets = {
")": "(",
"}": "{",
"]": "["
}
for char in string:
peek = len(stack)-1
if char in opening_brackets:
stack.append(char)
if char in closing_brackets:
if stack == []:
return False
if matching_brackets[char] == stack[peek]:
stack.pop()
else:
return False
return stack == []
|
8401b89e555a10d530a528355193b0207ac6be6c | codeking-hub/Coding-Problems | /AlgoExpert/moveElementToEnd/spacealsoopt.py | 321 | 3.578125 | 4 | def moveElementToEnd(array, toMove):
# Write your code here.
left = 0
right = len(array)-1
while left < right:
while left < right and array[right] == toMove:
right -= 1
if array[left] == toMove:
array[left], array[right] = array[right], array[left]
left += 1
return array
# time O(n)
# space O(n)
|
171042e8da302efa359e350feaf92915e9d33b8b | codeking-hub/Coding-Problems | /AlgoExpert/find3LargestNums.py | 711 | 4.125 | 4 | def findThreeLargestNumbers(array):
# Write your code here.
three_largest = [None, None, None]
for num in array:
updateThreeLargest(num, three_largest)
return three_largest
def updateThreeLargest(num, three_largest):
if three_largest[2] == None or num > three_largest[2]:
shiftValue(three_largest, num, 2)
elif three_largest[1] == None or num > three_largest[1]:
shiftValue(three_largest, num, 1)
elif three_largest[0] == None or num > three_largest[0]:
shiftValue(three_largest, num, 0)
def shiftValue(array, num, idx):
for i in range(idx + 1):
if i == idx:
array[i] = num
else:
array[i] = array[i+1]
|
e328b1b43b04ea504d88dc37e936a0c3925cea60 | codeking-hub/Coding-Problems | /AlgoExpert/2Sum/s2.py | 257 | 3.875 | 4 | def twoNumberSum(array, targetSum):
# Write your code here.
nums = {}
for num in array:
complement = targetSum-num
if complement in nums:
return [complement, num]
else:
nums[num] = True
return []
# time complexity O(n)
|
e2519f0ca1c42f5cb04287a8d63bd563e136a2de | codeking-hub/Coding-Problems | /AlgoExpert/branchSums.py | 601 | 3.703125 | 4 | # This is the class of the input root. Do not edit it.
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def branchSums(root):
# Write your code here.
sums = []
findbranchSums(root, 0, sums)
return sums
def findbranchSums(node, currentSum, sums):
if node is None:
return
newCurrentNode = currentSum + node.value
if node.left is None and node.right is None:
sums.append(newCurrentNode)
return
findbranchSums(node.left, newCurrentNode, sums)
findbranchSums(node.right, newCurrentNode, sums)
|
49e336496e2452c7c33621dbd888c78ba43405b0 | codeking-hub/Coding-Problems | /AlgoExpert/binarySearch/recersive.py | 476 | 3.875 | 4 | def binarySearch(array, target):
# Write your code here.
return binarySearchHelper(array, target, 0, len(array)-1)
def binarySearchHelper(array, target, low, high):
if low > high:
return -1
mid = (low+high)//2
match = array[mid]
if match == target:
return mid
elif target < match:
return binarySearchHelper(array, target, low, mid-1)
elif target > match:
return binarySearchHelper(array, target, mid+1, high)
|
3ddab9cd05622d64529fb633064ee8cfa0db0492 | luciano588/d30-family-api | /src/datastructures.py | 2,768 | 4.0625 | 4 |
"""
update this file to implement the following already declared methods:
- add_member: Should add a member to the self._members list
- delete_member: Should delete a member from the self._members list
- update_member: Should update a member from the self._members list
- get_member: Should return a member from the self._members list
"""
from random import randint
class FamilyStructure:
def __init__(self, last_name):
self.last_name = last_name
# example list of members
self._members = [
{
"id": self._generateId(),
"first_name": "John",
"last_name": last_name,
"lucky_number": [1]
},
{
"id": self._generateId(),
"first_name": "John",
"last_name": last_name,
},
{
"id": self._generateId(),
"first_name": "John",
"last_name": last_name,
}
]
# John Jackson
# 33 Years old
# Lucky Numbers: 7, 13, 22
# read-only: Use this method to generate random members ID's when adding members into the list
def _generateId(self):
return randint(0, 99999999)
def add_member(self, member):
# fill this method and update the return
# Add a new object to an array
# if member["id"] is None:
# member["id"] = self._generateId()
if "id" not in member:
member.update(id=self._generateId())
member["last_name"]= self.last_name
self._member.append(member)
return member
def delete_member(self, id):
# fill this method and update the return`
status = ""
try:
for i,x in enumerate(self._members):
if x["id"] == id:
self._members.pop(i)
status = {
"status": "Successfully deleted member"
}
break
else:
status = False
except:
status = False
return status
def get_member(self, id):
# fill this method and update the return
member = {}
# try:
# for x in self._members:
# if x["id"] == id:
# member = x
# except:
# member = {
# "Status": "Not Found"
# }
for i,x in enumerate(self._members):
if x["id"]== id:
member= x
break
else:
member= False
return member
# this method is done, it returns a list with all the family members
def get_all_members(self):
return self._members
|
77d7c4b29aad0ad0d7d7ab04b1f7d3231bf2d0b7 | Symas1/metaprogramming_lab1 | /meta_method.py | 1,468 | 3.703125 | 4 | import utils
class MetaMethod:
def __init__(self):
self.name = utils.input_identifier('Enter method\'s name: ')
self.arguments = []
self.add_arguments()
def add_arguments(self):
if utils.is_continue('arguments'):
while True:
name = utils.input_agrument('Enter argument\'s name: ')
if name in self.arguments:
print(f'An argument with name: {name} already exists, '
f'please, try again')
elif utils.starts_with_symbol(name, 1, '*') and any(
utils.starts_with_symbol(arg_name, 1, '*') for arg_name in self.arguments):
print(f'Can\'t have more than one argument with * at the beginning: {name}, '
f'please, try again')
elif utils.starts_with_symbol(name, 2, '*') and any(
utils.starts_with_symbol(arg_name, 2, '*') for arg_name in self.arguments):
print(f'Can\'t have more than one argument with ** at the beginning: {name}, '
f'please, try again')
else:
self.arguments.append(name)
if utils.is_continue('another argument'):
continue
break
def get_arguments(self):
return self.arguments
def set_arguments(self, arguments):
self.arguments = arguments
|
48458c3ba2011e0c23112d26a5b65d7d0822c5bf | RECKLESS6321/Libaries | /BFS(queue).py | 483 | 4 | 4 | def bfs(graph, start_vertex, target_value):
path = [start_vertex]
vertex_and_path = [start_vertex, path]
bfs_queue = [vertex_and_path]
visited = set()
while bfs_queue:
current_vertex, path = bfs_queue.pop(0)
visited.add(current_vertex)
for neighbor in graph[current_vertex]:
if neighbor not in visited:
if neighbor is target_value:
return path + [neighbor]
else:
bfs_queue.append([neighbor, path + [neighbor]])
|
8e7e80d3e42f32e4cb414d8e90e3c4ae079d8038 | RahulNewbie/Job_REST_API | /job_insertion.py | 984 | 3.84375 | 4 | import csv
import sqlite3
import os
import constants
def job_insertion():
"""
Read the CSV file and insert records in Database
"""
con = sqlite3.connect(constants.DB_FILE)
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS job_data_table (Id,Title,Description,Company,"
"Location,Job_Category);")
with open('job_listing.csv', 'rt') as fin:
# csv.DictReader read line by line
dr = csv.DictReader(fin)
to_db = [(i['Id'], i['Title'], i['Description'],
i['Company'], i['Location'], i['Job_Category'])
for i in dr]
cur.executemany("INSERT INTO job_data_table "
"(Id,Title,Description,Company,Location,"
"Job_Category) "
"VALUES (?, ?, ?, ?,?, ?);", to_db)
print("database insertion finished")
con.commit()
con.close()
if __name__ == "__main__":
job_insertion()
|
6c0dc7a54d1e00bd5cb02b06bf6fa804cd665de9 | kadhirash/leetcode | /problems/happy_number/solution.py | 593 | 3.546875 | 4 | class Solution:
def isHappy(self, n: int) -> bool:
#happy =
# positive integer --- (n > 0)
# replace num by sum of square of its digits --- replace n by sum(square of digits)
# repeat until == 1
# if 1 then happy, else false
hash_set = set()
total_sum = 0
while n > 0 and n != 1:
for i in str(n):
n= sum(int(i) ** 2 for i in str(n))
if n in hash_set:
return False
else:
hash_set.add(n)
else:
return True
|
4d138ec4e0f4349b3eeb9842acc10f2a0c1ca748 | kadhirash/leetcode | /problems/minesweeper/solution.py | 1,131 | 3.6875 | 4 | class Solution:
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
x, y = click
surround = [(-1, 0), (1, 0), (0, 1), (0, -1), (1, -1), (1, 1), (-1, 1), (-1, -1)]
def available(x, y):
return 0 <= x < len(board) and 0 <= y < len(board[0])
def reveal(board, x, y):
# reveal blank cell with dfs
if not available(x, y) or board[x][y] != "E":
return
# count adjacent mines
mine_count = 0
for dx, dy in surround:
if available(dx+x, dy+y) and board[dx+x][dy+y] == "M":
mine_count += 1
if mine_count:
# have mines in adjacent cells
board[x][y] = str(mine_count)
else:
# not adjacent mines
board[x][y] = "B"
for dx, dy in surround:
reveal(board, dx+x, dy+y)
if board[x][y] == "M":
board[x][y] = "X"
elif board[x][y] == "E":
reveal(board, x, y)
return board |
374eb12b1ec6126e692a94315444e4a7bcf0621b | kadhirash/leetcode | /problems/search_suggestions_system/solution.py | 1,011 | 3.671875 | 4 | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort() # time O(nlogn)
array_len = len(products)
ans = []
input_char = ""
for chr in searchWord:
tmp = []
input_char += chr
insertion_index = self.binary_search(products, input_char) # find where input_char can be inserted in-order in the products array
for word_ind in range(insertion_index, min(array_len, insertion_index+3)): # check the following 3 words, if valid
if products[word_ind].startswith(input_char):
tmp.append(products[word_ind])
ans.append(tmp)
return ans
def binary_search(self, array, target): # bisect.bisect_left implementation
lo = 0
hi = len(array)
while lo < hi:
mid = (lo + hi) //2
if array[mid] < target: lo = mid + 1
else: hi = mid
return lo
|
5b27c86e6e8a8286719120abc005c3766632d7f0 | ElenaPontecchiani/Python_Projects | /0-hello/16-for.py | 306 | 4.09375 | 4 | for letter in "lol":
print(letter)
friends = ["Kim", "Tom", "Kris"]
for friend in friends:
print(friend)
#altro modo per fare la stessa cosa con range
for index in range(len(friends)):
print(friends[index])
for index in range(10):
print(index)
for index in range(3,10):
print(index) |
8467f46df1d0750c60bdd4c67ece16ef34707c48 | ElenaPontecchiani/Python_Projects | /0-hello/35-sortedAdvanced.py | 531 | 3.53125 | 4 | #format=(nome, raggio, denisità, distanza dal sole)
planets =[
("Mercury", 2440, 5.43, 0.395),
("Venus", 6052, 5.24, 0.723),
("Earth", 6378, 5.52, 1.000),
("Mars", 3396, 3.93, 1.530),
("Jupiter", 71492, 1.33, 5.210),
("Saturn", 60268, 0.69, 9.551),
("Uranus", 25559, 1.27, 19.213),
("Neptune", 24764, 1.64, 30.070),
]
#se voglio riordinare per vari parametri, faccio una f che torna il risultato dell'op di sort
size = lambda planet: planet[1]
planets.sort(key = size, reverse=True)
print(planets) |
a9bbd74af9b343cf940c2a7eeb6de12dbcc4bdd9 | ElenaPontecchiani/Python_Projects | /0-hello/12-calculatorV2.py | 466 | 4.1875 | 4 | n1 = float(input("First number: "))
n2 = float(input("Second number: "))
operator = input("Digit the operator: ")
def calculatorV2 (n1, n2, operator):
if operator == '+':
return n1+n2
elif operator == '-':
return n1-n2
elif operator == '*':
return n1*n2
elif operator == '/':
return n1/n2
else:
print("Error, operator not valid")
return 0
result = calculatorV2(n1, n2, operator)
print(result)
|
e5d0c701272a91bb56882ffb433ead594311d5b5 | ElenaPontecchiani/Python_Projects | /0-hello/2-variable.py | 555 | 3.953125 | 4 | character_name= "Jhon"
character_age= 50.333
is_male= False
#cincionamenti con le variabili
print("His name is " +character_name)
print (character_name)
print (character_name.upper().islower())
print(len(character_name))
print(character_name[0])
print(character_name.index("J"))
print(character_name.index("ho"))
phrase= "giraffe academy"
print(phrase.replace("giraffe", "lol"))
#this is a comment
#cincionamenti con i numeri
my_num= -2.097
print(my_num)
print((-2.097 + 8)*7)
print(str(my_num) + "my favorite number")
print(abs(my_num))
print(max(1,4)) |
0eeeef457fd8543b7ba80d2645b0bac3624dffc3 | fanjiamin1/cryptocurrencies | /scratchpad/exponentiation.py | 564 | 3.703125 | 4 |
def modularpoweroftwo(number,poweroftwo,module):
#returns number**(2**poweroftwo) % module
value=number%module
currexponent=0
while currexponent<poweroftwo:
value=(value*value)%module
currexponent+=1
return value
def fastmodularexponentiation(number,exponent,module):
value=1
for i in range(len(bin(exponent)[2:][::-1])):
if bin(exponent)[2:][::-1][i]=='1':
value*=modularpoweroftwo(number,i,module)
return value
print(fastmodularexponentiation(5,3,200))
|
c9a49ce478ccbe1df25e3b5c0ee18932ae222f86 | mateuszkanabrocki/LMPTHW | /ex11/project/tail.py | 804 | 3.734375 | 4 | #! /usr/bin/env python3
from sys import argv, exit, stdin
# history | ./tail -25
def arguments(argv):
try:
lines_num = int(argv[1].strip('-'))
return lines_num
except IndexError:
print('Number of lines not gien.')
exit(1)
def main():
count = arguments(argv)
if len(argv) > 2:
try:
lines = []
for file in argv[2:]:
with open(file, 'r') as f:
for line in f.readlines():
lines.append(line)
except FileNotFoundError:
print('File not found.')
exit(1)
else:
lines = stdin.readlines()
result_lines = lines[-count:]
for line in result_lines:
print(line.strip('\n'))
if __name__ == '__main__':
main()
|
def2e855860ded62733aa2ddcfe4b51029a8edd2 | PSReyat/Python-Practice | /car_game.py | 784 | 4.125 | 4 | print("Available commands:\n1) help\n2) start\n3) stop\n4) quit\n")
command = input(">").lower()
started = False
while command != "quit":
if command == "help":
print("start - to start the car\nstop - to stop the car\nquit - to exit the program\n")
elif command == "start":
if started:
print("Car has already started.\n")
else:
started = True
print("Car has started.\n")
elif command == "stop":
if started:
started = False
print("Car has stopped.\n")
else:
print("Car has already stopped.\n")
else:
print("Input not recognised. Please enter 'help' for list of valid inputs.\n")
command = input(">").lower()
print("You have quit the program.") |
f6b50fb2c608e9990ed1e3870fd73e2039e17b3d | ananyo141/Python3 | /uptoHundred.py | 301 | 4.3125 | 4 | #WAP to print any given no(less than 100) to 100
def uptoHundred(num):
'''(num)-->NoneType
Print from the given number upto 100. The given num should be less than equal to 100.
>>>uptoHundred(99)
>>>uptoHundred(1)
'''
while(num<=100):
print(num)
num+=1 |
004253ee0f2505f145d011e35d28ed4e9f96f36b | ananyo141/Python3 | /Automate The Boring Stuff/sandwichMaker.py | 1,484 | 4.09375 | 4 | # Make a sandwich maker and display the cost.
from ModuleImporter import module_importer
pyip = module_importer('pyinputplus', 'pyinputplus')
orderPrice = 0
print("Welcome to Python Sandwich!".center(100,'*'))
print("We'll take your order soon.\n")
breadType = pyip.inputMenu(['wheat','white','sourdough'],prompt="How do you like your bread?\n",blank=True)
if breadType:
orderPrice += 20
proteinType = pyip.inputMenu(['chicken','turkey','ham','tofu'],prompt="\nWhat is your protein preference?\n",blank=True)
if proteinType:
orderPrice += 35
cheese = pyip.inputYesNo(prompt = '\nDo you prefer cheese?: ')
if cheese == 'yes':
cheeseType = pyip.inputMenu(['cheddar','Swiss','mozarella'],prompt="Enter cheese type: ")
orderPrice += 10
mayo = pyip.inputYesNo(prompt='\nDo you want mayo?: ')
if mayo == 'yes':
orderPrice += 5
mustard = pyip.inputYesNo(prompt='\nDo you want to add mustard?: ')
if mustard == 'yes':
orderPrice += 2
lettuce = pyip.inputYesNo(prompt='\nDo you want lettuce?: ')
tomato = pyip.inputYesNo(prompt='\nDo you want tomato in your sandwich?: ')
orderQuantity = pyip.inputInt('\nHow many sandwiches do you want to order?: ',min=1)
confirmation = pyip.inputYesNo(prompt='\nConfirm your order?: ')
if confirmation == 'yes':
totalOrderPrice = orderPrice * orderQuantity
print(f"\nYour order has been confirmed! Total order price is Rs.{totalOrderPrice} for {orderQuantity} sandwiches.")
else:
print('\nYou cancelled your order')
|
437c321c8a52c3ae13db3bfa5e48c7a5dac2c1eb | ananyo141/Python3 | /gradeDistribution/functions.py | 2,519 | 4.15625 | 4 | # This function reads an opened file and returns a list of grades(float).
def findGrades(grades_file):
'''(file opened for reading)-->list of float
Return a list of grades from the grades_file according to the format.
'''
# Skip over the header.
lines=grades_file.readline()
grades_list=[]
while lines!='\n':
lines=grades_file.readline()
lines=grades_file.readline()
while lines!='':
# No need to .rstrip('\n') newline as float conversion removes it automatically.
grade=float(lines[lines.rfind(' ')+1:])
grades_list.append(grade)
lines=grades_file.readline()
return grades_list
# This function takes the list of grades and returns the distribution of students in that range.
def gradesDistribution(grades_list):
'''(list of float)-->list of int
Return a list of ints where each index indicates how many grades are in these ranges:
0-9: 0
10-19: 1
20-29: 2
:
90-99: 9
100 : 10
'''
ranges=[0]*11
for grade in grades_list:
which_index=int(grade//10)
ranges[which_index]+=1
return ranges
# This function writes the histogram of grades returned by distribution.
def writeHistogram(histogram,write_file):
'''(list of int,file opened for writing)-->NoneType
Write a histogram of '*'s based on the number of grades in the histogram list.
The output format:
0-9: *
10-19: **
20-29: ******
:
90-99: **
100: *
'''
write_file.write("0-9: ")
write_file.write('*' * histogram[0]+str(histogram[0]))
write_file.write('\n')
# Write the 2-digit ranges.
for i in range(1,10):
low = i*10
high = low+9
write_file.write(str(low)+'-'+str(high)+': ')
write_file.write('*'*histogram[i]+str(histogram[i]))
write_file.write('\n')
write_file.write("100: ")
write_file.write('*' * histogram[-1]+str(histogram[-1]))
write_file.write('\n')
write_file.close
# Self-derived algorithm, have bugs.(Not deleting for further analysis and possible debugging.)
# for i in range(0,100,9):
# write_file.write(str(i))
# write_file.write('-')
# write_file.write(str(i+9))
# write_file.write(':')
# write_file.write('*'*histogram[(i//10)])
# write_file.write(str(histogram[(i//10)]))
# write_file.write('\n')
# write_file.close()
|
65c9becebedca46aed5c13c04aa0bff47460d23b | ananyo141/Python3 | /Automate The Boring Stuff/clipboardNumbering.py | 1,238 | 4 | 4 | #!python3
# WAP that takes the text in the clipboard and adds a '*' and space before each line and copies to the
# clipboard for further usage.
import sys
from ModuleImporter import module_importer
pyperclip = module_importer('pyperclip', 'pyperclip')
def textNumbering(text, mode):
'''(str,str)-->str
Returns a ordered or unordered string according to newlines of the given text argument and
mode.
'''
textList = text.split('\n')
if mode.lower()=='unordered':
for i in range(len(textList)):
textList[i] = "* "+textList[i]
elif mode.lower()=='ordered':
numbering = 1
for i in range(len(textList)):
textList[i] = str(numbering)+') '+textList[i]
numbering += 1
else:
sys.exit("Invalid Choice")
processedText = ('\n').join(textList)
return processedText
def main():
# Uses terminal argument as mode-choice for easier operation #
if len(sys.argv)<2:
sys.exit("Usage: python [filename.py] [mode]")
choice=sys.argv[1]
clipboard=pyperclip.paste()
numberedText=textNumbering(clipboard,choice)
pyperclip.copy(numberedText)
print("Successfully completed.")
if __name__ == '__main__':
main()
|
0cc53ef8c755669e55176ebad4cd5b0c0d758eef | ananyo141/Python3 | /Automate The Boring Stuff/passwordStrengthNOREGEX.py | 3,765 | 4.03125 | 4 | # Give the user option to find the passwords in the given text, or enter one manually.
# Check the password and give rating as weak, medium, strong, unbreakable and include tips to improve it.
import re, time, sys
from ModuleImporter import module_importer
pyperclip = module_importer('pyperclip', 'pyperclip')
def passwordFinder(text):
'''(str)--->list
Find and return matching password strings in the given text.
'''
passwordRegex = re.compile(r'''(
(password | pass) # Starts with 'password'
(?: : | -)? # optional separator
(?: \s*)? # Optional whitespaces
(\S{3,}) # Atleast 3 non-space characters
)''', re.VERBOSE | re.IGNORECASE)
passwordsFound = []
for tupleGroup in passwordRegex.findall(text):
passwordsFound.append(tupleGroup[2])
return passwordsFound
def passwordStrength(passw):
'''(str)--->NoneType
Print the strength of the given password between weak, medium, strong and unbreakable along with
tips to strengthen the password.
'''
specialCharRegex = re.compile(r'[!@#$%^&*-+]')
characterCheck = uppercaseCheck = lowercaseCheck = digitCheck = specialCharCheck = False
strengthScore = 0
if len(passw) >= 8:
characterCheck = True
strengthScore += 1
# Find uppercase
for char in passw:
if char.isupper():
uppercaseCheck = True
strengthScore += 1
break
# Find lowercase
for char in passw:
if char.islower():
lowercaseCheck = True
strengthScore += 1
break
# Find digit
for char in passw:
if char.isdecimal():
digitCheck = True
strengthScore += 1
break
# Find special Character
specialChar = specialCharRegex.search(passw)
if specialChar:
specialCharCheck = True
strengthScore += 1
# Score strength
if strengthScore == 5:
print("Unbreakable\nYou can challenge a hacker!")
elif strengthScore == 4:
print("Strong")
elif strengthScore == 3:
print("Medium")
elif strengthScore < 3:
print("Weak")
# Add tips to strengthen the password
if not characterCheck:
print("Password length is too short")
if not uppercaseCheck:
print("Tip: Add an uppercase letter.")
if not lowercaseCheck:
print("Tip: Add a lowercase letter.")
if not digitCheck:
print("Tip: Add a digit.")
if not specialCharCheck:
print("Tip: Add a special character.")
def main():
if len(sys.argv)>1:
if sys.argv[1].lower().startswith('clip'):
clipboard = pyperclip.paste()
passwords = passwordFinder(clipboard)
if len(passwords) == 0:
sys.exit("No passwords found")
print("Analyzing".ljust(20,'.'))
time.sleep(1)
for i in range(len(passwords)):
print("\nPassword found:", passwords[i])
passwordStrength(passwords[i])
time.sleep(0.25)
sys.exit("\nThanks for trying this out!")
else:
sys.exit("Enter 'clip' during script execution {python <filename>.py clip}\nto find and analyze passwords from your clipboard.")
password = input("Enter the password: ")
if ' ' in password:
sys.exit("Passwords can't contain spaces. Invalid.")
print("Analyzing......")
time.sleep(0.5)
passwordStrength(password)
# Usage Reminder
print('''\nYou can also enter 'clip' during script execution {python <filename>.py clip}
to find and analyze passwords from your clipboard.''')
if __name__ == '__main__':
main()
|
67613b888eaa088a69a0fec26f1ace376f95cbbb | ananyo141/Python3 | /calListAvg.py | 624 | 4.15625 | 4 | # WAP to return a list of averages of values in each of inner list of grades.
# Subproblem: Find the average of a list of values
def calListAvg(grades):
'''(list of list of num)--list of num
Return the list of average of numbers from the list of lists of numbers in grades.
>>> calListAvg([[5,2,4,3],[4,6,7,8],[4,3,5,3,4,4],[4,35,3,45],[56,34,3,2,4],[5,3,56,6,7,6]])
[3.5, 6.25, 3.833, 21.75, 19.8, 13.833]
'''
avg_list=[]
for sublist in grades:
total=0
for grade in sublist:
total+=grade
avg_list.append(total/len(sublist))
return avg_list |
aba312740d42e2f175d79984bc2d3ec8042b891b | ananyo141/Python3 | /area_of_triangle.py | 184 | 4.1875 | 4 | def area(base, height):
''' (num,num)--> float
Return the area of a triangle of given base and height.
>>>area(8,12)
48.0
>>>area(9,6)
27.0
'''
return (base*height)/2
|
0689366efad35236c8baddc7eb27bd398a51da8b | ananyo141/Python3 | /Automate The Boring Stuff/blankRowInserter.py | 1,735 | 3.828125 | 4 | # Insert blank rows in a excel spreadsheet at a given row
import tkinter.filedialog, openpyxl, sys, os
from ModuleImporter import module_importer
openpyxl = module_importer('openpyxl', 'openpyxl')
def main():
print("Enter the file you want to add rows to:")
filename = tkinter.filedialog.askopenfilename(filetypes=[('Excel Spreadsheet', '*.xlsx')])
if not filename:
sys.exit("No file selected")
try:
rowNum = int(input("Enter the row number where you want to insert gaps: "))
gapNum = int(input("Enter the number of gaps: "))
except:
sys.exit("Integer value expected")
print("Opening Workbook")
workbook = openpyxl.load_workbook(filename)
sheetSrc = workbook.active
print("Creating a new workbook")
newWorkbook = openpyxl.Workbook()
sheetDst = newWorkbook.active
print("Copying the data and adding gaps")
# write the first rowNum number of rows
for row in range (1, rowNum):
for column in range(1, sheetSrc.max_column + 1):
try:
sheetDst.cell(row = row, column = column).value = sheetSrc.cell(row = row, column = column).value
except:
continue
# write the gapped rows
for row in range(rowNum, sheetSrc.max_row + 1):
for column in range(1, sheetSrc.max_column + 1):
try:
sheetDst.cell(row = row + gapNum, column = column).value = sheetSrc.cell(row = row, column = column).value
except:
continue
saveDir = filename[:filename.rfind(os.sep) + 1]
newWorkbook.save(saveDir + 'gappedWorkbook.xlsx')
print("Output workbook is saved at " + saveDir)
if __name__ == '__main__':
main()
|
b7e98df96a4a263667a93d2ae87d397457cd0cb4 | ananyo141/Python3 | /addColor.py | 362 | 4.1875 | 4 | #WAP to input colors from user and add it to list
def addColor():
'''(NoneType)-->list
Return the list of colors input by the user.
'''
colors=[]
prompt="Enter the color you want to add, press return to exit.\n"
color=input(prompt)
while color!='':
colors.append(color)
color=input(prompt)
return colors |
1fe0f75ae821de46be7b338fc5d738d2a9a499e8 | ananyo141/Python3 | /doubleAltObj.py | 348 | 3.890625 | 4 | #WAP to modify the given list and double alternative objects in a list
def doubleAltObj(list):
'''(list)--> NoneType
Modify the list so that every alternative objet value is doubled, starting at index 0.
'''
# for i in range(0,len(list),2):
# list[i]*=2
i=0
while i<len(list):
list[i]*=2
i+=2
|
61c640eccbdf20c3ad65081414f33e8adba4475e | ananyo141/Python3 | /Automate The Boring Stuff/DataExtractorTool/functions.py | 3,547 | 4.34375 | 4 | import re
# Regex to find the phone numbers
def findPhoneNumbers(string):
'''(str)-->list
Return all the matching phone numbers in the given string as a list.
'''
phoneNumbersIN = re.compile(r'''( # Indian phone numbers (+91)9590320525
( ((\+)?\d{2}) | \(((\+)?\d{2})\) )? # (+91) parenthesis and + optional or whole is optional, but if present area code 91 is mandatory
( \s* |-| \. )? # optional separator
(\d{5})
( \s*|-|\. )? # optional separator
(\d{5})
)''', re.VERBOSE)
phoneNumbersAmer = re.compile(r'''(
( \d{3} | \( \d{3} \) )? # area code
(\s |-| \.)? # optional separator
(\d{3}) # first 3 digits
(\s |-| \.) # required separator
(\d{4}) # last 4 digits
(\s*(ext|x|ext.)\s*(\d{2,5}))? # optional extension
)''', re.VERBOSE)
# Find the numbers and return them in a list container
numbers = []
indianNum = []
indianNum.append("Indian Numbers:")
for tupleGroup in phoneNumbersIN.findall(string): # findall() returns tuples of regex group strings
numberFound = '(+91) '+tupleGroup[7]+'-'+tupleGroup[9]
if len(numberFound) >= 17:
indianNum.append(numberFound)
if len(indianNum) > 1:
numbers.extend(indianNum)
amerNum = []
amerNum.append("American Numbers:")
for tupleGroup in phoneNumbersAmer.findall(string):
phoneNum = '-'.join([tupleGroup[1],tupleGroup[3],tupleGroup[5]])
if tupleGroup[8] != '':
phoneNum += ' x' + tupleGroup[8] # 8 can only be justified if nested group is counted separatedly,index starting from the outer group
if len(phoneNum) >= 12:
amerNum.append(phoneNum)
if len(amerNum) > 1:
numbers.extend(amerNum)
return numbers
# Regex to find email addresses
def findEmailAddr(string):
'''(str)-->list
Return all the matching email addresses in the given string as a list.
'''
emailRegex = re.compile(r'''(
[a-zA-Z0-9._%+-]+ # one or more of the characters defined in the class (username)
@ # @ symbol
[a-zA-Z0-9.-]+ # one or more of the characters defined in the class (domain name)
(\.[a-zA-Z]{2,4}) # dot-something
)''', re.VERBOSE | re.IGNORECASE)
emailMatch = []
for tupleGroup in emailRegex.findall(string):
emailMatch.append(tupleGroup[0].lower()) # FLAGGED #
return emailMatch
# Regex to find website URL
def findWebsites(string):
'''(str)-->list
Return a list of matching websites found in the given string.
'''
websiteRegex = re.compile(r'''(
( http:// | https:// )? # optional protocol
(www\.) # prefix
[a-z0-9.$-_. +! *'()]+ # host name
(\.) # period
([a-z]{2,4}) # top-level domain name
(\.)? # optional domains
([a-z]{2,4})?
(\.)?
([a-z]{2,4})?
)''', re.VERBOSE | re.IGNORECASE)
websitesMatch = []
for tupleGroup in websiteRegex.findall(string):
formatter = tupleGroup[0].lstrip('https://www./')
websitesMatch.append(('www.'+formatter).lower())
return websitesMatch
|
190135679eb8848b33a40be02482aca18b41aa7e | tscotn/tscotn.github.io | /Python Scripts/web scraping/__main__.py | 1,456 | 3.5 | 4 | #!/usr/bin/env python
import requests
from bs4 import BeautifulSoup
import sys
import os
def GetHTML(article_url):
article_raw = requests.get(article_url)
article_soup = BeautifulSoup(article_raw.content, 'html.parser')
return article_soup
#def GetArticleHeader(article_soup):
# article_header: str = ''
# for header in article_soup.find_all('h3'):
# article_header += header.get_text()
# return article_header
def GetRecipeText(article_soup):
# article_text: str = ''
for paragraph in article_soup.find_all('p'):
return paragraph
# article_text += paragraph.get_text()
# return article_text
def GetArticle(article_url):
article_soup = GetHTML(article_url)
# article = GetArticleHeader(article_soup) + "\n" + GetArticleText(article_soup)
article = GetRecipeText(article_soup)
return article#[:article.find("Comment")]
def InsertTxt(article): # this opens/creates a new .txt file, writes webText to it, closes .txt file
file = "//Users/scot/Desktop/Github/Recipe Reader/article.html"
f = open(file, "w+")
f.write('<!DOCTYPE html><html><body>' + str(article) + '</body></html>')
f.close()
#url = requests.GET("url")
#print(url)
InsertTxt(GetArticle(sys.argv[1]))
os.system('open //Users/scot/Desktop/Github/Recipe\ Reader/article.html')
# take a link as a sysargv, return article text, launch html file that formats the article in browser, save link in file?
|
1766b55fbf0337bcff4a3514a1e6542c8bceb78e | ktkthakre/Python-Crash-Course-Practice-files | /Chapter 3/guestlist.py | 1,767 | 4.4375 | 4 | #list exercise 3.4
guest = ['dog','cat','horse']
print(f"Please join us to dinner Mr.{guest[0].title()}.")
print(f"Please join us to dinner Mr.{guest[1].title()}.")
print(f"Please join us to dinner Mr.{guest[2].title()}.")
#list exercise 3.5
print(f"\nOh No, Mr.{guest[2].title()} cannot join us for dinner.")
cancled = guest.pop(2)
guest.append('cow')
print(f"So, Mr.{guest[2].title()} will be joining us instead.")
print(f"Atleast Mr.{guest[0].title()} and Mr.{guest[1].title()} will be still with us")
#list exercise 3.6
print("Hey, I just found a bigger table.")
guest.insert(0, 'bird')
guest.insert(4, 'boar')
guest.append('bull')
print("\nHere are the new invites : ")
print(f"\nPlease join us to dinner Mr.{guest[0].title()}.")
print(f"Please join us to dinner Mr.{guest[1].title()}.")
print(f"Please join us to dinner Mr.{guest[2].title()}.")
print(f"Please join us to dinner Mr.{guest[3].title()}.")
print(f"Please join us to dinner Mr.{guest[4].title()}.")
print(f"Please join us to dinner Mr.{guest[5].title()}.")
#displaying number of list using len() method
print(f"{len(guest)} guests will be joining us for dinner.")
#list exercise 3.7
print("\nHoly cow, the bigger table I ordered won't be here in time.\n\tOnly two guests can be adjusted at the dinner.")
print(f"\nSorry Mr.{guest[5].title()}, for letting you down.")
guest.pop()
print(f"\nSorry Mr.{guest[4].title()}, for letting you down.")
guest.pop()
print(f"\nSorry Mr.{guest[3].title()}, for letting you down.")
guest.pop()
print(f"\nSorry Mr.{guest[2].title()}, for letting you down.")
guest.pop()
print(f"Mr.{guest[0].title()} you will still be with us.\nAnd you too Mr.{guest[1].title()}")\
del guest[1]
del guest[0]
print(guest) |
22da279601e248edb946f76cc4dba2e12b02315b | sakshitonwer/course-1 | /HW3/Student-2/src/one.py | 85 | 3.609375 | 4 | def diff(a, b):
c=a + b
return c
print("The sum is %i" % (6, 8, diff(6, 8)))
|
f063e7b57973fe43d7b4cefc481775c2c949a262 | wdavid73/TheBigBangTheory_NumeroPecfecto | /NumeroPerfecto.py | 1,915 | 3.90625 | 4 | from typing import AnyStr
def NumeroPerfecto(numero : int):
cont = 0
cont2 = 0
# Validar si es primo
if numero < 9:
print("el numero debe ser mayor a 9")
else:
if( es_primo(numero) == True):
cont = contar_primos(numero)
newNumber = str(numero)[::-1]
# comparamos su espejo
if( es_primo(int(newNumber))):
cont2 = contar_primos(int(newNumber))
if( str(cont) == str(cont2)[::-1]):
if(int(str(numero)[0]) * int(str(numero)[1]) == int(cont)):
binNumero = dec_to_bin(numero)
if( str(binNumero) == str(binNumero)[::-1]):#comparamos si es palindromo
print(f"el numero {numero} es un numero perfecto")
else:
print(f"el numero {numero} es binario no es palindromo")
else:
print(f"el numero {numero} separado y multiplado es {str(numero)[0]} x {str(numero)[1]} es difente de {cont}")
else:
print(f"el numero {numero} es el {cont} primo y su espejo el {newNumber} es el {cont2} primo , tienen que ser iguales")
else:
print(f"el numero {numero} es primo , pero su espejo no lo es")
else:
print(f"el numero {numero} no es primo")
def es_primo(numero : int):
if numero < 2:
return False
for num in range(2, numero):
if numero % num == 0:
return False
return True
def contar_primos(numero : int) -> int:
cont = 0
for num in range(2, numero):
# Contamos cuantos primos hay
if es_primo(num) == True:
cont += 1
cont += 1
return cont
def dec_to_bin(x):
return int(bin(x)[2:])
numero = int(input("Ingrese su Numero : "))
NumeroPerfecto(numero)
|
f05be9154a3ddf89509d7075cd35f35df216800b | IPcamerabykitri/nmap | /ISEEU_Interface_new/Network_Scan_Module/entropy.py | 579 | 3.59375 | 4 | import math
from collections import Counter
def calculate_entropy(symbol_list):
entropy = 0
total_symbol_count = float(len(symbol_list))
values_symbol = Counter(symbol_list) # counts the elements' frequency
for symbol_count in values_symbol.values():
percentage = symbol_count/total_symbol_count
reverse_percentage = total_symbol_count/symbol_count
entropy += percentage * math.log(reverse_percentage,2)
#return value by Dictionary
return {"total_symbol_count":total_symbol_count,"values_symbol":values_symbol,"entropy":entropy} |
1a67cbcabc8f93f42cbb39a1b30531e12226b655 | katesorotos/module3 | /ch05_testing_tools/calculator_app_test.py | 498 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 30 09:59:29 2019
@author: Kate Sorotos
"""
import unittest
from calculator_app import Calculator
class calculator_test(unittest.TestCase):
def setUp(self):
self.calc = Calculator()
def test_add_method(self):
result = self.calc.add(2,2)
self.assertEqual(4,result)
def test_error_message(self):
self.assertRaises(ValueError, self.calc.add, 'two', 'three')
if __name__ == '__main__':
unittest.main() |
93bb07c59455eb12a995e7597807d619dc4823ac | DavieV/Euler | /test.py | 220 | 3.78125 | 4 | import math
def is_prime(x):
if x % 2 == 0:
return False
for i in range(3, int(math.sqrt(x))):
if x % i == 0:
print i
return False
return True
print is_prime(2433601) |
a1ee96883d6f41e3cd4d75f535658b95e4cb3780 | yang4978/LeetCode | /Python3/0994. Rotting Oranges.py | 855 | 3.5 | 4 | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
oranges = 0
queue = []
m = len(grid)
n = len(grid[0])
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
oranges += 1
elif grid[i][j] == 2:
queue.append((i,j))
directions = [(0,1),(0,-1),(1,0),(-1,0)]
t = 0
while queue and oranges:
t += 1
for _ in range(len(queue)):
x, y = queue.pop(0)
for dx, dy in directions:
if 0<=dx+x<m and 0<=dy+y<n and grid[x+dx][y+dy] == 1:
grid[x+dx][y+dy] = 2
oranges -= 1
queue.append((x+dx,y+dy))
return -1 if oranges else t
|
2057326205e39c27b6f96b6718983578a90425b4 | yang4978/LeetCode | /Python3/0143. Reorder List.py | 1,046 | 3.890625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverse_list(self,head):
if not head:
return head
temp = head
new_head = None
while temp:
tt = temp.next
temp.next = new_head
new_head = temp
temp = tt
return new_head
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head:
return head
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
l1 = head
l2 = self.reverse_list(slow.next)
slow.next = None
while l2 != None:
t = l2.next
l2.next = l1.next
l1.next = l2
l1 = l2.next
l2 = t
return head
|
2f0e0aeb2b240f6a771ac67d4e5bae902da83481 | yang4978/LeetCode | /Python3/0461. Hamming Distance.py | 337 | 3.578125 | 4 | class Solution:
def hammingDistance(self, x: int, y: int) -> int:
# n = x^y
# res = 0
# while n:
# res += n%2
# n //= 2
# return res
res = 0
mask = 1
while(mask<=x or mask<=y):
res += mask&x!=mask&y
mask <<= 1
return res
|
f6c7ca63b6a6915e6ee3024460bb39df878604f1 | yang4978/LeetCode | /Python3/0500. Keyboard Row.py | 277 | 3.859375 | 4 | class Solution:
def findWords(self, words: List[str]) -> List[str]:
set1 = set('qwertyuiopQWERTYUIOP')
set2 = set('asdfghjklASDFGHJKL')
set3 = set('zxcvbnmZXCVBNM')
return [s for s in words if(set(s)<=set1 or set(s)<=set2 or set(s)<=set3)]
|
098f29472231beddb24634a49769bc3fa9c61c90 | yang4978/LeetCode | /Python3/0538. Convert BST to Greater Tree.py | 1,305 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
stack = []
total = 0
head = root
while root:
stack.append(root)
root = root.right
while stack:
root = stack.pop()
root.val += total
total = root.val
node = root.left
while node:
stack.append(node)
node = node.right
return head
# def __init__(self):
# self.val = 0
# def convertBST(self, root: TreeNode) -> TreeNode:
# if not root:
# return
# self.convertBST(root.right)
# root.val += self.val
# self.val = root.val
# self.convertBST(root.left)
# return root
# def travesral(self,root):
# if not root:
# return
# self.travesral(root.right)
# root.val += self.val
# self.val = root.val
# self.travesral(root.left)
# def convertBST(self, root: TreeNode) -> TreeNode:
# self.val = 0
# self.travesral(root)
# return root
|
6c8aa894c50bc79c86e7f0229762d9db877d58ad | yang4978/LeetCode | /Python3/0333. Largest BST Subtree.py | 662 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def countNode(self,root):
if not root:
return [0,float('inf'),-float('inf')]
l = self.countNode(root.left)
r = self.countNode(root.right)
if l[2]<root.val<r[1]:
return [1+l[0]+r[0],min(l[1],root.val),max(r[2],root.val)]
return [max(l[0],r[0]),-float('inf'),float('inf')]
def largestBSTSubtree(self, root: TreeNode) -> int:
res = self.countNode(root)
return res[0]
|
e22f54173153779b1d010c781a4611e3c67550ec | yang4978/LeetCode | /Python3/0549. Binary Tree Longest Consecutive Sequence II.py | 994 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def traversal(self,root):
if not root:
return [1,1]
neg = 1
pos = 1
if root.left:
nl,pl = self.traversal(root.left)
if root.val - root.left.val == 1:
pos = max(pos,pl+1)
elif root.val - root.left.val == -1:
neg = max(neg,nl+1)
if root.right:
nr,pr = self.traversal(root.right)
if root.val - root.right.val == 1:
pos = max(pos,pr+1)
elif root.val-root.right.val == -1:
neg = max(neg,nr+1)
self.res = max(self.res,pos,neg,pos+neg-1)
return [neg,pos]
def longestConsecutive(self, root: TreeNode) -> int:
self.res = 0
self.traversal(root)
return self.res
|
8e14dba3414955281a929d243d5f2432a9be9935 | yang4978/LeetCode | /Python3/0124. Binary Tree Maximum Path Sum.py | 1,122 | 3.609375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
max_value = -float('inf')
def PathSum(self,root):
if not root:
return -float('inf')
l = self.PathSum(root.left)
r = self.PathSum(root.right)
max_path_sum = max(l,r,0) + root.val
self.max_value = max(self.max_value, l + r + root.val, max_path_sum)
return max_path_sum
def maxPathSum(self, root: TreeNode) -> int:
res = self.PathSum(root)
return self.max_value
# def PathSum(self,root):
# if not root:
# return [-float('inf'),-float('inf')]
# max_l, l = self.PathSum(root.left)
# max_r, r = self.PathSum(root.right)
# max_value = max(max_l, max_r, l, r, l + r + root.val, root.val)
# max_path_sum = max(l,r,0) + root.val
# return [max_value,max_path_sum]
# def maxPathSum(self, root: TreeNode) -> int:
# res = self.PathSum(root)
# return max(res)
|
a74072cc0077517c67acfd7a4790a8426b79c813 | yang4978/LeetCode | /Python3/0099. Recover Binary Search Tree.py | 3,434 | 3.90625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# def recoverTree(self, root: TreeNode) -> None:
# """
# Do not return anything, modify root in-place instead.
# """
############ Use Morris Traversal ##############
def recoverTree(self, root: TreeNode) -> None:
first_node = None
second_node = None
last_node = TreeNode(-float('inf'))
while root:
if not root.left:
if root.val < last_node.val:
second_node = root
if not first_node:
first_node = last_node
last_node = root
root = root.right
else:
node = root.left
while node.right and node.right!=root:
node = node.right
if not node.right:
node.right = root
root = root.left
else:
node.right = None
if root.val < last_node.val:
second_node = root
if not first_node:
first_node = last_node
last_node = root
root = root.right
first_node.val, second_node.val = second_node.val, first_node.val
# ############ Use Inorder Traversal ##############
# def visitAllLeft(self,stack):
# while stack[-1].left:
# stack.append(stack[-1].left)
# def recoverTree(self, root: TreeNode) -> None:
# """
# Do not return anything, modify root in-place instead.
# """
# stack = [root]
# self.visitAllLeft(stack)
# last_val = -float('inf')
# first_node = None
# second_node = None
# while stack:
# node = stack.pop()
# if node.right:
# stack.append(node.right)
# self.visitAllLeft(stack)
# if first_node and node.val<first_node.val and node.val<last_val:
# second_node = node
# if not first_node and stack and node.val>stack[-1].val:
# first_node = node
# last_val = node.val
# first_node.val, second_node.val = second_node.val, first_node.val
############ Use Hashmap and Inorder Traversal ##############
# def visitAllLeft(self,stack):
# while stack[-1].left:
# stack.append(stack[-1].left)
# def recoverTree(self, root: TreeNode) -> None:
# """
# Do not return anything, modify root in-place instead.
# """
# arr = []
# node_map = {}
# stack = [root]
# self.visitAllLeft(stack)
# while stack:
# node = stack.pop()
# node_map[node.val] = node
# arr.append(node.val)
# if node.right:
# stack.append(node.right)
# self.visitAllLeft(stack)
# sorted_arr = sorted(arr)
# for i in range(len(arr)):
# if arr[i] != sorted_arr[i]:
# break
# node_map[arr[i]].val = sorted_arr[i]
# node_map[sorted_arr[i]].val = arr[i]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.