blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d102f2726a361dc4fcd14fff34e0c7b7edf9cfe6 | DionEngels/PLASMON | /test codes/test_plot.py | 1,866 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 7 13:13:07 2020
@author: s150127
"""
import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt
def gaussian(height, center_x, center_y, width_x, width_y):
"""Returns a gaussian function with the given parameters"""
width_x = float(width_x)
width_y = float(width_y)
return lambda x,y: height*np.exp(
-(((center_x-x)/width_x)**2+((center_y-y)/width_y)**2)/2)
def moments(data):
"""Returns (height, x, y, width_x, width_y)
the gaussian parameters of a 2D distribution by calculating its
moments """
total = data.sum()
X, Y = np.indices(data.shape)
x = (X*data).sum()/total
y = (Y*data).sum()/total
col = data[:, int(y)]
width_x = np.sqrt(np.abs((np.arange(col.size)-y)**2*col).sum()/col.sum())
row = data[int(x), :]
width_y = np.sqrt(np.abs((np.arange(row.size)-x)**2*row).sum()/row.sum())
height = data.max()
return height, x, y, width_x, width_y
def fitgaussian(data):
"""Returns (height, x, y, width_x, width_y)
the gaussian parameters of a 2D distribution found by a fit"""
params = moments(data)
errorfunction = lambda p: np.ravel(gaussian(*p)(*np.indices(data.shape)) -
data)
p, success = optimize.leastsq(errorfunction, params)
p2 = optimize.least_squares(errorfunction, params)
return [p2.x, p2.nfev]
# Create the gaussian data
Xin, Yin = np.mgrid[0:9, 0:9]
data = gaussian(3, 2, 4, 2, 2)(Xin, Yin) #+ np.random.random(Xin.shape)
loops = range(0,1)
for loop in loops:
params, nfev = fitgaussian(data)
fit = gaussian(*params)
#plt.matshow(data)
plt.imshow(data, extent=[0,data.shape[0],data.shape[0],0], aspect='auto')
plt.scatter(params[2]+.5, params[1]+.5, s=500, c='red', marker='x', alpha=0.5)
plt.title("Test")
plt.show() |
41a30f28f4204c0b546d49c6b0d6f8a05c7a9ef2 | Arjun-Pinpoint/Code-Book | /Python/Composite.py | 224 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 21 16:32:29 2019
@author: Arjun
"""
n=int(input())
f=0
for i in range(2,n):
if n%i==0:
f=1
break
if f==0:
print("no")
else:
print("yes")
|
c2774c7df38827415fbae9e51b9402143bf23350 | MarloDelatorre/leetcode | /0103_Binary_Tree_Zigzag_Level_Order_Traversal.py | 1,335 | 3.84375 | 4 | from collections import deque
from typing import List
from unittest import main
from datastructures.binarytree import TreeNode, binarytree
from testutil import ListOfListsTestCase
def zigzagLevelOrder(root: TreeNode) -> List[List[int]]:
if not root:
return []
left_to_right = True
queue = deque([root])
levels = []
while queue:
size = len(queue)
level = deque()
for _ in range(size):
node = queue.popleft()
if left_to_right:
level.append(node.val)
else:
level.appendleft(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
levels.append(level)
left_to_right = not left_to_right
return [list(level) for level in levels]
class Test(ListOfListsTestCase):
def test_given_case(self):
self.assert_list_of_lists_equal(
zigzagLevelOrder(binarytree([3, 9, 20, None, None, 15, 7])),
[[3], [20, 9], [15, 7]]
)
def test_empty_tree(self):
self.assert_list_of_lists_equal(zigzagLevelOrder(None), [])
def test_root_node_only(self):
self.assert_list_of_lists_equal(zigzagLevelOrder(TreeNode(1)), [[1]])
if __name__ == "__main__":
main() |
2e53bd9ed404aac01f18dfd8540ce76552922649 | emilianoNM/Clase2018Tecnicas | /palindromo.py | 641 | 4.09375 | 4 | print ("Palindromo\n")
print ("Tecnicas de programacion\n")
print ("Este programa le dice si una secuencia de numeros, frase o palabra\n")
print ("es palindroma o no, osea, que significa lo mismo si se lee de\n ")
print ("derecha a izquierda y viceversa\n")
palabra1 = raw_input("Ingrese la palabra\n\n")
#.lower hace que todas las letras se hagan minuculas
#.replace quita los espacio y junta la frase
palabra1 = palabra1.lower().replace(' ','')
#invirte la palabra con [::-1]
palabra2 = palabra1[::-1]
if palabra2 == palabra1:
print "La frase que ingreso es palindroma"
else:
print"La frase que ingreso no es palindroma"
|
f6bbc3ec567514089f5035ed4236f5c088b36ade | here0009/LeetCode | /Python/FrogPositionAfterTSeconds.py | 3,346 | 3.640625 | 4 | """
Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from the vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices it jumps randomly to one of them with the same probability, otherwise, when the frog can not jump to any unvisited vertex it jumps forever on the same vertex.
The edges of the undirected tree are given in the array edges, where edges[i] = [fromi, toi] means that exists an edge connecting directly the vertices fromi and toi.
Return the probability that after t seconds the frog is on the vertex target.
Example 1:
Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4
Output: 0.16666666666666666
Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666.
Example 2:
Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7
Output: 0.3333333333333333
Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1.
Example 3:
Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 20, target = 6
Output: 0.16666666666666666
Constraints:
1 <= n <= 100
edges.length == n-1
edges[i].length == 2
1 <= edges[i][0], edges[i][1] <= n
1 <= t <= 50
1 <= target <= n
Answers within 10^-5 of the actual value will be accepted as correct
"""
from collections import defaultdict
class Solution:
def frogPosition(self, n: int, edges, t: int, target: int) -> float:
visited = [0]*(n+1)
e_dict = defaultdict(list)
for p,q in edges:
e_dict[p].append(q)
e_dict[q].append(p)
# print(e_dict)
prob_dict = {1:1}
visited[1] = 1
while t > 0:
prob_dict2 = dict()
for k,v in prob_dict.items():
children = set()
for c in e_dict[k]:
if visited[c] == 0:
children.add(c)
visited[c] = 1
len_children = len(children)
if len_children == 0:
prob_dict2[k] = v
else:
for c in children:
prob_dict2[c] = v/len_children
if prob_dict == prob_dict2:
break
prob_dict = prob_dict2
# print(prob_dict)
t -= 1
if target in prob_dict:
return prob_dict[target]
else:
return 0
S = Solution()
n = 7
edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]]
t = 2
target = 4
print(S.frogPosition(n,edges,t,target))
n = 7
edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]]
t = 1
target = 7
print(S.frogPosition(n,edges,t,target))
n = 7
edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]]
t = 20
target = 6
print(S.frogPosition(n,edges,t,target))
n = 3
edges = [[2,1],[3,2]]
t = 1
target = 2
print(S.frogPosition(n,edges,t,target))
|
6e5ed24b487825aa39827078b726d6d8e8b4a5b4 | stoyaneft/HackBulgariaProgramming-101 | /week5/1-sqlite-starter/create_company.py | 1,211 | 3.5625 | 4 | import sqlite3
db = sqlite3.connect('company.db')
db.row_factory = sqlite3.Row
cursor = db.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS employees(id INTEGER PRIMARY KEY, name TEXT,
monthly_salary INTEGER, yearly_bonus INTEGER, position TEXT)
''')
emloyee_Ivan = ("Ivan Ivanov", 5000, 10000, "Software Developer")
emloyee_Rado = ("Rado Rado", 500, 0, "Technical Support Intern")
employee_Ivo = ("Ivo Ivo", 10000, 100000, "CEO")
employee_Petar = ("Petar Petrov", 3000, 1000, "Marketing Manager")
employee_Maria = ("Maria Georgieva", 8000, 10000, "COO")
cursor.execute('''
INSERT INTO employees(name, monthly_salary, yearly_bonus, position)
VALUES(?,?,?,?)''', emloyee_Ivan)
cursor.execute('''
INSERT INTO employees(name, monthly_salary, yearly_bonus, position)
VALUES(?,?,?,?)''', emloyee_Rado)
cursor.execute('''
INSERT INTO employees(name, monthly_salary, yearly_bonus, position)
VALUES(?,?,?,?)''', employee_Ivo)
cursor.execute('''
INSERT INTO employees(name, monthly_salary, yearly_bonus, position)
VALUES(?,?,?,?)''', employee_Petar)
cursor.execute('''
INSERT INTO employees(name, monthly_salary, yearly_bonus, position)
VALUES(?,?,?,?)''', employee_Maria)
db.commit()
|
729a22cfc797c8bbc2a6aa8016e01e1a82dcaab8 | aaroncymor/codefights | /solved/sorted_by_guide.py | 1,162 | 3.515625 | 4 | def SortByGuide(a,guide):
sort_a = []
sort_guide = []
index = []
for i in range(len(a)):
if guide[i] != -1:
sort_a.append(a[i])
sort_guide.append(guide[i])
index.append(i)
restart = False
i = 0
while True:
if (i + 1) < len(sort_guide):
if sort_guide[i] > sort_guide[i + 1]:
temp = sort_guide[i + 1]
sort_guide[i + 1] = sort_guide[i]
sort_guide[i] = temp
temp = sort_a[i + 1]
sort_a[i + 1] = sort_a[i]
sort_a[i] = temp
restart = True
if restart and i == len(sort_guide) - 1:
restart = False
i = 0
elif not restart and i == len(sort_guide) - 1:
break
else:
i += 1
for i in range(len(index)):
a[index[i]] = sort_a[i]
return a
print SortByGuide([27, 67, 80, 38, 21],[2, 5, 3, 1, 4])
print SortByGuide([70, 10, 15, 800, 400, 4, 225, 438, 509, 1000],[6, 1, 4, -1, -1, 2, -1, -1, 5, 3])
print SortByGuide([700, 800, 400, 100, 900, 325],[2, -1, 1, -1, 3, -1])
print SortByGuide([2, 5, 3, 1, 4, 70, 8],[2, 5, 1, 3, -1, 4, -1])
print SortByGuide([45, 56, 78],[-1, 2, 1])
print SortByGuide([56, 78, 3, 45, 4, 66, 2, 2, 4],[3, 1, -1, -1, 2, -1, 4, -1, 5]) |
b1386980559e04a15c06adb7a75bb2d6c5d3dfc4 | kabaliisa/levelup | /multiple.py | 204 | 3.765625 | 4 | def multiple():
numbers = range(2000, 3201)
num = []
for number in numbers:
if number % 7 == 0 and number % 5 != 0:
num.append(number)
return num
print(multiple())
|
3a9b328593cf6fc91376ee5bcad559c990c6c1d3 | meryreddoor/Bitcoins_Scraping | /src/main.py | 1,692 | 3.515625 | 4 | import funciones
import argparse
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
def parser():
parser = argparse.ArgumentParser(description='Selecciona los datos que quieres ver')
parser.add_argument('x', type=str, help='Moneda Seleccionada')
parser.add_argument('y', type=str,help='Fecha')
args = parser.parse_args()
return args
def main():
args = parser()
x,y = args.x, args.y
df = pd.read_csv("OUTPUT/final_table.csv")
info(df,x,y)
#Historical graphic - Shows all the 'Close Prices' from 2013 to 2019
funciones.graphic(df)
#S. Desviation graphic - Shows the variation rate for each day.
funciones.variation(df).plot.bar()
plt.gcf().set_size_inches(10,10)
plt.show()
def info(table,x,y):
print('-------------------------------------------------------------')
print('\n')
print(f"Características moneda {x} a fecha {y}")
print('\n')
filter_table=monedaFecha(table,x,y)
print(filter_table)
print('\n')
print('-------------------------------------------------------------')
print('\n')
print(f'CAPITALIZACION BURSATIL: Media Historica de {x} (Desde 2013 a 2019)')
print('\n')
print(table.groupby(['Currency']).get_group(x).mean()[3:4])
print('\n')
print('-------------------------------------------------------------')
print('\n')
print('PRECIO DE CIERRE DE TODAS MONEDAS EN MEDIAS, D.STA, GAUSS..')
print('\n')
print(funciones.describe(table))
return filter_table
def monedaFecha(final_table,x,y):
filter_table=funciones.descriptions(final_table, x, y)
return filter_table
if __name__ == '__main__':
main()
|
32b348fdd07dc5913a7f82e0910686f359f64c4f | Sultan1007/Homeworks.py | /Homework2.py | 1,296 | 3.8125 | 4 | # Complex
# 1) magic method (+, -, /, *)
# 2) return Complex ->
# complex2 = Complex(2, 5)
# complex3 = complex1 + complex2
# 3) __str__
class Complex:
def __init__(self, real=0, imag=0):
self.real = real
self.imag = imag
def __add__(self, other):
return Complex(self.real + other.real, self.imag + other.imag)
def __sub__(self, other):
return Complex(self.real - self.real, self.imag - other.imag)
def __truediv__(self, other):
return Complex(self.real / other.real, self.imag / other.imag)
def __mul__(self, other):
real = self.real * other.real - self.imag * other.imag
imag = self.imag * other.imag + self.imag * other.imag
new_complex = Complex(real, imag)
return new_complex
def __str__(self):
return f"{self.real} + {self.imag}i" if self.imag >= 0 else f'{self.real}{self.imag}i'
complex1 = Complex(1, 2)
complex2 = Complex(2, 5)
result = complex1 * complex2
complex3 = complex1 + complex2
complex4 = complex1 + complex2
complex5 = complex1 - complex2
complex6 = complex1 / complex2
print(complex3.real)
print(complex3.imag)
print()
print(complex4.real)
print(complex4.imag)
print()
print(complex5.real)
print(complex5.imag)
print()
print(complex6.real)
print(complex6.imag)
|
42fd2a28378fb6341f6d443aa07e77df5278f1f7 | kangyongxin/Backup | /MuscleMemory/run.py | 5,414 | 3.671875 | 4 | """
复现Dyna-Q算法, 环境是之前的maze
参考 : https://github.com/thomas861205/RL-HW3
1.实现基本 的 one step q learning
2. 实现一个记录状态动作对儿的模型
3. planning 引入到 q表的 更新中
"""
"""
Qlearning 的基本步骤:
1 初始化 q表
2 观测值
3 用 greedy方法采样 动作
4 实施动作 得到 反馈
5 用反馈值 和状态动作一起 更新q表
6 循环
"""
"""
需要外加的部分:
model 要初始化
model 每次有新的值就要更新一下,(这里其实只是把见到的状态记录一下而已,并没有训练什么函数,是个确定性模型)
然后每次迭代之后,都要有n次planning的过程,n是我们要比较的量
"""
from baselines.MuscleMemory.maze_env import Maze
from baselines.MuscleMemory.RL_brain import QLearningTable,InternalModel
import matplotlib.pyplot as plt
import math
import numpy as np
"""
obs are something we see
states are something we know
state is the hidden variable
"""
def obs_to_state(obs):
"""
obs=[45.0, 5.0, 75.0, 35.0]
第1行 第2列
state = 2
state:
1 2 3 4 5
6 7 8 9 10
...
"""
states= ((obs[1]+15.0 - 20.0)/40)*5 + (obs[0] +15.0 - 20.0)/40 +1
return int(states)
"""
stochastic characters of trj
先后经历的状态,以及相应状态的个数
"""
def stochastic_trj(seq):
print("trj,", seq)
u_state = [] # list of the unique state
count_state = [] # list of the number of state
k = 0
for i in seq:
if u_state.count(i) == 0:
count_state.append(seq.count(i))
u_state.append(i)
k = k + 1
print("u_s", u_state)
print("count_s", count_state)
return u_state, count_state
def update():
steps_plot = []
a =[]
e=[]
r =[]
oo = []
for i in range(25):
oo.append(i)
n_state= len(oo)
n_trj= 100
for episode in range(n_trj):
# initial observation
observation = env.reset()
steps = 0
tao=0
trj = []
while True:
# fresh env
state = obs_to_state(observation)
trj.append(state)
#env.render()
steps= steps+1
tao=tao+1
# RL choose action based on observation
action = RL.choose_action(str(observation))
#action = RL.random_action(str(observation))
# RL take action and get next observation and reward
observation_, reward, done = env.step(action)
if dynaQplus :
if model.check(observation, action, observation_, reward):
tao=tao-1
reward = reward - kappa*math.sqrt(tao)
# RL learn from this transition
#print(reward)
RL.learn(str(observation), action, reward, str(observation_))
# 根新模型
model.store(observation, action, observation_, reward)
# swap observation
observation = observation_
""" planning n """
for n in range(plan_n):
(stateP, actionP, next_stateP, rewardP) = model.sample()#这里是随机采的,但是可以与当前状态相关地采吗?
RL.learn(str(stateP), actionP, rewardP, str(next_stateP))
# break while loop when end of this episode
if done:
break
steps_plot.append(steps)
#________________________________________
#
[u_state, count_state] = stochastic_trj(trj)
a.append(u_state)
e.append(trj)
r.append(count_state)#每条轨迹的统计特性。状态出现的次数
p = np.zeros((n_state, 1))
u = np.zeros((n_state, 1))
uo = np.zeros((n_state, 1))
for j in range(n_trj): # 第j条轨迹
for i in range(len(oo)): # 某个状态
for w in range(len(a[j])): # 第w个 出现
if a[j][w] == oo[i]:
p[i] = p[i] + sum(r[j][0:w]) # 第j条轨迹中第i个状态出现之前所有的状态频率统计
u[i] = u[i] + w # 出现的顺序 越晚月重要?轨迹中
uo[i] = uo[i] + r[j][w] # 第 i 个状态在所有轨迹中出现的次数总和
print("oo", oo)
print("p", p)
print("u", u)
print("uo", p / uo)
temp= uo
# # plt.plot(oo,p)
# # plt.show()
# plt.plot(oo, p / uo)
# plt.show()
# # 第一行第一列图形
# ax1 = plt.subplot(3, 1, 1)
# # 第一行第二列图形
# ax2 = plt.subplot(3, 1, 2)
# # 第二行
# ax3 = plt.subplot(3, 1, 3)
#
# plt.sca(ax1)
# # 绘制红色曲线
# plt.plot(oo, p, color='red',marker='*')
# plt.ylabel('p')
#
# plt.sca(ax2)
# # 绘制蓝色曲线
# plt.plot(oo, u, color='blue',marker='*')
# plt.ylabel('u')
#
# plt.sca(ax3)
# # 绘制绿色曲线
# plt.plot(oo, temp, color='green',marker='*')
# plt.ylabel('uo')
#
# plt.show()
plt.plot(steps_plot, label='%d steps planning ahead' % (plan_n))
plt.show()
# end of game
print('game over')
env.destroy()
if __name__ == "__main__":
env = Maze()
dynaQplus= False
if dynaQplus:
kappa=0.00001
RL = QLearningTable(actions=list(range(env.n_actions)))
model = InternalModel()
plan_n = 50
env.after(100, update)
env.mainloop() |
4584a37ca2e60108fa95b50215978964311f66ba | fank-cd/python_leetcode | /Problemset/swap-nodes-in-pairs/swap-nodes-in-pairs.py | 599 | 3.8125 | 4 |
# @Title: 两两交换链表中的节点 (Swap Nodes in Pairs)
# @Author: 2464512446@qq.com
# @Date: 2020-11-23 15:08:45
# @Runtime: 40 ms
# @Memory: 13.5 MB
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
first_node = head
second_node = head.next
first_node.next = self.swapPairs(second_node.next)
second_node.next = first_node
return second_node
|
cf6eaad8b31dc7ec3b4213568efa629b44176c97 | SB1996/Python | /Object Otiented/Polymorphism/OperatorOverloading.py | 2,030 | 4.1875 | 4 | # Operator Overloading in Python ...!
# Behind the seen in Python
# print(f"Addition : {10+20}")
# # --or--
# print(f"Addition : {int.__add__(10, 20)}")
#
# print(f"Result : {'Santanu' + ' Banik'}")
# # --or--
# print(f"Result : {str.__add__('Santanu', ' Banik')}")
class OverloadOperator:
def __init__(self, arg):
self.Data = arg
# adding two objects ...
def __add__(self, other):
return self.Data + other.Data
obj00 = OverloadOperator(100)
obj01 = OverloadOperator(200)
print(obj00 + obj01)
strObj00 = OverloadOperator("Santanu ")
strObj01 = OverloadOperator("Banik")
print(strObj00 + strObj01)
##########################################
class complex:
def __init__(self, arg00, arg01):
self.arg00 = arg00
self.arg01 = arg01
# adding two objects ...
# Overload '+' Operator
def __add__(self, other):
return self.arg00 + other.arg00, self.arg01 + other.arg01
def __str__(self):
return self.arg00, self.arg01
object00 = complex(10, 20)
object01 = complex(50, 60)
result = object00 + object01
# Behind the seen....in python ....
#
# object00 = complex(10, 20) ==> object00.arg00 = 10
# object00.arg01 = 20
#____________________________________________________
# object01 = complex(50, 60) ==> object01.arg00 = 50
# object01.arg01 = 60
#____________________________________________________
# object00 + object01 ==> __add__(object00, object01):
# return (object00.arg00 + object01.arg00, object00.arg01 + object01.arg01)
# [(10 + 50), (20 + 60)] ==> (60, 80)
print(f"Result : {result}")
obj00 = complex("A", "B")
# obj00 = complex("A", "B") ==> obj00.arg00 = "A"
# obj00.arg01 = "B"
obj01 = complex("Z", "Y")
# obj01 = complex("Z", "Y") ==> obj01.arg00 = "Z"
# obj01.arg01 = "Y"
result00 = obj00 + obj01
print(f"Result : {result00}") |
4c3894a2a989d04478bb721661c455a7051f7350 | GaborVarga/Exercises_in_Python | /46_exercises/4.py | 820 | 4.3125 | 4 | #!/usr/bin/env python
#######################
# Author: Gabor Varga #
#######################
# Exercise description :
#
# Write a function that takes a character (i.e. a string of length 1)
# and returns True if it is a vowel, False otherwise.
#
# http://www.ling.gu.se/~lager/python_exercises.html
from pip._vendor.distlib.compat import raw_input
###############
# Function(s) #
###############
def checkchar (c):
vowels = ['a','e','i','o','u']
if c in vowels:
print("\nThis is a vowel!")
return True
else :
print("This is not a vowel.")
return False
##########
# Script #
##########
singlechar = raw_input("Please type 1 character: ")
while len(singlechar) != 1 :
singlechar = raw_input("Please type only 1 character: ")
print(checkchar(singlechar))
|
ce2d1c23c1a1855fe73b2d766d3525a4b18868f5 | Yinlianlei/Work | /AI-Learn/test-5_1.py | 2,270 | 3.984375 | 4 | # Let's do that again.
# We will repeat what we did in step 3, but change the decision boundary.
import warnings
warnings.filterwarnings("ignore")
import matplotlib.pyplot as graph
# %matplotlib inline
graph.rcParams['figure.figsize'] = (15,5)
graph.rcParams["font.family"] = 'DejaVu Sans'
graph.rcParams["font.size"] = '12'
graph.rcParams['image.cmap'] = 'rainbow'
import pandas as pd
import numpy as np
from sklearn import linear_model
dataset = pd.read_csv('Data/football_data.txt', index_col = False, sep = '\t', header = 0)
print(dataset.head())
###
# REPLACE THE <numberOfGoals> WITH THE NUMBER OF GOALS YOU WANT TO EVALUATE
###
p = 2
###
# Here we build the new logistic regression model.
# The C=200 is where we change the decision boundary.
clf = linear_model.LogisticRegression(C=200)
###
# REPLACE <addWonCompetition> BELOW WITH 'won_competition' (INCLUDING THE QUOTES)
train_Y = dataset['won_competition']
# REPLACE <addAverageGoals> BELOW WITH 'average_goals_per_match' (INCLUDING THE QUOTES)
train_X = dataset['average_goals_per_match']
# This step fits (calculates) the model
# We are using our feature (x - number of goals scored) and our outcome/label (y - won/lost)
clf.fit(train_X[:, np.newaxis], train_Y)
# This works out the loss
def sigmoid(train_X):
return 1 / (1 + np.exp(-train_X))
X_test = np.linspace(0, 3, 300)
loss = sigmoid(X_test * clf.coef_ + clf.intercept_).ravel()
# This makes the prediction for your chosen number of goals.
probOfWinning = clf.predict_proba([[p]])[0][1]
# This prints out the result.
print("Probability of winning this year")
print(str(probOfWinning * 100) + "%")
# This plots the result.
graph.scatter(train_X, train_Y, c = train_Y, marker = 'D')
graph.yticks([0, probOfWinning, 1], ['No = 0.0', round(probOfWinning,3), 'Yes = 1.0'])
graph.plot(X_test, loss, color = 'gold', linewidth = 3)
graph.plot(p, probOfWinning, 'ko') # result point
graph.plot(np.linspace(0, p, 2), np.full([2],probOfWinning), dashes = [6, 3], color = 'black') # dashed lines (to y-axis)
graph.plot(np.full([2],p), np.linspace(0, probOfWinning, 2), dashes = [6, 3], color = 'black') # dashed lines (to x-axis)
graph.ylabel("Competition Win Likelihood")
graph.xlabel("Average number of goals per match")
graph.show()
|
c16a18effe2adfa7fddf29c5007a96a4d646c0d0 | hero5512/leetcode | /problem179.py | 1,096 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 05 16:44:54 2017
@author: Crystal
思路:1、依次选择首位最大的元素放在第一位
2、如果首位相同就比较第二位,第二位大的依次排列,依次类推
[3, 30, 34, 5, 9]=9534330
1、python两个字符串居然可以比较大小
2、交换两个变量有个简便的形式
3、除此之外注意sort还可以自定义比较函数
4、判断字符串全为0的方法int("".join(num))
"""
class Solution:
# @param {integer[]} nums
# @return {string}
def largestNumber(self, nums):
if not any(nums):
return "0"
for i in xrange(len(nums)):
for j in xrange(len(nums)-1,i,-1):
if self.compare(nums[j],nums[j-1]):
nums[j],nums[j-1]=nums[j-1],nums[j]
print "".join(map(str,nums))
def compare(self,num1,num2):
return str(num1)+str(num2)>str(num2)+str(num1)
if __name__=='__main__':
sol=Solution()
sol.largestNumber([3, 30, 34, 5, 9]) |
dc989ac64b6544e2fcc0e56b7b9a689a52362568 | Pizzabakerz/codingsuperstar | /python-codes/codes/15.lambda_map_example/lamba.py | 346 | 4.09375 | 4 | # lambda function
# regular expression
# maps
# normal funtiion
def multi(mul): # replace this with lambda
return mul*5
print(multi(2))
multi = lambda a:a*5 # lambda function
print(multi(2))
# example for lambda funtion as filter
mylist = [1,2,3,4,5,6,7,8,9,0]
list2 = list(filter(lambda x:(x%2 == 0),mylist))
print(list2) |
4995806e6824eb0a3c390112117ea8e319734b90 | rohernandezz/Serifas | /Scripts/SandwichTorneo_3.py | 534 | 3.796875 | 4 | upper = "AÁBCDEFGHIJKLMNÑOPQRSTUÜV&"
lower = "aábcdefghijklmnñopqrstuüv"
nums = "0136"
punct = ".,"
def letterSandwicher(letters, bread):
sandwich = bread
for letter in letters:
sandwich += letter + bread
return sandwich
print(letterSandwicher(upper,"H"))
print(letterSandwicher(upper,"O"))
print(letterSandwicher(lower,"n"))
print(letterSandwicher(lower,"o"))
print(letterSandwicher(nums,"H"))
print(letterSandwicher(nums,"O"))
print(letterSandwicher(punct,"H"))
print(letterSandwicher(punct,"O")) |
9b0af5952d6b8bba8df4a039c968a066a9fb4e95 | adam-xiao/PythonMasterclass | /Sequences/number_lists.py | 652 | 4.09375 | 4 | even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
# print(min(even))
# print(max(even))
# print(min(odd))
# print(max(odd))
#
# print()
#
# print(len(even))
# print(len(odd))
#
# print()
#
# print("mississippi".count("s"))
# print("mississippi".count("iss"))
# print("mississippi".count("issi")) # the count is not 2 since letters are reused, aka middle "i"
# method is the same as function, except its bound to an object
even.extend(odd) # adds the items in odd to even
print(even)
even.sort()
print(even)
another_even = even
print(even)
even.sort(reverse=True) # Does not create a new list
print(even)
print(another_even) # even is same as another_even |
72b769b627b8360650eb76c555419d7c3f8b16b8 | mayurigaikwad1724/function.py | /largest num.py | 213 | 3.875 | 4 | def function_largest():
num=[50,40,23,70,56,12,5,10,7]
largest=num[0]
i=0
while i<len(num):
if num[i]>largest:
largest=num[i]
i=i+1
print(largest)
function_largest() |
f88d04bae0336838335507261a8cb1a8e666bff0 | jonm/prep-mint-txns | /prep-mint-txns.py | 745 | 3.625 | 4 | #!/usr/bin/env python
# Copyright (C) 2018 Jonathan T. Moore
import csv
import datetime
import sys
def excerpt_month(in_f, out_f, month, year):
reader = csv.reader(in_f)
writer = csv.writer(out_f)
first = True
for row in reader:
if first:
writer.writerow(row)
first = False
continue
d = datetime.datetime.strptime(row[0], "%m/%d/%Y")
if d.month == month and d.year == year:
writer.writerow(row)
if __name__ == "__main__":
if len(sys.argv) > 1:
month = int(sys.argv[1])
year = int(sys.argv[2])
else:
now = datetime.datetime.now()
month = now.month
year = now.year
excerpt_month(sys.stdin, sys.stdout, month, year)
|
27fde534c776279cbb37b0b5f0937922410537a5 | alu-rwa-dsa/Data-Structures-and-Algorithms-Python | /implementation_5/test_dLinkedList.py | 2,496 | 3.640625 | 4 | import unittest # import the unittest module to test the class methods
from implementation_5.doubly_linked_list import DLinkedList
from implementation_5.doubly_linked_list import Node
class TestSLinkedList(unittest.TestCase):
def test_prepend(self):
myObj = DLinkedList() # initialize a new object of the class DLinkedList
myObj.prepend(120) # prepend a new value to the beginning of the linked list
myObj.prepend(130)
self.assertEqual(myObj.get_head(), 130) # check the data in the head node
self.assertEqual(myObj.get_tail(), 120) # check the data in the tail node
def test_pop_first(self):
myObj = DLinkedList()
myObj.prepend(120)
myObj.prepend(130)
self.assertEqual(myObj.pop_first(), 130) # delete the head 130
def test_append(self):
myObj = DLinkedList()
myObj.append(120)
myObj.append(130)
self.assertEqual(myObj.get_head(), 120)
self.assertEqual(myObj.get_tail(), 130)
def test_pop_last(self):
myObj = DLinkedList()
myObj.append(120)
myObj.append(130)
self.assertEqual(myObj.pop_last(), 130) # delete the head 130
def test_pop_last_2(self):
"""
test deleting the last element from a non empty Linked List
"""
myObj = DLinkedList()
with self.assertRaises(IndexError):
myObj.pop_last()
def test_append_2(self):
"""
Test the head and tail after appending one value only
"""
myObj = DLinkedList()
myObj.prepend(120)
self.assertEqual(myObj.get_head(), 120)
self.assertEqual(myObj.get_tail(), 120)
def test_insert_node(self):
"""
Test inserting a node to the Linked List giving the previous node
"""
myObj = DLinkedList()
myObj.append(120)
myObj.append(100)
self.assertEqual(myObj.insert_node(Node(1000), myObj.head), [120, 1000, 100])
def test_delete_node(self):
"""
Test deleting a node from the Linked List given the node
"""
myObj = DLinkedList()
myObj.append(120)
myObj.append(100)
myObj.detete_node(myObj.head.next)
myObj.detete_node(myObj.head)
self.assertEqual(myObj.get_head(), None)
self.assertEqual(myObj.get_tail(), None)
if __name__ == '__main__':
unittest.main()
|
dcabe4e7395062c7a0982da34d05b7ed748a3d89 | mj-hd/lab_pre | /first/2.py | 538 | 3.9375 | 4 | #!/usr/bin/python
def gcd(m, n):
if n == 0:
return m
else:
return gcd(n, m % n)
def is_prime(n):
MAX_A = 10 # attempt a up to
prime = lambda a, n: a**(n-1) % n == 1 # prime condition
for a in range(2, MAX_A):
if gcd(a, n) != 1: # not disjoint
continue
if not(prime(a, n)):
return False
return True
print "please input a number:"
n = input()
result = "%d is " % n
if is_prime(n):
result += "prime"
else:
result += "not prime"
print result
|
b4d1d11a094028c621368cd8a8c2d1729d0bda88 | Wictor-dev/ifpi-ads-algoritmos2020 | /iteração/24_salario_numero_filhos.py | 800 | 3.78125 | 4 | def main():
hab = int(input('Digite o numero de habitantes: '))
media = media_filhos = salario_ate_mil = 0
count = 1
while count <= hab:
print(f'### funcionario {count} ###')
salario = int(input('Digite o salário: '))
filhos = int(input('Digite o numero de filhos: '))
media += salario
media_filhos += filhos
if(salario <= 1000):
salario_ate_mil += 1
count += 1
media = media / hab
media_filhos = media_filhos / hab
print(f'A média dos salários é: R$ {media:.2f} ') # A)
print(f'A média de filhos é {media_filhos}') #B)
salario_ate_mil = salario_ate_mil * 100 / hab
print(f'{salario_ate_mil:.0f}% dos habitantes possuem salario de até 1000 reais') #C)
main()
|
994c5c68a025812d29ad20ffa34de19aa8c4146d | kentronnes/datacamp | /Python_Data_Science_Toolbox_Part_2/List_comprehensions_and_generators/List_comprehensions_vs_generators.py | 1,715 | 4.34375 | 4 | # List comprehensions vs generators
# You've seen from the videos that list comprehensions and generator
# expressions look very similar in their syntax, except for the use
# of parentheses () in generator expressions and brackets [] in list
# comprehensions.
# In this exercise, you will recall the difference between list
# comprehensions and generators. To help with that task, the
# following code has been pre-loaded in the environment:
# # List of strings
fellowship = ['frodo', 'samwise', 'merry', 'aragorn', 'legolas'
, 'boromir', 'gimli']
# # List comprehension
fellow1 = [member for member in fellowship if len(member) >= 7]
# # Generator expression
fellow2 = (member for member in fellowship if len(member) >= 7)
# Try to play around with fellow1 and fellow2 by figuring out their
# types and printing out their values. Based on your observations
# and what you can recall from the video, select from the options
# below the best description for the difference between list
# comprehensions and generators.
# INSTRUCTIONS
# Possible Answers
# List comprehensions and generators are not different at all; they
# are just different ways of writing the same thing.
# A list comprehension produces a list as output, a generator
# produces a generator object.
# A list comprehension produces a list as output that can be
# iterated over, a generator produces a generator object that can't
# be iterated over.
In [1]: print(fellow1)
['samwise', 'aragorn', 'legolas', 'boromir']
In [2]: print(fellow2)
<generator object <genexpr> at 0x7f049c58ff10>
In [3]: type(fellow1)
Out[3]: list
# Answer: A list comprehension produces a list as output, a generator produces a generator object. |
674f8bff466a3bf1287ecd185cec3729244d1327 | AkshayKumar-n/Project | /bookmenudriven.py | 1,185 | 3.9375 | 4 |
bookslist=[]
class bookDetails:
def AddBook(self,title,description,price,publisher,distributor):
dict2={"title":title,"description":description,"price":price,"publisher":publisher,"distributor":distributor}
bookslist.append(dict2)
obj1=bookDetails()
while(True):
print("1. add book ")
print("2. view book ")
print("3. View all books in alphabetical order ")
print("4. search a book using title")
print("5. exit")
choice=int(input("Enter a choice: "))
if choice==1:
title=input("Enter title of book: ")
description=input("Enter description of book: ")
price=input("Enter price of book: ")
distributor=input("Enter distributor of book: ")
publisher=input("Enter publisher of book: ")
obj1.AddBook(title,description,price,publisher,distributor)
if choice==2:
print(bookslist)
if choice==3:
print(sorted(bookslist,key=lambda i:i["title"]))
if choice==4:
search=input("Enter title to search product: ")
print(list(filter(lambda a:a["title"]==search,bookslist)))
if choice==5:
break |
614b3db91c471455c67ba2cbaf2a74a3afa8e2fc | jianhui-ben/leetcode_python | /Snap_523. Continuous Subarray Sum.py | 1,989 | 3.796875 | 4 | #523. Continuous Subarray Sum
#Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to a multiple of k, that is, sums up to n*k where n is also an integer.
#Example 1:
#Input: [23, 2, 4, 6, 7], k=6
#Output: True
#Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6.
class Solution:
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
##brute force: time O(n3), space O(1)
# for start in range(len(nums)-1):
# for end in range(start+1, len(nums)):
# tot= sum(nums[start:end+1])
# if tot==k or (k!=0 and tot%k==0):
# return True
# return False
# ## better brute force: O(n**2), space O(n)
# cum_sum=[0]
# temp=0
# for i in nums:
# temp+=i
# cum_sum.append(temp)
# for start in range(len(nums)-1):
# for end in range(start+1, len(nums)):
# tot= cum_sum[end+1]-cum_sum[start]
# if tot==k or (k!=0 and tot%k==0):
# return True
# return False
# hashmap + math
if len(nums)<2: return False
k=abs(k)
#special case of 0
if k==0:
for i in range(len(nums)-1):
if nums[i]==0 and nums[i+1]==0:
return True
return False
if k==1 and len(nums)>=2: return True
mod_map=collections.defaultdict(None)
mod_map[0]=-1
cum_sum=0
for i, v in enumerate(nums):
cum_sum+=v
# if cum_sum==k: return True
if k!=0:
mod=cum_sum%k
# if mod==0: return True
if mod not in mod_map:
mod_map[mod]=i
elif i-mod_map[mod]>=2:
return True
return False
|
94ace1f6fbabc9721c11d8bfa1f5f22c3218334a | millmill/scrabblegame | /Board.py | 5,220 | 3.765625 | 4 | from Square import Square
from Tile import Tile
from random import randint
class Board(Square):
def __init__(self, size=15):
super().__init__()
self._size = size
self._square_array = [[Square() for i in range(self._size)] for j in range(self._size)]
for row in range(self._size):
for col in range(self._size):
sq = self._square_array[row][col]
sq.position = [row, col]
# Size of the board correspond to how many rows and columns it will have.
# All the squares will be held in an arrays, which will create a matrix.
def __iter__(self):
for row in self._square_array:
for square in row:
yield square
def __getitem__(self, coords):
# support for indexing
# usage: single int for iterative position or tuple
# board[80], board[5][13]
x, y = self.parse_coords(coords)
return self._square_array[x][y]
def parse_coords(self, coords):
if isinstance(coords, int):
x = coords // self._size
y = coords % self._size
else:
x = coords[0]
y = coords[1]
if x < self._size and y < self._size:
return x, y
def get_square(self, coords):
# usage: single int for iterative position or tuple for x, y
# board[80], board[5][13]
x, y = self.parse_coords(coords)
return self._square_array[x][y]
def place_tile(self, coords, tile):
# coords must be tuple or an array of length 2
# Based on square's x, y coordinates, it will place
# tile into correct position on the board.
x, y = self.parse_coords(coords)
self._square_array[x][y].place_tile(tile)
def make_board(self):
# use with newly created instance of board only (blank boards)
doubleL = Tile("doubleL", 0)
tripleL = Tile("tripleL", 0)
doubleW = Tile("doubleW", 0)
tripleW = Tile("tripleW", 0)
bonus_square_colours = ["doubleL", "tripleL", "doubleW", "tripleW"]
bonus_square_values = [2, 3, 2, 3]
# creating random amount of bonus squares
double_letter = randint(15, 25) # 20
triple_letter = randint(9, 15) # 12
double_word = randint(12, 20) # 16
triple_word = randint(6, 10) # 8
for idx, num_of_bonus_squares in enumerate([double_letter, triple_letter, double_word, triple_word]):
while num_of_bonus_squares:
random_square = self._square_array[randint(0, self._size - 1)][randint(0, self._size - 1)]
# changing colour and multipliers for square
if random_square.colour == "default":
multiplier = idx % 2
if idx // 2:
random_square.word_multiplier = bonus_square_values[multiplier]
if idx % 2 == 0:
random_square.has_tile = doubleW
else:
random_square.has_tile = tripleW
else:
random_square.tile_multiplier = bonus_square_values[multiplier]
if idx % 2 == 0:
random_square.has_tile = doubleL
else:
random_square.has_tile = tripleL
random_square.colour = bonus_square_colours[idx]
num_of_bonus_squares -= 1
def __str__(self):
output = ""
line = ("----" * self._size + "-\n")
for arr in self._square_array:
output += line
for sq in arr:
if sq.is_occupied():
output += ("|" + sq.get_tile().__str__())
else:
if sq.colour != "default":
bonus = ""
if sq.tile_multiplier == 2:
bonus = "dl "
elif sq.tile_multiplier == 3:
bonus = "tl "
elif sq.word_multiplier == 2:
bonus = "dw "
elif sq.word_multiplier == 3:
bonus = "tw "
output += ("|" + bonus)
else:
output += "| "
output += "|\n"
output += line
return output
def main():
t1 = Tile("R", 1)
t2 = Tile("X", 8)
t3 = Tile("Q", 10)
print("blank board, no tiles")
b = Board()
print(b)
b.place_tile((10, 10), t1)
b.place_tile([5, 5], t2)
b.place_tile([6, 6], t3)
print("board with few tiles placed")
print(b)
print("details of individual squares")
print(b.get_square([3, 3]))
print(b.get_square([10, 10]))
print("#############################")
print("creating random board state for new game")
b2 = Board()
b2.make_board()
print("printing first 20 squares")
for i in range(20):
print(b2[i])
b2.place_tile((13, 14), t3)
print(b2)
if __name__ == "__main__":
main()
|
0fe67a243b28f5e44ed8a2b6e1120324d6e4431e | oxhead/CodingYourWay | /src/lt_740.py | 1,846 | 3.734375 | 4 | """
https://leetcode.com/problems/delete-and-earn
Related:
- lt_198_house-robber
"""
"""
Given an array nums of integers, you can perform operations on the array.
In each operation, you pick any nums[i] and delete it to earn nums[i] points. After, you must delete every element equal to nums[i] - 1 or nums[i] + 1.
You start with 0 points. Return the maximum number of points you can earn by applying such operations.
Example 1:
Input: nums = [3, 4, 2]
Output: 6
Explanation:
Delete 4 to earn 4 points, consequently 3 is also deleted.
Then, delete 2 to earn 2 points. 6 total points are earned.
Example 2:
Input: nums = [2, 2, 3, 3, 3, 4]
Output: 9
Explanation:
Delete 3 to earn 3 points, deleting both 2's and the 4.
Then, delete 3 again to earn 3 points, and 3 again to earn 3 points.
9 total points are earned.
Note:
The length of nums is at most 20000.
Each element nums[i] is an integer in the range [1, 10000].
"""
class Solution:
def deleteAndEarn(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# Time: O(n), where n = max(nums)
# Space: O(n)
# Hints:
# 1) Reduce to the house rob problem
if not nums: return 0
max_n = max(nums)
rewards = [0] * (max_n + 1)
for n in nums:
rewards[n] += n
previous, current = 0, 0
for i in range(1, len(rewards)):
previous, current = current, max(previous + rewards[i], current)
return current
if __name__ == '__main__':
test_cases = [
([], 0),
([1], 1),
([3, 4, 2], 6),
([2, 2, 3, 3, 3, 4], 9),
]
for test_case in test_cases:
print('case:', test_case)
output = Solution().deleteAndEarn(test_case[0])
print('output:', output)
assert output == test_case[1]
|
661dd9aa780fd701fdcc15f8d6fe290ece284a90 | uvula6921/algorithm_prac | /week_4/07_get_all_ways_of_theater_seat.py | 612 | 3.65625 | 4 | seat_count = 10
vip_seat_array = [2, 6, 9]
dict = {
1: 1,
2: 2
}
def fibo(n, memo):
if n in memo:
return memo[n]
memo[n] = fibo(n-1, memo) + fibo(n-2, memo)
return fibo(n-1, memo) + fibo(n-2, memo)
def get_all_ways_of_theater_seat(total_count, fixed_seat_array):
multi = 1
for i in range(len(fixed_seat_array)-1):
multi *= fibo(fixed_seat_array[i+1]-fixed_seat_array[i]-1, dict)
multi *= fibo(fixed_seat_array[0]-1, dict) * fibo(total_count - fixed_seat_array[-1], dict)
return multi
# 12가 출력되어야 합니다!
print(get_all_ways_of_theater_seat(seat_count, vip_seat_array)) |
0864af14ed0d49dcda394e790915c00be5d850c7 | StasNovikov/simple-games-on-Python | /OOP/GUI/movie_chooser2.py | 2,438 | 3.875 | 4 | # киноман-2
# Демонстрирует переключатель
from tkinter import *
class Application(Frame):
""" GUI-приложение, позволяющее выбрать один любимый жанр кино """
def __init__(self, master):
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
""" Создает элементы, с помощью которых пользователь будет выбирать """
# Метка описание
Label(self, text="Укажите ваш любимый жанр кино").grid(row=0, column=0, sticky=W)
# Метка-инструкиця
Label(self, text="Выберите ровно один:").grid(row=1, column=0, sticky=W)
# переменная для хранения сведений о единственном любимом жанре
self.favorite = StringVar()
self.favorite.set(None)
# положение "Комедия" переключателя
Radiobutton(self, text="Комедия", variable=self.favorite, value="комедия.", command=self.update_text).grid(
row=2, column=0, sticky=W)
# положение "Драма" переключателя
Radiobutton(self, text="Драма", variable=self.favorite, value="драма.", command=self.update_text).grid(
row=3, column=0, sticky=W)
# положение "Кино о любви" переключателя
Radiobutton(self, text="Кино о любви", variable=self.favorite, value="кино о любви.", command=self.update_text).grid(
row=4, column=0, sticky=W)
# текстовая область с результатами
self.resut_text = Text(self, width=40, height=5, wrap=WORD)
self.resut_text.grid(row=5, column=0, columnspan=3)
def update_text(self):
""" Обновляя текстовую область, вписывает в нее любимый жанр """
message = "Ваш любимый киножанр: "
message += self.favorite.get()
self.resut_text.delete(0.0, END)
self.resut_text.insert(0.0, message)
# Основная частт
root = Tk()
root.title("Киноман-2")
root.geometry("350x150")
app = Application(root)
root.mainloop() |
f3d29d2e7b0f37f6fce94c60602e9a7e5354cbad | mattyr3200/python | /week 5.py | 324 | 4.0625 | 4 | def week5():
name = str(input("hello, whats your name?\n"))
if not name:
print("hello world")
elif name[:4].capitalize() == "Sir ":
print("hello, Sir", name[4:].capitalize() + ". it is good to meet you.")
else:
print("hello, ", name.capitalize() + ". it is good to meet you.")
week5() |
2dcc303ec37f129ca91e7b53c47accd217b724c4 | apromessi/interviewprep | /ariana_prep/oct_practice/HR_binary_tree_problems.py | 943 | 4.0625 | 4 | '''
class Node:
def __init__(self,info):
self.info = info
self.left = None
self.right = None
'''
# The height of a binary tree is the number of edges between the
# tree's root and its furthest leaf.
def height(root):
if root.left and root.right:
return 1 + max(height(root.left), height(root.right))
elif root.left:
return 1 + height(root.left)
elif root.right:
return 1 + height(root.right)
else:
return 0
# Find lowest common ancestor of two node values in a binary search tree
def lca(root, v1, v2):
current = root
while current.info != v1 and current.info != v2:
if current.left and v1 < current.info and v2 < current.info:
current = current.left
elif current.right and v1 > current.info and v2 > current.info:
current = current.right
else:
return current
return current
|
3f45254a597fd55e1739e8e0995a97f20466d1c1 | v1ktos/Python_RTU_08_20 | /Diena_6_lists/uzd1_2_g2.py | 1,872 | 4.0625 | 4 | my_list = []
while True:
my_input = input("ievadiet skaitli vai Q lai beigtu: ")
if my_input.lower().startswith('q'):
break
my_input = float(my_input)
my_list.append(my_input)
my_list_sorted = sorted(my_list, reverse=True)
print(f"3 lielākās un 3 mazākās vērtības no {len(my_list)} ievadītajām:\n{my_list_sorted[:3]} ... {my_list_sorted[-3:]}")
print(f"ievadītās vērtības to ievadīšanas secībā:\n{my_list}\nto vidējā vērtība: {sum(my_list)/len(my_list)}")
# my_list = []
# while True:
# my_number = (input("PRESS b to quite! Enter the number : "))
# if my_number == "b":
# print("Game over")
# break
# else:
# if my_number.isdigit():
# my_list += [float(my_number)]
# print(f"Your list: {my_list}")
# print(f"Sum = : {sum(my_list)}")
# print(f"Avarage = {sum(my_list)/len(my_list)}")
# my_list_2 = sorted(my_list,reverse=True)
# print(f"Your Bottom 3 list: {my_list_2[-3:]} Your Top 2 list {my_list_2[:3]}")
# else:
# my_number = input("Enter the number : ")
# # from typing import Reversible
# # count = 0
# # totalSum = 0
# # allNumbers = []
# # while True:
# # number = input("ievadiet skaitli")
# # if number.isnumeric():
# # number = float(number)
# # count += 1
# # totalSum += number
# # average = (totalSum) / count
# # allNumbers.append(number)
# # allNumbers.sort(reverse=True)
# # top3list = allNumbers[:3]
# # bottom3list = allNumbers[-3:]
# # print(f"ievadīto skaitļu vidējā vērtība ir {average}, visi ievadītie skaitļi ir: {allNumbers}, TOP3 ir: {top3list}, BOTTOM3 ir: {bottom3list}")
# # if str(number) == "q":
# # print("Paldies par piedalīšanos :)")
# # break |
2ec0bb2408c51f314e4fd36702ce2280c568e807 | tanman13/oopljpl | /myExercises/Collatz.py | 707 | 3.828125 | 4 | #!/usr/bin/env python3
from sys import stdin
def cycle_length (n) :
assert n > 0
c = 1
while n > 1 :
if (n % 2) == 0 :
n = (n / 2)
else :
n = (3 * n) + 1
c += 1
assert c > 0
return c
def max_cycle_length (i, j) :
s = 0
for v in range (i, j+1) :
t = cycle_length (v)
if t > s :
s = t
return (s)
if __name__ == "__main__" :
for v in stdin :
s = v.split(" ")
i = int (s[0])
j = int (s[1])
if j < i :
t = max_cycle_length (j, i)
else :
t = max_cycle_length (i,j)
s = v.replace("\n","") + " " + str(t)
print (s)
|
4143f5c5491d632ce2681c7cb16e52f66bc72084 | Chandler-Song/sample | /python/oopap/multi_inherit.py | 2,520 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'多重继承'
# 首先,主要的类层次仍按照哺乳类和鸟类设计
class Animal(object):
pass
# 大类
class Mammal(Animal):
pass
class Bird(Animal):
pass
# 现在,我们要给动物再加上Runnable和Flyable的功能,只需要先定义好Runnable和Flyable的类:
class Runnable(object):
def run(self):
print('Running...')
class Flyable(object):
def fly(self):
print('Flying...')
class RunnableMixIn(object):
def run(self):
print('Running...')
# 各种动物
# 对于需要Runnable功能的动物,就多继承一个Runnable,例如Dog:
# 通过多重继承,一个子类就可以同时获得多个父类的所有功能。
class Dog(Mammal,Runnable):
pass
class Bat(Mammal,Flyable):
pass
class Parrot(Bird,Flyable):
pass
# 在设计类的继承关系时,通常,主线都是单一继承下来的,例如,Ostrich继承自Bird。但是,如果需要“混入”额外的功能,通过多重继承就可以实现,比如,让Ostrich除了继承自Bird外,再同时继承Runnable。这种设计通常称之为MixIn。
# 为了更好地看出继承关系,我们把Runnable和Flyable改为RunnableMixIn和FlyableMixIn。类似的,你还可以定义出肉食动物CarnivorousMixIn和植食动物HerbivoresMixIn,让某个动物同时拥有好几个MixIn:
class Ostrich(Bird,RunnableMixIn):
pass
# MixIn的目的就是给一个类增加多个功能,这样,在设计类的时候,我们优先考虑通过多重继承来组合多个MixIn的功能,而不是设计多层次的复杂的继承关系。
# Python自带的很多库也使用了MixIn。举个例子,Python自带了TCPServer和UDPServer这两类网络服务,而要同时服务多个用户就必须使用多进程或多线程模型,这两种模型由ForkingMixIn和ThreadingMixIn提供。通过组合,我们就可以创造出合适的服务来。
# 比如,编写一个多进程模式的TCP服务,定义如下:
''' class MyTCPServer(TCPServer,ForkingMixIn):
pass '''
# 编写一个多线程模式的UDP服务,定义如下:
''' class MyUDPServer(UDPServer,ThreadingMixIn):
pass '''
# 如果你打算搞一个更先进的协程模型,可以编写一个CoroutineMixIn:
''' class MyTCPServer(TCPServer, CoroutineMixIn):
pass '''
# 这样一来,我们不需要复杂而庞大的继承链,只要选择组合不同的类的功能,就可以快速构造出所需的子类。
|
5e3fe09f9273bdfd88e7563bcf9e6c68698e1dcd | mjwestcott/priorityqueue | /priorityqueue.py | 11,467 | 3.78125 | 4 | """
priorityqueue.py
Priority Queue Implementation with a O(log n) Remove Method
This file implements min- amd max-oriented priority queues based on binary
heaps. I found the need for a priority queue with a O(log n) remove method.
This can't be achieved with any of Python's built in collections including
the heapq module, so I built my own. The heap is arranged according to a given
key function.
Usage:
>>> from priorityqueue import MinHeapPriorityQueue
>>> items = [4, 0, 1, 3, 2]
>>> pq = MinHeapPriorityQueue(items)
>>> pq.pop()
0
A priority queue accepts an optional key function.
>>> items = ['yy', 'ttttttt', 'z', 'wwww', 'uuuuuu', 'vvvvv', 'xxx']
>>> pq = MinHeapPriorityQueue(items, key=len)
>>> pq.pop()
'z'
>>> pq.pop()
'yy'
Internally, the queue is a list of tokens of type 'Locator', which contain
the priority value, the item itself, and its current index in the heap.
The index field is updated whenever the heap is modified. This is what
allows us to remove in O(log n). Appending an item returns it's Locator.
>>> token = pq.append('a')
>>> token
Locator(value=1, item='a', index=0)
>>> pq.remove(token)
'a'
If we want to be able to remove any item in the list we can maintain an
auxiliary dictionary mapping items to their Locators. Here's a simple
example with unique items:
>>> items = [12, 46, 89, 101, 72, 81]
>>> pq = MinHeapPriorityQueue()
>>> locs = {}
>>> for item in items:
... locs[item] = pq.append(item)
>>> locs[46]
Locator(value=46, item=46, index=1)
>>> pq.remove(locs[46])
46
Iterating with 'for item in pq' or iter() will produce the items, not the
Locator instances used in the internal representation. The items will be
generated in sorted order.
>>> items = [3, 1, 0, 2, 4]
>>> pq = MinHeapPriorityQueue(items)
>>> for item in pq:
... print(item)
0
1
2
3
4
"""
# Inspired by:
# - AdaptableHeapPriorityQueue in 'Data Structures and Algorithms in Python'
# - the Go Standard library's heap package
# - Python's heapq module
# - Raymond Hettinger's SortedCollection on ActiveState
# - Peter Norvig's PriorityQueue in the Python AIMA repo
class MinHeapPriorityQueue():
"""A locator-based min-oriented priority queue implemented with a binary
heap, arranged according to a key function.
Operation Running Time
len(P), P.peek() O(1)
P.update(loc, value, item) O(log n)
P.append(item) O(log n)*
P.pop() O(log n)*
P.remove(loc) O(log n)*
*amortized due to occasional resizing of the underlying python list
"""
def __init__(self, iterable=(), key=lambda x: x):
self._key = key
decorated = [(key(item), item) for item in iterable]
self._pq = [self.Locator(value, item, i) for i, (value, item) in enumerate(decorated)]
if len(self._pq) > 1:
self._heapify()
class Locator:
"""Token for locating an entry of the priority queue."""
__slots__ = '_value', '_item', '_index'
def __init__(self, value, item, i):
self._value = value
self._item = item
self._index = i
def __eq__(self, other):
return self._value == other._value
def __lt__(self, other):
return self._value < other._value
def __le__(self, other):
return self._value <= other._value
def __repr__(self):
return '{}(value={!r}, item={!r}, index={})'.format(
self.__class__.__name__,
self._value,
self._item,
self._index
)
#------------------------------------------------------------------------------
# non-public
def _parent(self, j):
return (j-1) // 2
def _left(self, j):
return 2*j + 1
def _right(self, j):
return 2*j + 2
def _swap(self, i, j):
"""Swap the elements at indices i and j of array."""
self._pq[i], self._pq[j] = self._pq[j], self._pq[i]
# Update the indices in the Locator instances.
self._pq[i]._index = i
self._pq[j]._index = j
def _upheap(self, i):
parent = self._parent(i)
if i > 0 and self._pq[i] < self._pq[parent]:
self._swap(i, parent)
self._upheap(parent)
def _downheap(self, i):
n = len(self._pq)
left, right = self._left(i), self._right(i)
if left < n:
child = left
if right < n and self._pq[right] < self._pq[left]:
child = right
if self._pq[child] < self._pq[i]:
self._swap(i, child)
self._downheap(child)
def _fix(self, i):
self._upheap(i)
self._downheap(i)
def _heapify(self):
start = self._parent(len(self) - 1) # Start at parent of last leaf
for j in range(start, -1, -1): # going to and includng the root.
self._downheap(j)
#------------------------------------------------------------------------------
# public
def append(self, item):
"""Add an item to the heap"""
token = self.Locator(self._key(item), item, len(self._pq))
self._pq.append(token)
self._upheap(len(self._pq) - 1) # Upheap newly added position.
return token
def update(self, loc, newval, newitem):
"""Update the priority value and item for the entry identified by Locator loc."""
j = loc._index
if not (0 <= j < len(self) and self._pq[j] is loc):
raise ValueError('Invalid locator')
loc._value = newval
loc._item = newitem
self._fix(j)
def remove(self, loc):
"""Remove and return the item identified by Locator loc."""
j = loc._index
if not (0 <= j < len(self) and self._pq[j] is loc):
raise ValueError('Invalid locator')
if j == len(self) - 1:
self._pq.pop()
else:
self._swap(j, len(self) - 1)
self._pq.pop()
self._fix(j)
return loc._item
def peek(self):
"""Return but do not remove item with minimum priority value."""
loc = self._pq[0]
return loc._item
def pop(self):
"""Remove and return item with minimum priority value."""
self._swap(0, len(self._pq) - 1)
loc = self._pq.pop()
self._downheap(0)
return loc._item
@property
def items(self):
return [token._item for token in self._pq]
def __len__(self):
return len(self._pq)
def __contains__(self, item):
return item in self.items
def __iter__(self):
return iter(sorted(self.items))
def __repr__(self):
return '{}({})'.format(self.__class__.__name__, self._pq)
class MaxHeapPriorityQueue(MinHeapPriorityQueue):
"""A locator-based max-oriented priority queue implemented with a binary
heap, arranged according to a key function.
Operation Running Time
len(P), P.peek() O(1)
P.update(loc, value, item) O(log n)
P.append(item) O(log n)*
P.pop() O(log n)*
P.remove(loc) O(log n)*
*amortized due to occasional resizing of the underlying python list
"""
# Override all relevant private methods of MinHeapPriorityQueue
# with max-oriented versions.
def _upheap(self, i):
parent = self._parent(i)
if i > 0 and self._pq[parent] < self._pq[i]:
self._swap(i, parent)
self._upheap(parent)
def _downheap(self, i):
n = len(self._pq)
left, right = self._left(i), self._right(i)
if left < n:
child = left
if right < n and self._pq[left] < self._pq[right]:
child = right
if self._pq[i] < self._pq[child]:
self._swap(i, child)
self._downheap(child)
def __iter__(self):
return iter(sorted(self.items, reverse=True))
__doc__ += """
>>> import random; random.seed(42)
>>> from priorityqueue import MinHeapPriorityQueue, MaxHeapPriorityQueue
Function to verify the min-heap invariant is true for all elements of pq.
>>> def verify(pq):
... n = len(pq._pq)
... for i in range(n):
... left, right = 2*i + 1, 2*i + 2
... if left < n:
... assert pq._pq[i] <= pq._pq[left]
... if right < n:
... assert pq._pq[i] <= pq._pq[right]
Function to verify the max-heap invariant is true for all elements of pq.
>>> def verify_max(pq):
... n = len(pq._pq)
... for i in range(n):
... left, right = 2*i + 1, 2*i + 2
... if left < n:
... assert pq._pq[i] >= pq._pq[left]
... if right < n:
... assert pq._pq[i] >= pq._pq[right]
>>> items = [random.randint(1, 100) for _ in range(10000)]
>>> pq = MinHeapPriorityQueue(items)
>>> verify(pq)
>>> pq = MaxHeapPriorityQueue(items)
>>> verify_max(pq)
Check multiple signs for priority values.
>>> items = list(range(100, -100, -1))
>>> random.shuffle(items)
>>> pq = MinHeapPriorityQueue(items)
>>> verify(pq)
>>> pq = MaxHeapPriorityQueue(items)
>>> verify_max(pq)
Test pop, peek, append, remove, update, __len__, and __contains__ operations.
>>> items = ['jjjjjjjjjj', 'iiiiiiiii', 'hhhhhhhh',
... 'ggggggg', 'ffffff', 'eeeee',
... 'dddd', 'ccc', 'bb', 'a']
>>> pq = MinHeapPriorityQueue(items, key=len)
>>> verify(pq)
>>> pq.pop()
'a'
>>> pq.pop()
'bb'
>>> pq.peek()
'ccc'
>>> pq.pop()
'ccc'
>>> pq.pop()
'dddd'
>>> pq.peek()
'eeeee'
>>> pq.pop()
'eeeee'
>>> _ = pq.append('a')
>>> _ = pq.append('bb')
>>> verify(pq)
>>> pq = MaxHeapPriorityQueue(key=len)
>>> pq.append([1, 2, 3])
Locator(value=3, item=[1, 2, 3], index=0)
>>> pq.append([1, 2, 3, 4, 5, 6])
Locator(value=6, item=[1, 2, 3, 4, 5, 6], index=0)
>>> pq.append([1])
Locator(value=1, item=[1], index=2)
>>> pq.append([1, 2, 3, 4, 5, 6, 7, 8, 9])
Locator(value=9, item=[1, 2, 3, 4, 5, 6, 7, 8, 9], index=0)
>>> len(pq)
4
>>> [1] in pq
True
>>> [1, 2, 3, 4, 5] in pq
False
>>> items = list(range(1, 10001))
>>> random.shuffle(items)
>>> pq = MinHeapPriorityQueue(items)
>>> verify(pq)
>>> len(pq) == 10000
True
>>> for i in range(1, 10001):
... x = pq.pop()
... assert x == i
>>> pq = MinHeapPriorityQueue()
>>> locs = {}
>>> for x in items:
... locs[x] = pq.append(x)
>>> pq.remove(locs[1])
1
>>> pq.remove(locs[2])
2
>>> pq.pop()
3
>>> for i in range(4, 100):
... _ = pq.remove(locs[i])
>>> pq.pop()
100
>>> verify(pq)
>>> pq.update(locs[999], 1, 'test')
>>> 999 in pq
False
>>> pq.pop()
'test'
>>> 998 in pq
True
Test the items and __repr__ methods.
>>> items = ['a', 'b', 'c']
>>> pq = MinHeapPriorityQueue(items)
>>> pq
MinHeapPriorityQueue([Locator(value='a', item='a', index=0), Locator(value='b', item='b', index=1), Locator(value='c', item='c', index=2)])
>>> pq.items == ['a', 'b', 'c']
True
Check that __iter__ generates items in sorted order.
>>> items = list(range(1000))
>>> pq = MinHeapPriorityQueue(items)
>>> for i, x in enumerate(pq):
... assert i == x
>>> pq = MaxHeapPriorityQueue(items)
>>> for i, x in enumerate(pq):
... assert 999 - i == x
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
|
2f1624bc1d9a184e0041dac8f9dcd20414e5ff71 | Divyakennady/AI-based-health-club-management-system | /main.py | 437 | 3.859375 | 4 | import pandas as pd
homeno=int(input("enter the home no:"))
homename=input("enter home name:")
place=input("enter place:")
sqfeet=int(input("enter square feet:"))
price=int(input("enter the price:"))
d={"homeno":[homeno,1,2],"homename":[homename,"sh","jk"],"place":[place,"chakkai","soul"],"squarefeet":[sqfeet,7,8],"price":[price,9,10]}
print(d)
df=pd.DataFrame(d)
print(df)
df.to_excel("sample.xlsx")
df.to_csv("sample.csv") |
2916739dc626b54562056b54d4cf82c4261378a2 | pabnguyen/nguyenphuonganh-fundamentals-c4e13 | /Session 1/example.py | 143 | 4.03125 | 4 | n = int(input("Enter a number: "))
for i in range(n):
if (i % 2) == 0:
print("Fizz")
elif (i % 3) == 0:
print("Buzz")
|
b5174e0b5e5c716b8d1ea136f627a6f67512a0aa | welchbj/almanac | /almanac/types/comparisons.py | 1,129 | 3.625 | 4 | from typing import Any, Type
from typing_inspect import is_union_type, get_args
def is_matching_type(
_type: Type,
annotation: Any
) -> bool:
"""Return whether a specified type matches an annotation.
This function does a bit more than a simple comparison, and performs the following
extra checks:
- If the ``annotation`` is a union, then the union is unwrapped and each of
its types is compared against ``_type``.
- If the specified ``_type`` is generic, it will verify that all of its
parameters match those of a matching annotation.
"""
# Look for an easy win.
if _type == annotation:
return True
# If annotation is Union, we unwrap it to check against each of the possible inner
# types.
if is_union_type(annotation):
if any(_type == tt for tt in get_args(annotation, evaluate=True)):
return True
# If both the global type and the argument annotation can be reduced to
# the same base type, and have equivalent argument tuples, we can
# assume that they are equivalent.
# TODO
return False
|
d7d327a0ddeec0ba044583207d815ccaf93fa896 | gincheong/leetcode | /Top Interview Questions/src/101.symmetric-tree.py | 1,678 | 4.09375 | 4 | #
# @lc app=leetcode id=101 lang=python3
#
# [101] Symmetric Tree
#
from typing import List
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
# recursively
# if not root:
# return True
# return self.compare_recursive(root.left, root.right)
# iteratively
if not root:
return True
stack = [root.left, root.right]
while len(stack) > 0:
node1 = stack.pop()
node2 = stack.pop()
if not node1 and not node2:
continue
if not node1 or not node2:
return False
if node1.val == node2.val:
stack.append(node1.left)
stack.append(node2.right)
stack.append(node1.right)
stack.append(node2.left)
else:
return False
return True
def compare_recursive(self, node1: TreeNode, node2: TreeNode) -> bool:
if not node1 and not node2:
# 둘 다 None인 경우
return True
if not node1 or not node2:
# 둘 다 None인 경우를 제외하고, 둘 중 하나만 None이면
return False
if node1.val == node2.val:
return self.compare(node1.left, node2.right) and self.compare(node2.left, node1.right)
else:
return False
# @lc code=end
'''
[1,2,2,null,3,null,3]
''' |
010da5f282b5330c736da473b3abdf09f387cb84 | gautamits/hackerrank | /algorithms/greedy/largest-permutation.py | 991 | 3.625 | 4 | #!/bin/python
import sys
def largestPermutation(arr, n, k):
# Auxiliary array of storing the position of elements
pos = {}
for i in range(n):
pos[arr[i]] = i
for i in range(n):
# If K is exhausted then break the loop
if k == 0:
break
# If element is already largest then no need to swap
if (arr[i] == n-i):
continue
# Find position of i'th largest value, n-i
temp = pos[n-i]
# Swap the elements position
pos[arr[i]] = pos[n-i]
pos[n-i] = i
# Swap the ith largest value with the value at
# ith place
arr[temp], arr[i] = arr[i], arr[temp]
# Decrement K after swap
k = k-1
return arr
if __name__ == "__main__":
n, k = raw_input().strip().split(' ')
n, k = [int(n), int(k)]
arr = map(int, raw_input().strip().split(' '))
result = largestPermutation(arr,n,k)
print " ".join(map(str, result))
|
cdfef7939864a3b2a2b876bb872117628b71a3bf | Ryccass/Old-Python-Code- | /Python_Test_2/main.py | 349 | 3.875 | 4 | def front_back(str):
list_str = list(str)
first_char = str[0]
last_char = str[len(str) - 1]
str_length = len(str)
list_str[0] = ""
list_str[len(list_str)-1] = ""
list_str.insert(0, last_char)
list_str.insert(str_length-1, first_char)
normal_str = ''.join(list_str)
print(normal_str)
front_back("kitten") |
3b169fc528f50767ce2d3bacaf058f92827f62c3 | UtkarshS20/Practice_code_with_harry | /pythonProject1/oops45cwh.py | 971 | 3.96875 | 4 | #dunder methods-methods which start and end with __ .
class Employee:
no_of_leaves=8
def __init__(self,aname,asalary,arole):
self.name=aname
self.salary=asalary
self.role=arole
def printdetails(self):
return f"name is {self.name} salary is {self.salary} role is {self.role}"
@classmethod
def change_leaves(cls,newleaves):
cls.no_of_leaves=newleaves
def __add__(self, other):
return self.salary+other.salary
def __truediv__(self, other):
return self.salary/other.salary
def __repr__(self):
#return self.printdetails()
return f"Employee('{self.name}', {self.salary}, '{self.role}')"
def __str__(self):
return f"name is {self.name} salary is {self.salary} role is {self.role}"
emp1=Employee("utkarsh",30000,"sde")
#emp2=Employee("vaibhav",20000,"sde(trainee)")
#print(emp1+emp2)
#print(emp1/emp2)
print(emp1) #str is preferred over repr
print(repr(emp1)) |
96e30986176a407eab1606edf04884711fef94d9 | Rhysj125/tensorflow | /src/neural-net.py | 1,900 | 3.84375 | 4 | import tensorflow as tf
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_Data/", one_hot=True)
# Number of inputs
x = tf.placeholder(tf.float32, shape=[None, 784])
# Stores probability predicted for that digit 0-9
# Number of outputs
y_ = tf.placeholder(tf.float32, [None, 10])
# Weights and balances
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# Define model
y = tf.nn.softmax(tf.matmul(x, W) + b)
# Define loss as cross entropy
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
# Each training step want to minize the cross entropy error
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
# Set number of training steps
num_training_steps = 1000
# Set number of iterations to complete before providing an update on the accuracy
display_interval = 100
# Perform given number of training steps
for i in range(num_training_steps):
# Get 100 random data points from data. batch_xs = images
# batch_ys is the label
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
if (i % display_interval) == 0:
# Compare highest probability output with label
# actual = y, predicted = y_
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
test_accuracy = sess.run(accuracy, feed_dict={x:mnist.test.images, y_: mnist.test.labels})
print("Test accuracy: {0}%".format(test_accuracy * 100.0))
|
9d3adfb5be96ff8362121be2a14ce921dcaf063c | aashnagarg/My-Coding-Practice | /subtractLists.py | 644 | 4 | 4 | def subtractLists(arr1,arr2):
'''
for elem in arr2: Time complexity O(len(arr1)*len(arr2))
if elem in arr1:
arr1.remove(elem)
return arr1
'''
#return list(set(arr1)-set(arr2)) #Time complexity O(len(arr1))
ptr1=0
ptr2=0
while arr1[ptr1] and arr2[ptr2]:
if arr1[ptr1]<arr2[ptr2]:
ptr1+=1
elif arr1[ptr1] == arr2[ptr2]:
del arr1[ptr1]
ptr1+=1
else:
ptr2+=1
try:
arr1[ptr1] and arr2[ptr2]
except IndexError:
return arr1
print subtractLists([1,3,4,5,7],[2,3,5])
|
7fccae498043dddc8074438c444d57dbe1d8863b | tankan63/randomprojects | /print.py | 706 | 3.9375 | 4 | # this is a simple text analyser that displays tthe frequency of each letter in a string
def count_char(text,char):
count=0
for c in text:
if c==char:
count +=1
return count
file=open("new1.txt","w")
file.write("""The quick brown fox jumps over the lazy dog""") #enter any text here
file.close() #executing this line will overwrite the original file and close it
#alternatively, if you simple wish to analyse the letters in any file without
#overwriting it, the 'file.write()' command can be forgone
filename="new1.txt"
with open(filename) as f:
text=f.read()
for char in "abcdefghijklmnopqrstuvwxyz":
perc=100 * count_char(text,char)/len(text)
print("{0}-{1}".format(char, round(perc,2)))
|
b4a2b712fff7cef2ecc5a1fb43699ba476b24cac | ug2057pz/Tic_Tac_Teo | /SoccerTeam.py | 1,294 | 3.8125 | 4 | class FootballPlayer:
name = "Chris Smalling"
team = "Man United"
years_in_leage = 0
def printPlayer(self):
print(self.name + " playing for the "+ self.team)
def isGood(self):
print("Error ! is Good is not defined !")
return False
#Quarterback is the child of FootballPlayer, and it inherets characteristics of the parent.
class Quarterback(FootballPlayer):
pass_attempted = 0
completion = 0
pass_yard = 0
def compltionRate(self):
return self.completion/self.pass_attempted
def yardsPerAttempt(self):
return self.pass_yard/self.pass_attempted
class Runningback(FootballPlayer):
rushes = 0
rush_yards = 0
def yardsPerRush(self):
return self.rush_yards/self.rushes
#Create instance of the class
player1 = Quarterback()
player1.name = "Luke Show"
player1.team = "Man United"
player1.pass_attempted = 45
player1.pass_yard = 190
player1.completion = 40
player2 = Runningback()
player2.name = "Antonio Valencia"
player2.team = "Man United"
player2.rush_yards = 90
player2.rushes = 600
playerList = []
playerList.append(player1)
playerList.append(player2)
for player in playerList:
player.printPlayer()
if (player.isGood()):
print("Is a good player!")
else:
print("Is not a good player")
|
21cabce19f3a7dd0d39107c4fa93742c4e2d5acc | wzgdavid/python_kecheng | /samples/history/BDA2/day2/func.py | 710 | 3.53125 | 4 | #def add(*arg,**kwarg):
# print(arg, kwarg)
#add(3,4,5,key=1, reverse=False, name='cat')
#print(type(foo))
#add(1,2,3,4,5,5,5,5,5,5,5)
#print(a)
#b, *c,a,d = 1,2,3,4,5,5,5,5,5,5,55
#print(b, a)
class ArgExcetiopn(Exception):
pass
def add(a, b):
if not isinstance(a, int) or not isinstance(b, int):
raise ArgExcetiopn('we need int')
return a+b
#a = add(1, '')
try:
a = add(1, '')
print(a)
except ArgExcetiopn as e:
print(e)
print('--------------ArgExcetiopn--------------')
except NameError as e:
print(e)
print('--------------NameError--------------')
except Exception as e:
print(e)
print('-------------Exception---------------')
print('llllll') |
ae76397afe89f3716a182eb0f108b7ccd3c4f0b9 | yang-XH/coursera---machine-learning | /_1_ML_linear_regression/ex1_multi.py | 1,567 | 3.875 | 4 | import numpy as np
import pandas as pd
# 数据标准化的包
from sklearn import preprocessing
import matplotlib.pyplot as plt
from _1_ML_linear_regression import ex1
#TODO
# 为啥运行或者debug会把ex1再运行一遍???????????????????
def gradientDescentMulti(X_, y_, theta_, alpha_, num_iters_):
theta_, J_history_ = ex1.gradientDescent(X_, y_, theta_, alpha_, num_iters_)
return theta_, J_history_
data = pd.read_table('ex1data2.txt', header=None, sep=',')
X = np.array(data.iloc[:, :2])
# reshape将y转换为列向量
y = np.array(data.iloc[:, 2]).reshape(-1, 1)
m = len(y)
# Scale features and set them to zero mean
# 多变量时,数标准化!!! 此处采用z-score: (x-μ)/σ
X_scale = preprocessing.scale(X, axis=0)
X_scale = np.c_[np.ones(m), X_scale]
alpha = 0.01
num_iters = 400
theta = np.zeros((3, 1))
theta, J_history = gradientDescentMulti(X_scale, y, theta, alpha, num_iters)
plt.plot(list(range(num_iters)), J_history)
plt.xlabel('Number of iterations')
plt.ylabel('Cost J')
plt.show()
print('Theta computed from gradient descent: \n')
print(theta)
# compute the closed form solution for linear regression using the normal equations
# normal equation θ = (XTX)-1 XTy
# 不使用梯度下降,则不需对变量进行数据标准化
# 此处将Numpy的array转换为matrix,乘法则不需写为np.dot
X_ones = np.c_[np.ones(m), X]
X_n = np.mat(X_ones)
y_n = np.mat(y)
theta_n = (X_n.T * X_n).I * X_n.T * y_n
print('Theta computed from the normal equations: \n')
print(theta)
|
77387e4b9e9eff0ee33874aa618215ed114f7165 | GenryEden/kpolyakovName | /2272.py | 274 | 3.5625 | 4 | from functools import lru_cache
@lru_cache
def f(n):
if n <= 3:
return n
elif n % 2 == 0:
return n + 3 + f(n-1)
else:
return n*n + f(n-2)
cnt = 0
for x in range(1, 1000+1):
res = f(x)
if res % 7 == 0:
cnt += 1
print(cnt)
|
8f6cb8fd8de1fa4f5e76907743d501b266ad4405 | dsardelic/Battleships | /battleships/board.py | 22,379 | 4.09375 | 4 | """This module contains data structures for managing board data."""
import functools
import itertools
from typing import Any, DefaultDict, Dict, Iterable, List, Set
from battleships.grid import FieldType, FieldTypeGrid, Position, Series
from battleships.ship import Ship
class Board:
"""Represents a puzzle board object.
A board is a numbered grid of FieldType elements. Each number
indicates how many ship fields remain to be marked in the
corresponding row or column.
In order to ease grid index checks and marking of ships near grid
edges, the grid is extended with a sea field rim. Therefore, the
resulting grid is 2 rows and 2 columns bigger than the input grid.
Class instance attributes:
grid (battleships.grid.FieldTypeGrid): Grid of FieldType
elements.
number_of_ship_fields_to_mark_in_series (Dict[
battleships.grid.Series, List[int]]): For each Series type
indicates how many ship fields remain to be marked in the
corresponding series.
"""
__slots__ = ("grid", "number_of_ship_fields_to_mark_in_series")
def __init__(
self,
grid: FieldTypeGrid,
number_of_ship_fields_to_mark_in_series: Dict[Series, List[int]],
) -> None:
"""Initialize a new Board object.
Args:
grid (battleships.grid.FieldTypeGrid): Grid of FieldType
elements.
number_of_ship_fields_to_mark_in_series
(Dict[battleships.grid.Series, List[int]]):
For each Series type indicates how many ship fields
remain to be marked in the corresponding series.
"""
self.grid = grid
self.number_of_ship_fields_to_mark_in_series = (
number_of_ship_fields_to_mark_in_series
)
def __repr__(self) -> str:
"""Return a string representation of self.
Returns:
str: String representation of self.
"""
return self.repr(True)
def __eq__(self, other: Any) -> bool:
"""Compare self with some other object.
Args:
other: The object to compare with self.
Returns:
bool: True if objects are equal, False otherwise.
"""
if isinstance(other, self.__class__):
return (
other.grid == self.grid
and other.number_of_ship_fields_to_mark_in_series
== self.number_of_ship_fields_to_mark_in_series
)
return False
@classmethod
def parse_board(
cls,
grid: FieldTypeGrid,
number_of_ship_fields_to_mark_in_rows: List[int],
number_of_ship_fields_to_mark_in_cols: List[int],
) -> "Board":
"""Create a Board object from original board data.
Unlike Board object data, original board data correspond to what
a person solving the puzzle on paper would see.
Args:
grid (battleships.grid.FieldTypeGrid): Input grid of
FieldType elements.
number_of_ship_fields_to_mark_in_rows (List[int]): List of
numbers of ship fields to mark in each corresponding
input grid row.
number_of_ship_fields_to_mark_in_cols (List[int]): List of
numbers of ship fields to mark in each corresponding
input grid column.
Returns:
battleships.board.Board: Board object created from original
board data.
"""
board_size = len(number_of_ship_fields_to_mark_in_rows) + 2
board_grid = FieldTypeGrid() # type: FieldTypeGrid
board_grid.append([FieldType.SEA] * board_size)
board_grid += [[FieldType.SEA, *grid_row, FieldType.SEA] for grid_row in grid]
board_grid.append([FieldType.SEA] * board_size)
board_number_of_ship_fields_to_mark_in_series = {
Series.ROW: [0, *number_of_ship_fields_to_mark_in_rows, 0],
Series.COLUMN: [0, *number_of_ship_fields_to_mark_in_cols, 0],
}
for row_index, row in enumerate(grid, 1):
for col_index, field in enumerate(row, 1):
if field == FieldType.SHIP:
board_number_of_ship_fields_to_mark_in_series[Series.ROW][
row_index
] -= 1
board_number_of_ship_fields_to_mark_in_series[Series.COLUMN][
col_index
] -= 1
return Board(board_grid, board_number_of_ship_fields_to_mark_in_series)
@classmethod
def get_copy_of(cls, original_board: "Board") -> "Board":
"""Create a copy of a Board object.
Args:
original_board (battleships.board.Board): The board to copy.
Returns:
battleships.board.Board: A copy of the input Board object.
"""
board_copy_grid = FieldTypeGrid([[*row] for row in original_board.grid])
board_copy_number_of_ship_fields_to_mark_in_series = {
Series.ROW: [
*original_board.number_of_ship_fields_to_mark_in_series[Series.ROW]
],
Series.COLUMN: [
*original_board.number_of_ship_fields_to_mark_in_series[Series.COLUMN]
],
}
return cls(board_copy_grid, board_copy_number_of_ship_fields_to_mark_in_series)
@property
def size(self) -> int:
"""Return size of self's grid.
The grid is expected to be square-shaped, thus both dimensions
have the same size.
Returns:
int: Size of self's grid.
"""
return len(self.grid)
def repr(self, with_ship_fields_to_mark_count: bool) -> str:
"""Return a string representation of self.
Args:
with_ship_fields_to_mark_count (bool): True if number of
ship fields to mark in each row and column is to be
included in the representation, False otherwise.
Returns:
str: String representation of self.
"""
grid = FieldTypeGrid(
[row[1 : self.size - 1] for row in self.grid[1 : self.size - 1]]
)
top_frame_border = (
"\u2554\u2550" + "\u2550\u2550\u2550\u2550" * (self.size - 2) + "\u2557\n"
)
fieldtype_rows = ""
for row_index, grid_row_repr in enumerate(repr(grid).split("\n"), 1):
row_rep = "".join(["\u2551 ", grid_row_repr.strip("\n"), " \u2551"])
if with_ship_fields_to_mark_count:
row_rep += "".join(
[
"(",
str(
self.number_of_ship_fields_to_mark_in_series[Series.ROW][
row_index
]
),
")",
]
)
fieldtype_rows += row_rep + "\n"
bottom_frame_border = (
"\u255A\u2550" + "\u2550\u2550\u2550\u2550" * (self.size - 2) + "\u255D\n"
)
ret_val = "".join([top_frame_border, fieldtype_rows, bottom_frame_border])
if with_ship_fields_to_mark_count:
ret_val += (
" "
+ "".join(
"(" + str(x) + ") "
for x in self.number_of_ship_fields_to_mark_in_series[
Series.COLUMN
][1 : self.size - 1]
)
+ "\n"
)
return ret_val.strip("\n")
def set_ship_fields_as_unknown(self, ship_fields_positions: Set[Position]) -> None:
"""Mark current FieldType as unknown on all given ship positions
in self's grid.
Args:
ship_fields_positions (Set[battleships.grid.Position]):
Positions of which to perform the field type
replacement.
"""
for position in ship_fields_positions:
self.grid[position.row][position.col] = FieldType.UNKNOWN
self.number_of_ship_fields_to_mark_in_series[Series.ROW][position.row] += 1
self.number_of_ship_fields_to_mark_in_series[Series.COLUMN][
position.col
] += 1
def get_ship_fields_positions(self) -> Set[Position]:
"""Get all self's grid positions containing ship fields.
Returns:
Set[battleships.grid.Position]: Set of self's grid positions
containing ship fields.
"""
return functools.reduce(
set.union,
[
self.grid.fieldtype_positions_in_series(
FieldType.SHIP, Series.ROW, row_index
)
for row_index in range(1, self.size - 1)
],
)
def mark_sea_in_series_with_no_rem_ship_fields(self) -> None:
"""In those series where there are no more ship fields to be
marked in self's grid, replace unknown fields with sea fields.
"""
for series in Series:
for series_index in range(1, self.size - 1):
if not self.number_of_ship_fields_to_mark_in_series[series][
series_index
]:
self.grid.replace_fields_in_series(
FieldType.UNKNOWN, FieldType.SEA, series, series_index
)
def mark_diagonal_sea_fields_for_positions(
self, ship_fields_positions: Set[Position]
) -> None:
"""Mark sea fields in all self's grid's positions diagonal to
given positions.
While another potential ship piece might be found right next to
a particular position (in the same row or column), all positions
diagonal to the given position cannot contain anything other
than sea fields.
Args:
ship_fields_positions (Set[battleships.grid.Position]):
Positions for which to mark sea fields on diagonal
positions.
"""
for position in ship_fields_positions:
for offset_row, offset_col in ((-1, -1), (-1, 1), (1, -1), (1, 1)):
self.grid[position.row + offset_row][
position.col + offset_col
] = FieldType.SEA
def ship_is_within_playable_grid(self, ship: Ship) -> bool:
"""Check whether ship is within self's grid playable part.
Playable grid part is the board grid without the surrounding sea
fields extension.
Args:
ship (battleships.ship.Ship): Ship whose placement to check.
Returns:
bool: True is ship is within self's grid's playable part,
False otherwise.
"""
return (
ship.position.row > 0
and ship.position.col > 0
and all(
ship.max_ship_field_index_in_series[series] < self.size - 1
for series in Series
)
)
def sufficient_remaining_ship_fields_to_mark_ship(self, ship: Ship) -> bool:
"""Check whether there are enough remaining ship fields to mark
a ship onto self's grid.
The check is run for rows and columns that the ship would
occupy.
Args:
ship (battleships.ship.Ship): Ship whose potential placement
to check.
Returns:
bool: True if there are sufficient remaining ship fields to
mark ship onto self's grid, False otherwise.
"""
return all(
self.number_of_ship_fields_to_mark_in_series[series][series_index]
>= ship.ship_fields_count_in_series[series]
for series in Series
for series_index in ship.ship_fields_range[series]
)
def no_disallowed_overlapping_fields_for_ship(self, ship: Ship) -> bool:
"""Check whether ship marking onto self's grid would result in
disallowed field overlaps.
The check takes into consideration the entire ship's zone of
control.
Args:
ship (battleships.ship.Ship): Ship whose potential placement
to check.
Returns:
bool: True if no disallowed overlappings would occur by
marking the ship, False otherwise.
"""
return all(
board_field == FieldType.UNKNOWN
or (board_field == FieldType.SEA and ship_field == FieldType.SEA)
for board_row, ship_row in zip(
self.grid[ship.zoc_slice[Series.ROW]], ship.grid
)
for board_field, ship_field in zip(
board_row[ship.zoc_slice[Series.COLUMN]], ship_row
)
)
def can_fit_ship(self, ship: Ship) -> bool:
"""Check if ship fits onto self's grid.
Args:
ship (battleships.ship.Ship): Ship whose placement to check.
Returns:
bool: True if ship fits onto self's grid, False otherwise.
"""
return all(
(
self.ship_is_within_playable_grid(ship),
self.sufficient_remaining_ship_fields_to_mark_ship(ship),
self.no_disallowed_overlapping_fields_for_ship(ship),
)
)
def mark_ship_group(self, ships_to_mark: Iterable[Ship]) -> None:
"""Simulate marking of a group of ships onto self's grid.
Args:
ships_to_mark (Iterable[battleships.ship.Ship]): Ships to
mark onto self's grid.
Raises:
battleships.board.InvalidShipPlacementException: If the
ships to mark cannot all at the same time be placed onto
self's grid.
"""
for ship_to_mark in ships_to_mark:
if self.can_fit_ship(ship_to_mark):
self.mark_ship_and_surrounding_sea(ship_to_mark)
self.mark_sea_in_series_with_no_rem_ship_fields()
else:
raise InvalidShipPlacementException
def find_definite_ship_fields_positions(self) -> Set[Position]:
"""Find a set of self's grid positions that definitely contain
ship fields.
Definite ship fields can be determined by comparing the number
of ship fields remaining to be marked in a series to the number
of unknown fields in that same series. If the numbers are equal,
then all unknown fields are definitely ship fields.
The algorithm keeps track of all newly detected definite ship
fields, as well as marks all newly discovered sea fields.
The discovery procedure is repeated until no new definite ship
fields are found.
Returns:
Set[battleships.grid.Position]: Self's grid positions which
are determined to definitely contain ship fields.
"""
ship_fields_to_be = set() # type: Set[Position]
board_to_be = Board.get_copy_of(self)
continue_searching = True
while continue_searching:
continue_searching = False
ship_fields_to_be_new = set() # type: Set[Position]
for series, series_index in itertools.product(
Series, range(1, board_to_be.size - 1)
):
ship_fields_to_mark_count, unknown_fields_count = (
board_to_be.number_of_ship_fields_to_mark_in_series[series][
series_index
],
board_to_be.grid.fieldtype_count_in_series(
FieldType.UNKNOWN, series, series_index
),
)
if (
ship_fields_to_mark_count > 0
and ship_fields_to_mark_count == unknown_fields_count
):
continue_searching = True
unknown_positions = board_to_be.grid.fieldtype_positions_in_series(
FieldType.UNKNOWN, series, series_index
)
ship_fields_to_be_new.update(unknown_positions)
for position in ship_fields_to_be_new:
board_to_be.grid[position.row][position.col] = FieldType.SHIP
board_to_be.mark_diagonal_sea_fields_for_positions({position})
board_to_be.number_of_ship_fields_to_mark_in_series[Series.ROW][
position.row
] -= 1
board_to_be.number_of_ship_fields_to_mark_in_series[Series.COLUMN][
position.col
] -= 1
board_to_be.mark_sea_in_series_with_no_rem_ship_fields()
ship_fields_to_be.update(ship_fields_to_be_new)
return ship_fields_to_be
def get_possible_ships_occupying_positions(
self, positions: Set[Position], ship_sizes: Iterable[int]
) -> Dict[Position, Set[Ship]]:
"""For each given position in self's grid determine a set of
ships whose ship fields might - one at a time - cover that
position.
Args:
positions (Set[battleships.grid.Position]): Board positions
that are to be covered.
ship_sizes (Iterable[int]): Allowed sizes of ships to cover
the board positions.
Returns:
Dict[battleships.grid.Position, Set[battleships.ship.Ship]]:
For each position a set of ships whose ship fields might
- one at a time - cover that position.
"""
ships_occupying_positions = DefaultDict(
set
) # type: DefaultDict[Position, Set[Ship]]
for ship_size in [ship_size for ship_size in ship_sizes if ship_size != 1]:
for position in positions:
possible_ship_positions_for_orientation = {
Series.ROW: (
Position(position.row, col_index)
for col_index in range(
max(position.col - (ship_size - 1), 1),
min(position.col, self.size - 1 - ship_size) + 1,
)
),
Series.COLUMN: (
Position(row_index, position.col)
for row_index in range(
max(position.row - (ship_size - 1), 1),
min(position.row, self.size - 1 - ship_size) + 1,
)
),
}
ships_occupying_positions[position].update(
{
Ship(position, ship_size, orientation)
for orientation in Series
for position in possible_ship_positions_for_orientation[
orientation
]
if self.can_fit_ship(Ship(position, ship_size, orientation))
}
)
if 1 in ship_sizes:
for position in positions:
ships_occupying_positions[position].update(
{Ship(position, 1, Series.ROW)}
)
return ships_occupying_positions
def get_possible_ships_of_size(self, size: int) -> Set[Ship]:
"""Get all possible ships of a given size that can - one at a
time - be placed anywhere on self's grid.
Args:
size (int): Size of ship i.e. number of ship fields it
contains.
Returns:
Set[battleships.ship.Ship]: Ships of given size that can -
one at a time - be placed onto self's grid.
"""
if size == 1:
return {
Ship(Position(row_index, col_index), size, Series.ROW)
for row_index, row in enumerate(self.grid[1 : self.size - 1], 1)
for col_index, field in enumerate(row[1 : self.size - 1], 1)
if field == FieldType.UNKNOWN
and self.can_fit_ship(
Ship(Position(row_index, col_index), size, Series.ROW)
)
}
return {
Ship(Position(row_index, col_index), size, orientation)
for row_index, row in enumerate(self.grid[1 : self.size - 1], 1)
for col_index, field in enumerate(row[1 : self.size - 1], 1)
for orientation in Series
if field == FieldType.UNKNOWN
and self.can_fit_ship(
Ship(Position(row_index, col_index), size, orientation)
)
}
def mark_ship_and_surrounding_sea(self, ship: Ship) -> None:
"""Mark ship and its surrounding sea onto self's grid.
Args:
ship (battleships.ship.Ship): Ship to mark onto self's grid.
"""
for ship_row_index, board_row in enumerate(
self.grid[ship.zoc_slice[Series.ROW]]
):
board_row[ship.zoc_slice[Series.COLUMN]] = ship.grid[ship_row_index]
for series in Series:
self.number_of_ship_fields_to_mark_in_series[series][
ship.ship_fields_slice[series]
] = [
x - ship.ship_fields_count_in_series[series]
for x in self.number_of_ship_fields_to_mark_in_series[series][
ship.ship_fields_slice[series]
]
]
def is_overmarked(self) -> bool:
"""Check whether the number of ship fields to mark in any self's
grid series is bigger than the number of available unknown
fields in that same series.
Returns:
bool: True if the number of ship fields to mark in any
self's grid series is bigger than the number of
available unknown fields in that same series, False
otherwise.
"""
return any(
self.number_of_ship_fields_to_mark_in_series[series][series_index]
> self.grid.fieldtype_count_in_series(
FieldType.UNKNOWN, series, series_index
)
for series in Series
for series_index in range(1, self.size - 1)
)
class InvalidShipPlacementException(Exception):
"""Raised when ship's placement onto the board is invalid."""
|
89ad6ef8776b049047b8c4e899825e665994ecd3 | sralloza/aes | /aes/text.py | 1,414 | 3.921875 | 4 | """Manages text encription."""
from typing import Union
from cryptography.fernet import InvalidToken
from .exceptions import IncorrectPasswordError
from .utils import get_fernet
StrOrBytes = Union[str, bytes]
def encrypt_text(text: StrOrBytes, password: str = None) -> bytes:
"""Encrypts text.
Args:
text (StrOrBytes): text to encrypt.
password (str, optional): password to encrypt the file. If None,
the user will have to type it. Defaults to None.
Returns:
bytes: text encrypted.
"""
fernet = get_fernet(password=password, ensure=True)
if isinstance(text, str):
text = text.encode()
return fernet.encrypt(text)
def decrypt_text(text: StrOrBytes, password: str = None) -> bytes:
"""Decrypts text.
Args:
text (StrOrBytes): text to decrypt.
password (str, optional): password to decrypt the file. If None,
the user will have to type it. Defaults to None.
Raises:
IncorrectPasswordError: if the AES algorithm doesn't work due
to an incorrect password.
Returns:
bytes: text decrypted.
"""
fernet = get_fernet(password=password, ensure=False)
if isinstance(text, str):
text = text.encode()
try:
return fernet.decrypt(text)
except InvalidToken as exc:
raise IncorrectPasswordError("Incorrect password") from exc
|
3e1a9cf7b7fdfa77375331dfd403f905d77f00b9 | yl123168/Hello_world | /05Lecture练习8字符in字符串递归.py | 415 | 3.765625 | 4 | def isIn(char, aStr):
i = len(aStr)
if aStr == '':
return False
elif len(aStr) == 1 and char == aStr:
return True
elif char == aStr[i/2]:
return True
elif char < aStr[i/2]:
print(aStr)
return isIn(char,aStr[:i/2])
elif char > aStr[i/2]:
print(aStr)
return isIn(char,aStr[i/2+1:])
print(isIn('e','bcccceff')) |
bd59bf34da6ef34cea0c2eb47969da798e5fff4e | smvemula/MasterPython | /TakeABreak.py | 326 | 3.609375 | 4 | import webbrowser
import time
print("Program is start at" + time.ctime())
#creating a for loop to run 3 times
for index in range(3):
#print("Program is running for #" + (index + 1))
#sleep for 10 seconds
time.sleep(10)
#open youtube app at the end of timer
webbrowser.open('https://www.youtube.com/watch?v=tAGnKpE4NCI') |
c36970acd2e1aa67c4a1d1150e3962ab9963dc83 | Kohdz/Algorithms | /DataStructures/Trees/DFS_preOrder.py | 2,444 | 4.25 | 4 | class Stack():
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
class Node:
def __init__(self, value=None):
self.value = value
self.left = None
self. right = None
def get_value(self):
return self.value
def set_value(self, value):
self.value = value
def set_left_child(self, node):
self.left = node
def set_right_child(self, node):
self.right = node
def get_left_child(self):
return self.left
def get_right_child(self):
return self.right
def has_left_child(self):
return self.left != None
def has_right_child(self):
return self.left != None
def __repr__(self):
return f"Node({self.get_value()})"
def __str__(self):
return f"Node({self.get_value()})"
class Tree(object):
def __init__(self, value):
self.root = Node(value)
def get_root(self):
return self.root
# creating the tree
# apple
# / \
# banana cherry
# /
# dates
tree = Tree("apple")
tree.get_root().set_left_child(Node("banana"))
tree.get_root().set_right_child(Node("cherry"))
tree.get_root().get_left_child().set_left_child(Node("dates"))
# use stack to see what nodes we have visited
visit_order = list()
stack = Stack()
# start at the root node, visit it and then add it to the stack
node = tree.get_root()
stack.push(node)
print(f"""
visit_order {visit_order}
stack:
{stack}
""")
# check if apple/node has a left child
print(f"{node} has left child? {node.has_left_child()}")
# since apple has a left child (bannan)
# we'll visit banana and add it to the stack
visit_order.append(node.get_value())
print(f"""visit order {visit_order}
{stack}
""")
if node.has_left_child():
node = node.get_left_child()
stack.push(node)
print(f"""
visit_order{visit_order}
stack:
{stack}
""")
# visit banana
print(f"visit {node}")
visit_order.append(node.get_value())
print(f""" visit_order {visit_order}""")
# check if banana has a left child
print(f"{node} has left child? {node.has_left_child()}")
# since banana has a left c hild "dates"
# we'll visit "dates" and add it to the stack
if node.has_left_child():
node = node.get_left_child()
stack.push(node)
print(f"""
visit_order {visit_order}
stack:
{stack}
"""
)
|
bf595b009dd982212f2de1bdf7a9623b0d00faf0 | vishnuchauhan107/pythonBasicToAdvance | /python_notes_by_vishnu/vch/file_handling/file_handling.py | 8,141 | 4.40625 | 4 | '''
File Handling
As the part of programming requirement, we have to store our data permanently for
future purpose. For this requirement we should go for files.
Types of Files:
There are 2 types of files
1. Text Files:
Usually we can use text files to store character data
eg: abc.txt
2. Binary Files:
Usually we can use binary files to store binary data like images,video files, audio files etc...
'''
# Opening a File:
# Before performing any operation (like read or write) on the file,first we have to open that
# file.For this we should use Python's inbuilt function open()
# f = open(filename, mode)
'''The allowed modes in Python are
1. r open an existing file for read operation. The file pointer is positioned at the
beginning of the file.If the specified file does not exist then we will get
FileNotFoundError.This is default mode.
2. w open an existing file for write operation. If the file already contains some data
then it will be overridden. If the specified file is not already avaialble then this mode will
create that file.
3. a open an existing file for append operation. It won't override existing data.If the
specified file is not already avaialble then this mode will create a new file.
4. r+ To read and write data into the file. The previous data in the file will not be
deleted.The file pointer is placed at the beginning of the file.
5. w+ To write and read data. It will override existing data.
6. a+ To append and read data from the file.It wont override existing data.
7. x To open a file in exclusive creation mode for write operation. If the file already
exists then we will get FileExistsError
'''
# Closing a File:
# After completing our operations on the file,it is highly recommended to close the file.
# For this we have to use close() function.
# f.close()
# Various properties of File Object:
# name Name of opened file
# mode Mode in which the file is opened
# closed Returns boolean value indicates that file is closed or not
# readable() Retruns boolean value indicates that whether file is readable or not
# writable() Returns boolean value indicates that whether file is writable or not.
f=open("abc.txt", 'w')
print("File Name: ",f.name)
print("File Mode: ",f.mode)
print("Is File Readable: ",f.readable())
print("Is File Writable: ",f.writable())
print("Is File Closed : ",f.closed)
f.close()
print("Is File Closed : ",f.closed)
# out-File Name: abc.txt
# File Mode: w
# Is File Readable: False
# Is File Writable: True
# Is File Closed : False
# Is File Closed : True
# Writing data to text files:
# We can write character data to the text files by using the following 2 methods.
# write(str)
# writelines(list of lines)
f=open("abcd.txt", 'w')
f.write("vishnu\n")
f.write("Software\n")
f.write("Solutions\n")
print("Data written to the file successfully")
f.close()
# in abcd.txt:
# Durga
# Software
# Solutions
#Data written to the file successfully
f=open("abcd.txt", 'w')
list=["sunny\n","bunny\n","vinny\n","chinny"]
f.writelines(list)
print("List of lines written to the file successfully")
f.close()
# in abcd.txt:
# sunny
# bunny
# vinny
# chinny
# Note: while writing data by using write() methods, compulsory we have to provide line
# seperator(\n),otherwise total data should be written to a single line.
# Reading Character Data from text files:
# We can read character data from text file by using the following read methods.
# read() To read total data from the file
# read(n) To read 'n' characters from the file
# readline() To read only one line
# readlines() To read all lines into a list
f=open("abcd.txt", 'r')
data=f.read()
print(data)
f.close()
# out sunny
# bunny
# vinny
# chinny
f=open("abcd.txt", 'r')
data=f.read(10)
print(data)
f.close()
# out-sunny
# bunn
f=open("abcd.txt", 'r')
line1=f.readline()
print(line1,end='')
line2=f.readline()
print(line2,end='')
line3=f.readline()
print(line3,end='')
f.close()
# out-sunny
# bunny
# vinny
f=open("abcd.txt", 'r')
lines=f.readlines()
for line in lines:
print(line,end='')
f.close()
# out-bunny
# vinny
# chinny
f=open("abcd.txt", "r")
print(f.read(3))
print(f.readline())
print(f.read(4))
print("Remaining data")
print(f.read())
# out-sun
# ny
#
# bunn
# Remaining data
# y
# vinny
# chinny
# The with statement:
# The with statement can be used while opening a file.We can use this to group file
# operation statements within a block.
with open("abc.txt", "w") as f:
f.write("vishnu\n")
f.write("Software\n")
f.write("Solutions\n")
print("Is File Closed: ", f.closed)
print("Is File Closed: ", f.closed)
# out-Is File Closed: True
# Is File Closed: True
'''The seek() and tell() methods:
tell():
==>We can use tell() method to return current position of the cursor(file pointer) from
beginning of the file. [ can you plese telll current cursor position]
The position(index) of first character in files is zero just like string index.
'''
f=open("abc.txt", "r")
print(f.tell())
print(f.read(2))
print(f.tell())
print(f.read(3))
print(f.tell())
# out-0
# vi
# 2
# shn
# 5
# seek():
# We can use seek() method to move cursor(file pointer) to specified location.
# [Can you please seek the cursor to a particular location]
# f.seek(offset, fromwhere)
# The allowed values for second attribute(from where) are
# 0---->From beginning of file(default value)
# 1---->From current position
# 2--->From end of the file
data="All Students are STUPIDS"
f=open("abc.txt", "w")
f.write(data)
with open("abc.txt", "r+") as f:
text = f.read()
print(text)
print("The Current Cursor Position: ", f.tell())
f.seek(17)
print("The Current Cursor Position: ", f.tell())
f.write("GEMS!!!")
f.seek(0)
text = f.read()
print("Data After Modification:")
print(text)
# out- All Students are STUPIDS
# The Current Cursor Position: 24
# The Current Cursor Position: 17
# Data After Modification:
# All Students are GEMS!!!
# Handling Binary Data:
# It is very common requirement to read or write binary data like images,video files,audio
# files etc.
# Q. Program to read image file and write to a new image file?
'''f1=open("rossum.jpg","rb")
f2=open("newpic.jpg","wb")
bytes=f1.read()
f2.write(bytes)
print("New Image is available with the name: newpic.jpg")'''
# Zipping and Unzipping Files:
# It is very common requirement to zip and unzip files.
# To perform zip and unzip operations, Python contains one in-bulit module zip file.
# This module contains a class : ZipFile
# To create Zip file:
# We have to create ZipFile class object with name of the zip file,mode and constant
# ZIP_DEFLATED. This constant represents we are creating zip file.
# f = ZipFile("files.zip","w","ZIP_DEFLATED")
# Once we create ZipFile object,we can add files by using write() method.
# f.write(filename)
'''from zipfile import *
f=ZipFile("file.zip",'w',ZIP_DEFLATED)
f.write("file1.txt")
f.write("file2.txt")
f.write("file3.txt")
f.close()
print("files.zip file created successfully")'''
# To perform unzip operation:
# We have to create ZipFile object as follows
# f = ZipFile("files.zip","r",ZIP_STORED)
# names = f.namelist()
from zipfile import *
f=ZipFile("files.zip", 'r', ZIP_STORED)
names=f.namelist()
for name in names:
print( "File Name: ",name)
print("The Content of this file is:")
f1=open(name,'r')
print(f1.read())
print()
# Working with Directories:
# It is very common requirement to perform operations for directories like
# 1. To know current working directory
# 2. To create a new directory
# 3. To remove an existing directory
# 4. To rename a directory
# 5. To list contents of the directory
# Q1. To Know Current Working Directory:
import os
cwd=os.getcwd()
print("Current Working Directory:",cwd)
# out-Current Working Directory: /home/vishnu/Desktop/PythonTutorials/file_handling
# Q2. To create a sub directory in the current working directory:
import os
os.mkdir("hii")
print("mysub directory created in cwd")
# mysub directory created in cwd
# Q3. To create a sub directory in mysub directory:
import os
os.mkdir("mysub/mysub2")
print("mysub2 created inside mysub") |
4054ba3596551d61d35079079727c337cdd29ffd | fagan2888/Leetcode-Solutions-1 | /first_missing_positive/solution.py | 2,085 | 3.53125 | 4 | from typing import List, Tuple
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
num_positives = 0
the_min = len(nums)
the_max = 0
the_sum = 0
for i in range(len(nums)):
if nums[i] > 0:
num_positives += 1
the_sum += nums[i]
if nums[i] < the_min:
the_min = nums[i]
if nums[i] > the_max:
the_max = nums[i]
print('the_min', the_min)
if the_min != 1:
return 1
expected_sum_given_length = num_positives * (num_positives + 1) / 2
expected_sum_given_max = the_max * (the_max + 1) / 2
if the_sum == expected_sum_given_length and the_sum == expected_sum_given_max:
return the_max + 1
for i in range(len(nums)):
# Bucket sort.
if nums[i] < 1 or nums[i] > len(nums):
nums[i] = None
else:
swapped = nums[nums[i] - 1]
nums[nums[i] - 1] = nums[i]
if swapped is None or swapped < 1 or swapped > len(nums):
nums[i] = None
else:
nums[i] = swapped
counter = 0
while 1:
if nums[i] is None or nums[i] == i + 1:
break
swapped = nums[nums[i] - 1]
if swapped == nums[i]:
break
else:
nums[nums[i] - 1] = nums[i]
if swapped is None or swapped < 1 or swapped > len(nums):
nums[i] = None
else:
nums[i] = swapped
counter += 1
#if counter > 3:
# import pdb; pdb.set_trace()
for i in range(len(nums)):
if nums[i] is None or nums[i] != i + 1:
return i+1
return len(nums)
if __name__ == '__main__':
pass
|
c0c09032615a22cf2ebd3ea437372ecdef541f95 | NatheZIm/nguyensontung-homework-c4e14 | /Lab3/turtle_ex_5_6.py | 390 | 3.953125 | 4 | from turtle import *
speed(-1)
color("blue")
def draw_star(x,y,z):
count = 0
penup()
setx(x)
sety(y)
pendown()
while count <= 5:
forward(z)
right(144)
count += 1
for i in range(100):
import random
x = random.randint(-300, 300)
y = random.randint(-300, 300)
length = random.randint(3,10)
draw_star(x, y, length)
mainloop()
|
b099a4a9db22f087e41e7946df76019510354beb | mojianhua/python | /newStudyPython/day11/wraper.py | 4,529 | 3.953125 | 4 | import time
# 时间截
print(time.time())
# 休眠
# time.sleep(5)
print('123')
# def b():
# time.sleep(0.01)
# print('jim123')
#
# def a(f):
# start = time.time()
# f()
# end = time.time()
# return end - start
#
# print(a(b))
# 装饰器函数
# def timer(f):
# def inner():
# start = time.time()
# ret = f() # 被装饰器函数
# end = time.time()
# print(end - start)
# return ret
# return inner
#
# @timer #语法糖,@装饰器名 = func = timer(func)
# def func():
# print('JIM123')
# return 'Ok'
#
# #func = timer(func)
# res = func()
# print(res)
# 装饰器是对扩展是开发的,对修改是封闭的
# 语法糖
# 装饰带参数的装饰器
# def timer(f):
# def inner(a):
# start = time.time()
# ret = f(a) # 被装饰器函数
# end = time.time()
# print(end - start)
# return ret
# return inner
#
# @timer #语法糖,@装饰器名 = func = timer(func)
# def func(a):
# print('JIM12333333----' + str(a))
# return 'Ok'
#
# #func = timer(func)
# a = 1
# res = func(a)
# print(res)
# def timer(f):
# def inner(*args,**kwargs):
# start = time.time()
# ret = f(*args,**kwargs) # 被装饰器函数
# end = time.time()
# print(end - start)
# return ret
# return inner
#
# @timer #语法糖,@装饰器名 = func = timer(func)
# def func(a):
# print('JIM12333333----' + str(a))
# return 'Ok'
#
# @timer #语法糖,@装饰器名 = func = timer(func)
# def func(a,b):
# print('JIM12333333----' + str(a) + str(b))
# return 'Ok'
#
# #func = timer(func)
# res = func(1,b = 123)
# print(res)
# 装饰器的固定模式
# def warpper(f): #装饰器的名词,f是被装饰的函数
# def inner(*args,**kwargs):
# # 在被装饰函数之前要做的事
# print('在被装饰函数之前要做的事')
# ret = f(*args,**kwargs) #被装饰函数
# # 在被装饰函数之后要做的事
# print('在被装饰函数之后要做的事')
# return ret
# return inner
#
# @ warpper # 语法糖 func = warpper(func)
# def func(*args,**kwargs):
# print('111111')
# print(args)
# print(kwargs)
# print('jim12ddddddddddd3')
# return 'oK1111'
#
# print(func(1,2,3,4,a = 1 ,c =1)) # 实际上是执行 inner
def wrapper(function):
def inner(*args,**kwargs):
print('函数调用前执行')
ret = function(*args,**kwargs)
print('函数调用后执行')
return ret
return inner
@wrapper # === function = warrper(function)
def function(*args,**kwargs):
print('旧函数执行前执行')
print(args)
print(kwargs)
print('JIM123')
return '最后修改'
print(function(1,2,3,4,a = 1,b = 2))
# 如果想跳过装饰器,直接调用旧的function的函数,不想调用装饰器的warpper
# from functools import wraps
# def wrapper(function):
# @wraps(function)
# def inner(*args,**kwargs):
# print('函数调用前执行')
# ret = function(*args,**kwargs)
# print('函数调用后执行')
# return ret
# return inner
#
# @wrapper # === function = warrper(function)
# def function(*args,**kwargs):
# '''
# :param args:
# :param kwargs:
# :return: 旧的function
# '''
# print('旧函数执行前执行')
# print(args)
# print(kwargs)
# print('JIM123')
# return '最后修改'
#
# print(function.__name__) # 打印方法名
# print(function.__doc__) # 打印函数里面的注释
# print(function(1,2,3,4,a = 1,b = 2))
#带参数装饰器,又称为带参数装饰器
from functools import wraps
STATUS = False
def timerStatus(STATUS):
def timer(func):
# 完美装饰器添加的
@wraps(func)
def inner(*args,**kwargs):
if STATUS:
start = time.time()
ret = func(*args,**kwargs)
end = time.time()
print(end - start)
else:
ret = func(*args, **kwargs)
return ret
return inner
return timer
@timerStatus(STATUS) # 1、timer = timeStatus(STATUS);2、timer = timer(a)
def a():
time.sleep(0.01)
print('aaaaaaaaaaaaaaaaaaaaaaaa')
# 1、timer = timeStatus(STATUS);2、timer = timer(b)
@timerStatus(STATUS)
def b():
time.sleep(0.01)
print('bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')
a()
b() |
0aa5e76b97e8688b3ebfae55bf539b8ca7e3ef98 | mananiac/Codeforces | /Young Physicist.py | 249 | 3.640625 | 4 | countx,county,countz = 0,0,0
for _ in range(int(input())):
x,y,z = map(int,input().split())
countx,county,countz = countx+x,county+y,countz+z
#print(x,y,z)
if(countz==0 and county==0 and countx==0) :
print("YES")
else:
print("NO")
|
e300e3a6056503ca551632ef0d446fd1c3798d6b | larsgroeber/prg1 | /PRG1/sheet11/graph_generator.py | 3,758 | 4.09375 | 4 | class GraphGenerator:
def __init__(self):
self.graph: {[]} = dict()
self.length = 0
def setup_vertexes(self):
num_vertexes = input(
"Please enter the number of vertexes in your graph (integer).\n>>> ")
if not num_vertexes.isdigit() or int(num_vertexes) < 2:
print("Please enter an integer larger than one!")
return self.setup_vertexes()
num_vertexes = int(num_vertexes)
self.length = num_vertexes
for i in range(1, num_vertexes + 1):
self.graph[str(i)] = []
def setup_edges(self):
print("Now you can enter connections between nodes.")
print(
f"Enter two numbers between 1 and {self.length} (space separated) to add an undirected connection.")
print(
f"Enter two numbers between 1 and {self.length} separated by '>' to add an directed connection.")
print("Enter 'show' to visualize the current graph or 'done' to finish setting up edges.")
curr_input = ""
while True:
curr_input = input(">>> ")
if curr_input == 'show':
self.show_graph()
if curr_input == 'done':
break
input_list = curr_input.split(" ")
if len(input_list) > 1:
if len(input_list) > 2 or any(map(lambda x: x not in self.graph, input_list)):
print(
f"Please enter two number between 1 and {self.length} (space separated).")
continue
self.add_undirected_connection(input_list[0], input_list[1])
continue
input_list = curr_input.split(">")
if len(input_list) > 1:
if len(input_list) > 2 or any(map(lambda x: x not in self.graph, input_list)):
print(
f"Please enter two number between 1 and {self.length} (space separated).")
continue
self.add_directed_connection(input_list[0], input_list[1])
def show_graph(self):
print(self.graph)
def add_undirected_connection(self, node1, node2):
self.graph[node1].append(node2)
self.graph[node2].append(node1)
def add_directed_connection(self, node1, node2):
self.graph[node1].append(node2)
@staticmethod
def is_tree(graph):
generator = GraphGenerator()
generator.graph = graph
return not generator.has_cycles() and generator.are_all_nodes_connected()
def are_all_nodes_connected(self):
for node in self.graph:
if node != "1" and not self.are_nodes_connected("1", node):
return False
return True
def has_cycles(self):
for i in self.graph:
if self.are_nodes_connected(i, i):
return True
return False
def are_nodes_connected(self, start, end, visited_nodes=[], curr_node=None):
if curr_node is None:
curr_node = start
visited_nodes = visited_nodes + [curr_node]
for node in self.graph[curr_node]:
if len(visited_nodes) == 2 and node == start:
continue
if node == end or (node not in visited_nodes
and self.are_nodes_connected(start, end, visited_nodes, node)):
return True
return False
def are_nodes_adjacent(self, node1, node2):
return node2 in self.graph[node1] or node1 in self.graph[node2]
if __name__ == "__main__":
g = GraphGenerator()
g.setup_vertexes()
g.setup_edges()
print("This graph is a tree/forest." if GraphGenerator.is_tree(g.graph)
else "This graph is not a tree/forest.")
|
6014a277d9810adb2d0c8099753761d8eed8cd4c | ViAugusto/Logica-de-programacao-python | /ordenacao.py | 222 | 4 | 4 | a = int(input("Digite um valor: "))
b = int(input("Digite outro valor: "))
c = int(input("Digite mais um valor: "))
if a < b and b < c: {
print("crescente")
}
else: {
print("não está em ordem crescente")
}
|
ee2d27fda5751ef479b840bfdab135285f3b703f | AnTznimalz/python_prepro | /Prepro2019/guess_game.py | 290 | 4 | 4 | """Guess Game"""
def main():
"""Main Func."""
goal = int(input())
num = int(input())
while num != goal:
if num < goal:
print("Too low.")
else:
print("Too high.")
num = int(input())
print("Correct ! It's %d." %goal)
main()
|
73b4fed971b3a1dabbf0aa017c95fa30e26b3f86 | sakti2k6/DS_Algorithms_Specialization_Coursera | /Algorithmic_Toolbox/week2_algorithmic_warmup/1_fibonacci_number/fibonacci.py | 372 | 3.703125 | 4 | # Uses python3
def calc_fib(n):
if (n <= 1):
return n
return calc_fib(n - 1) + calc_fib(n - 2)
n = int(input())
#print(calc_fib(n))
def calc_fib_fast(n):
array = [];
i = 0
array.append(0)
array.append(1)
for i in range(2,n+1):
array.append(array[i-1] + array[i-2]);
return array[n];
print(calc_fib_fast(n)) |
c5aeb162bcee60648f71d9642d23a679d12ceced | nirmalrajkumar/python_training | /Day_6/classrecshape.py~ | 253 | 3.84375 | 4 | class shape:
def __init__(self):
print "shape"
class rec(shape):
def __init__(self,a,b):
self.a=a
self.b=b
def rect(self):
return self.a*self.b
def __str__(self):
return str(self.a)+str(self.b)
def pe(self):
return 2* self.a+ self.b
|
f35781b80debfd9055a5516ce81744ab6fb8b7a9 | zjzjgxw/leetcode | /py/maxPathSum.py | 759 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import sys
class Solution(object):
maxSum = -sys.maxsize-1
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def maxSumRootToLeaf(root):
if root is None:
return 0
left = max(0, maxSumRootToLeaf(root.left))
right = max(0, maxSumRootToLeaf(root.right))
self.maxSum = max(self.maxSum, left+right+root.val)
return root.val + max(maxSumRootToLeaf(root.left), maxSumRootToLeaf(root.right))
maxSumRootToLeaf(root)
return self.maxSum
|
717cf9611ab1ff2414075d3276fa7502847adac5 | Ekeopara-Praise/python-challenge-solutions | /Ekeopara_Praise/Phase 2/FILE I & O/Day84 Tasks/Task2.py | 311 | 4.28125 | 4 | '''2. Write a Python program to generate 26 text files named A.txt, B.txt, and so on up to Z.txt. '''
import string, os
if not os.path.exists("letters"):
os.makedirs("letters")
for letter in string.ascii_uppercase:
with open(letter + ".txt", "w") as f:
f.writelines(letter)
#Reference: w3resource |
8160cee21f66f52b23caccc17d3d520df3f0994c | adagio/advent-of-code | /source/day01/tests/test_addition.py | 483 | 3.6875 | 4 | from unittest import TestCase
from modules.addition import process
class AdditionTestCase(TestCase):
def test_process_example_1(self):
input_ = "+1, +1, +1".split(', ')
self.assertEqual(process(input_), 3)
def test_process_example_2(self):
input_ = "+1, +1, -2".split(', ')
self.assertEqual(process(input_), 0)
def test_process_example_3(self):
input_ = "-1, -2, -3".split(', ')
self.assertEqual(process(input_), -6)
|
7a471cba10bce3ac31d051d99bd970d68d35d5f2 | ninoude/leetcode | /problems/0025-reverse-nodes-in-k-group/sample.py | 1,175 | 3.78125 | 4 | from typing import List
from typing import Optional
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
arr = []
answer = point = ListNode(0)
check = k % 2 #even or odd
while head:
arr.append(head.val)
head = head.next
for index,item in enumerate(arr):
if (index+1) % k == 0:
self.rearrangeArr(arr,index,k,check)
for x in arr:
point.next = ListNode(x)
point = point.next
return answer.next
def rearrangeArr(self, arr, index, k, check):
num = int(k/2)
if check == 1:
for i in range(num):
tmp = arr[index-num-i-1]
arr[index-num-i-1] = arr[index-num+i+1]
arr[index-num+i+1] = tmp
else:
for i in range(num):
tmp = arr[index-num-i]
arr[index-num-i] = arr[index-num+1+i]
arr[index-num+1+i] = tmp
|
95d4f76bfaf8e24570e6c8685261e4fdd60ba37c | shreeharshas/LeetCode | /easy/9_PalindromeNumber/9.py | 433 | 3.5625 | 4 | # https://leetcode.com/problems/palindrome-number/
class Solution:
def isPalindrome(self, x: int) -> bool:
if x <= 0:
return False
s = []
while x > 0:
r = x % 10
x = int(x/10)
s.append(r)
for i in range(len(s)):
if s[i] != s[len(s) - i-1]:
return False
return True
ss = Solution()
print(ss.isPalindrome(12))
|
456f4f23b321fae09d01102e4aff8765a6c14afa | BronsonLotty/SelfProjects | /mystudy/mytree.py | 2,538 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 15 19:55:25 2018
@author: xutingxi
"""
#学习树和图
'''
跟据前序遍历创建二叉树链表。
输入为list,表示从list中的i点为根结点,访问visit点,并创建where树
eg list=['A','B','#','D','#','#','C','#','#']
'''
Trees={}
visit=0
global Trees
global visit
def CreateTree(l,index=0,visit=0,where='left'):
print('index=%s,visit=%s'%(index,visit))
if l[visit]=='#':
newval={'LeftTree':'#','data':'#','RightTree':'#'}
print('创建第%d结点,结点为空'%visit)
Trees[visit]=newval
if visit>=1 and where =='left':Trees[index]['LeftTree']=visit
if visit>=3 and where =='right':Trees[index]['RightTree']=visit
return visit
else:
if visit>=1 and where =='left':Trees[index]['LeftTree']=visit
if visit>=3 and where =='right':Trees[index]['RightTree']=visit
newval={'LeftTree':0,'data':l[visit],'RightTree':0}
print('创建第%d结点'%visit)
Trees[visit]=newval
index=visit
visit+=1
print('递归调用,创建左树')
visit=CreateTree(l,index,visit,'left')#创建左树
visit+=1
#index=visit-1
print('递归调用,创建右树')
visit=CreateTree(l,index,visit,'right')#创建右树
return visit
mysort=['A','B','#','D','#','#','C','#','#']
CreateTree(mysort)
'''
根据中序遍历创建二叉树链表。
'''
newval={'LeftTree':'#','data':'#','RightTree':'#'}
Tree={0:newval}
global Trees
def midsortTree(l,index=1,visit=1,where='left'):
if l[visit]=='#':
newval={'LeftTree':'#','data':'#','RightTree':'#'}
Trees[visit]=newval
# index+=1
visit+=1
midsortTree(l,index,visit,'parent')
midsortTree(l,index,visit,'right')
else:
newval={'LeftTree':0,'data':l[visit],'RightTree':0}
Trees[visit]=newval
if visit>=1 and where =='parent':
Trees[visit]['LeftTree']=index
if l[visit]=='#':
return
index=visit
visit+=1
midsortTree(l,index,visit,'right')
if visit>=2 and where =='left':
Trees[visit]['LeftTree']=index
index=visit
visit+=1
midsortTree(l,index,visit,'right')
if visit>=2 and where =='right':Trees[index]['RightTree']=visit
return
|
ed98ecb5631f2a24cb134ee2d6ce45dcc68d562a | devbaj/python_oop | /zoo.py | 1,677 | 3.828125 | 4 | class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
self.health = 100
self.happiness = 100
def display_info(self):
print(f"Animal: {self.name}, Age: {self.age}, Health Index {self.health}, Happiness Index: {self.health}")
return self
def feed(self):
self.health += 10
self.happiness += 10
return self
class Lion(Animal):
def __init__(self, name, age):
super().__init__(name, age)
self.health = 70
self.happiness = 20
class Bear(Animal):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
self.health = 80
self.happiness = 100
class Platypus(Animal):
def __init__(self, name, age):
super().__init__(name, age)
self.health = 30
self.happiness = 50
class Zoo:
def __init__(self, zoo_name):
self.animals = []
self.name = zoo_name
def add_lion(self, name, age):
self.animals.append( Lion(name, age) )
return self
def add_bear(self, name, age, color):
self.animals.append( Bear(name, age, color) )
return self
def add_platypus(self, name, age):
self.animals.append( Platypus(name, age))
return self
def print_zoo_info(self):
print ("-"*30, self.name, "-"*30)
for animal in self.animals:
animal.display_info()
zoo1 = Zoo("Safari XTREME")
zoo1.add_lion("Nala", 8).add_bear("Koda", 4, "brown").add_platypus("Parry", 12).add_lion("Mufasa", 25)
zoo1.print_zoo_info()
zoo1.animals[1].feed()
zoo1.animals[3].feed()
zoo1.print_zoo_info() |
16b2756a229c792332043b619c5220e918517e2f | cholsi20/Python | /Python Files/StopWatch.py | 475 | 3.5625 | 4 | import time
class StopWatch:
def __init__(self):
self.__startTime = time.time()
#get methods for start and end
def getStartTime(self):
return self.__startTime
def getEndTime(self):
return self.__endTime
#define start and stop
def start(self):
self.__startTime = time.time()
def stop(self):
self.__endTime = time.time()
#getting elapsed time
def getElapsedTime(self):
elapsedTime = (self.__endTime - self.__startTime) * 1000
return elapsedTime |
3d97c97345d6d48de7b69e908f1a396f9ffb7d22 | fjimenez81/test_pyhton | /inversa.py | 140 | 3.625 | 4 | def inversa(x):
cont=""
for i in x:
cont=i+cont
return cont
print(inversa(input("Ingresa algo para darlo la vuelta: "))) |
2789db209e4e19a3412a46278875f6eb8f090cc4 | gambxxxx/scripts | /practice-stuff/python-stuff/Tic_Tac_Toe.py | 3,628 | 3.71875 | 4 | import random
the_board = [' '] * 10
def display_board(board):
def display_board(a,b):
print(f'Available TIC-TAC-TOE\n moves\n\n {a[7]}|{a[8]}|{a[9]} {b[7]}|{b[8]}|{b[9]}\n ----- -----\n {a[4]}|{a[5]}|{a[6]} {b[4]}|{b[5]}|{b[6]}\n ----- -----\n {a[1]}|{a[2]}|{a[3]} {b[1]}|{b[2]}|{b[3]}\n')
display_board(available,theBoard)
def player_input():
marker =''
#Keep asking to choose X or O
#assign vtoriot na sprotivnoto
while not(marker == 'X' or marker == 'O'):
marker=input('Player1 choose X or O').upper()
if marker == 'X':
return ('X','O')
else:
return ('O','X')
def place_marker(board, marker, position):
board[position]=marker
def win_check(board, mark):
return ((board[7] == mark and board[8] == mark and board[9] == mark) or
(board[4] == mark and board[5] == mark and board[6] == mark) or
(board[1] == mark and board[2] == mark and board[3] == mark) or
(board[7] == mark and board[4] == mark and board[1] == mark) or
(board[8] == mark and board[5] == mark and board[2] == mark) or
(board[9] == mark and board[6] == mark and board[3] == mark) or
(board[7] == mark and board[5] == mark and board[3] == mark) or
(board[9] == mark and board[5] == mark and board[1] == mark))
def choose_first():
if random.randint(0,1) == 0:
return 'Player 2'
else:
return 'Player 1'
def space_check(board, position):
board[position]==' '
def full_board_check (board):
for i in range(1,10):
if space_check(board,i):
return False
return True
def player_choice(board):
position=0
while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board,position):
position=(input('Choose position 1-9'))
return position
def replay():
return input('play again? yes/no').lower().startswith('y')
print('Welcome to Tic tac Toe!')
test_board=['#','X','O','X','O','X','X','O','X','O','X']
display_board(test_board)
while True:
# Set the game up here
the_board=[' ']*10
player1_marker,player2_marker = player_input()
turn=choose_first()
print(turn+ ' will go first ')
play_game=input('Ready to play? y or n?')
if play_game.lower()[0] == 'y':
game_on= True
else:
game_on= False
while game_on:
if turn == 'Player 1':
#show position
display_board(the_board)
position=player_choice(the_board)
place_marker(the_board,player1_marker,position)
if win_check(the_board,player1_marker):
display_board(the_board)
print('Player1 has won')
game_on = False
else:
if full_board_check(the_board):
display_board(the_board)
print('Tie game')
break
else:
turn='Player 2'
else:
display_board(the_board)
position=player_choice(the_board)
place_marker(the_board,player2_marker,position)
if win_check(the_board,player2_marker):
display_board(the_board)
print('Player2 has won')
game_on = False
else:
if full_board_check(the_board):
display_board(the_board)
print('Tie game')
break
else:
turn='Player1'
# while game_on:
# player1's turn
# player2's turn.
# pass
if not reply():
break
|
cc8812ea32486b8d784c884fe39e93a5fb35f069 | KistVictor/exercicios | /exercicios de python/Mundo Python/032.py | 431 | 3.875 | 4 | '''ano = int(input('Digite um ano: '))
anob = ano/4
if anob%1 == 0:
print('O ano é bissexto')
else:
print('O ano não é bissexto')'''
from datetime import date
ano = int(input('Digite um ano ("0" para o ano atual): '))
if ano == 0:
ano = date.today().year
if ano%4 == 0 and ano % 100 != 0 or ano % 400 == 0:
print('O ano de {} é bissexto'.format(ano))
else:
print('O ano de {} não é bissexto'.format(ano)) |
9e0cd1cdce22f645c9a9c4b75b7d40a063b2ed8e | amatyas2084/AndrewMatyas | /Python files/codes5.py | 6,361 | 3.8125 | 4 | '''
Author: Andrew Matyas
Date: 2/5
Description:
This program does stuff with binary
'''
class Binary():
def __init__(self, arg='0'):
""" Each Binary object has one instance variable, a list called
num_list. num_list has integers 0 or 1 in the same order as
the corresponding characters in the argument. If the string
is less than 16 characters long, num_list should be padded by
repeating the leftmost digit until the list has 16 elements.
This is done by calling the pad() method.
Args:
self
arg -- (str) 0's and 1's, 16 or less chars. Default is 0
returns:
n/a
"""
num_list = []
if len(arg) > 16:
raise RuntimeError
elif len(arg) == 0:
num_list.append(0)
else:
arg = list(arg)
for i in arg:
if not(i is '0' or i is '1'):
raise RuntimeError
num_list.append(int(i))
self.num_list = num_list
if len(num_list) < 16:
self.pad()
def pad(self):
""" Pad num_list by repeating the leftmost digit until the list
has 16 elements.
Args:
self
returns:
none
"""
to_repeat = self.num_list[0]
self.num_list.reverse()
for i in range(len(self.num_list), 16):
self.num_list.append(to_repeat)
self.num_list.reverse()
def __repr__(self):
""" Returns a 16-character string representing the fixed-width
binary number.
Args:
self -- (Binary) containing a 16-digit list
returns:
(string) representation on Binary object
"""
r = ""
for i in self.num_list:
r += str(i)
return r
def __add__(self, to_add):
""" Returns a new Binary instance that represents the sum of self
and the argument. If the sum requires more than 16 digits,
raise a RuntimeError.
Args:
self -- (Binary) base object
to_add -- (Binary) an object to add to base
returns:
(Binary) result of added objects.
(RuntimeError) if results cannot be added
"""
first_neg = (self.num_list[0] == 1)
second_neg = (to_add.num_list[0] == 1)
added = []
total = 0
carry = 0
for i in range(16):
total = self.num_list[15 - i] + to_add.num_list[15 - i] + carry
if total == 0 or total == 1:
added.append(total)
carry = 0
elif total == 2:
added.append(0)
carry = 1
else:
added.append(1)
carry = 1
added.reverse()
if added[0] == 1 and (not first_neg and not second_neg):
raise RuntimeError("Overflow!")
if carry != 0 and (first_neg and second_neg) and added[0] == 0:
raise RuntimeError("Overflow!")
new_nums = Binary("")
new_nums.num_list = added
return new_nums
def __neg__(self):
""" Return a new Binary instance that equals -self.
Args:
self
returns:
(Binary) negative of self
"""
flip = Binary("")
for i in range(16):
if self.num_list[i] == 0:
flip.num_list[i] = 1
else:
flip.num_list[i] = 0
flip = flip + Binary("01")
return flip
def __sub__(self, to_subtract):
""" Takes a Binary object as an argument. Returns a new Binary
instance that represents self – the argument.
Args:
self
to_subtract -- (Binary) to subtract from self
returns:
(Binary)
"""
return self + -to_subtract
def __int__(self):
""" Return the decimal value of the Binary object. This method
should never raise a RuntimeError due to overflow. It is not
used anywhere else in this program
Args:
self
returns:
(int) corresponding to the Binary object
"""
digits = self
if self.num_list == [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]:
return -32768
int_num = 0
neg = False
if self.num_list[0] == 1 :
neg = True
digits = (-digits)
for i in range(16):
if digits.num_list[15-i] == 1:
int_num += 2**i
if neg:
int_num = -int_num
return int_num
def __eq__(self, other):
""" Takes a Binary object. Returns True if self == the argument,
False otherwise.
Args:
self
other: (Binary) object to be compared
returns:
Boolean representing equality of objects
"""
return self.num_list == other.num_list
def __lt__(self, compare):
""" Takes a Binary object as an argument. Return True if
self < the argument, False otherwise. This method should
never raise a RuntimeError due to overflow.
Args:
self
compare -- (Binary) object to compare to self
returns:
(Boolean) is 'self' less than 'compare'?
"""
if self.num_list[0] == 0 and compare.num_list[0] == 1:
return False
elif self.num_list[0] == 1 and compare.num_list[0] == 0:
return True
else:
return (self - compare).num_list[0] == 1
def __abs__(self):
""" Return a new instance that is the absolute value of self.
Args:
self
returns:
(Binary) absolute value of self
"""
if self.num_list[0] == 1:
return -self
return self+Binary()
def main():
'''
Write a description of what happens when you run
this file here.
'''
if __name__ == '__main__':
main()
|
af8fdedbb354bdae31163aedd47c0fd5e16928ee | kefitaib/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 179 | 3.59375 | 4 | #!/usr/bin/python3
"""
Module
"""
def append_write(filename="", text=""):
""" function """
with open(filename, 'a', encoding='utf8') as f:
return f.write(text)
|
ab8bec632c541d62b600f0c80119dfdfb333041f | benbryson789/JWT-Auth | /readme/public_key_cryptography.py | 1,696 | 3.796875 | 4 | import random
class Key:
def __init__(self, public_key_base, public_key_modulus):
self.public_key_base = public_key_base
self.public_key_modulus = public_key_modulus
self.private_key = random.randint(1,100)
def generate_public_key(self):
return pow(self.public_key_base, self.private_key) % self.public_key_modulus
def generate_shared_secret(self, another):
return pow(another, self.private_key) % self.public_key_modulus
def return_shared_secret():
public_key_base = 3
public_key_modulus = 23
alice_private_secret = Key(public_key_base, public_key_modulus)
bob_private_secret = Key(public_key_base, public_key_modulus)
shared_secret_alice = alice_private_secret.generate_shared_secret(bob_private_secret.generate_public_key())
shared_secret_bob = bob_private_secret.generate_shared_secret(alice_private_secret.generate_public_key())
return {
"shared_secret_alice": shared_secret_alice,
"shared_secret_bob": shared_secret_bob
}
# import random
# # https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
# # http://billatnapier.com/security02.aspx
# # both g and p should be primes
# # s is the shared secret, known only to alice and bob
# # both of these are public
# g = 3
# p = 23
# alice_private = random.randint(1,100) # only Alice knows this
# alice = pow(g, alice_private) % p
# bob_private = random.randint(1,100) # only Bob knows this
# bob = pow(g, bob_private) % p
# print(f"alice: {alice}, bob: {bob}")
# s_alice = pow(bob, alice_private) % p
# s_bob = pow(alice, bob_private) % p
# print(f"s_alice = {s_alice}, s_bob = {s_bob}") |
c4dc7497a4106e5b75930302dc6e3bb2b5a6dea3 | redashu/shubhredhat | /function_sample2.py | 283 | 3.75 | 4 | #!/usr/bin/python2
import time,commands
def sum(x,y):
print x+y
###### now adding two numbers
if __name__ == '__main__' :
a=int(raw_input("type first number : "))
b=int(raw_input("type second number : "))
sum(a,b)
else :
print "not in mood"
|
2735b492eec33ec89163721785010d4c349084cc | riadhassan/numericalAnalysisLab | /NewtonsBackwardInterpolution/backword formula.py | 1,260 | 3.6875 | 4 | import math
#read input value from file
file_name = input("Enter file name with extension: ") #code and input file should be in same folder
f = open(file_name, "r")
data = f.read()
print(data)
data = data.split()
x, y = [], []
for i,j in zip(data[0::2], data[1::2]):
x.append(float(i))
y.append(float(j))
inp = float(input("Enter value of x for interpolation: "))
#calculation of table
table = [y]
for l in range(len(y)-1):
yn = []
for i,k in zip(y[1::1], y[0::1]):
yn.append(i-k)
table.append(yn)
y = yn
#print table
formated_table = [["x", "f(x)", "∇f(x)"]]
for i in range(2,len(table)):
formated_table[0].append("∇^" + str(i) + "f(x)")
for i in range(len(x)):
row = []
for j in range(len(table)-i):
row.append(str(round(table[j][i],5)))
row.insert(0, str(x[i]))
formated_table.append(row)
for row in formated_table:
print("\t".join(row))
#calculation of r
r = (inp - x[-1])/(x[1]-x[0])
#result calculation
r_component = 1
partial_result = 0
for i in range(1, len(table)):
r_component = r_component*(r+i-1)
partial_result = partial_result + (table[i][-1]*r_component)/math.factorial(i)
final_result = table[0][-1] + partial_result
print("f(" + str(inp)+ ") = ", final_result)
|
e3cacf99737ef490191d3501930bffce97c1b699 | HANXU2018/HBU2019programingtext | /信安作业jpg/3kaisa.py | 228 | 3.546875 | 4 | s=input('凯撒加密字符串')
n=eval(input('偏移量(这道题是13)'))
for i in s:
if(ord(i)< 97 or ord(i)> 122):
print(i,end='')
else:
d=(ord(i)-97+26-n)%26
print(chr(d+97),end='')
|
6f74495598ce1f25550f5f7e8e6ef3bc8e3a4744 | xiangcao/Leetcode | /python_leetcode_2020/Python_Leetcode_2020/261_graph_valid_tree.py | 2,635 | 4.1875 | 4 | """
Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
Example 1:
Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]]
Output: true
Example 2:
Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
Output: false
Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0,1] is the same as [1,0] and thus will not appear together in edges.
"""
class Solution(object):
def validTree(self, n: int, edges: List[List[int]]) -> bool:
if len(edges) != n - 1: return False
adj_list = [[] for _ in range(n)]
for A, B in edges:
adj_list[A].append(B)
adj_list[B].append(A)
seen = set()
def dfs(node, parent):
if node in seen: return False;
seen.add(node)
for neighbour in adj_list[node]:
if neighbour == parent:
continue
if not dfs(neighbour, node): return False
return True
# We return true iff no cycles were detected,
# AND the entire graph has been reached.
return dfs(0, -1) and len(seen) == n
"""
Depending on how much graph theory you know, there's a better definition for determining whether or not a given graph is a tree.
For the graph to be a valid tree, it must have exactly n - 1 edges. Any less, and it can't possibly be fully connected. Any more, and it has to contain cycles. Additionally, if the graph is fully connected and contains exactly n - 1 edges, it can't possibly contain a cycle, and therefore must be a tree!
Going by this definition, our algorithm needs to do the following:
Check whether or not there are n - 1 edges. If there's not, then return false.
Check whether or not the graph is fully connected. Return true if it is, false if otherwise.
# don't need to check if there is a cycle or not.
def validTree(self, n, edges):
if len(edges) != n - 1: return False
# Create an adjacency list.
adj_list = [[] for _ in range(n)]
for A, B in edges:
adj_list[A].append(B)
adj_list[B].append(A)
# We still need a seen set to prevent our code from infinite
# looping if there *is* cycles (and on the trivial cycles!)
seen = set()
def dfs(node):
if node in seen:
return
seen.add(node)
for neighbour in adj_list[node]:
dfs(neighbour)
dfs(0)
return len(seen) == n
|
ec45d25f887b7553b69fea998c5e866c13628b91 | amriteshs/comp9021-codes | /Exams/Mid-Sem Practice/2017/exercise06.py | 3,969 | 3.984375 | 4 | import sys
def f(a, b):
'''
Finds all numbers i and j with a <= i <= j <= b such that:
- i + j is even;
- when read from left to right, the digits in i are strictly increasing
- when read from left to right, the digits in j are strictly decreasing
- when read from left to right, the digits in the average of i and j are
either strictly increasing or strictly decreasing
Outputs the solutions from smallest i to largest i,
and for a given i from smallest j to largest j.
>>> f(10, 20)
12 and 20 with 16 as average
14 and 20 with 17 as average
16 and 20 with 18 as average
18 and 20 with 19 as average
>>> f(30, 50)
34 and 40 with 37 as average
34 and 42 with 38 as average
34 and 50 with 42 as average
35 and 41 with 38 as average
35 and 43 with 39 as average
36 and 40 with 38 as average
36 and 42 with 39 as average
36 and 50 with 43 as average
37 and 41 with 39 as average
37 and 43 with 40 as average
38 and 40 with 39 as average
38 and 42 with 40 as average
39 and 41 with 40 as average
39 and 43 with 41 as average
46 and 50 with 48 as average
48 and 50 with 49 as average
>>> f(400, 700)
456 and 630 with 543 as average
457 and 521 with 489 as average
458 and 520 with 489 as average
459 and 621 with 540 as average
468 and 510 with 489 as average
478 and 542 with 510 as average
479 and 541 with 510 as average
489 and 531 with 510 as average
567 and 653 with 610 as average
568 and 610 with 589 as average
568 and 652 with 610 as average
569 and 651 with 610 as average
578 and 642 with 610 as average
579 and 641 with 610 as average
589 and 631 with 610 as average
589 and 651 with 620 as average
589 and 653 with 621 as average
'''
if a <= 0 or b < a:
sys.exit()
#Insert your code here
i = a
while i <= b:
x = str(i)
order = ['i', 'd']
order_a = 'x'
if len(x) is 1:
order_a = order[0]
else:
l1 = list(x)
l1.sort()
s1 = set(l1)
tmp1 = ''.join(l1)
if x == tmp1 and len(l1) == len(s1):
order_a = 'i'
if order_a is order[0]:
j = i
while j <= b:
y = str(j)
order_b = 'x'
if len(y) is 1:
order_b = order[1]
else:
l2 = list(y)
l2.sort(reverse=True)
s2 = set(l2)
tmp2 = ''.join(l2)
if y == tmp2 and len(l2) == len(s2):
order_b = 'd'
if order_b is order[1] and not (i + j) % 2:
avg = (i + j) // 2
z = str(avg)
order_c = 'x'
if len(z) is 1:
order_c = 'i'
else:
l3 = list(z)
s3 = set(l3)
l3.sort()
tmp31 = ''.join(l3)
l3.sort(reverse=True)
tmp32 = ''.join(l3)
if len(l3) == len(s3):
if z == tmp31:
order_c = 'i'
elif z == tmp32:
order_c = 'd'
if order_c in order:
print(f'{i} and {j} with {avg} as average')
j += 1
i += 1
# Possibly define other functions
if __name__ == '__main__':
import doctest
doctest.testmod()
|
20ee546460536192ca557381a6ace716e63d8ee8 | charliedmiller/coding_challenges | /insertion_sort_list.py | 2,553 | 3.890625 | 4 | # Charlie Miller
# Leetcode - 147. Insertion Sort List
# https://leetcode.com/problems/insertion-sort-list/
"""
This implementation sorts in-place, and swaps nodes, not values
maintain 4 pointers: 1 for the insert node - the node we are
"inserting" for the sort, and 1 for what we're comparing, and
both's respective previous. compare the insert node with the
compare node and previous to determine if node should be inserted there
if so rearrange the necessary pointers and advance insert node, otherwise
advance compare node
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
insert_prev = None
insert_node = head
#we can only insert into a "sorted set" which is as long
#as how many we've sorted so far
sorted_ct = 0
while insert_node:
#compare nodes init
prev = None
cur_node = head
for _ in range(sorted_ct):
#insert node should be first
if not prev and insert_node.val <= cur_node.val :
temp_next_insert = insert_node.next
insert_node.next = head
#make insert node head
head = insert_node
if insert_prev:
insert_prev.next = temp_next_insert
#make insert node it's prev so it advances correctly
insert_node = insert_prev
break
elif prev and prev.val < insert_node.val and insert_node.val <= cur_node.val:
temp_next_insert = insert_node.next
insert_node.next = cur_node
prev.next = insert_node
if insert_prev:
insert_prev.next = temp_next_insert
#make insert node it's prev so it advances correctly
insert_node = insert_prev
break
#advance compare nodes
prev = cur_node
cur_node = cur_node.next
#advance insert node
insert_prev = insert_node
insert_node = insert_node.next
sorted_ct += 1
return head |
04cfd5ad30fbf9ee1b5f59a7702d408c9457fcf6 | Vagacoder/Codesignal | /python/Arcade/Core/C94BeautifulText.py | 3,069 | 4.21875 | 4 | #
# * Core 94. Beautiful Text
# * Medium
# * Consider a string containing only letters and whitespaces. It is allowed to
# * replace some (possibly, none) whitespaces with newline symbols to obtain a
# * multiline text. Call a multiline text beautiful if and only if each of its
# * lines (i.e. substrings delimited by a newline character) contains an equal
# * number of characters (only letters and whitespaces should be taken into account
# * when counting the total while newline characters shouldn't). Call the length
# * of the line the text width.
# Given a string and some integers l and r (l ≤ r), check if it's possible to
# obtain a beautiful text from the string with a text width that's within the
# range [l, r].
# * Example
# For inputString = "Look at this example of a correct text", l = 5, and r = 15, the output should be
# beautifulText(inputString, l, r) = true.
# We can replace 13th and 26th characters with '\n', and obtain the following multiline text of width 12:
# Look at this
# example of a
# correct text
# For inputString = "abc def ghi", l = 4, and r = 10, the output should be
# beautifulText(inputString, l, r) = false.
# There are two ways to obtain a text with lines of equal length from this input, one has width = 3 and another has width = 11 (this is a one-liner). Both of these values are not within our bounds.
# * Input/Output
# [execution time limit] 4 seconds (py3)
# [input] string inputString
# Guaranteed constraints:
# 10 ≤ inputString.length ≤ 40.
# [input] integer l
# A positive integer.
# Guaranteed constraints:
# 1 ≤ l ≤ r.
# [input] integer r
# A positive integer.
# Guaranteed constraints:
# l ≤ r ≤ 15.
# [output] boolean
#%%
# * Solution 1
def beautifulText(inputString: str, l: int, r: int)-> bool:
n = len(inputString)
wsIndices = []
for i in range(n):
if inputString[i].isspace():
wsIndices.append(i)
print(n)
print(wsIndices)
for j in wsIndices:
if l <= j <= r:
if n%(j+1) != j:
continue
good = True
nextJ = j
while good and nextJ < n :
if not nextJ in wsIndices:
good = False
nextJ += (j+1)
if good:
return True
return False
# * Solution 2
def beautifulText2(inputString, l, r):
for w in range(l, r+1):
i = w
while i < len(inputString):
if inputString[i] != ' ':
break
i += w+1
if i == len(inputString):
return True
return False
a1 = 'Look at this example of a correct text'
l1 = 5
r1 = 15
r1 = beautifulText(a1, l1, r1)
print(r1)
a1 = 'abc def ghi'
l1 = 4
r1 = 10
r1 = beautifulText(a1, l1, r1)
print(r1)
a1 = 'a a a a a a a a'
l1 = 1
r1 = 10
r1 = beautifulText(a1, l1, r1)
print(r1)
a1 = 'aa aa aaaaa aaaaa aaaaa'
l1 = 6
r1 = 11
r1 = beautifulText(a1, l1, r1)
print(r1)
|
efbc091632f2335377d4e549f699037184102ffb | Matieljimenez/Algoritmos_y_programacion | /Taller_estruturas_de_control_secuenciales/Python_yere/Ejercicio_11.py | 1,176 | 4.15625 | 4 | """
Entradas
nombre del trabajador-->str-->a
Sueldo base del trabajador-->float-->b
precio por hora normal del trabajador-->c
horas normales de trabajo realizadas-->int-->d
horas extra de trabajo realizadas-->int-->e
número de actualización academica del trabajador-->int-->f
número de hijos del trabajador-->int-->g
Salidas
asignaciones del trabajador-->float-->j
deducciones del trabajador-->float-->k
sueldo neto del trabajador-->float-->l
"""
a=str(input("Ingrese el nombre del trabajador "))
b=float(input("Ingrese el sueldo base del trabajador "))
c=float(input("Ingrese el valor por hora normal "))
d=int(input("Ingrese la cantidad de horas normales trabajadas "))
e=int(input("Ingrese la cantidad de horas extras trabajadas "))
f=int(input("Ingrese la cantidad de actualizaciones academicas hechas por el trabajador "))
g=int(input("Ingrese la cantidad de hijos del trabajador "))
h=(c*0.25)*e
i=d*c
j=(250000*f)+(173000*g)+180000
k=((b*0.05)+(b*0.02)+(b*0.07))
l=b+j+h+i-k
print("Las asignaciones del trabajador son: "+str(j))
print("Las deducciones del trabajador son: "+str(k))
print("El sueldo neto del trabajador "+str(a)+" en el mes de diciembre es: "+str(l)) |
53603c74512a52a6adaeabe98265c11c9c0ee848 | suribhatt/chatbot | /logger/logger.py | 1,089 | 3.640625 | 4 | from datetime import datetime
import sqlite3
class Log:
def __init__(self):
pass
def write_log(self, sessionID, log_message):
self.file_object = open("conversationLogs/"+sessionID+".txt", 'a+')
self.now = datetime.now()
self.date = self.now.date()
self.current_time = self.now.strftime("%H:%M:%S")
self.file_object.write(
str(self.date) + "/" + str(self.current_time) + "\t\t" + log_message + "\n")
self.file_object.close()
self.insert_to_database(self.current_time,log_message)
def insert_to_database(self, date, log_message):
try:
conn = sqlite3.connect('chat')
curr = conn.cursor()
curr.execute("""create table if not exists log_data(
date text,
log_message text
)""")
query = """insert into log_data values('%s','%s')"""%(date,log_message)
curr.execute(query)
conn.commit()
conn.close()
except:
pass
|
7caa948b5b07817ea9517eea861d46b7c806e829 | Raihan9797/Python-Crash-Course | /chapter_11/test_v2_survey.py | 1,366 | 4.0625 | 4 | ## setUp() method
## MAKE SURE THE 'U' IS IN CAPS
'''
when you include setup() method in a testclass case, python runs the setup() method before running each method starting with test_.
Any objects created in the setup() method are then available in each test method you write
'''
import unittest
from chapter_11.survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
"""Tests for the class AnonymousSurvey"""
def setUp(self):
"""
Create a survey and a set of responses for use in all test methods.
"""
question = "What language did you first learn to speak?"
self.my_survey = AnonymousSurvey(question)
self.responses = ['English', 'Spanish', 'Mandarin']
def test_store_single_response(self):
"""Test that a single response is stored properly"""
# store 'english'
self.my_survey.store_response(self.responses[0])
# check 'english'
self.assertIn(self.responses[0], self.my_survey.responses)
def test_store_three_responses(self):
"""Test that a single response is stored properly"""
# insert responses
for r in self.responses:
self.my_survey.store_response(r)
# checking responses
for r in self.responses:
self.assertIn(r, self.my_survey.responses)
unittest.main()
|
6012ec6c72c9976ede543601dd8da2e8b7334d02 | yuanguLeo/yuanguPython | /CodeDemo/shangxuetang/一期/面向对象/静态方法.py | 919 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/9/26 9:25
'''
与“类对象”无关的方法,称为“静态方法”
“静态方法”和在模块中定义普通函数没有区别,只不过“静态方法”放到了“类的名字空间里面”,需要通过“类调用”
静态方法格式:
@staticmethod
def 静态方法名([形参列表]):
函数体
重点如下:
1、@staticmathod 必须位于方法上面一行
2、调用静态方法格式:“类名.静态方法名(参数列表)”
3、静态方法中访问实例属性和实例方法会导致错误
'''
class Studen:
company = "SXT"
def __init__(self,name,age):
self.name = name
self.age = age
@staticmethod
def test_01(a,b):
print("{0}+{1}={2}".format(a,b,a+b))
#print(self.age) # 类方法中不能调用实例方法和实例属性
Studen.test_01(1,2)
|
eb8bd757131ffbc194a85c5b8852ddc923a70777 | SandraTang/Encryptors-and-Cryptology-Practice | /affine-encryptor-spanish.py | 1,251 | 3.9375 | 4 | #Affine Cipher Encryptor (Spanish)
#by Sandra Tang
from random import randint
# (ax + b) % m
#intro
print "Affine Cipher Encryptor (Spanish)"
#value of a
a = raw_input("Value of a: ")
a_int = True
try:
val = int(a)
except ValueError:
a_int = False
while a_int == False:
print "That's not an int. Try again."
a = raw_input("Value of a: ")
a_int = True
try:
val = int(a)
except ValueError:
a_int = False
#value of b
b = raw_input("Value of b: ")
b_int = True
try:
val = int(b)
except ValueError:
b_int = False
while b_int == False:
print "That's not an int. Try again."
b = raw_input("Value of b: ")
b_int = True
try:
val = int(b)
except ValueError:
b_int = False
word = raw_input("What do you want to encrypt?").upper()
alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "Ñ", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
numbers = []
for c in word:
if c == " ":
numbers.append(" ")
else:
numbers.append(alphabet.index(c))
encrypted = []
for x in numbers:
encrypted.append( ((int(a)*int(x))+int(b))%27 )
code = ""
for n in encrypted:
code = code + alphabet[n]
print "The affine encryption of " + word + " is " + code + "."
|
eb46653bb495ba43e14807012a79c6cfb0019dbc | Venkatraman9214/python-coding-challenges | /challenges/4.D.Min_Value/main.py | 130 | 3.59375 | 4 | numbers = [8, 2, 4, 3, 6, 5, 9, 1]
### Modify the code below ###
lowest = numbers
### Modify the code above ###
print(lowest)
|
fd54ae168dd10301ff09ab6e08f976873814b559 | MaRTeKs-prog/Self-Taught | /Ch 9/csvreader_work.py | 185 | 3.59375 | 4 | import csv
with open('E:\\Programming\\Literature\\The Self-Taught Programmer\\Ch 9\\t.csv', 'r') as f:
r = csv.reader(f, delimiter = ',')
for row in r:
print(','.join(row))
|
11c883d9575da3171a9f22777b006e893dd8bbf8 | Empythy/Algorithms-and-data-structures | /队列实现栈.py | 1,048 | 3.921875 | 4 | from collections import deque
class MyStack():
"""
push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空
"""
def __init__(self):
# 用两个队列实现
self.data_q = deque()
self.t_q = deque()
def push(self, item):
self.t_q.append(item)
while len(self.data_q) > 0:
self.t_q.append(self.data_q.popleft())
while len(self.t_q) > 0:
self.data_q.append(self.t_q.popleft())
def pop(self):
if len(self.data_q) >0 :
return self.data_q.popleft()
def top(self):
if len(self.data_q) >0:
return self.data_q[0]
def empty(self):
return len(self.data_q) > 0
class MyStack1():
def __init__(self):
self.data = deque()
def push(self, item):
size = len(self.data)
self.data.append(item)
while size > 0:
self.data.append(self.data.popleft())
size -= 1
def pop(self):
if len(self.data) > 0:
return self.data.popleft()
def top(self):
if len(self.data) > 0:
return self.data[0]
def empty(self):
return len(self.data) == 0 |
c178380ac694613cb77996274db70bbabfe61df1 | schnip/thesis | /scrap/test.py | 247 | 3.578125 | 4 | def gcd(a, b):
if (b == 0):
return a
if (b > a):
return gcd(b, a)
a = a % b
return gcd(b, a)
import sys
a = int(sys.argv[1])
b = int(sys.argv[2])
print(gcd(a,b))
from deap import tools
print(tools.cxTwoPoint([1,1,1,1,1,1],[2,2,2,2,2,2])) |
770917bb4424d8c67c335704f82d8412f152e86a | itsjw/python_exercise | /python_20740628/chapter_one/1.py | 102 | 3.734375 | 4 | def max(num1, num2):
if num1 > num2:
return num1
elif num2 > num1:
return num2
print(max(8,4)) |
e021706231b8d9364b81f619a59f8b6e906f333a | AnDa-creator/John-hunt-chapterwise-solutions-self-made | /Exercise_ch_22.py | 1,506 | 4.03125 | 4 | class Distance:
def __init__(self, value):
self.value = value
def __str__(self):
return "Distance[{}]".format(self.value)
def __add__(self, other):
new_value = self.value + other.value
return Distance(new_value)
def __sub__(self, other):
new_value = self.value - other.value
return Distance(new_value)
def __mul__(self, other):
if isinstance(other, Distance):
new_value = self.value * other.value
return Distance(new_value)
elif isinstance(other, int):
new_value = self.value * other
return Distance(new_value)
else:
raise ValueError
def __truediv__(self, other):
if isinstance(other, Distance):
new_value = self.value / other.value
return Distance(new_value)
elif isinstance(other, int):
new_value = self.value / other
return Distance(new_value)
else:
raise ValueError
def __floordiv__(self, other):
if isinstance(other, Distance):
new_value = self.value // other.value
return Distance(new_value)
elif isinstance(other, int):
new_value = self.value // other
return Distance(new_value)
else:
raise ValueError
if __name__ == "__main__":
d1 = Distance(6)
d2 = Distance(3)
print(d1 + d2)
print(d1 - d2)
print(d1 / 2)
print(d2 // 2)
print(d2 * 2) |
52653780f29f19fc64fe8c2f96c716f897275d5b | mipt-m06-803/PuchkovaDasha | /hw4/ex6_2.py | 238 | 3.640625 | 4 | L1 = [elem for elem in input().split()]
L2 = [elem for elem in input().split()]
L2_reverse = L2[::-1]
s2_reverse = ' '.join(L2_reverse)
s1 = ' '.join(L1)
s2 = ' '.join(L2)
if s2 in s1:
s1 = s1.replace(s2, s2_reverse, 1)
print(s1) |
bbc6043027187202b5fe057400af97ba8dd6c208 | huynhtuan17ti/Generate-testcase-for-cp | /GenerativeFunction.py | 4,952 | 3.640625 | 4 | import numpy as np
import random
def split_array(arr, num_parts):
#split an array into several parts
assert num_parts > 1, "number of splited part must greater than 1"
split_arr = np.array_split(np.array(arr), num_parts)
return split_arr
def generate_permutation(len, base = 0):
#generate a permutaion
return np.random.permutation(len) + base
def shuffle_array(arr):
#shuffle an array
return np.random.permutation(arr)
def random_array(start, end, len):
#random a len-length integer array with values between [start, end]
return np.random.randint(start, end+1, len)
def random_unique_array(start, end, len):
#random a len-length unique integer array with values between [start, end]
assert end - start + 1 >= len, "length of array larger than range values"
a = random.sample(range(start, end+1), len)
a = shuffle_array(a)
return a
def random_float(start, end, decimal_places = 2):
#random a float number up to x decimal places between [start, end]
return round(random.uniform(start, end), decimal_places)
def random_int(start, end):
#random an integer number in range [start, end]
return np.random.randint(start, end+1)
def random_choice(arr):
return np.random.choice(arr)
def percentage_chose(percent = 50):
# 50% return True, else return False
assert 0 <= percent <= 100, "percentage must in range [0, 100]"
x = random_int(1, 100)
if x <= percent:
return True
else:
return False
def random_swap(a, b):
if percentage_chose():
return b, a
return a, b
def generate_tree(num_vertex, base = 0):
#generate a tree graph
edges = []
permu_vertex = generate_permutation(num_vertex, base = base)
for i in range(1, len(permu_vertex)):
u = permu_vertex[i]
v = permu_vertex[random_int(0, i-1)]
edges.append(random_swap(u, v))
assert len(edges) == num_vertex-1
return edges
def generate_forest(num_vertex, base = 0):
#generate a forest (>= 1 tree graph)
edges = []
permu_vertex = generate_permutation(num_vertex, base = base)
for i in range(1, len(permu_vertex)):
if percentage_chose(70):
u = permu_vertex[i]
v = permu_vertex[random_int(0, i-1)]
edges.append(random_swap(u, v))
assert len(edges) <= num_vertex-1
return edges
def generate_edge(num_vertex, base = 0):
u = random_int(base, num_vertex-1+base)
v = random_int(base, num_vertex-1+base)
while v == u: #prevent from u = v
v = random_int(base, num_vertex-1+base)
return u, v
def generate_graph(num_vertex, num_edge, duplicate = False, base = 0):
if duplicate == False:
assert num_edge <= num_vertex*(num_vertex-1)/2, "number of edges must be equal or lower than number of all possible edges"
duplicate_set = set()
edges = []
for i in range(num_edge):
edge = generate_edge(num_vertex, base = base)
if duplicate == False:
u, v = edge
while (u, v) in duplicate_set: #or (v, u) in duplicate_set:
u, v = generate_edge(num_vertex, base = base)
edge = u, v
duplicate_set.add(edge)
edges.append(edge)
assert len(edges) == num_edge
return edges
def generate_cycle_component(verties):
edges = []
for i in range(len(verties)):
if i == len(verties) - 1:
edges.append((verties[i], verties[0]))
else:
edges.append((verties[i], verties[i+1]))
return edges
def generate_connected_graph(num_vertex, num_edge, duplicate = False, base = 0):
if duplicate == False:
assert num_edge <= num_vertex*(num_vertex-1)/2, "number of edges must be equal or lower than number of all possible edges"
assert num_edge >= num_vertex-1, "number of edges must be equal or greater then number of verties minus one"
edges = generate_tree(num_vertex = num_vertex, base = base)
duplicate_set = set(edges)
for i in range(num_vertex-1, num_edge):
edge = generate_edge(num_vertex, base = base)
if duplicate == False:
u, v = edge
while (u, v) in duplicate_set: #or (v, u) in duplicate_set:
u, v = generate_edge(num_vertex, base = base)
edge = u, v
duplicate_set.add(edge)
edges.append(edge)
assert len(edges) == num_edge
return edges
def add_weight_egdes(edges, start, end, integer = True):
#add weight to edges of graph. If integer = False, random float value
weight_edges = set()
for u, v in edges:
if integer:
weight_edges.add((u, v, random_int(start, end)))
else:
weight_edges.add((u, v, random_float(start, end)))
return weight_edges
if __name__ == '__main__':
#testing
split_arr = split_array([1, 5, 2, 4, 5], 3)
print(random.sample([6], 1))
for i in range(3):
print(split_arr[i]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.