blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
a0cb315d486e5be8ac2c9e910dfeaeeed49ce238 | MatiwsxD/ayed-2019-1 | /Labinfo_4/punto_3.py | 361 | 3.703125 | 4 | from sys import stdin
def mochila(x,y,n):
if x == 0 or n == 0:
return 0
elif y [n-1]> x:
return mochila(x,y,n-1)
else:
return max (mochila(x,y,n-1),1 + mochila(x - y[n-1],y,n-1))
def main():
prec = [int(x) for x in stdin.readline().split(" ")]
dine = int(input())
print(mochila(dine,prec,len(prec)))
main()
|
be46099f6f6631f66d6dcc5044413589e7fc02c8 | MatiwsxD/ayed-2019-1 | /Labinfo_7/B - String reverse.py | 323 | 3.71875 | 4 | from sys import stdin
def reverse(lista,vacio):
while len(lista) != 0:
vacio.append(lista.pop())
x = ""
for i in range(len(vacio)):
x += vacio[i]
return x
def main():
x = input()
lista = []
for i in range(len(x)):
lista.append(x[i])
print(reverse(lista,[]))
main() |
3b23c557ebbba3ff8d5a0ec958e054f11be80937 | Pankirey/web | /week8/1/b.py | 102 | 3.796875 | 4 | a =int(input())
b=a+1
c=a-1
print("The next number for the number "+str(a)+" is "+str(b))
|
f79ec881de35f556e4872c0f850a0af5684657c3 | yongfang117/data_process | /DataProcess/PCADim/pcanews.py | 2,303 | 3.765625 | 4 | # coding:utf8
from numpy import *
import matplotlib
import matplotlib.pyplot as plt
'''
Description:PCA新闻数据降维并可视化分析
Author:伏草惟存
Prompt: code in Python3 env
'''
'''加载数据集'''
def loadDataSet(fileName, delim='\t'):
fr = open(fileName)
stringArr = [line.strip().split(delim) for line in fr.readlines()]
datArr = [list(map(float, line)) for line in stringArr]
return mat(datArr)
# 将NaN替换成平均值函数:secom.data 为1567篇文章,每篇文章590个单词
def replaceNanWithMean():
datMat = loadDataSet('./secom.data', ' ')
numFeat = shape(datMat)[1]
for i in range(numFeat):
meanVal = mean(datMat[nonzero(~isnan(datMat[:, i].A))[0], i])
datMat[nonzero(isnan(datMat[:, i].A))[0],i] = meanVal
return datMat
# 主成分降维
def pca(dataMat, topNfeat=9999999):
# 1 计算每一列的均值
meanVals = mean(dataMat, axis=0) # axis=0表示列,axis=1表示行
# 2 去平均值,每个向量同时都减去均值
meanRemoved = dataMat - meanVals
# 3 计算协方差矩阵的特征值与特征向量
covMat = cov(meanRemoved, rowvar=0)
eigVals, eigVects = linalg.eig(mat(covMat))
print('特征值:\n', eigVals,'\n特征向量:\n', eigVects) # 很多特征值为0
# 4 将特征值排序
eigValInd = argsort(eigVals)
# 5 保留前N个特征
eigValInd = eigValInd[:-(topNfeat+1):-1]
redEigVects = eigVects[:, eigValInd]
# print('重组n特征向量最大到最小:\n', redEigVects.T)
# 6 将数据转换到新空间
lowDDataMat = meanRemoved * redEigVects
reconMat = (lowDDataMat * redEigVects.T) + meanVals
return lowDDataMat, reconMat
'''降维后的数据和原始数据可视化'''
def show_picture(dataMat, reconMat):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(dataMat[:, 0].flatten().A[0], dataMat[:, 1].flatten().A[0], marker='^', s=5,c='green')
ax.scatter(reconMat[:, 0].flatten().A[0], reconMat[:, 1].flatten().A[0], marker='o', s=5, c='red')
plt.show()
if __name__ == "__main__":
dataMat = replaceNanWithMean()
# 分析数据
lowDmat, reconMat = pca(dataMat,17)
print(shape(lowDmat)) # 1567篇文章,提取前20个单词
show_picture(dataMat, reconMat)
|
b247d17e042d33f72d1699733b0cb2e7314e7757 | yongfang117/data_process | /DataProcess/ExtractText/ConvFormat.py | 2,377 | 3.671875 | 4 | # coding=utf-8
"""
Description: 批量文档格式自动转化txt
Author:伏草惟存
Prompt: code in Python3 env
"""
import ExtractTxt as ET
import os,time
'''
功能描述:遍历目录,对子文件单独处理
参数描述:1 rootDir 根目录 2 deffun:方法参数 3 saveDir: 保存路径
'''
class TraversalFun():
# 1 初始化
def __init__(self,rootDir,func=None,saveDir=""):
self.rootDir = rootDir # 目录路径
self.func = func # 参数方法
self.saveDir = saveDir # 保存路径
# 2 遍历目录文件
def TraversalDir(self):
# 切分文件上级目录和文件名
dirs,latername = os.path.split(self.rootDir)
# print(rootDir,'\n',dirs,'\n',latername)
# 保存目录
save_dir = ""
if self.saveDir=="": # 默认文件保存路径
save_dir = os.path.abspath(os.path.join(dirs,'new_'+latername))
else: save_dir = self.saveDir
# 创建目录文件
if not os.path.exists(save_dir): os.makedirs(save_dir)
print("保存目录:\n"+save_dir)
# 遍历文件并将其转化txt文件
TraversalFun.AllFiles(self,self.rootDir,save_dir)
# 3 递归遍历所有文件,并提供具体文件操作功能
def AllFiles(self,rootDir,save_dir=''):
# 返回指定目录包含的文件或文件夹的名字的列表
for lists in os.listdir(rootDir):
# 待处理文件夹名字集合
path = os.path.join(rootDir, lists)
# 核心算法,对文件具体操作
if os.path.isfile(path):
self.func(os.path.abspath(path),os.path.abspath(save_dir))
# 递归遍历文件目录
if os.path.isdir(path):
newpath = os.path.join(save_dir, lists)
if not os.path.exists(newpath):
os.mkdir(newpath)
TraversalFun.AllFiles(self,path,newpath)
if __name__ == '__main__':
time_start=time.time()
# 根目录文件路径
rootDir = r"../dataSet/Corpus/EnPapers"
# saveDir = r"./Corpus/TxtEnPapers"
tra=TraversalFun(rootDir,ET.Files2Txt) # 默认方法参数打印所有文件路径
tra.TraversalDir() # 遍历文件并进行相关操作
time_end=time.time()
print('totally cost',time_end-time_start,'s') |
808f7e1ab95187468e9904ea83525b673ffe16db | enio-infotera/VernamCipher | /py/encrypt.py | 441 | 3.640625 | 4 | #
#
# Use: encrypt("hello", "XMCKL")
# => "eqnvz"
#
#
def encrypt(st, key):
if len(st) != len(key):
return "Text and Key have to be the same length."
alphabet = list("abcdefghijklmnopqrstuvwxyz")
nText = []
kText = []
for i in range(len(st)):
nText.append(alphabet.index(st[i].lower()))
kText.append(alphabet.index(key[i].lower()))
out = ""
for i in range(len(nText)):
out += alphabet[(nText[i] + kText[i]) % 26]
return out;
|
f1fd9da0eed37c4f65f9217a3db04173c8e6b000 | rebeccahawke/msl-qt | /msl/qt/toggle_switch.py | 3,378 | 3.5 | 4 | """
A toggle switch :class:`QtWidgets.QWidget`.
"""
from . import QtWidgets, QtCore, QtGui
class ToggleSwitch(QtWidgets.QAbstractButton):
def __init__(self, parent=None, height=None, checked_color='#009688', unchecked_color='#B4B4B4'):
"""Constructs a toggle switch, |toggle_switch|
.. |toggle_switch| image:: ../../docs/_static/toggle_switch.gif
:scale: 40 %
Parameters
----------
parent : :class:`QtWidgets.QWidget`, optional
The parent :class:`QtWidgets.QWidget`.
height : :class:`int`, optional
The height, in pixels, of the toggle switch.
checked_color : :class:`QtGui.QColor`, optional
The color to draw the switch when it is in the checked state.
Can be any data type and value that the constructor of a
:class:`QtGui.QColor` accepts.
unchecked_color : :class:`QtGui.QColor`, optional
The color to draw the switch when it is **not** in the checked state.
Can be any data type and value that the constructor of a
:class:`QtGui.QColor` accepts.
Example
-------
To view an example with the :class:`ToggleSwitch` run:
>>> from msl.examples.qt import toggle_switch
>>> toggle_switch.show() # doctest: +SKIP
"""
super(ToggleSwitch, self).__init__(parent=parent)
screen_height = QtWidgets.QDesktopWidget().availableGeometry(self).height()
self._height = height if height is not None else int(screen_height*0.03)
self._pad = 4
self._checked_brush = QtGui.QBrush(QtGui.QColor(checked_color))
self._unchecked_brush = QtGui.QBrush(QtGui.QColor(unchecked_color))
self.setCheckable(True)
def enterEvent(self, event):
"""Overrides `enterEvent <https://doc.qt.io/qt-5/qwidget.html#enterEvent>`_."""
self.setCursor(QtCore.Qt.PointingHandCursor)
def paintEvent(self, event):
"""Overrides `paintEvent <https://doc.qt.io/qt-5/qwidget.html#paintEvent>`_."""
diameter = self._height - 2 * self._pad
radius = diameter * 0.5
if self.isChecked():
brush = self._checked_brush
x = self.width() - diameter - self._pad
opacity = 0.3
else:
brush = self._unchecked_brush
x = self._pad
opacity = 0.5
p = QtGui.QPainter(self)
p.setPen(QtCore.Qt.NoPen)
p.setRenderHint(QtGui.QPainter.Antialiasing, True)
ellipse = QtCore.QRect(x, self._pad, diameter, diameter)
w = max(diameter, self.width() - 2 * self._pad)
rect = QtCore.QRect(self._pad, self._pad, w, diameter)
if self.isEnabled():
p.setBrush(brush)
p.setOpacity(opacity)
p.drawRoundedRect(rect, radius, radius)
p.setOpacity(1.0)
p.drawEllipse(ellipse)
else:
p.setBrush(QtCore.Qt.black)
p.setOpacity(0.12)
p.drawRoundedRect(rect, radius, radius)
p.setOpacity(1.0)
p.setBrush(QtGui.QColor('#BDBDBD'))
p.drawEllipse(ellipse)
def sizeHint(self):
"""Overrides `sizeHint <https://doc.qt.io/qt-5/qwidget.html#sizeHint-prop>`_."""
return QtCore.QSize(2 * (self._height + self._pad), self._height + 2 * self._pad)
|
b5f9fab2a9f7ad2e2bdd40637e34c8b35dabc9ed | sudo-hemant/curated_questions_dsa | /tree/inorder_traversal.py | 2,018 | 3.796875 | 4 |
# https://leetcode.com/problems/binary-tree-inorder-traversal/
# NOTE: using stack
class Solution:
def inorderTraversal(self, root):
if not root:
return []
stack = []
result = []
stack.append(root)
current = root.left
while True:
while current:
stack.append(current)
current = current.left
if stack:
popped_element = stack.pop()
result.append(popped_element.val)
current = popped_element.right
else:
break
return result
# NOTE: using morris traversal
# Video reference ---- https://www.youtube.com/watch?v=BuI-EULsz0Y
class Solution2:
def inorderTraversal2(self, root):
if not root:
return []
result = []
current = root
while current:
if not current.left:
result.append(current.val)
current = current.right
else:
# finds right most node in left subtree
predecessor = self.predecessor(current)
# if the link is not created to its predecessor, then we ll create it i.e., predecessor.right = current
if not predecessor.right:
predecessor.right = current
current = current.left
# if the link already exists, then we delete the link ( which was created by us)
elif predecessor.right == current:
predecessor.right = None
result.append(current.val)
current = current.right
return result
def predecessor(self, root):
current = root.left
while current.right and current.right != root:
current = current.right
return current |
872479c15c4c5e2e9f17f8ae0d1416f0c7059901 | sudo-hemant/curated_questions_dsa | /searching-and-sorting.py/find-missing-and-repeating.py | 359 | 3.75 | 4 |
def findTwoElement(arr):
ans = []
for i in range(len(arr)):
if arr[abs(arr[i]) - 1] < 0:
ans.append(abs(arr[i]))
else:
arr[abs(arr[i]) - 1] *= -1
for i in range(len(arr)):
if arr[i] > 0:
ans.append(i + 1)
return ans
print(findTwoElement([1, 3, 3])) |
2203621573e93df69067c62301c89799e7a527f7 | sudo-hemant/curated_questions_dsa | /graph/manucian_and_liverbird_go_bar_hopping.py | 3,429 | 3.734375 | 4 |
# TODO: NOT COMPLETED YET
# NOTE: THIS METHOD WILL GIVE US TLE BCOS WE WILL REVERSE AND TRAVERSE GRAPH AGAIN AND AGAIN TO
# FIND THE ANS, SO TO OPTIMIZE WE WILL STORE IT IN ARRAY, LOOK AT METHOD -- 2
from collections import defaultdict
def dfs(node, adj_graph, count):
for neighbour in adj_graph[node]:
count = dfs(neighbour, adj_graph, count + 1)
return count
def reverse_direction(adj_graph):
pass
# if __name__ == '__main__':
# size = int(input())
# directions = [int(x) for x in input().split()]
# operations = int(input())
# result = []
# adj_graph = defaultdict(list)
# for i in range(1, size):
# if directions[i - 1]:
# adj_graph[i].append(i + 1)
# else:
# adj_graph[i + 1].append(i)
# for _ in range(operations):
# update_or_query = list(input().split())
# if update_or_query[0] == 'Q':
# temp = dfs( int(update_or_query[1]), adj_graph, 0 )
# result.append(temp + 1)
# else:
# reverse_direction(adj_graph)
# print(result)
# ----------------------------------------------------------------------
# NOTE: METHOD -- 2
size = int(input())
# to store the directions of the node
directions = [int(x) for x in input().split()]
# store the ans
result = []
# the first row will store the possible paths from left and the second row will store the
# paths from left if the direction gets reversed
left_reach = [ [0] * size ] * 2
# the first row will store the possible paths from right and the second row will store the
# paths from right if the direction gets reversed
right_reach = [ [0] * size ] * 2
# there will be always one way from left for the first node (i.e. from itself)
left_reach[0][0] = 1
left_reach[1][0] = 1
# there will be always one way from right for the last node (i.e. from itself)
right_reach[0][-1] = 1
right_reach[1][-1] = 1
# iterate for the second node till the last,
# first row will store the paths from left and second row will store the paths from
# left if the edges gets reversed
for i in range(1, size):
if directions[i - 1]:
left_reach[0][i] = left_reach[0][i - 1] + 1
left_reach[1][i] = 1
else:
left_reach[0][i] = 1
left_reach[1][i] = left_reach[1][i - 1] + 1
# iterate from the last second node till the first,
# first row will store the paths from right and second row will store the paths from
# right if the edges gets reversed
for i in reversed(range(size - 1)):
if directions[i]:
right_reach[0][i] = 1
right_reach[1][i] = right_reach[1][i + 1] + 1
else:
right_reach[0][i] = right_reach[0][i + 1] + 1
right_reach[1][i] = 1
# to store the current direct of nodes,
# if its 0 that means the direction is same as the directions given
# if its 1 that means the direction is opposite of the directions which was given to us
type = 0
operations = int(input())
for _ in range(operations):
update_or_query = list(input().split())
if update_or_query[0] == 'Q':
s = update_or_query[1]
total_paths = left_reach[int(s) - 1][type] + right_reach[int(s) - 1][type] - 1
# total_paths = left_reach[int(s) - 1][type] + right_reach[int(s) - 1][type] - 1
# result.append(total_paths)
print(total_paths)
else:
type ^= 1
# print(result) |
4f85dc8a026ff62378e0aa6e16b615a08e5329f2 | sudo-hemant/curated_questions_dsa | /tree/diagonal_traversal_binary_tree.py | 1,075 | 4 | 4 |
# https://www.geeksforgeeks.org/diagonal-traversal-of-binary-tree/
# NOTE: this problem is quite similar to vertical traversal of binary tree,
# here we keep track of a the current level, and assign +1 to its left child
# and same level to right child and store it in dictionary i.e., default dict
# to save accessing dictionary twice for same operations
from collections import defaultdict
def diagonal(root):
dic = defaultdict(list)
ans = []
deepest = [0]
diagonal_util(root, 0, dic, deepest)
# for i in range(0, diagonal_util.deepest + 1):
# ans.extend(dic[i])
for i in range(0, deepest[0] + 1):
ans.extend(dic[i])
return ans
def diagonal_util(root, level, dic, deepest):
if not root:
return
dic[level].append(root.data)
diagonal_util(root.left, level + 1, dic, deepest)
diagonal_util(root.right, level, dic, deepest)
deepest[0] = max(deepest[0], level)
# diagonal_util.deepest = max(diagonal_util.deepest, level)
|
659c48af7f0de3a942a34744d9fa9aaf7f231ce6 | sudo-hemant/curated_questions_dsa | /searching-and-sorting.py/weighted-job-scheduling.py | 3,262 | 3.609375 | 4 |
class Job:
def __init__(self, start, end, profit):
self.start = start
self.end = end
self.profit = profit
# -------------------------------------------------------
# NOTE: SOLUTION - 1 ( RECURSION )
# TC : O( N * 2^N)
# n for finding latest non conflicting job and 2 options for every position(include or exclude)
def latest_non_conflicting_job(arr, end):
for i in reversed(range(end)):
if arr[i].end <= arr[end].start:
return i
return -1
def max_profit_recursive(arr, n):
if n < 0:
return 0
if n == 0:
return arr[0].profit
index = latest_non_conflicting_job(arr, n)
profit_if_included = arr[n].profit + max_profit_recursive(arr, index)
profit_if_excluded = max_profit_recursive(arr, n - 1)
return max(profit_if_included, profit_if_excluded)
if __name__ == '__main__':
jobs = [
Job(0, 6, 60), Job(1, 4, 30), Job(3, 5, 10),
Job(5, 7, 30), Job(5, 9, 50), Job(7, 8, 10)
]
jobs.sort(key=lambda x: x.end)
print(max_profit_recursive(jobs, len(jobs) - 1))
# --------------------------------------------------------------------------
# NOTE: TC : (N ^ 2)
# N for every index and n for finding non conflicting job
def latest_non_conflicting_job_2(arr, end):
for i in reversed(range(end)):
if arr[i].end <= arr[end].start:
return i
return -1
def max_profit_dp(arr, n):
arr.sort(key = lambda x: x.end)
max_profit = [0] * len(arr)
max_profit[0] = arr[0].profit
for i in range(1, len(arr)):
index = latest_non_conflicting_job_2(arr, i)
profit_if_included = arr[i].profit
if index != -1:
profit_if_included += max_profit[index]
max_profit[i] = max( profit_if_included, max_profit[i - 1] )
return max_profit[-1]
if __name__ == '__main__':
jobs = [
Job(0, 6, 60), Job(1, 4, 30), Job(3, 5, 10),
Job(5, 7, 30), Job(5, 9, 50), Job(7, 8, 10)
]
jobs.sort(key=lambda x: x.end)
print(max_profit_dp(jobs, len(jobs) - 1))
# ----------------------------------------------------------------------
# NOTE: TC : O(N LOG(N))
# n for the for loop and log(n) for finding non-conflicting job
def latest_non_conflicting_job_3(arr, end):
low, high = 0, end - 1
ans = -1
while low <= high:
mid = low + (high - low) // 2
if arr[mid].end <= arr[end].start:
ans = mid
low = mid + 1
else:
high = mid - 1
return ans
def max_profit_logn(arr, n):
arr.sort(key=lambda x: x.end)
max_profit = [0] * len(arr)
max_profit[0] = arr[0].profit
for i in range(1, len(arr)):
index = latest_non_conflicting_job_3(arr, i)
profit_if_included = arr[i].profit
if index != -1:
profit_if_included += max_profit[index]
max_profit[i] = max( profit_if_included, max_profit[i - 1] )
return max_profit[-1]
if __name__ == '__main__':
jobs = [
Job(0, 6, 60), Job(1, 4, 30), Job(3, 5, 10),
Job(5, 7, 30), Job(5, 9, 50), Job(7, 8, 10)
]
jobs.sort(key=lambda x: x.end)
print(max_profit_logn(jobs, len(jobs) - 1))
|
9a71665d3569a1b1db259ee0f04b5eedc1c38087 | pankajnuaa/LearningPython | /_06ControlStatements.py | 122 | 4 | 4 | # if statement
if 4>5:
print("if is true")
elif 4>3:
print("elif is true")
else:
print("else is true") |
373ef96ccb789124d4c34ef4b12310fc6c9e5816 | Kevinliao0857/Road-of-Python | /checkio electronic station/words order.py | 1,129 | 4.03125 | 4 | def words_order(text: str, words: list) -> bool:
text_words = {w for w in text.split() if w in words}
return list(sorted(text_words, key=text.index)) == words
if __name__ == '__main__':
print("Example:")
print(words_order('hi world im here', ['world', 'here']))
# These "asserts" are used for self-checking and not for an auto-testing
assert words_order('hi world im here', ['world', 'here']) == True
assert words_order('hi world im here', ['here', 'world']) == False
assert words_order('hi world im here', ['world']) == True
assert words_order('hi world im here',
['world', 'here', 'hi']) == False
assert words_order('hi world im here',
['world', 'im', 'here']) == True
assert words_order('hi world im here',
['world', 'hi', 'here']) == False
assert words_order('hi world im here', ['world', 'world']) == False
assert words_order('hi world im here',
['country', 'world']) == False
assert words_order('hi world im here', ['wo', 'rld']) == False
assert words_order('', ['world', 'here']) == False
print("Coding complete? Click 'Check' to earn cool rewards!")
|
60f2e7afeae3d4fdb84aaef829d45791682e5104 | gamahead/htm_cla | /htm.py | 9,975 | 3.609375 | 4 | import random
import random as r
from math import *
import numpy
# =============================================
# Utilities
# =============================================
def partition(vector, left, right, pivotIndex):
pivotValue = vector[pivotIndex]
vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex] # Move pivot to end
storeIndex = left
for i in range(left, right):
if vector[i] < pivotValue:
vector[storeIndex], vector[i] = vector[i], vector[storeIndex]
storeIndex += 1
vector[right], vector[storeIndex] = vector[storeIndex], vector[right] # Move pivot to its final place
return storeIndex
def _select(vector, left, right, k):
"Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive."
while True:
pivotIndex = random.randint(left, right) # select pivotIndex between left and right
pivotNewIndex = partition(vector, left, right, pivotIndex)
pivotDist = pivotNewIndex - left
if pivotDist == k:
return vector[pivotNewIndex]
elif k < pivotDist:
right = pivotNewIndex - 1
else:
k -= pivotDist + 1
left = pivotNewIndex + 1
def select(vector, k, left=None, right=None):
"""
Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1].
left, right default to (0, len(vector) - 1) if omitted
"""
if left is None:
left = 0
lv1 = len(vector) - 1
if right is None:
right = lv1
assert vector and k >= 0, "Either null vector or k < 0 "
assert 0 <= left <= lv1, "left is out of range"
assert left <= right <= lv1, "right is out of range"
return _select(vector, left, right, k)
# =============================================
# HTM Params & Basic Objects
# =============================================
class Synapse:
def __init__(self, source_input, permanence = 0.5):
self.source_input = source_input
self.permanence = permanence
class Cell:
def __init__(self):
self.active_state = [r.randint(0,1), r.randint(0,1)]
self.predictive_state = [r.randint(0,1), r.randint(0,1)]
self.segments = []
def get_active_segment(self, t, active_state):
return([s for s in self.segments if s.state == 1])
class Segment:
def __init__(self, source_cell):
self.source_cell = source_cell
self.state = r.randint(0,1)
self.strength = r.uniform(0,1)
def set_state(self):
self.state = 1 if self.source_cell.active_state[-1] == 1 else 0
def update(self):
self.strength += update_function(self.source_cell.active_state[-1], self.strength)
# Simple linear updating for now, but hope to implement some kind of logit function
# Modularized like this because I think the synapse updating function will be important
def update_function(self, source_active, strength):
return(max(min(strength + (.1 if source_active else -0.1), 1), 0))
class Column:
def __init__(self, connected_synapses, cells_per_column = 5, x=0, y=0, hist_num=1000):
self.connected_synapses = connected_synapses # [s for s in connected_synapses if s.permanence >= .5]
# self.potential_synapses = [s for s in connected_synapses if s.permanence < .5]
self.x = x
self.y = y
self.hist_num = hist_num # How much history do we want to keep?
self.overlap = 0
self.min_duty_cycle = 0
self.active_duty_cycle_history = [r.randint(0,1) for _ in range(0,hist_num)] # Record last hist_num iterations
self.overlap_duty_cycle_history = [r.randint(0,1) for _ in range(0,hist_num)] # And init with randoms
self.active_duty_cycle = 0
self.overlap_duty_cycle = 0
self.boost = 1
self.connected_perm = .5
# TP
self.cells = [Cell()] * cells_per_column
self.predicted = 0
self.predicted_w_strength = 0
class Retina:
def __init__(self, x, y):
self.x = x
self.y = y
self.receptors = numpy.zeros((x,y), dtype=numpy.int)
class HTM:
def __init__(self,
num_columns = 25,
cells_per_column = 5,
t = 1,
inhibition_radius = 10,
desired_local_activity = 10,
connected_perm = .5,
num_synapses = 10,
min_overlap = 5):
self.num_columns = num_columns
self.cells_per_column = cells_per_column
self.t = t
self.inhibition_radius = inhibition_radius
self.desired_local_activity = desired_local_activity
self.connected_perm = connected_perm
self.min_overlap = min_overlap
self.columns = []
self.x = 5
self.y = 5
i = 0
j = 0
for _ in range(0, self.num_columns):
new_synapses = [ ( r.randint(0,self.x-1), r.randint(0,self.y-1) ) for _ in range(0,num_synapses)]
self.columns.append( Column( [Synapse(s, permanence = r.uniform(0,1)) for s in new_synapses], x=i, y=j) )
i += 1
if i % 5 == 0:
i = 0
j += 1
self.active_columns = [self.columns]
self.input_space = Retina(self.x,self.y)
def get_input(self, t, source_input):
return(self.input_space.receptors[source_input])
def set_input_space(self, new_inputs):
self.input_space.receptors = new_inputs
# =============================================
# Spatial Pooling
# =============================================
def kth_score(columns, desired_local_activity):
return select([c.overlap for c in columns], desired_local_activity)
def max_duty_cycle(columns):
return max([c.active_duty_cycle for c in columns])
# This implementation assumes 2D data because it was built for saccadic vision,
# so the neighbors are considered the columns in a circular radius
def neighbors(column, htm):
x = column.x
y = column.y
return([c for c in htm.columns if sqrt((c.x - x)**2 + (c.y - y)**2) <= htm.inhibition_radius])
def boost_function(active_duty_cycle, min_duty_cycle):
return(1 if active_duty_cycle >= min_duty_cycle else min_duty_cycle/active_duty_cycle)
def update_active_duty_cycle(column):
column.active_duty_cycle_history.pop(0)
column.active_duty_cycle_history.append(1 if column.overlap > 0 else 0)
return(sum(column.active_duty_cycle_history)/column.hist_num)
def update_overlap_duty_cycle(column):
column.overlap_duty_cycle_history.pop(0)
column.overlap_duty_cycle_history.append(1 if column.overlap > 0 else 0)
return(sum(column.overlap_duty_cycle_history)/column.hist_num)
def increase_permanences(column, perm_inc):
for s in column.connected_synapses:
s.permanence += perm_inc
def average_receptive_field_size(columns):
def receptive_field_size(c):
return(sum([1 for s in c.connected_synapses if s.permanence >= c.connected_perm]))
# return( sum( [receptive_field_size(c) for c in columns] ) / len(columns) )
print([receptive_field_size(c) for c in columns])
return(numpy.mean([receptive_field_size(c) for c in columns]))
# def get_input(t, source_input):
# return(1 if source_input else 0)
def Spatial(htm):
# House keeping to fix indexing errors
htm.active_columns.append([])
print(htm.active_columns)
###############################################
# Phase 1: Overlap
###############################################
for c in htm.columns:
c.overlap = 0
for s in c.connected_synapses:
c.overlap += htm.get_input(htm.t, s.source_input)
if c.overlap < htm.min_overlap:
c.overlap = 0
else:
c.overlap += c.boost
###############################################
# Phase 2: Inhibition
###############################################
for c in htm.columns:
htm.min_local_activity = kth_score(neighbors(c, htm), htm.desired_local_activity)
if c.overlap > 0 and c.overlap >= htm.min_local_activity:
htm.active_columns[htm.t].append(c)
###############################################
# Phase 3: Learning
###############################################
for c in htm.active_columns[htm.t]:
for s in c.connected_synapses:
if s.active:
s.permanence += htm.permanence_inc
s.permanence = min(1.0, s.permanence)
else:
s.permanence -= htm.permanence_dec
s.permanence = max(0.0, s.permanence)
for c in htm.columns:
c.min_duty_cycle = 0.01 * max_duty_cycle(neighbors(c,htm))
c.active_duty_cycle = update_active_duty_cycle(c)
c.boost = boost_function(c.active_duty_cycle, c.min_duty_cycle)
c.overlap_duty_cycle = update_overlap_duty_cycle(c)
if c.overlap_duty_cycle < c.min_duty_cycle:
increase_permanences(c, 0.1*htm.connected_perm)
htm.inhibition_radius = average_receptive_field_size(htm.columns)
# =============================================
# Temporal Pooling
# =============================================
def Temporal(htm):
# House-keeping: add a 0 to the lists to keep index in-bounds
for c in htm.columns:
for cell in c.cells:
cell.active_state.append(0)
cell.predictive_state.append(0)
###############################################
# Phase 1: Inference and Learning
###############################################
for c in htm.active_columns[t]:
bu_predicted = False
lc_chosen = False
for cell in c.cells:
if cell.predictive_state[htm.t-1]:
bu_predicted = True
cell.active_state[htm.t] = 1
if not bu_predicted:
for cell in c.cells:
cell.active_state[htm.t] = 1
# Update segment strengths
# Every segment gets strengthened if correct or weakened if incorrect prediction
for cell in c.cells:
for s in cell.segments:
s.update()
###############################################
# Phase 2: Calculate Predictive States
###############################################
for c in htm.active_columns[htm.t]:
c.predicted = 0
for cell in c.cells:
for s in cell.segments:
if s.source_cell.active_state[htm.t]:
c.predicted += 1
cell.predictive_state[t] = 1
htm.t += 1
if __name__ == '__main__':
my_htm = HTM()
input1 = numpy.array([1]*10 + [0]*15).reshape((5,5))
input2 = numpy.array([0]*15 + [1]*10).reshape((5,5))
for i in range(0,1000):
if i % 2 == 0:
iput = input1
else:
iput = input2
Spatial(my_htm)
my_htm.set_input_space(iput)
print(my_htm.input_space.receptors)
print('done')
|
3ef3ce08a8abc0f0a8093e0322ca561bd549a691 | ArnavRupde/cs50 | /pset6/greedy.py | 519 | 3.640625 | 4 | import cs50
def main():
while True:
print("O hai! How much change is owed?")
amount = cs50.get_float()
if amount >= 0:
break
number_of_coins = 0
cents = int(round(amount * 100))
number_of_coins += cents // 25
cents %= 25
number_of_coins += cents // 10
cents %= 10
number_of_coins += cents // 5
cents %= 5
number_of_coins += cents
print("{}".format(number_of_coins))
if __name__ == "__main__":
main() |
6270514755856bede4d6144a3493fccc9627e836 | ucd-python-bootcamp/bootcamp2020 | /TutorialFiles/day1_tutorial.py | 7,821 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
Python Workshop 9/22/20
The Basics
"""
"""
Part 1
-Variable Types: Integers, Floats, Strings
-Print Statements
"""
a = 10
b = 10.1
c = 'ten'
#a is an integer, b is a float, c is a string
print('integer:',a)
print('float:',b)
print('string:',c)
print(a,b,c)
print('The answers are:',a,b,c)
#You can change types between integers, floats, and strings.
print(float(a))
print(int(b))
print(str(b))
#note that this rounds to 10
#Note that there are variable names you shouldn't use because they are built in functions.
print(list)
#this prints as a recognized class. A random unassigned variable raises an error when printed.
#print(randomword)
"""
Part 2
-Lists
"""
#let's assign a, b, and c to a list
varlist = [a,b,c]
#"list" is now a variable that contains a list of other variables.
#Note that list= [10, 10.1, 'ten'] is functionally the same.
print('variable list:',varlist)
#appending to a list let's you add more items on the end
d = 100
varlist.append(d)
print('list with d:',varlist)
# if you only need one item in a list, you can index it
print('first thing in list=', varlist[0])
#python starts counting at 0!
"""
Part 3
-mathematical operations
"""
e=9.5
f=6.1
eplus = e+f
print('e+f = ',eplus)
eminus = e-f
print('e-f = ',eminus)
emult = e*f
print('e*f = ',emult)
fdiv = f/2.0
print('f/2.0 =', fdiv)
esquare = e**2
print('e squared = ', esquare)
fsqrt = f**0.5
print('sqrt of f = ',fsqrt)
emod1 = e % 3
print('e modulus 3 = ',emod1)
fmod2 = 43 % f
print('43 modulus f = ', fmod2)
#
##these operations work on integers and floats
##combine an integer with a float and it becomes a float
list2=[e,f]
list3=[f,f,f]
#you can multiply a list by an integer to make it repeat itself
mult=list2*4
print('multiplied list:',mult)
#
added=list2+list3
print('added list:', added)
"""
Part 4
-for loops
"""
buildlist=[]
#This list is empty, but we are going to use the append command to add values to it.
#We could do this...
a=1**2
buildlist.append(a)
b=2**2
buildlist.append(b)
c=3**2
buildlist.append(c)
d=4**2
buildlist.append(d)
print(buildlist)
#But this takes a long time to type out, and we've only added 4 values to the list.
#We can do exactly the same thing with a for loop- it is much more efficient!
startlist=[1,2,3,4,5,6,7,8,9]
finallist=[]
for i in startlist:
#during the first loop, i = 1, then i = 2, until the end of startlist.
n = i**2
#during the first loop, n = 1, then n = 4, then n = 9, etc.
print(n)
#always start with a lot of print statements when you make a loop
#this way, you know exactly what is happening in the loop
finallist.append(n)
#Add value "n" to a list
print(finallist)
#print the list during each loop to make sure it gets longer each time.
m=1
mlist=[]
#In this loop, let's add 1+2+3+4+5+...+20
for j in range(2,21):
#this will loop over values of j=1 to j=20
m+=j
#this is equivalent to m=m+j
print(m)
#this will show m increasing during each loop.
mlist.append(m)
#let's also add each increasing value of m to a list, and print that too.
print(mlist)
"""
Part 5
-functions
"""
#functions allow you to use the same set of code over and over again, but with different variables.
#we can turn a for loop from the last section into a function.
def squarelist(mylist):
#"mylist" is a placeholder that can be replaced by any list when the function is called
newlist=[]
for i in mylist:
n = i**2
newlist.append(n)
return newlist
#this ends the function, and means that the output is this "newlist"
#now call the function
listfunc = [7,6,5,4,3,2,1]
listfunc2 = [3,4,5,6]
listfunc3 = [55,31,9]
print(squarelist(listfunc))
#this will print newlist, when listfunc is the function input.
print(squarelist(listfunc2))
print(squarelist(listfunc3))
#adding a print statement into the function will cause the output to print whenever the function is called
def squarelist2(mylist):
#"list" is a placeholder that can be replaced by any list when the function is called
newlist=[]
for i in mylist:
n = i**2
newlist.append(n)
print(newlist)
return newlist
squarelist2(listfunc3)
#It is possible to use a function inside of a different function.
#Let's take the output list of the squarelist function, and subtract each value in that list from a value in a different list.
def subtract_lists(list1,list2):
difference_list=[]
squares=squarelist(list1)
for i in range(len(list2)):
#i will now go from 0 to the length of list2 (which should be the same as list 1)
diffs=squares[i]-list2[i]
difference_list.append(diffs)
return difference_list
p=[3,4,5,6]
q=[4,3,2,1]
print(subtract_lists(p,q))
"""
Part 6
-NumPy
"""
import numpy as np
#NumPy is a python library that has a ton of useful functions. Many are for math but the uses are broad.
#Here are just a couple of useful NumPy functions.
#an array can often be used like a list, but it can be multi-dimensional like a matrix
#make an array of zeros
arr1 = np.zeros((3,3))
print('zero array:',arr1)
#make an array of random numbers
#note the parentheses!
arr2 = np.random.rand(3,3)
print('random array:',arr2)
#make an array from 0 to 50 with 5 evenly spaced values
arr3 = np.linspace(0,50,5)
print('linspace:',arr3)
#make an array from 0 to 50 in intervals of 5
arr4 = np.arange(0,50,5)
print('arange:',arr4)
#arrays are great for math, you can do an operation on the whole array at once
multarr3 = arr4*10
print(multarr3)
"""
Part 7
-simple plotting
"""
import matplotlib.pyplot as plt
x=np.arange(0,100,5)
y=np.arange(0,20,1)
#plt.plot(x,y)
#plt.title("Scatter Plot Example")
#plt.xlabel("x axis")
#plt.ylabel("y axis")
#plt.show()
#
#plt.scatter(x,y)
#plt.title("Scatter Plot Example")
#plt.xlabel("x axis")
#plt.ylabel("y axis")
#plt.savefig("Example.png")
"""
Part 8
-import data from text or csv file
"""
x_list=[]
y_list=[]
#start with two empty lists, these are where we will put the data from our text file
#open your file externally first and make sure your know what is in it!
#this file contains the amplitude and frequency values from the microwave spectrum of the cis-beta-cyanovinyl
with open("survey1775.txt","r") as filename:
#this file contains the amplitude and frequency values from the microwave spectrum of the cis-beta-cyanovinyl
#this opens the survey1775.txt file and assigns its contents to the variable "filename"
#the "r" means read, because we just want to read the context. "w" is write, but we don't want to change the file.
#we can now manipulate this "file" variable
junk=filename.readline()
print(junk)
#The first line of my file is not data, just words.
#I don't want it in my lists of data so I'm just assigning it to a junk variable
#now when I use the "file" variable, it won't include this first line
for line in filename:
#this loops through every line in the file
x,y = line.split()
#this takes each line and splits it into two separate variables
#this only works if there are separated values on each line
#if the values are comma separated add "," inside the parentheses
x_list.append(float(x))
y_list.append(float(y))
#Now I have lists of my frequency values (x) and amplitudes (y)
print(x_list)
print(y_list)
|
7f5d67d5e20cdc67f839886d39b207df0585d247 | ZeroVM-dot/lecture2 | /loops0.py | 138 | 4.15625 | 4 | for i in range(5):
print(i)
print("=====Other Loop type=====")
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(name)
|
615efb92487e6d4043e69ec3d7a137beff7364e7 | Erdalien/Movies | /Movies/main.py | 4,084 | 4.09375 | 4 | '''
Problem:
We want to build a system to pick the best (or worst) movies for the person provided.
The algorithm makes its decision based on Euclidian scoring and users opinions.
To run the code you have to specific an user, e.g:
python3 main.py --user "Adam Tomporowski"
Author:
Adam Tomporowski, s16740
Piotr Baczkowski, s16621
'''
# To run this script you just have to import below modules
import argparse, json
import numpy as np
from operator import itemgetter
# This script uses Euclidean distance algorithm to calculate the best bets
# You can learn more here https://en.wikipedia.org/wiki/Euclidean_distance
from compute_scores import euclidean_score
def build_arg_parser():
'''
The argparse module makes it easy to write user-friendly command-line interfaces
:return: a command with parameter
'''
parser = argparse.ArgumentParser(description='Find users who are similar to the input user')
parser.add_argument('--user', dest='user', required=True,
help='Input user')
return parser
# Finds users in the dataset that are similar to the input user
def find_similar_users(dataset, user, num_users):
'''
Finds users with similar scores
:param dataset: tells the function which json file to read
:param user: Name of the user to find best/worst bets
:param num_users: Specifics the number of users to get recommendations from. Notice they are picked from the best
matching to worst
:return: Return users with matching score
'''
if user not in dataset:
raise TypeError('Cannot find ' + user + ' in the dataset')
# Compute Pearson score between input user
# and all the users in the dataset
scores = np.array([[x, euclidean_score(dataset, user,
x)] for x in dataset if x != user])
# Sort the scores in decreasing order
scores_sorted = np.argsort(scores[:, 1])[::-1]
# Extract the top 'num_users' scores
top_users = scores_sorted[:num_users]
return scores[top_users]
if __name__ == '__main__':
# Parsed args
args = build_arg_parser().parse_args()
# Assigns arg to user variable
user = args.user
# Name of the dataset file
ratings_file = 'ratings.json'
with open(ratings_file, 'r') as f:
data = json.loads(f.read())
# print('\nUsers similar to ' + user + ':\n')
similar_users = find_similar_users(data, user, 6)
# print(similar_users)
# print('User\t\t\tSimilarity score')
# print('-' * 41)
# for item in similar_users:
# print(item[0], '\t\t', round(float(item[1]), 2))
# This list stores names of users with most similar taste, without scoring
guys = []
# Dict to save recommendations
best_bets = {}
# This for separates names and scores
for item in similar_users:
guys.append(item[0])
# print("List of users with similar taste: ")
# print(guys)
# Assigns all movies watched by guys[] with scores
for item in guys:
best_bets.update(data[item])
# Dict of films already watched by the user
already_watched = {}
# Assigns titles to the above dict
for key in data:
if key == user:
already_watched.update(data[user])
# Assign all the films from best matching users
movies_to_watch = []
movies_to_watch_merged = {}
for item in data:
for guy in guys:
if item == guy:
movies_to_watch.append(data[item])
# Removes duplicates
for i in movies_to_watch:
movies_to_watch_merged = {key: i.get(key, 0) + movies_to_watch_merged.get(key, 0)
for key in set(i) | set(movies_to_watch_merged)}
# Sorts by a key value
movies_to_watch_merged = (sorted(movies_to_watch_merged.items(), key=itemgetter(1), reverse=True))
# Removes already watched films from the final list
for i in movies_to_watch_merged:
for y in already_watched:
if i[0] == y:
movies_to_watch_merged.remove(i)
print("Top 5 movies recommended for you based on others opinion: ")
print(movies_to_watch_merged[:5])
print("Worst 5 movies for you:")
print(movies_to_watch_merged[-5:]) |
c7d37dda67399bb51fd436305f1bd17a6846a77b | atsss/nyu_deep_learning | /examples/beginner/ABC085B.py | 234 | 3.53125 | 4 | # from collections import Counter
#
# N = int(input())
#
# D = []
# for i in range(N): D.append(int(input()))
#
# counter = Counter(D)
#
# print(len(counter))
N = int(input())
D = [int(input()) for i in range(N)]
print(len(set(D)))
|
22211d989fd3f2e16b2b089ce09b2fd6a4b1a3dc | atsss/nyu_deep_learning | /algorithm/combination.py | 394 | 3.5625 | 4 | from itertools import permutations, combinations,combinations_with_replacement,product
a=['a','b','C']
print(list(permutations(a)))
print(list(combinations(a,2)))
print(list(combinations_with_replacement(a,3)))
a=list(product(['+','-'],repeat=3))
print(a)
s=['5', '5', '3', '4']
for i in a:
ans=s[0]+i[0]+s[1]+i[1]+s[2]+i[2]+s[3]
if eval(ans)==7:
print(ans+'=7')
break
|
7b63664677834170f014c9885e6f1ccc220e5fcf | ldaniil32l/course_work_2021 | /course_work.py | 9,794 | 3.578125 | 4 | # Автор: Попов Даниил
# Группа 131-Мко
from math import factorial, sin, log2, pi
from cmath import cosh, sinh
from tkinter import *
from tkinter import ttk
# Функция произведения матриц (для поиска степеней матриц)
def multi_matrix(A, B):
multi_AB = []
for i in range(len(A)):
multi_row = []
for j in range(len(A)):
multi_row.append(0)
multi_AB.append(multi_row)
for i in range(len(A)):
for j in range(len(A)):
for k in range(len(A)):
multi_AB[i][j] += A[i][k] * B[k][j]
return multi_AB
# Функция умножения матрицы на число
def multi_matrix_number(A, k):
for i in range(len(A)):
for j in range(len(A)):
A[i][j] = A[i][j] * k
return A
# Функция сложения матриц
def sum_matrix(A, B):
for i in range(len(A)):
for j in range(len(A)):
A[i][j] += B[i][j]
return A
# Функция нахождения коэффициентов p характеристического многочлена
def coefficients_p(A):
p = []
s = []
first_degree_A = A
for i in range(len(A)):
s.append(trace_matrix(first_degree_A))
first_degree_A = multi_matrix(first_degree_A, A)
if i == 0:
p.append(s[i])
else:
p.append(s[i])
k = i - 1
for j in range(i):
p[i] -= p[j] * s[k]
k -= 1
p[i] /= (i + 1)
return p
# Функция поиска следа матрицы
def trace_matrix(A):
tr = 0
for i in range(len(A)):
tr += A[i][i]
return tr
def B_in_kappa (g, n, p):
if g >= 0 and g <= (n - 2):
return 0
elif g == (n - 1):
return 1
elif g >= n:
b_sum = 0
for l in range(1, n):
b_sum += p[l - 1] * B_in_kappa(g - l, n, p)
return b_sum
else:
return "ERROR"
def search_for_kappa (index, n, Np, p):
kappa = 1 / factorial(index)
for g in range(index):
temp_p = p[n - index + g - 1]
for j in range(n, (n + Np)):
temp_sum = B_in_kappa(j - 1 - g, n, p) / factorial(j)
kappa += temp_p * temp_sum
return kappa
# Основная часть программы
# Численное решение
Np = 11
n = 4
# lamda_0 - длина волны
lambda_0 = 830
k0 = 2 * pi / lambda_0
theta = pi / 3
# d - толщина слоя
d = 500
G = complex(0.4322, 0.0058)
eps1 = eps2 = eps3 = complex(-4.8984, 19.415)
im = complex(0, 1)
Wd = [
[0, (1 - (sin(theta) ** 2 / eps3)) * im * k0, 0, 0],
[eps1 * im * k0, 0, k0 * G, 0],
[0, 0, 0, im * k0],
[-k0 * G, 0, im * k0 * (eps2 - sin(theta) ** 2), 0]
]
# Теорема
# Поиск максимального элемента матрицы Wd
maxWd = 0
for i in range(n):
for j in range(n):
if abs(Wd[i][j]) >= abs(maxWd):
maxWd = Wd[i][j]
# Поиск m
m = 2
while True:
temp_beta = abs(maxWd) * d * (n + 4) / 2 / m
if temp_beta < 1:
break
else:
m *= 2
def no_param(*args):
try:
m = int(param_m.get())
while True:
m *= 2
if abs(maxWd) * (n + 4) / 2 / m < 1:
param_m.set(m)
break
except ValueError:
pass
# Полиномиальная аппроксимация
def yes_param(*args):
A = []
m = int(param_m.get())
for i in range(n):
temp_row = []
for j in range(n):
temp_row.append(Wd[i][j] / m)
A.append(temp_row)
p = coefficients_p(A)
first_degree_A = A
for i in range(n):
if i == 0:
identity_matrix = []
for l in range(len(A)):
identity_row = []
for k in range(len(A)):
if l == k:
identity_row.append(1)
else:
identity_row.append(0)
identity_matrix.append(identity_row)
exp_A = multi_matrix_number(identity_matrix, search_for_kappa(i, n, Np, p))
else:
exp_A = sum_matrix(exp_A, \
multi_matrix_number(A, search_for_kappa(i, n, Np, p)))
A = multi_matrix(A, first_degree_A)
# Возведение exp_A в степень m
for i in range(int(log2(m))):
exp_A = multi_matrix(exp_A, exp_A)
exp_Wd = exp_A
# Таблица 1
for i in range(n):
for j in range(n):
e = Entry(mainframe, font=('Arial', 10))
e.grid(row=i+3, column=j, sticky=(W, E))
if exp_Wd[i][j].imag < 0:
val = f"{'%.4f' % exp_Wd[i][j].real} - " \
f"{'%.4f' % abs(exp_Wd[i][j].imag)}i"
else:
val = f"{'%.4f' % exp_Wd[i][j].real} + " \
f"{'%.4f' % exp_Wd[i][j].imag}i"
e.insert(END, val)
def exact(*args):
# точное решение
# z - количетсво слоев
z = 1
sigma_2 = k0 ** 2 * ((1 - ((sin(theta) ** 2) / eps3)) * eps1 +
(eps2 - (sin(theta) ** 2) - (G * G) / eps3))
sigma_4 = k0 ** 4 * eps1 * ((G * G + eps2 * sin(theta) ** 2 \
- sin(theta) ** 4) / eps3 - eps2 + sin(theta) ** 2)
beta_1 = (sigma_2 / 2 + (sigma_2 ** 2 / 4 + sigma_4) ** 0.5) ** 0.5
beta_2 = (sigma_2 / 2 - (sigma_2 ** 2 / 4 + sigma_4) ** 0.5) ** 0.5
Sigma_0 = (beta_1 ** 2 * cosh(z * beta_2) - beta_2 ** 2
* cosh(z * beta_1)) / (beta_1 ** 2 - beta_2 ** 2)
Sigma_1 = (beta_1 ** 3 * sinh(z * beta_2) - beta_2 ** 3
* sinh(z * beta_1)) / (beta_1 * beta_2 *
(beta_1 ** 2 - beta_2 ** 2))
Sigma_2 = (cosh(z * beta_2) - cosh(z * beta_1)) \
/ (beta_1 ** 2 - beta_2 ** 2)
Sigma_3 = (beta_1 * sinh(z * beta_2) - beta_2 *
sinh(z * beta_1)) / (beta_1 * beta_2 *
(beta_1 ** 2 - beta_2 ** 2))
w2 = multi_matrix(Wd, Wd)
w3 = multi_matrix(w2, Wd)
t11 = Sigma_0 + Sigma_1 * Wd[0][0] + Sigma_2 \
* w2[0][0] + Sigma_3 * w3[0][0]
t12 = Sigma_1 * Wd[0][1] + Sigma_2 * w2[0][1] + Sigma_3 * w3[0][1]
t13 = Sigma_1 * Wd[0][2] + Sigma_2 * w2[0][2] + Sigma_3 * w3[0][2]
t14 = Sigma_1 * Wd[0][3] + Sigma_2 * w2[0][3] + Sigma_3 * w3[0][3]
t21 = Sigma_1 * Wd[1][0] + Sigma_2 * w2[1][0] + Sigma_3 * w3[1][0]
t22 = Sigma_0 + Sigma_1 * Wd[1][1] + Sigma_2 \
* w2[1][1] + Sigma_3 * w3[1][1]
t23 = Sigma_1 * Wd[1][2] + Sigma_2 * w2[1][2] + Sigma_3 * w3[1][2]
t24 = Sigma_1 * Wd[1][3] + Sigma_2 * w2[1][3] + Sigma_3 * w3[1][3]
t31 = Sigma_1 * Wd[2][0] + Sigma_2 * w2[2][0] + Sigma_3 * w3[2][0]
t32 = Sigma_1 * Wd[2][1] + Sigma_2 * w2[2][1] + Sigma_3 * w3[2][1]
t33 = Sigma_0 + Sigma_1 * Wd[2][2] + Sigma_2 \
* w2[2][2] + Sigma_3 * w3[2][2]
t34 = Sigma_1 * Wd[2][3] + Sigma_2 * w2[2][3] + Sigma_3 * w3[2][3]
t41 = Sigma_1 * Wd[3][0] + Sigma_2 * w2[3][0] + Sigma_3 * w3[3][0]
t42 = Sigma_1 * Wd[3][1] + Sigma_2 * w2[3][1] + Sigma_3 * w3[3][1]
t43 = Sigma_1 * Wd[3][2] + Sigma_2 * w2[3][2] + Sigma_3 * w3[3][2]
t44 = Sigma_0 + Sigma_1 * Wd[3][3] + Sigma_2\
* w2[3][3] + Sigma_3 * w3[3][3]
T = [[t11, t12, t13, t14],
[t21, t22, t23, t24],
[t31, t32, t33, t34],
[t41, t42, t43, t44]]
# Таблица 2
for i in range(n):
for j in range(n):
e = Entry(mainframe, font=('Arial', 10))
e.grid(row=i + 9, column=j, sticky=(W, E))
if T[i][j].imag < 0:
val = f"{'%.4f' % T[i][j].real} - " \
f"{'%.4f' % abs(T[i][j].imag)}i"
else:
val = f"{'%.4f' % T[i][j].real} + " \
f"{'%.4f' % T[i][j].imag}i"
e.insert(END, val)
root = Tk()
root.geometry("590x360")
root.title('Course Work. Popov Daniil.')
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
numeric_title = "Матрица переноса (численное вычисление)"
param_m_text = "Устроит ли параметр масштабирования m ="
param_m = StringVar()
param_m.set(m)
exact_title = "Матрица переноса (точное решение)"
style = ttk.Style()
style.map("TButton",
foreground=[('pressed', 'black'), ('active', 'blue')],
background=[('pressed', '!disabled', 'black'),
('active', 'white')]
)
ttk.Label(mainframe, text=numeric_title, font=('arial', 18),
foreground='black', background="white",
relief='solid').grid(row=0, column=0, columnspan=4, sticky=W)
ttk.Label(mainframe, text=param_m_text, font=('arial', 14),
foreground='black').grid(column=0, row=1, columnspan=3, sticky=W)
ttk.Label(mainframe, textvariable=param_m, font=('arial', 14),
foreground='black', relief='groove', width=5)\
.grid(column=3, row=1, sticky=W)
ttk.Button(mainframe, text="Да", command=yes_param)\
.grid(column=0, row=2, sticky=W)
ttk.Button(mainframe, text="Нет", command=no_param)\
.grid(column=1, row=2, sticky=W)
ttk.Label(mainframe, text=exact_title, font=('arial', 18),
foreground='black', background="white",
relief='solid').grid(row=7, column=0, columnspan=4,
pady=50, sticky=W)
ttk.Button(mainframe, text="Вычислить", command=exact)\
.grid(column=0, row=8, sticky=W)
for child in mainframe.winfo_children():
child.grid_configure(padx=5, pady=5)
root.mainloop()
|
98f13d4436271e68b559c29ca72a85f3718254f7 | Davidwang20201101/demo | /venv/2020/10/25.py | 6,144 | 3.609375 | 4 | # names =['Adeam','David','Lucy']
# print(names)
# names[2]='ass'
# print(names)
# names.insert(0,'billy')
# names.insert(2,'car')
# names.append('kris')
# names.remove('kris')
# print(names)
# 得到
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# ['Adeam', 'David', 'Lucy']
# ['Adeam', 'David', 'ass']
# ['billy', 'Adeam', 'car', 'David', 'ass']
# Process finished with exit code 0
# cars =['a','s','d','f']
# cars. sort()
# print(cars)
# 得到
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# ['a', 'd', 'f', 's']
#
# Process finished with exit code 0
# cars =['a','s','d','f']
# cars. sort(reverse=True)
# print(cars)
# 得到
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# ['s', 'f', 'd', 'a']
# Process finished with exit code 0
# cars =['a','s','d','f']
# print(cars)
# cars.reverse()
# print(cars)
# 得到————
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# ['a', 's', 'd', 'f']
# ['f', 'd', 's', 'a']
#
# Process finished with exit code 0
# cars =['a','s','d','f']
# l=len(cars)
# print(len(cars))
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# 4
#
# Process finished with exit code 0
# nums =(3,4,5,6)
# print(max(nums))
# print(min(nums))
# 得到————
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# 6
# 3
# Process finished with exit code 0
# cars =['a','s','d','f']
# cars.sort()#reverse=True
# print(cars)
# 得到————
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# ['a', 'd', 'f', 's']
#
# Process finished with exit code 0
# names =['Adeam','David','Lucy']
# for name in names:
# print(name)
#
# print(names)
# 得到————
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# Adeam
# David
# Lucy
# ['Adeam', 'David', 'Lucy']
# names =['Adeam','David','Lucy']
# for name in names: for loop ->for 临时变量 names是列表词
# print(name)
# print(names)
# names = ['Adeam', 'David', 'Lucy']
# for name in names:
# print(name .title()+",good evening ")
# print(name)
#
# print(names)
# 得出————
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# Adeam,good evening
# Adeam
# David,good evening
# David
# Lucy,good evening
# Lucy
# ['Adeam', 'David', 'Lucy']
#
# Process finished with exit code 0
# names = ['Adeam', 'David', 'Lucy']
# for name in names:
# print(name .title()+",good evening ")
# print(name.title()+"have a nice day")
#
# print(names)
# 得出————
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# Adeam,good evening
# Adeamhave a nice day
# David,good evening
# Davidhave a nice day
# Lucy,good evening
# Lucyhave a nice day
# ['Adeam', 'David', 'Lucy']
#
# Process finished with exit code 0
# for value in range(1, 5):
# print(value)
# 得出————
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# 1
# 2
# 3
# 4
#
# Process finished with exit code 0
# for value in range(1,11,2):
# print(value)
# 得出————
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# 1
# 3
# 5
# 7
# 9
#
# Process finished with exit code 0
# for value in range(2,11,2):
# print(value)
# 得出————
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# 2
# 4
# 6
# 8
# 10
#
# Process finished with exit code 0
# players =['a','b','c','d','e']
# print(players[0:3])
# 得出————
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# ['a', 'b', 'c']
#
# Process finished with exit code 0
# players =['a','b','c','d','e']
# print(players[2:4])
# 得出————
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# ['c', 'd']
#
# Process finished with exit code 0
# players =['a','b','c','d','e']
# print("there are the first these players on my team:")
# for player in players[:3]:
# print(player.title())
# 得出————
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# there are the first these players on my team:
# A
# B
# C
# Process finished with exit code 0
# my_foods = ['pizza','carrot', 'cake','kfc']
# friend_foods = my_foods[:]
#
# my_foods.append('cannoli')
# friend_foods.append('ice cream')
#
# print("my favorate foods are: ")
# print(my_foods)
#
# print("my favorate foods are: ")
# print(friend_foods)
# 得出————
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# my favorate foods are:
# ['pizza', 'carrot', 'cake', 'kfc', 'cannoli']
# my favorate foods are:
# ['pizza', 'carrot', 'cake', 'kfc', 'ice cream']
# Process finished with exit code 0
# tuple
# dimensions = (200,30,50)
# print(dimensions[0])
# print(dimensions[1])
# 得出————
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# 200
# 30
# Process finished with exit code 0
# dimensions = (200,30,50)
# print(dimensions[0])
# print(dimensions[1])
# dimensions = (200,30,50)
# for dimension in dimensions:
# print(dimension)
# print(dimensions)
# 得出————
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# 200
# 30
# 200
# 30
# 50
# (200, 30, 50)
# Process finished with exit code 0 |
9073d1f2d25f33fa6522ef6fe619974d9e9a6146 | Davidwang20201101/demo | /1206.py | 2,372 | 3.546875 | 4 | # 猴子吃桃问题:
# 猴子第一天吃了若干个桃子,当即吃了一半,还不解馋,又多吃了一个; 第二天,吃剩下的桃子的一半,还不过瘾,又多吃了一个;以后每天都吃前一天剩下的一半多一个,到第10天想再吃时,只剩下一个桃子了。问第一天共吃了多少个桃子?
# x=1
#
# for peach in range(9):
# x=(x+1)*2
# print(x)
# 1234四个数字,能组成那些3位数
# numbers=(1,2,3,4)
# for i in numbers:
# for j in numbers:
# for k in numbers:
# print(i,j,k)
# 1234四个数字,能组成那些个位相同3位数
# numbers=(1,2,3,4)
# for i in numbers:
# for j in numbers:
# for k in numbers:
# if(i!=j) and (i!=k) and(j!=k):
# print(i,j,k)
# "水仙花数"是一个 3 位数,它的每个位上的数字的 3次方之和等于它本身,是这个三位数本身。
# for i in range(1,10):
# for j in range(0,10):
# for k in range(0,10):
# if i*100+j*10+k== i**3 + j**3 +k ** 3:
# print(i,j,k)
# "玫瑰花数"是一种四位数,它每一位上的四个数,每一个数的四次方之和,是这一四位数本身,找出所有的玫瑰花数
# for i in range(1,10):
# for j in range(0,10):
# for k in range(0,10):
# for n in range(0,10):
# if i*1000+j*100+k*10+n == i**4+j**4+k**4+n**4:
# print(i,j,k,n)
# 两个乒乓球队,各出三人,每人只比一场。甲队有abc三人,乙队有xyz三人。抽签决定比赛名单。a不和x比,c不和x和z比
# for i in range(0,3):
# for j in range (0,3):
# for k in range (0,3):
# if(i!=j)and(i!=k)and(j!=k):
# if(i!=0)and(k!=0)and(k!=2):
# print(i,j,k)
# 有n个人围成一圈,从第一个人开始报数,从一到三,只要报到3的人就出去,问留下来的是第几号位
import tkinter
top=tkinter . Tk()
lable = tkinter.Label(top,text='Kuga',width=90,height=5,bg="red",font=("Arial",12))#ed
lable .pack()
lable = tkinter.Label(top,text='Agito',width=90,height=5,bg="orange",font=("Arial",12))
lable .pack()
lable = tkinter.Label(top,text='Ryuki',width=90,height=5,bg="yellow",font=("Arial",12))
lable .pack()
|
46b36e657e801721592b3de22e2085d5f3ea8924 | zjw641220480/pythonfirst | /src/simple/simple_if.py | 563 | 3.796875 | 4 | '''
Created on 2017年10月3日
@author: lengxiaoqi
'''
x=0
if x>0:
print("x is positive");
elif x<0:
print("x is negative");
else:
print("x is zero");
#在if判断中也可以使用各种表达式来作为判断条件;他们会被当做ture来处理
#None,0,空字符串,空列表,空集合会被当做false来处理;
#当然这种方式是不推荐的,推荐使用len(mylist)>0来判断一个列表是否为空
mylist=[1,2,3,4,5];
if mylist:
print("The first element is ",mylist[0]);
else:
print("there is no first element"); |
bf009002e5a2a62dafe139fefdec3c3d2e407754 | bsk17/LibraryPython | /main.py | 15,802 | 3.515625 | 4 | # tkinter is the GUI library like PyQt
from pymongo import MongoClient
from tkinter import*
from tkinter import ttk, messagebox
import random
from datetime import datetime
import tkinter.messagebox
client = MongoClient(port=27017)
db = client.Books
books = db.books
class Library:
# as soon as the class is initiated we can assign the window size and other specs
def __init__(self, root):
self.root = root
self.root.title("Library System")
self.root.geometry("1350x750+0+0")
self.root.configure(background="powder blue")
# creating variables
MType = StringVar()
Ref = StringVar()
Title = StringVar()
Firstname = StringVar()
Surname = StringVar()
Address1 = StringVar()
Address2 = StringVar()
Postcode = StringVar()
Mobileno = StringVar()
BookId = StringVar()
BookTitle = StringVar()
BookType = StringVar()
Author = StringVar()
DateBorrow = StringVar()
dateDue = StringVar()
SellingPrice = StringVar()
LateReturnFine = StringVar()
DateOverDue = StringVar()
DaysOnLoan = StringVar()
Prescription = StringVar()
# function to exit
def iExit():
iExit = tkinter.messagebox.askyesno("Library System", "Confirm if you want to exit")
if iExit > 0:
root.destroy()
return
# function to reset
def ireset():
MType.set("")
Ref.set("")
Title.set("")
Firstname.set("")
Surname.set("")
Address1.set("")
Address2.set("")
Postcode.set("")
Mobileno.set("")
BookId.set("")
BookTitle.set("")
BookType.set("")
Author.set("")
DateBorrow.set("")
dateDue.set("")
SellingPrice.set("")
LateReturnFine.set("")
DateOverDue.set("")
DaysOnLoan.set("")
self.txtDisplay.delete("1.0", END)
# function to add
def iadd():
# this will push the data into database
books.insert_one({"Member Type": MType.get(), "Reference No": Ref.get(), "Firstname": Firstname.get(),
"Surname": Surname.get(), "Address 1": Address1.get(), "Address 2": Address2.get(),
"Mobile No": Mobileno.get()})
messagebox.showinfo("Successful", "You have added a member")
# after adding we can clear the fields
MType.set("")
Ref.set("")
Title.set("")
Firstname.set("")
Surname.set("")
Address1.set("")
Address2.set("")
Postcode.set("")
Mobileno.set("")
# function to delete
def idelete():
ireset()
self.txtDisplay.delete("1.0", END)
# function to display data
def idisplayData():
self.txtFrameDetail.insert(END, "\t" + MType.get() + "\t" + Ref.get() + "\t" + Title.get() +
"\t" + Firstname.get() + "\t" + Surname.get() + "\t" + Address1.get() +
"\t" + Address2.get() + "\t" + Postcode.get() + "\t" + BookTitle.get() +
"\t" + DateBorrow.get() + "\t" + DaysOnLoan.get() + "\n")
def ireceipt():
self.txtDisplay.insert(END, 'Member Type : \t\t' + MType.get() + "\n")
self.txtDisplay.insert(END, 'Ref No : \t\t' + Ref.get() + "\n")
self.txtDisplay.insert(END, 'Title : \t\t' + Title.get() + "\n")
self.txtDisplay.insert(END, 'Firstname : \t\t' + Firstname.get() + "\n")
self.txtDisplay.insert(END, 'Surname : \t\t' + Surname.get() + "\n")
self.txtDisplay.insert(END, 'Address1 : \t\t' + Address1.get() + "\n")
self.txtDisplay.insert(END, 'Address2 : \t\t' + Address2.get() + "\n")
self.txtDisplay.insert(END, 'Post Code : \t\t' + Postcode.get() + "\n")
self.txtDisplay.insert(END, 'Mobile No : \t\t' + Mobileno.get() + "\n")
self.txtDisplay.insert(END, 'Book ID : \t\t' + BookId.get() + "\n")
self.txtDisplay.insert(END, 'Book Title : \t\t' + BookTitle.get() + "\n")
self.txtDisplay.insert(END, 'Author : \t\t' + Author.get() + "\n")
self.txtDisplay.insert(END, 'Date Borrowed : \t\t' + DateBorrow.get() + "\n")
# creating Frame
Mainframe = Frame(self.root)
Mainframe.grid()
TitleFrame = Frame(Mainframe, width=350, padx=20, bd=20, relief=RIDGE)
TitleFrame.pack(side=TOP)
self.lblTitle = Label(TitleFrame, width=30, font=('arial', 30, 'bold'),
text="\tLibrary System\t", padx=12)
self.lblTitle.grid()
ButtonFrame = Frame(Mainframe, bd=20, width=800, height=50, padx=20, relief=RIDGE)
ButtonFrame.pack(side=BOTTOM)
FrameDetail = Frame(Mainframe, bd=20, width=800, height=100, padx=20, relief=RIDGE)
FrameDetail.pack(side=BOTTOM)
DataFrame = Frame(Mainframe, bd=20, width=1300, height=400, padx=20, relief=RIDGE)
DataFrame.pack(side=BOTTOM)
DataFrameLeft = LabelFrame(DataFrame, bd=10, width=800, height=300, padx=20, relief=RIDGE,
font=('arial', 12, 'bold'), text="Library Membership Information",)
DataFrameLeft.pack(side=LEFT)
DataFrameRight = LabelFrame(DataFrame, bd=10, width=450, height=300, padx=20, relief=RIDGE,
font=('arial', 12, 'bold'), text="Book Details",)
DataFrameRight.pack(side=RIGHT)
# creating widgets for the left frame
# label for member type
self.lbMemberType = Label(DataFrameLeft, font=('arial', 12, 'bold'), text="Member Type:", padx=2, pady=2)
self.lbMemberType.grid(row=0, column=0, sticky=W)
# dropdown to select
self.cbMemberType = ttk.Combobox(DataFrameLeft, font=('arial', 12, 'bold'), state='readonly', textvariable=MType
, width=23)
self.cbMemberType['value'] = ('', 'Student', 'Professor', 'Admin Staff')
self.cbMemberType.current(0)
self.cbMemberType.grid(row=0, column=1)
# label for book id
self.lbBookId = Label(DataFrameLeft, font=('arial', 12, 'bold'), text="Book Id:", padx=2, pady=2)
self.lbBookId.grid(row=0, column=2, sticky=W)
# textfield entry for book id
self.txtBookId = Entry(DataFrameLeft, font=('arial', 12, 'bold'), width=25, textvariable=BookId)
self.txtBookId.grid(row=0, column=3)
# label for reference
self.lbRef = Label(DataFrameLeft, font=('arial', 12, 'bold'), text="Reference No:", padx=2, pady=2)
self.lbRef.grid(row=1, column=0, sticky=W)
# textfield entry for reference
self.txtRef = Entry(DataFrameLeft, font=('arial', 12, 'bold'), width=25, textvariable=Ref)
self.txtRef.grid(row=1, column=1)
# label for Book Title
self.lbBookTitle = Label(DataFrameLeft, font=('arial', 12, 'bold'), text="Book Title:", padx=2, pady=2)
self.lbBookTitle.grid(row=1, column=2, sticky=W)
# textfield entry for book id
self.txtBookTitle = Entry(DataFrameLeft, font=('arial', 12, 'bold'), width=25, textvariable=BookTitle)
self.txtBookTitle.grid(row=1, column=3)
# label for title of name
self.lblTitle = Label(DataFrameLeft, font=('arial', 12, 'bold'), text="Title:", padx=2, pady=2)
self.lblTitle.grid(row=2, column=0, sticky=W)
# combobox for title of name
self.cbTitle = ttk.Combobox(DataFrameLeft, state='readonly', font=('arial', 12, 'bold'), width=23, textvariable=Title)
self.cbTitle['value'] = ('', 'Mr.', 'Miss.', 'Mrs.', 'Dr.', 'Prof.')
self.cbTitle.current(0)
self.cbTitle.grid(row=2, column=1)
# label for author
self.lblAuthor = Label(DataFrameLeft, font=('arial', 12, 'bold'), text="Author:", padx=2, pady=2)
self.lblAuthor.grid(row=2, column=2, sticky=W)
# textfield entry for Author
self.txtAuthor = Entry(DataFrameLeft, font=('arial', 12, 'bold'), width=25, textvariable=Author)
self.txtAuthor.grid(row=2, column=3)
# label for First name
self.lblFirstName = Label(DataFrameLeft, font=('arial', 12, 'bold'), text="First Name:", padx=2, pady=2)
self.lblFirstName.grid(row=3, column=0, sticky=W)
# textfield entry for First name
self.txtFirstName = Entry(DataFrameLeft, font=('arial', 12, 'bold'), width=25, textvariable=Firstname)
self.txtFirstName.grid(row=3, column=1)
# label for date borrowed
self.lblDateBorrowed = Label(DataFrameLeft, font=('arial', 12, 'bold'), text="Date Borrowed:", padx=2, pady=2)
self.lblDateBorrowed.grid(row=3, column=2, sticky=W)
# textfield entry for date borrowed
self.txtDateBorrowed = Entry(DataFrameLeft, font=('arial', 12, 'bold'), width=25, textvariable=DateBorrow)
self.txtDateBorrowed.grid(row=3, column=3)
# label for Surname
self.lblSurname = Label(DataFrameLeft, font=('arial', 12, 'bold'), text="Surname:", padx=2, pady=2)
self.lblSurname.grid(row=4, column=0, sticky=W)
# textfield entry for Surname
self.txtSurname = Entry(DataFrameLeft, font=('arial', 12, 'bold'), width=25, textvariable=Surname)
self.txtSurname.grid(row=4, column=1)
# label for DateDue
self.lblDateDue = Label(DataFrameLeft, font=('arial', 12, 'bold'), text="Date Due:", padx=2, pady=2)
self.lblDateDue.grid(row=4, column=2, sticky=W)
# textfield entry for date due
self.txtDateDue = Entry(DataFrameLeft, font=('arial', 12, 'bold'), width=25, textvariable=dateDue)
self.txtDateDue.grid(row=4, column=3)
# label for Address1
self.lblAddress1 = Label(DataFrameLeft, font=('arial', 12, 'bold'), text="Address 1:", padx=2, pady=2)
self.lblAddress1.grid(row=5, column=0, sticky=W)
# textfield entry for Address1
self.txtAddress1 = Entry(DataFrameLeft, font=('arial', 12, 'bold'), width=25, textvariable=Address1)
self.txtAddress1.grid(row=5, column=1)
# label for days on loan
self.lblDaysOnLoan = Label(DataFrameLeft, font=('arial', 12, 'bold'), text="days on loan:", padx=2, pady=2)
self.lblDaysOnLoan.grid(row=5, column=2, sticky=W)
# textfield entry for Address1
self.txtDaysOnLoan = Entry(DataFrameLeft, font=('arial', 12, 'bold'), width=25, textvariable=DaysOnLoan)
self.txtDaysOnLoan.grid(row=5, column=3)
# label for Address2
self.lblAddress2 = Label(DataFrameLeft, font=('arial', 12, 'bold'), text="Address 2:", padx=2, pady=2)
self.lblAddress2.grid(row=6, column=0, sticky=W)
# textfield entry for Address2
self.txtAddress2 = Entry(DataFrameLeft, font=('arial', 12, 'bold'), width=25, textvariable=Address2)
self.txtAddress2.grid(row=6, column=1)
# label for fine
self.lblLateReturnFine = Label(DataFrameLeft, font=('arial', 12, 'bold'), text="Late return fine:", padx=2, pady=2)
self.lblLateReturnFine.grid(row=6, column=2, sticky=W)
# textfield entry fine
self.txtLateReturnFine = Entry(DataFrameLeft, font=('arial', 12, 'bold'), width=25, textvariable=LateReturnFine)
self.txtLateReturnFine.grid(row=6, column=3)
# label for Postcode
self.lblPostCode = Label(DataFrameLeft, font=('arial', 12, 'bold'), text="Post Code:", padx=2, pady=2)
self.lblPostCode.grid(row=7, column=0, sticky=W)
# textfield entry for Postcode
self.txtPostCode = Entry(DataFrameLeft, font=('arial', 12, 'bold'), width=25, textvariable=Postcode)
self.txtPostCode.grid(row=7, column=1)
# label for dateoverdue
self.lblDateOverDue = Label(DataFrameLeft, font=('arial', 12, 'bold'), text="Date Over Due:", padx=2, pady=2)
self.lblDateOverDue.grid(row=7, column=2, sticky=W)
# textfield dateoverdue
self.txtDateOverDue = Entry(DataFrameLeft, font=('arial', 12, 'bold'), width=25, textvariable=DateOverDue)
self.txtDateOverDue.grid(row=7, column=3)
# label for Mobile number
self.lblMobileNo = Label(DataFrameLeft, font=('arial', 12, 'bold'), text="Mobile Number:", padx=2, pady=2)
self.lblMobileNo.grid(row=8, column=0, sticky=W)
# textfield entry for Mobile Number
self.txtMobileNo = Entry(DataFrameLeft, font=('arial', 12, 'bold'), width=25, textvariable=Mobileno)
self.txtMobileNo.grid(row=8, column=1)
# label for selling price
self.lblSellingPrice = Label(DataFrameLeft, font=('arial', 12, 'bold'), text="Selling Price:", padx=2, pady=2)
self.lblSellingPrice.grid(row=8, column=2, sticky=W)
# textfield selling price
self.txtSellingPrice = Entry(DataFrameLeft, font=('arial', 12, 'bold'), width=25, textvariable=SellingPrice)
self.txtSellingPrice.grid(row=8, column=3)
# creating buttons to display,delete,rest and exit
self.btnDisplay = Button(ButtonFrame, command=idisplayData, text="Display Info", font=('arial', 12, 'bold'),
width=20, bd=4)
self.btnDisplay.grid(row=0, column=0)
self.btnDelete = Button(ButtonFrame, text="DELETE", command=idelete, font=('arial', 12, 'bold'), width=20, bd=4)
self.btnDelete.grid(row=0, column=1)
self.btnAdd = Button(ButtonFrame, text="ADD", font=('arial', 12, 'bold'), width=20, bd=4, command=iadd)
self.btnAdd.grid(row=0, column=2)
self.btnReset = Button(ButtonFrame, text="RESET", font=('arial', 12, 'bold'), width=20, bd=4, command=ireset)
self.btnReset.grid(row=0, column=3)
self.btnExit = Button(ButtonFrame, text="EXIT", font=('arial', 12, 'bold'), width=20, bd=4, command=iExit)
self.btnExit.grid(row=0, column=4)
# creating widgets for the right frame
# creating a display for list of books
self.txtDisplay = Text(DataFrameRight, font=('arial', 12, 'bold'), width=32, height=13, padx=8, pady=20)
self.txtDisplay.grid(row=0, column=2)
# creating a ScrollBar
scrollBar = Scrollbar(DataFrameRight)
scrollBar.grid(row=0, column=1, sticky='ns')
# creating a list of books
ListOfBooks = ["Compiler Design", "Computer Graphics", "Management Information System", "Enterprise Resource Planning", "Theory of Automata",
"Programming in Python", "Software Engineering", "Computer Networks"]
bookList = Listbox(DataFrameRight, width=28, height=12, font=('arial', 12, 'bold'))
bookList.bind('<<ListBoxSelect>>')
bookList.grid(row=0, column=0, padx=8)
scrollBar.config(command=bookList.yview)
for items in ListOfBooks:
bookList.insert(END, items)
# label to display about book
self.lbllabel=Label(FrameDetail, font=('arial', 10, 'bold'), pady=4,
text="Member Type\tReference No.\t Title\t Firstname\t Surname\t Address 1"
"\t Address 2\t post Code\t Book Title\t Date Borrowed\t Days on loan",)
self.lbllabel.grid(row=0, column=0)
self.txtDisplay = Text(FrameDetail, font=('arial', 12, 'bold'), width=121, height=4, padx=2, pady=4)
self.txtDisplay.grid(row=1, column=0)
if __name__ == '__main__':
root = Tk()
application = Library(root)
root.mainloop()
|
a213dd7895b140e92ecf9cd41ee429e477352849 | vikash-india/MathematicsNotes2Myself | /mathematics/concepts/01-basics/P007_Algebra_IndentityElement.py | 384 | 3.796875 | 4 | # Description: Identity Elements
from numpy import identity, zeros, ones
# Additive Identity
print zeros (3) # Returns 1X3 additive identity matrix with all element as 0.
# Multiplicative Identity
print identity(3) # Returns 3X3 multiplicative identity matrix.
# Related Functions
print ones(3) # Returns 1X3 Matrix with all element as 1.
# TODO
# - None
|
0971d34016d5a38b6f7aa8d801fc1cb0c1a525bf | 17-76018348/mycode | /data-structure/bubblesort.py | 1,678 | 3.84375 | 4 | import random
def performSelectionSort(lst):
for itr1 in range(0, len(lst)):
for itr2 in range(itr1+1, len(lst)):
if lst[itr1] < lst[itr2]:
lst[itr1], lst[itr2] = lst[itr2], lst[itr1]
return lst
def bubblesort(lst):
for idx1 in range(0, len(lst)):
for idx2 in range(0, idx1):
if lst[idx1] < lst[idx2]:
lst[idx1], lst[idx2] = lst[idx2], lst[idx1]
return lst
N = 10
lstNumbers = list(range(N))
random.shuffle(lstNumbers)
print(lstNumbers)
print(performSelectionSort(lstNumbers))
# lstNumbers2 = [2, 5, 0, 3, 3, 3, 1, 5, 4, 2]
print(lstNumbers)
print(bubblesort(lstNumbers))
#%%
import random
def performSelectionSort(lst):
for itr1 in range(0, len(lst)):
for itr2 in range(itr1+1, len(lst)):
if lst[itr1] < lst[itr2]:
lst[itr1], lst[itr2] = lst[itr2], lst[itr1]
return lst
N = 10
lstNumbers = list(range(N))
random.shuffle(lstNumbers)
print('Bubble sort 하기전:',lstNumbers)
print('Bubble sort 한 후',performSelectionSort(lstNumbers))
# %%
def bubblesort_1(lst):
for idx1 in range(0, len(lst)):
for idx2 in range(0, idx1):
if lst[idx1] < lst[idx2]:
lst[idx1], lst[idx2] = lst[idx2], lst[idx1]
print(lst)
return lst
def bubbleSort_2(lst):
for itr1 in range(0, len(lst)):
for itr2 in range(itr1+1, len(lst)):
if lst[itr1] < lst[itr2]:
lst[itr1], lst[itr2] = lst[itr2], lst[itr1]
print(lst)
return lst
lstNumbers2 = [3,1,6,5,2,4]
print(lstNumbers2)
print(performSelectionSort(lstNumbers2))
# %%
# %%
|
177116fdac6e2827d8d3ddb567ac8bc15952d7ad | anuradhaschougale18/PythonFiles | /ExceptionHandling/nestedtryException.py | 506 | 3.625 | 4 | '''
Nested try block
'''
def calc():
try:
try:
x=int(input("Enter value=>"))
y=int(input("Enter value=>"))
a=x/y
print("Answer is=",a)
except ZeroDivisionError as ze:
print(ze)
try:
l=[10,20]
i=int(input("Enter index to get element value=>"))
print(l[i])
except IndexError as ie:
print(ie)
except Exception as e:
print(e)
|
95b5d44432371958fb85efcb606729590797041d | anuradhaschougale18/PythonFiles | /21st day-BinarySearchTreee.py | 1,346 | 4.28125 | 4 | '''
Task
The height of a binary search tree is the number of edges between the
tree's root and its furthest leaf. You are given a pointer, root,
pointing to the root of a binary search tree.
Complete the getHeight function provided in your editor so that it returns the height of the binary search tree.
'''
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
root.left=cur
else:
cur=self.insert(root.right,data)
root.right=cur
return root
def getHeight(self,root):
#Write your code here
if root:
leftDepth = self.getHeight(root.left)
rightDepth = self.getHeight(root.right)
if leftDepth > rightDepth:
return leftDepth + 1
else:
return rightDepth + 1
else:
return -1
T=int(input())
myTree=Solution()
root=None
for i in range(T):
data=int(input())
root=myTree.insert(root,data)
height=myTree.getHeight(root)
print(height)
|
7ce0712c715ebc1a5eadac7d45520f3bd87bd947 | jalani2727/HackerRank | /Counting_Valleys.py | 770 | 4.1875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countingValleys function below.
# reverse engineer
# Every time you return to sea level (n) after n has decreased, one valley has been travelled through
def countingValleys(n, s):
valley_counter=0
compare_to = n
for letter in s:
if letter == "U":
compare_to += 1
if compare_to == n:
valley_counter +=1
else:
compare_to -= 1
return valley_counter
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
s = input()
result = countingValleys(n, s)
fptr.write(str(result) + '\n')
fptr.close()
|
fae91623b850d6208f9dbe4cfb0b0a67088913c3 | liqinglu/my_python_pattern | /myfactory.py | 346 | 3.59375 | 4 | # -*- coding: utf-8 -*-
class A(object):
def get(self):
print "in A"
class B(object):
def get(self):
print "in B"
def factory(where):
fact = dict(fromA=A,fromB=B)
return fact[where]()
def main():
a,b = factory("fromA"),factory("fromB")
for i in range(4):
if i%2:
a.get()
else:
b.get()
if __name__ == "__main__":
main() |
5b7b5b58d9f4cfc3c04e29db7ed222fd904b35f1 | suruchishrey/Client-Server-Systems | /client.py | 1,783 | 3.515625 | 4 | import socket
import sys
BUFFER_SIZE = 1024
def prompt():
sys.stdout.write("> ")
sys.stdout.flush()
class Client:
def __init__(self):
self.host = sys.argv[1]
self.port = int(sys.argv[2])
self.sock = None
self.connect_to_server()
def connect_to_server(self):
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create and return a new socket object to use IP v4 and TCP.
self.sock.settimeout(2)
# connect to the server
self.sock.connect((self.host, self.port))
except:
print ('Connection Refused! Unable to connect')
sys.exit()
print('Connected to remote host. Start sending arithmetic queries.')
data = self.sock.recv(BUFFER_SIZE)
sys.stdout.write(data.decode()+'\n')
prompt()
self.wait_for_messages()
def wait_for_messages(self):
try:
while True:
# user entered a message
msg = sys.stdin.readline()
self.sock.send(msg.encode())
prompt()
# incoming message from remote server
data = self.sock.recv(BUFFER_SIZE)
if not data:
print ('\nDisconnected from server')
sys.exit()
else:
# print data
sys.stdout.write('Server replied: '+data.decode()+'\n')
prompt()
except socket.error:
print('\nDisconnected from server')
if __name__ == '__main__':
if len(sys.argv)<3:
print('Enter %s [hostname] [portnumber]'%sys.argv[0])
sys.exit(1)
client = Client() |
621414d67c36c071b343e8979240cf5f051107a9 | Anaisdg/python-challenge | /PyPoll/main.py | 1,151 | 3.546875 | 4 |
# coding: utf-8
# In[69]:
import os
import csv
# In[70]:
file_to_open = "election_data_2 copy.csv"
with open(file_to_open, 'r') as election_data:
reader = csv.DictReader(election_data)
contents= set()
[contents.add(x["Candidate"]) for x in reader]
list_contents = list(contents)
#votes = []
#[votes.append(y["Candidate"]) for y in reader]
#total_votes = len(votes)
#print(votes)
with open(file_to_open, 'r') as election_data:
content = election_data.read()
ind_votes = []
total_votes=0
for i in range(0, len(list_contents)):
count = content.count(list_contents[i])
total_votes = total_votes + count
ind_votes.append(count)
percent_votes=[]
for x in range(0, len(ind_votes)):
percent = round((ind_votes[x]/total_votes)*100)
percent_votes.append(percent)
print(f' The Winner Is: {list_contents[0]}')
print(f' The Candidates Are: {list_contents}')
print(f' Respective Percent Won: {percent_votes}')
print(f' Respective Votes Per Candidate: {ind_votes}')
|
da8a8d569e99d24ac98074dc6a49855586957c68 | labeee/cdd-calculator | /CDD.py | 2,249 | 3.59375 | 4 | '''
Calculates CDD or CDH for different temperature thresholds defined
'''
import glob
import pandas
# Creates a list with the degrees chosen to be the threshold.
# If it's not needed to pick one by one, you can create a list called "THRESHOLDS"
# with whatever values you want.
MIN_THRESHOLD = 15
MAX_THRESHOLD = 22
THRESHOLDS = list(range(MIN_THRESHOLD, MAX_THRESHOLD+1))
# Allows to switch to CDH (Cooling Degree Hours)
CDH = True
if CDH:
cdh = 1
else:
cdh = 24
# Lists weather files in folder
FILES = glob.glob('*.epw')
#print(FILES)
def cdd_add(threshold, t):
# Calculates how much temperature is above threshold
if t > threshold:
cdd = t - threshold
else:
cdd = 0
return(cdd)
# Creates a dictionary to organize the values
DATA = {'FILE_NAME': []}
# Creates a CDD for each threshold defined by the THRESHOLD list
for threshold in THRESHOLDS:
DATA['CDD'+str(threshold)+'_DRY'] = []
DATA['CDD'+str(threshold)+'_WET'] = []
# Reads each .epw file listed in the folder
for file in FILES:
# Creates a list where each value on the list will be the CDD for each threshold
cdd_dry = [0] * (len(THRESHOLDS))
cdd_wet = [0] * (len(THRESHOLDS))
# Opens each file
with open(file, encoding = 'latin-1') as file_reader:
# Condition created so it doesn't take values from the header
start_sum = False
# Reads each line of the .epw file
for line in file_reader:
# Checks if it's over reading the header
if start_sum:
# Splits lines by comma
line = line.split(',')
# adds how much line's temperature is above threshold and adds it to the sum
for i in range(len(THRESHOLDS)):
cdd_dry[i] += cdd_add(THRESHOLDS[i], float(line[6]))
cdd_wet[i] += cdd_add(THRESHOLDS[i], float(line[7]))
# Checks if it's the last line of the header
if 'DATA PERIODS' in line:
start_sum = True
# Adds the filename and the CDDs to the dictionary
DATA['FILE_NAME'].append(file)
for i in range(len(THRESHOLDS)):
DATA['CDD'+str(THRESHOLDS[i])+'_DRY'].append(cdd_dry[i]/cdh)
DATA['CDD'+str(THRESHOLDS[i])+'_WET'].append(cdd_wet[i]/cdh)
# Turns de DATA as a pandas' Data Frame
output = pandas.DataFrame(DATA)
# Save pandas' Data Frame to a .csv file
output.to_csv("CDD.csv", index=False)
|
11baed41c81dafe19b3380c39a8d9adb442bf8ac | fanpl-sourse/mytestenv | /UIautoPlatform/test_case/test_wrapper.py | 813 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/8/3 17:35
# @Author : 饭盆里
# @File : test_wrapper.py
# @Software: PyCharm
# @desc : 装饰器
def wrapper(func):
print('hi')
func()
print('bye')
def wrapper1(func):
#允许所有类型的入参
def hello(*args,**kwargs):
print(args)
func()
print(kwargs)
return hello
@wrapper1
def temp1():
print("temp1")
def temp2():
print("temp2")
def tmp():
print('tmp')
def test():
#直接调用函数
# tmp()
#想要给函数前后增加内容时,可以用一个函数封装另一个函数,实现集中调用
# wrapper(tmp)
# wrapper(temp1)
#入参:函数名,返回:函数名
# wrapper1(tmp)(1,2,a=3)
#上述写法 加装饰器可简写为:
temp1(1,2,a=3)
|
85a46d9a4b047e7fbb62f20cc5aefe1692627a86 | yuwenfu/python-pratice | /table_cases.py | 710 | 4.0625 | 4 | #P33 3-1
name = ['python','linux','arm','avr','stm32']
print(name[0].title())
print(name[1].upper())
print(name[2].lower())
print(name[3])
print(name[4])
#P33 3-2
message = "My best friend is "+name[0].title()+'.'
print(message)
message = "My best friend is "+name[1].title()+'.'
print(message)
message = "My best friend is "+name[2].title()+'.'
print(message)
message = "My best friend is "+name[3].title()+'.'
print(message)
message = "My best friend is "+name[4].title()+'.'
print(message)
#P33 3-3
transportations = ['car','truck','bus','train','plane','bicycle','motorbike']
for transportation in transportations:
message = "I would like to own a "+transportation
print(message)
print("all over")
|
770ff29a7d5a80c9dcb269a6a6978189ce367aa9 | BCombs/python-projects | /crack.py | 3,137 | 4.03125 | 4 | import cs50
import sys
import crypt
def main():
#make sure there are 2 arguments at command line
if len(sys.argv) != 2:
print("Usage: python filename key")
exit(1)
#Get the hash entered at command line and the salt from userHash
userHash = sys.argv[1]
salt = userHash[0:3]
password = crack(userHash, salt)
print(password)
exit(0)
def crack(userHash, salt):
#Stores the hash generated by the crypt function
gHash = ""
#String we will iterate through
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
length = len(alphabet)
#The attempt we are hashing
attempt = ["a"]
#Check for a one char password
for i in range(length):
#Set the first char
attempt[0] = alphabet[i]
#Crypt attempt and see if it matches
sAttempt = ''.join(attempt)
gHash = crypt.crypt(sAttempt, salt)
if gHash == userHash:
return sAttempt
#Grow the list to two and continue
attempt.append("a")
#Check for two char passwords
for i in range(length):
#Set first char
attempt[0] = alphabet[i]
for j in range(length):
#Set second char
attempt[1] = alphabet[j]
#Crypt attempt and see if it matches
sAttempt = ''.join(attempt)
gHash = crypt.crypt(sAttempt, salt)
if gHash == userHash:
return sAttempt
#Grow the list to three and continue
attempt.append("a")
#check for three char passwords
for i in range(length):
#Set first char
attempt[0] = alphabet[i]
for j in range(length):
#Set second char
attempt[1] = alphabet[j]
for k in range(length):
#Set third char
attempt[2] = alphabet[k]
#Crypt attempt and see if it matches
sAttempt = ''.join(attempt)
gHash = crypt.crypt(sAttempt, salt)
if gHash == userHash:
return sAttempt
#Grow the list to four and continue
attempt.append("a")
#check for four char passwords
for i in range(length):
#Set first char
attempt[0] = alphabet[i]
for j in range(length):
#Set second char
attempt[1] = alphabet[j]
for k in range(length):
#Set third char
attempt[2] = alphabet[k]
for l in range(length):
#Set fourth char
attempt[3] = alphabet[l]
#Crypt attempt and see if it matches
sAttempt = ''.join(attempt)
gHash = crypt.crypt(sAttempt, salt)
if gHash == userHash:
return sAttempt
#The password was not found
return "Password not cracked."
if __name__ == "__main__":
main() |
6a6f40a8b8dddb89b04b2a0b9f6859f56d5dee9c | DesignCell/Euler | /P007.py | 645 | 3.796875 | 4 | # Problem 7
# 10,001st Prime
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
# we can see that the 6th prime is 13.
# What is the 10 001st prime number?
from time import time
from math import sqrt
start = time()
def prime(cnt2):
for cntp in range(2, (int(sqrt(cnt2)+1))):
if cnt2 % cntp == 0:
return False
def search():
top=10001 #Search for Nth Prime
cnt =3
pnum =1
while pnum <top:
if prime(cnt)!=False:
pnum+=1
if pnum == top:
print (str(pnum),' ',str(cnt))
cnt+=2
search()
print('Finished: Time ', ((time()-start)*1000),'ms')
# 10,001st Prime = 104743
# Solve time 782.33ms 04/17/18 |
d4fa68dc7565ac9b4412f36d2e35831e8643c8c7 | DesignCell/Euler | /P050.py | 1,919 | 3.59375 | 4 | # Problem 050
# Consecutive Prime Sum
# The prime 41, can be written as the sum of six consecutive primes:
# 41 = 2 + 3 + 5 + 7 + 11 + 13
# This is the longest sum of consecutive primes that adds to a prime below one-hundred.
# The longest sum of consecutive primes below one-thousand that adds to a prime,
# contains 21 terms, and is equal to 953.
# Which prime, below one-million, can be written as the sum of the most consecutive primes?
from time import time
stime = time()
import Functions # pylint: disable=import-error
def search_sum(lim):
prime_list_sum = primes_sieve_sum(lim)
prime_list = Functions.primes_sieve(lim)
con_max = 0
con_max_cnt = 0
for cnt1 in range(0,len(prime_list_sum)):
con_sum = prime_list_sum[cnt1]
con_cnt = 1
for cnt2 in range(cnt1+1,len(prime_list_sum)):
con_sum += prime_list_sum[cnt2]
con_cnt += 1
if con_cnt > con_max_cnt: #ingnor if not higher
if con_sum in prime_list: #if higher consecutive then start checking for prime
con_max_cnt = con_cnt
con_max = con_sum
print(con_max) #print Answer
def primes_sieve_sum(limit):
#Returns list of primes up to including argument
limitn = limit+1
primes = dict()
for i in range(2, limitn): primes[i] = True
for i in primes:
factors = range(i,limitn, i)
for f in factors[1:]:
primes[f] = False
#Consecutive Sum Limit
con_sum = 0
for seq in primes:
if con_sum < limit+1 and primes[seq] == True:
con_sum += seq
sum_limit = seq
elif con_sum > limit: break
return [i for i in primes if primes[i]==True and i < sum_limit]
search_sum(1000000)
print('Solve Time: ', round(((time() - stime) * 1000), 2), 'ms')
# Solution : 997651
# Solve time: 8566.54ms 11/30/18
|
da5488b7a450d4bb23d5967b82bbf9299d56444f | DesignCell/Euler | /P043.py | 1,532 | 3.671875 | 4 | # Problem 043
# Sub-String Divisibility
# The number, 1406357289, is a 0 to 9 pandigital number because it is made up
# of each of the digits 0 to 9 in some order, but it also has a rather interesting
# sub-string divisibility property.
# Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following:
# d2d3d4=406 is divisible by 2
# d3d4d5=063 is divisible by 3
# d4d5d6=635 is divisible by 5
# d5d6d7=357 is divisible by 7
# d6d7d8=572 is divisible by 11
# d7d8d9=728 is divisible by 13
# d8d9d10=289 is divisible by 17
# Find the sum of all 0 to 9 pandigital numbers with this property.
from time import time
stime = time()
#import Functions # pylint: disable=import-error
import itertools
set_perm = set()
def perm_funct():
pandigital = []
for cnt in range(0,10):
pandigital.append(cnt)
permutations = set()
permutations = itertools.permutations(pandigital,10)
for seq in permutations:
if seq[0] == '0': continue
seq_temp = int("".join(map(str,seq)))
if digit_div(seq_temp) == True: set_perm.add(seq_temp)
def digit_div(num):
div = [2,3,5,7,11,13,17] # Divisible sequence
for cnt in range(1,8): # 1-7 digit sequence
if int(str(num)[cnt:cnt+3:]) % div[cnt-1] != 0: return False
return True
perm_funct()
sum_num = 0
for seq in set_perm:
sum_num += seq
print(sum_num)
print('Solve Time: ', round(((time() - stime) * 1000), 2), 'ms')
# Solution : 16695334890
# Solve time: 17120.59ms 09-21-18
|
9a522eca985244fb52ecdbc9b295764f8e2bacac | DesignCell/Euler | /P001.py | 706 | 4.0625 | 4 | # Problem 1
# Multiples of 3 and 5
# If we list all the natural numbers below 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
from time import time
start = time()
# sumnum=0
# for num in range(1,1000):
# if num%3==0 or num%5==0: sumnum+=num
# print ('Sum of all the multiples of 3 or 5 below 1000 = '+str(sumnum))
# Sum of all the multiples of 3 or 5 below 1000 = 233168
# Solve Time: 0.494ms
def search(lim):
sumnum=0
for num in range(1,lim):
if num%3==0 or num%5==0: sumnum+=num
return str(sumnum)
print(search(1000))
print('Finished: Time ', ((time()-start)*1000),'ms') |
0feeb803fd420ce45b3afc5a986733d27123b364 | DesignCell/Euler | /P019.py | 997 | 3.90625 | 4 | from time import time
stime = time()
import datetime
# Problem 19
# Counting Sundays
# You are given the following information, but you may prefer to do some research for yourself.
# 1 Jan 1900 was a Monday.
# Thirty days has September,
# April, June and November.
# All the rest have thirty-one,
# Saving February alone,
# Which has twenty-eight, rain or shine.
# And on leap years, twenty-nine.
# A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
# How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
start_date = datetime.date(1901,1,6)
end_date = datetime.date(2000,12,31)
sum_sun = 0
for year in range (start_date.year,end_date.year+1):
for month in range(1,13):
if datetime.date(year,month,1).weekday() == 6:
sum_sun += 1
print(sum_sun)
print('Solve Time: ', round(((time() - stime) * 1000), 2), 'ms')
# Solution : 171
# Solve time: 4.36ms 05-14-18 |
ae6c90d344ea05a85e0e03e67ea5ea2df54e47ae | DesignCell/Euler | /P062.py | 1,773 | 3.765625 | 4 | # Problem 062
# Cubic Permutations
# The cube, 41063625 (345**3), can be permuted to produce two other cubes:
# 56623104 (384**3) and 66430125 (405**3). In fact, 41063625 is the smallest cube
# which has exactly three permutations of its digits which are also cube.
# Find the smallest cube for which exactly five permutations of its digits are cube.
from time import time
stime = time()
#import Functions # pylint: disable=import-error
def cube(lim_min,lim_max):
#compile cube list within range limits
num_list = []
for num in range(lim_min,lim_max):
num_list.append(num**3)
#Test list for permutations
for seq in num_list:
perm_cnt = 0
for sub_seq in num_list:
if sub_seq <= seq: continue #Limit sequnce to greater numbers in list
if arePermutation(seq,sub_seq) == True:
perm_cnt += 1
#print(perm_cnt,seq,sub_seq)
if perm_cnt == 4: return seq
return False
#Permutation Test, assumes same length, returns true/false
def arePermutation(num1,num2):
str1 = sorted(str(num1))
str2 = sorted(str(num2))
for cnt in range(len(str1)):
if str1[cnt] != str2[cnt]: return False
return True
print(cube(4642,10000)) # Examples 345, 384, 405
print('Solve Time: ', round(((time() - stime) * 1000), 2), 'ms')
# Solution : 127035954683
# Solve time: 3349.42ms 2019.09.14
"""
Solution:
127035954683
352045367981
373559126408
569310543872
589323567104
Num ** 3 = Digit Length
Search Reanges
01 1
02 3
03 5
04 10
05 22
06 47
07 100
08 216
09 465
10 1000
11 2155
12 4642
13 10000
14 21545
15 46416
16 100000
17 215444
18 464159
19 1000000
20 2154435
21 4641589
22 10000000
23 21544347
24 46415889
25 100000000
Solve Time: 51204.87 ms
""" |
cb7f42bde72c51f3c08da9e9cc528c3ab424ffe0 | SyntaxStacks/Dev-test-project | /1-finding-the-source/locations.py | 581 | 3.859375 | 4 | class Locations():
def __init__(self):
self.locations = []
def addLocation(self, location):
if location not in self.locations:
self.locations.append(location)
def cleanUpLocations(self):
pass
#TODO: remove all but the single point that all circles go through
def __repl__(self):
print("made it to printLocations")
if not self.locations:
print("Unable to determine location from current measurement data. Try adding more measurements!")
print("{} {}",format(location.x, location.y)) |
daea4f195777b8a1c925a68a2d5a3e58172a8e1a | zdravkob98/Python-Advanced-September-2020 | /Functions Advanced - Exercise/03. Min Max and Sum.py | 386 | 3.734375 | 4 | def min_res(*args):
min_result = min(*args)
return min_result
def max_res(*args):
max_result = max(*args)
return max_result
def sum_res(*args):
sum_result = sum(*args)
return sum_result
n = [int(x) for x in input().split()]
print(f'The minimum number is {min_res(n)}')
print(f'The maximum number is {max_res(n)}')
print(f'The sum number is: {sum_res(n)}') |
796cc3ea8feadf2156d6734bdbf62f83015ab51d | zdravkob98/Python-Advanced-September-2020 | /Multidimensional Lists - Exercise/01. Diagonal Difference.py | 409 | 3.6875 | 4 | rows = int(input())
matrix = [[int(x) for x in input().split()] for _ in range(rows)]
first_diagonal = 0
second_diagonal = 0
for i in range(rows):
first_diagonal += matrix[i][i]
second_diagonal += matrix[i][-i - 1]
# for i in range(rows):
# first_diagonal += matrix[i][i]
# for i in range(rows, 0, -1):
# second_diagonal += matrix[i - 1][-i]
print(abs(first_diagonal - second_diagonal)) |
4abdbbab21357a288a4cd7f92d09393e9b15f08e | zdravkob98/Python-Advanced-September-2020 | /Functions Advanced - Exercise/04. Negative vs Positive.py | 421 | 4.21875 | 4 | def find_biggest(numbers):
positive = sum(filter(lambda x: x >= 0, numbers))
negative = sum(filter(lambda x: x <= 0, numbers))
print(negative)
print(positive)
if abs(positive) > abs(negative):
print("The positives are stronger than the negatives")
else:
print("The negatives are stronger than the positives")
numbers = [int(x) for x in input().split()]
find_biggest(numbers) |
3b4ade606a2d8794bab84fa6ff1a364488ee15e7 | zdravkob98/Python-Advanced-September-2020 | /comprehensions - exercises/01. Word Filter.py | 102 | 3.671875 | 4 | text = input().split()
result = [word for word in text if len(word) % 2 == 0]
print('\n'.join(result)) |
a971623c1136cdad93427ede0855662339fe0e56 | zdravkob98/Python-Advanced-September-2020 | /Tuples and Sets - Exercise/05. Phonebook.py | 500 | 3.890625 | 4 | from _collections import defaultdict
phonebook = defaultdict(str)
search = input()
while True:
if search.isdigit():
break
else:
token = search.split('-')
name = token[0]
number = token[1]
phonebook[name] = number
search = input()
n = int(search)
for _ in range(n):
phone_name = input()
if phone_name in phonebook:
print(f'{phone_name} -> {phonebook[phone_name]}')
else:
print(f"Contact {phone_name} does not exist.") |
d8915245d0075e79e67d20e476a098d827f8dc96 | zdravkob98/Python-Advanced-September-2020 | /Multidimensional Lists - Exercise/04. Matrix Shuffling.py | 760 | 3.6875 | 4 | rows, cols = [int(x) for x in input().split()]
matrix = [input().split() for i in range(rows)]
command = input()
while command != 'END':
token = command.split()
if len(token) == 5:
swap = token[0]
row1 = int(token[1])
col1 = int(token[2])
row2 = int(token[3])
col2 = int(token[4])
if swap == 'swap' and row1 <= rows and col1 <= cols and row2 <= rows and col2 <= cols:
element = matrix[row1][col1]
matrix[row1][col1] = matrix[row2][col2]
matrix[row2][col2] = element
for i in range(len(matrix)):
print(' '.join(matrix[i]))
else:
print("Invalid input!")
else:
print("Invalid input!")
command = input()
|
bfb2e47d54a5fc7dbbbff14894db301a57113a19 | zdravkob98/Python-Advanced-September-2020 | /Multidimensional Lists - Exercise/02. 2x2 Squares in Matrix.py | 318 | 3.609375 | 4 | rows, cols = [int(x) for x in input().split()]
matrix = [input().split() for i in range(rows)]
count = 0
for i in range(rows - 1):
for j in range(cols - 1):
if matrix[i][j] == matrix[i+ 1][j] and matrix[i][j] == matrix[i][j+1] and matrix[i][j] == matrix[i + 1][j + 1]:
count += 1
print(count) |
d5b40e563b08098cdf293765d8db62ee2a210bee | zdravkob98/Python-Advanced-September-2020 | /Lists as Stacks and Queues - Exercise/06. Balanced Parentheses.py | 408 | 3.9375 | 4 | text = input()
par = []
parentheses = {'(': ')', '{': '}', '[': ']'}
status = True
for i in text:
if i in parentheses:
par.append(i)
else:
if len(par) == 0:
status = False
break
paren = par.pop()
if parentheses[paren] != i:
status = False
break
if status is True and len(par) == 0:
print('YES')
else:
print('NO') |
67d5c2ebec2c72df9fcb33435c0347607b645863 | DT9/programming-problems | /job/dtruong/spiral.py | 1,198 | 3.625 | 4 | def createSpiral(N):
spiral = [[0 for i in range(N)] for j in range(N)]
top = left = 0
bottom = right = N - 1
RIGHT, DOWN, LEFT, UP = 0, 1, 2, 3
direction = RIGHT
count = 1
while top <= bottom and left <= right:
if direction == RIGHT:
for i in range(left,right+1):
spiral[top][i] = count
count += 1
top += 1
elif direction == DOWN:
for i in range(top,bottom+1):
spiral[i][right] = count
count += 1
right -= 1
elif direction == LEFT:
for i in range(right,left-1,-1):
spiral[bottom][i] = count
count += 1
bottom -= 1
elif direction == UP:
for i in range(bottom,top-1,-1):
spiral[i][left] = count
count += 1
left += 1
direction = (direction + 1) % 4
return spiral
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("height", type=int)
args = parser.parse_args()
height = args.height
for row in createSpiral(height):
print(row)
|
808bb7a2aa620a8d4e966978a141103163838bca | sanjaybabu2210/mycaptain | /checkpos.py | 201 | 3.796875 | 4 | def pos_find(num):
lis = []
for x in num:
if x<0:
continue
else:
lis.append(x)
return lis
num = eval(input('enter the list'))
print(pos_find(num))
|
9f4b64cbf1ce55b9e0536454f048e8f6476bf67d | wilsonsamarques/OpenCV | /Intro_and_Images.py | 650 | 3.875 | 4 | # Contents Covered:
# Installation and Setup
# Loading an image
# Displaying an image
# Resizing an image
# Rotating an image
import cv2
img = cv2.imread('resources/lena.png', 1)
# img = cv2.resize(img, (0,0), fx=0.5, fy=0.5)
# img = cv2.rotate(img, cv2.cv2.ROTATE_90_COUNTERCLOCKWISE)
# cv2.imwrite('new_lena.jpg', img)
# -1, cv2.IMREAD_COLOR : Loads a color image. Any transparency of image will be neglected. It is the default flag.
# 0, cv2.IMREAD_GRAYSCALE : Loads image in grayscale mode
# 1, cv2.IMREAD_UNCHANGE : Loads image as such including alpha channel
#BGR
cv2.imshow('Image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
b4223446ccb2dc8d7e248ca50b84b44a60d802e7 | knshkp/hacktoberfest2021 | /Python/heapsort.py | 485 | 3.71875 | 4 | def heap(arr, n, i):
a = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
a = l
if r < n and arr[a] < arr[r]:
a = r
if a != i:
arr[i],arr[a] = arr[a],arr[i]
heap(arr, n, a)
def hS(arr):
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
heap(arr, n, i)
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heap(arr, i, 0)
arr = [ 12, 1, 33, 25, 63, 17]
hS(arr)
n = len(arr)
print ("Sorted array =")
for i in range(n):
print ("%d" %arr[i])
|
01165803a5ece1682e91f49d604a47f39bdba27a | jerryeml/Python_Class | /Class_List01.py | 769 | 4.125 | 4 | a_tuple = (12,3,5,15,6)
b_tuple = 2,4,6,7,8
a_list =[12,3,67,7,82]
a_list.append(0) #添加
a_list.insert(2,11) #添加在指定位置
a_list.remove(12) #只會刪除碰到第一個12
for i in range(len(a_list)): #依照list長度分別輸出第幾個元素的value
print(i,a_list[i])
print('Last element:',a_list[-1])#從最後一個開始數
#print(a_list)
print('first to three element:',a_list[0:3])
print('After No.3 element:',a_list[3:])
print('Before No.3 element:',a_list[:3])
print('back:',a_list[0:-2])
print('Find index 67:',a_list.index(67)) #找67的索引
print('Count numbers:',a_list.count(0)) #計算個數
print('reverse:',a_list[::-1])
print('normal:',a_list[::1])
#排序
a_list.sort()
print(a_list)
a_list.sort(reverse = True)
print(a_list)
|
5f60295d61b3be636d5015b934c3a79ded323c92 | bsherrill480/catch_phrase | /anny2/circle_graph.py | 5,062 | 4.1875 | 4 | class Node:
"""
its a node
"""
def __init__(self, data=None, name=None):
self.next = next
self.data = data
self.name = name
class Organizer:
"""
class to interact with data.
Uses nodes
"""
def __init__(self):
self.nodes = dict()
def make_and_give_node(self, data, name):
"""
makes a node with passed name and data
"""
node = Node(data, name)
self.nodes[name] = node
return node
# def set_next(self, name, next_item_name):
# """
#
# """
# self.nodes[name].next = self.nodes[next_item_name]
def set_next(self, name1, name2):
"""
makes name1's node's next name2's node.
"""
node1 = self.nodes[name1]
node2 = self.nodes[name2]
node1.next = node2
def delete_node(self, name):
"""
deletes a node from circle
"""
del self.nodes[name]
def is_perfect_circle(self):
"""
returns true if is perfect circle, else false.
"""
in_circle_set = set()
start_node = self.nodes.itervalues().next()
in_circle_set.add(start_node)
examine_node = start_node.next
while examine_node is not start_node:
if (examine_node in in_circle_set) or (examine_node is None):
return False
in_circle_set.add(examine_node)
examine_node = examine_node.next
return len(self.nodes) == len(in_circle_set)
def client_id_lists(self):
"""
returns list of (list of client_id's showing cycles). See visual_nodes()
understanding list format.
"""
# master_list = []
# list_of_cycles = self.visual_nodes()
# for cycle in list_of_cycles:
# one_cycle = []
# for node in cycle:
# one_cycle.append(node.client_id)
# master_list.append(one_cycle)
#
# return master_list
return [[node.data.client_id for node in cycle]for cycle in self.visual_nodes()]
def visual_strings(self):
"""
returns list of strings which contain nicknames showing cycles.
e.g. "a,b,c,d,a"
See visual_nodes() understanding list format.
"""
master_list = []
list_of_cycles = self.visual_nodes()
for cycle in list_of_cycles:
one_cycle = ""
for node in cycle:
one_cycle = one_cycle + node.data.nickname + " "
master_list.append(one_cycle)
return master_list
def visual_nodes(self):
"""
returns list of (lists where the leading node points is pointing at
the next node). e.g.
a ->b
b ->c
c ->d
d ->a
the list would look like [[a,b,c,d,a]]
but if
a ->b
b ->c
c ->d
d ->c
you would get something like [[a,b,c,d,c]] or [[d,c,d], [a,b,c,d,c]].
algorithm used:
make master_list. call step1 (below) with set of all nodes.
step1) pick random node in set of nodes, add it to list called node_seq.
keep going until we either none or the start node. add node_seq to master list.
step2)If there are any leftover nodes, do step1 again remaining nodes.
"""
master_list = []
self._visual_helper(master_list, set(self.nodes.values()))
return master_list
def _visual_helper(self, master_list, unused_nodes):
"""
helper method for visual_nodes()
"""
if unused_nodes: #if not empty
node_seq = []
used_nodes = set()
start_node = unused_nodes.__iter__().next()
used_nodes.add(start_node)
node_seq.append(start_node)
examine_node = start_node.next
while True:
if examine_node in used_nodes:
node_seq.append(examine_node)
break
if examine_node is None:
break
used_nodes.add(examine_node)
node_seq.append(examine_node)
examine_node = examine_node.next
master_list.append(node_seq)
unused_nodes = unused_nodes.difference(used_nodes)
self._visual_helper(master_list, unused_nodes)
if __name__ == '__main__':
#for debugging
node1 = Node(None, "1")
node2 = Node(None, "2")
node3 = Node(None, "3")
node4 = Node(None, "4")
organizer = Organizer()
l = [node1, node2, node3, node4]
for i in range(len(l)):
if i == len(l) - 1:
j = 0
else:
j = i + 1
node = l[i]
node.next = l[j]
#printing to see
for node in l:
print node.next.name
node4.next = node3
for node in l:
organizer.nodes[node.name] = node
print organizer.is_perfect_circle()
vis = organizer.visual_nodes()
for loop in vis:
print [x.name for x in loop] |
0de01265da280f211a9dfca29b13bc8427e746a5 | deeppavlov/learning-to-learn | /learning_to_learn/controller.py | 13,969 | 3.890625 | 4 | import copy
from learning_to_learn.useful_functions import construct, get_elem_from_nested
class Controller(object):
"""Controller is a class which instances are used for computing changing learning parameters. For example
learning rate. It is also responsible for training stopping
Usage:
1. Construct controller by passing him 'storage' (a dictionary with monitored parameters, usually if used in
_train method of Environment class 'storage' is self._storage) and specifications. Specifications is
a dictionary with necessary parameters for computing the controlled value
2. Use 'get' method to get current value
3. If you wish to use Controller instance with new specifications you should:
- add new private method to Controller which will be responsible for processing new specifications. It
should take no arguments and return monitored value.
- add elif entry in __init__ method for assigning 'get' with newly created method
- if new approach requires parameters not provided in self._storage than add them. Also don't forget
to pass this parameters to _update_storage method in the bottom of _train"""
@staticmethod
def create_change_tracking_specifications(specifications):
if isinstance(specifications, list):
old_specs = construct(specifications)
if isinstance(specifications, dict):
old_specs = [dict(specifications)]
new_specs = dict()
new_specs['old_specs'] = old_specs
new_specs['type'] = 'changes_detector'
return new_specs
@staticmethod
def spec_value_map():
return dict(
exponential_decay='init',
fixed='value',
linear='start',
adaptive_change='init',
)
def __init__(self, storage, specifications):
# print("(Controller.__init__)specifications:", specifications)
self._storage = storage
if 'changing_parameter_controller' in specifications:
changing_parameter_controller = specifications['changing_parameter_controller']
self._specifications = copy.deepcopy(specifications)
if 'changing_parameter_controller' in specifications:
self._specifications['changing_parameter_controller'] = changing_parameter_controller
if self._specifications['type'] == 'limit_steps':
self.get = self._limit_steps
elif self._specifications['type'] == 'exponential_decay':
self.get = self._exponential_decay
elif self._specifications['type'] == 'fixed':
self.get = self._fixed
elif self._specifications['type'] == 'periodic_truth':
self.get = self._periodic_truth
elif self._specifications['type'] == 'true_on_steps':
self.get = self._true_on_steps
elif self._specifications['type'] == 'always_false':
self.get = self._always_false
elif self._specifications['type'] == 'changes_detector':
self._value_controllers = list()
self._last_values = list()
for value_specs in self._specifications['old_specs']:
self._value_controllers.append(Controller(self._storage, value_specs))
self._last_values.append(self._value_controllers[-1].get())
self.get = self._changes_detector
elif self._specifications['type'] == 'linear':
self.get = self._linear
elif self._specifications['type'] == 'adaptive_change':
self.get = self._adaptive_change
self._specifications = dict(self._specifications)
self._specifications['impatience'] = 0
self._specifications['value'] = self._specifications['init']
self._specifications['line_len_after_prev_get_call'] = -1
self._init_ops_for_adaptive_controller()
elif self._specifications['type'] == 'fire_at_best':
self.get = self._fire_at_best
self._init_ops_for_adaptive_controller()
elif self._specifications['type'] == 'while_progress':
self.get = self._while_progress
self._specifications = dict(self._specifications)
self._specifications['impatience'] = 0
self._specifications['cur_made_prog'] = False
self._specifications['prev_made_prog'] = True
self._init_ops_for_adaptive_controller()
self._specifications['current_value'] = self._specifications['changing_parameter_controller'].get()
elif self._specifications['type'] == 'while_progress_no_changing_parameter':
self.get = self._while_progress_no_changing_parameter
self._specifications = dict(self._specifications)
self._specifications['impatience'] = 0
self._init_ops_for_adaptive_controller()
elif self._specifications['type'] == 'logarithmic_truth':
self.get = self._logarithmic_truth
else:
raise ValueError(
"Not supported controller type {}".format(repr(self._specifications['type']))
)
def _init_ops_for_adaptive_controller(self):
if 'direction' not in self._specifications:
self._specifications['direction'] = 'down'
# if self._specifications['direction'] == 'down':
# self._specifications['comp_func'] = self._comp_func_gen(min)
# else:
# self._specifications['comp_func'] = self._comp_func_gen(max)
# print(self._storage)
if 'best' not in self._specifications:
if self._specifications['direction'] == 'down':
self._specifications['best'] = float('+inf')
else:
self._specifications['best'] = float('-inf')
self._specifications['line'] = get_elem_from_nested(
self._storage,
self._specifications['path_to_target_metric_storage']
)
# Length of list of target values when get() was called last time.
# It is used to make controller do not change the value if no measurements were made.
# For instance 'should_continue' and 'learning_rate' are called frequently whereas
# validations are rare. Changes in length of list with target values are used
# for detecting of new measurement and making a decision to increase impatience.
self._specifications['line_len_after_prev_get_call'] = -1
def _is_improved(self):
# print("(controller.Controller._is_improved)self._specifications:", self._specifications)
if self._specifications['direction'] is 'down':
return min(self._specifications['line'], default=float('+inf')) < self._specifications['best']
return max(self._specifications['line'], default=float('-inf')) > self._specifications['best']
def _update_best(self):
if self._specifications['direction'] is 'down':
self._specifications['best'] = min(self._specifications['line'], default=float('+inf'))
else:
self._specifications['best'] = max(self._specifications['line'], default=float('-inf'))
def get_best_target_metric_value(self):
return self._specifications.get('best', None)
def get_target_metric_storage_path(self):
return self._specifications.get('path_to_target_metric_storage', None)
@staticmethod
def _comp_func_gen(comp):
def f(line):
if len(line) == 0:
return True
elif len(line) == 1:
return comp(line) == line[-1]
else:
return comp(line) == line[-1] and comp(line[:-1]) != line[-1]
return f
def _changes_detector(self):
something_changed = False
for idx, (last_value, controller) in enumerate(zip(self._last_values, self._value_controllers)):
if last_value != controller.get():
something_changed = something_changed or True
self._last_values[idx] = controller.get()
return something_changed
def _exponential_decay(self):
num_stairs = self._storage['step'] // self._specifications['period']
returned_value = self._specifications['init']
return returned_value * self._specifications['decay'] ** num_stairs
def _linear(self):
start = self._specifications['start']
end = self._specifications['end']
step_interval = self._specifications['interval']
step = self._storage['step']
if step < step_interval:
return start + (end - start) * step / step_interval
else:
return end
def _limit_steps(self):
if self._storage['step'] >= self._specifications['limit']:
return False
else:
return True
def _fixed(self):
return self._specifications['value']
def _periodic_truth(self):
if self._storage['step'] % self._specifications['period'] == 0:
return True
else:
return False
@staticmethod
def _next_in_log_truth(start, factor):
new_value = int(round(start * factor))
if new_value <= start:
return start + 1
else:
return new_value
def _logarithmic_truth(self):
while self._storage['step'] > self._specifications['start']:
self._specifications['start'] = self._next_in_log_truth(
self._specifications['start'],
self._specifications['factor']
)
if self._storage['step'] == self._specifications['start'] \
and self._specifications['start'] < self._specifications['end']:
return True
else:
return False
def _true_on_steps(self):
if self._storage['step'] in self._specifications['steps']:
return True
else:
return False
def _adaptive_change(self):
"""Controller value does not change until specs['max_no_progress_points'] + 1
no progress points are collected."""
specs = self._specifications
# if specs['comp_func'](specs['line']):
if self._is_improved():
specs['impatience'] = 0
self._update_best()
return specs['value']
else:
if specs['line_len_after_prev_get_call'] < len(specs['line']):
specs['impatience'] += 1
specs['line_len_after_prev_get_call'] = len(specs['line'])
if specs['impatience'] > specs['max_no_progress_points']:
specs['value'] *= specs['decay']
specs['impatience'] = 0
return specs['value']
def _fire_at_best(self):
specs = self._specifications
# if specs['comp_func'](specs['line']) and specs['line_len_after_prev_get_call'] < len(specs['line']):
if self._is_improved():
# specs['line_len_after_prev_get_call'] = len(specs['line'])
self._update_best()
return True
else:
return False
def _while_progress(self): # for example if learning does not bring improvement return False
"""Returns False if two values of target parameter (learning_rate) did not improve the results
or when previous parameter value did not bring improvement and specs['max_no_progress_points']
points on target metric no progress has been made."""
specs = self._specifications
value = specs['changing_parameter_controller'].get()
if specs['current_value'] == value:
# if specs['comp_func'](specs['line']):
if self._is_improved():
specs['impatience'] = 0
specs['cur_made_prog'] = True
self._update_best()
ret = True
else:
if not specs['prev_made_prog'] \
and specs['impatience'] > specs['max_no_progress_points']:
ret = False
else:
if specs['line_len_after_prev_get_call'] < len(specs['line']):
specs['impatience'] += 1
ret = True
else:
if not specs['cur_made_prog'] and not specs['prev_made_prog']:
return False
else:
specs['prev_made_prog'] = specs['cur_made_prog']
specs['cur_made_prog'] = False
specs['impatience'] = 0
specs['current_value'] = value
ret = True
specs['line_len_after_prev_get_call'] = len(specs['line'])
return ret
def _while_progress_no_changing_parameter(self):
specs = self._specifications
# print("(Controller._while_progress_no_changing_parameter)specs['impatience']:",
# specs['impatience'])
# if specs['comp_func'](specs['line']):
if self._is_improved():
self._update_best()
specs['impatience'] = 0
ret = True
else:
if specs['impatience'] > specs['max_no_progress_points']:
ret = False
else:
if specs['line_len_after_prev_get_call'] < len(specs['line']):
specs['impatience'] += 1
ret = True
specs['line_len_after_prev_get_call'] = len(specs['line'])
return ret
@staticmethod
def _always_false():
return False
@property
def name(self):
return self._specifications['name']
@classmethod
def get_logarithmic_truth_steps(cls, spec):
steps = []
step = spec['start']
while True:
step = cls._next_in_log_truth(
step,
spec['factor']
)
if step > spec['end']:
steps.append(spec['end'])
break
steps.append(step)
return steps
|
56ed53478852a695eaab1d6b41d5c867fa48909e | LoyalSkm/Home_work_2_base | /hw2_task_3.py | 1,866 | 4.25 | 4 | print(''' 3. "Нарисовать" в консоли прямоугольный треугольник из символов "*",
пользователь задаёт высоту и ширину(в количестве элементов).
''')
print('''Задавай какую хочешь высоту, но триугольник будит пропорциональным только если высота<ширины в 2 раза
''')
import numpy #позволит мне сделать список из е целых чисел
while True:
try:
n = int(input("Высота: "))
d = float(input("Ширина: "))
break
except ValueError:
print("Введите Целое число")
s = [n, d]
bl = max(s)/min(s) #коефициент для случая когда высота больше ширины
bh = min(s)/max(s) #когда ширина больше высоты
max = max(s)
if max%2 == 0: #условие для того чтобы сцентрировать триугольник относительно максимального значения
r = int(max)
else:
r = int(max+1)
list_L = [X for X in numpy.arange(1, d+1, bl)] #список для случая высоты больше ширины
list_H = [Y for Y in numpy.arange(1, d+1, bh)] #навпакы)
# print(list_L)
# print(list_H)
if n<=d: #Тут я делаю 1 переменную которая меняется от случая n<d и n>=d
koef = list_L
elif n>d:
koef = list_H
poz = -1 #переменная старта звёздочек
for i in range(1, n+1):
poz += 1
kol = int(round(koef[poz])) #типо позиция в списках list_L или list_LL
print("*" * kol)
|
1e2e21bc8a6f6854b8b4bbb637e7a41af0490221 | viren-nadkarni/codu | /madf/ms.py | 729 | 4.0625 | 4 | #!/bin/python
# Sorting a List using Mergesort in Python
# 2011-05-16
def mergeSort(toSort):
if len(toSort) <= 1: #if single/no element, return
return toSort
mIndex = len(toSort) / 2 #find midpoint
left = mergeSort(toSort[:mIndex]) #split into left
right = mergeSort(toSort[mIndex:]) #and right array
result = []
while len(left) > 0 and len(right) > 0:
if left[0] > right[0]:
result.append(right.pop(0))
else:
result.append(left.pop(0))
if len(left) > 0:
result.extend(mergeSort(left))
else:
result.extend(mergeSort(right))
return result
def main():
l = [187,62,155,343,184,958,365,427,78,121,388]
sortedList = mergeSort(l)
print sortedList
if __name__ == '__main__':
main()
|
416b3647bf749bbb017c22c0bfb33aa43252730f | viren-nadkarni/codu | /dm/4b_covariance.py | 760 | 3.5 | 4 | #!/usr/bin/env python
import math
x = [-3, 6, 0, 3, -6]
y = [ 1, -2, 0, -1, 2]
def mean(x):
m = 0
for i in x:
m += i
return m/float(len(x))
def covar(x, y):
if len(x) != len(y):
raise AssertionError
mx = mean(x)
my = mean(y)
print 'mean(x) =', mx
print 'mean(y) =', my
o = 0
for i in zip(x, y):
o += (i[0] - mx) * (i[1] - my)
return o / (float(len(x)) - 1)
def std_dev(x):
mx = mean(x)
o = 0
for i in x:
o += (i - mx) ** 2
return math.sqrt(o / (float(len(x)) - 1))
def main():
cv = covar(x, y)
print 'covariance(x, y) =', cv
print 'correlation(x, y) =', cv / (std_dev(x) * std_dev(y))
if __name__ == '__main__':
main()
|
fd9cb978295bc517b3bcd61dcc50b19210879064 | NhanNgocThien/IlearnPython | /counter_gui.py | 3,859 | 3.75 | 4 | # Date created: 27/01/2019
# A simple GUI counter provides two mode: count up, count down. It also has stop, and reset button
# Import modules
try:
from tkinter import *
except:
from Tkinter import *
# Constants
SCREEN_W = 350
SCREEN_H = 200
BUTTON_W = 10
BUTTON_H = 1
S_START = 1
S_STOP = 2
S_RESET = 3
S_UP = 4
S_DOWN = 5
M_UP = True
M_DOWN = False
# Counter class
class Counter():
def __init__(self):
# Create main window
self.root = Tk()
self.root.geometry(str(SCREEN_W) + 'x' + str(SCREEN_H))
#self.root.resizable(False, False)
self.root.title('Counter')
# Declare attributes
self.state = S_STOP
self.count_enable = False
self.count_up_event = None
self.count_down_event = None
self.mode = M_UP
self.count_value = StringVar()
self.count_value.set('0')
# Create main frame
self.frame = Frame()
# Create the display of counter's value
self.label = Label(self.frame)
self.label.config(textvariable = self.count_value, font = ("Helvetica", 36))
# Create count up button
self.b_up = Button(self.frame, command = self.count_up)
self.b_up.config(text = 'COUNT UP', width = BUTTON_W, height = BUTTON_H)
# Create count down button
self.b_down = Button(self.frame, command = self.count_down)
self.b_down.config(text = 'COUNT DOWN', width = BUTTON_W, height = BUTTON_H)
# Create stop button
self.b_stop = Button(self.frame, command = self.stop)
self.b_stop.config(text = 'STOP', width = BUTTON_W, height = BUTTON_H)
# Create reset button
self.b_reset = Button(self.frame, command = self.reset)
self.b_reset.config(text = 'RESET', width = BUTTON_W, height = BUTTON_H)
# Display widgets
self.frame.place(relx = 0.5, rely = 0.5, anchor = CENTER)
self.label.grid(row = 0, columnspan = 3)
self.b_up.grid(row = 1, column = 0)
self.b_down.grid(row = 1, column = 1)
self.b_stop.grid(row = 2, column = 0)
self.b_reset.grid(row = 2, column = 1)
def count_up(self):
if self.state != S_UP: # To prevent rapid function callback caused by rapid clicks fr
self.state = S_UP
self.count_enable = True
self.mode = M_UP
self.start_counting()
def count_down(self):
if self.state != S_DOWN:
self.state = S_DOWN
self.count_enable = True
self.mode = M_DOWN
self.start_counting()
def stop(self):
if self.state != S_STOP:
self.state = S_STOP
self.count_enable = False
def reset(self):
if self.state != S_RESET:
self.state = S_RESET
self.count_enable = False
self.count_value.set('0')
def start_counting(self):
if (self.count_enable == True):
self.temp_count_value = int(str(self.count_value.get()))
self.temp_count_value += (1 if self.mode == M_UP else -1)
self.count_value.set(str(self.temp_count_value))
if self.mode == M_UP:
self.count_up_event = self.root.after(1000,self.start_counting)
if self.count_down_event is not None:
self.root.after_cancel(self.count_down_event)
else:
self.count_down_event = self.root.after(1000,self.start_counting)
if self.count_up_event is not None:
self.root.after_cancel(self.count_up_event)
else:
self.root.after_cancel(self.count_up_event)
self.root.after_cancel(self.count_down_event)
# Create counter object and run it
master = Counter()
master.root.mainloop()
|
5709f54d68f6ae8d2dadbee5418d5162ac644852 | josayko-courses/chess_tournament | /chess_tournament/models/round.py | 731 | 3.84375 | 4 | """Round information
"""
from datetime import datetime
class Round:
"""Holds round information"""
def __init__(self, name, games, start=None, end=None):
self.name = name
if start is None:
self.start = datetime.today().strftime('%Y-%m-%d %H:%M')
else:
self.start = start
if end is None:
self.end = ""
else:
self.end = end
self.games = games
def serialize(self):
"""Create data from round instance to save in db"""
return {'name': self.name, 'start': self.start, 'end': self.end, 'games': self.games}
def __repr__(self):
return f"Round({self.name}, {self.start}, {self.end}, {self.games})"
|
c2903426b0ef376db087dc5559bf8a176d7c6835 | lavalleed/IntroToProgramming-Python | /Assigment05_v1_5.py | 6,968 | 3.875 | 4 | # Title: Working with Dictionaries#
# Dev: DLaVallee
# Date: November 12, 2012
# ChangeLog: (Who, When, What)
# RRoot, 11/02/2016, Created starting template
# <DLaVallee>, 11/17/2018, Added code to complete assignment 5#
# Known bugs: List creation key to value pair is showing additional ':'?
# -- Data --#
# declare variables and constants
# objFile = An object that represents a file
# strData = A row of text data from the file
# dicRow = A row of data separated into elements of a dictionary {Key= 'Name', Values = 'Task','Priority'}
# lstTable = A dictionary that acts as a 'table' of rows
# strMenu = A menu of user options
# strChoice = Capture the user option selection
# -- Input/Output --#
# Initialize - Read persistent text file and display existing data (Step 1)
# User can see a Menu (Step 2)
# User can see data (Step 3)
# User can insert or delete data(Step 4 and 5)
# User can save to file (Step 6)
#Open the text file to make sure it is there before rest of script runs
objfile = open ("C:\\_PythonClass\\assignment05\\module05\\ToDo.txt", "a+")
# -- Processing --#
# Step 1
# When the program starts, load data from
# a text file called ToDo.txt # First step is to open the text file and load data into a List and Dictionary objects
objfile = open("C:\\_PythonClass\\assignment05\\module05\\ToDo.txt", "r")
def LoadFileList():
# create a list and dictionary object to store the text data being read from the text file
try:
list_todo = []
objfile = open("C:\\_PythonClass\\assignment05\\module05\\ToDo.txt", "r")
#print (objfile.read ()) remove comment tag to check to see what is in the raw file
#load text into list object
list_todo = objfile.read().splitlines()
print(list_todo)
#load text into dictionary object
objfile.close()
except IOError:
print("Text File Could not be Opened!")
def LoadFileDict():
# create a list and dictionary object to store the text data being read from the text file
try:
dict_todo = {}
objfile = open ("C:\\_PythonClass\\assignment05\\module05\\ToDo.txt", "r")
# print (objfile.read ()) remove comment tag to check to see what is in the raw file
# load text into dictionary object
for row in objfile:
row.lstrip ()
x = row.rstrip ('\n').split (',')
a = x[0]
b = x[1]
c = x[2]
s = ","
dict_todo[a] = b + s + c
print(dict_todo)
objfile.close ()
except IOError:
print("Text File Could not be Opened!")
def AddItem():
# open and read text file. Add item to the Multi-Dimension List of Dictionary key:value pairs
try:
add_todo = []
objfile = open("C:\\_PythonClass\\assignment05\\module05\\ToDo.txt", "r")
# print (obj_file.read ()) remove comment tag to check to see what is in the raw file
# load text into list object
add_todo = objfile.read().splitlines()
print(add_todo)
while (True):
int_kid = int(input("Enter a Unique Key Integer to add into the Dictionary range index: "))
print(" This will be your new unique key index number = ", int_kid)
str_value1 = str(input("Enter Task description: "))
str_value2 = str(input("Enter Priority: "))
print("I will insert KID #: ", int_kid, " Description: ", str_value1,
" Priority: ", str_value2,'\n')
#save to dictionary for possible future manipulation
dicNewRow = {"KID":int_kid, "Task":str_value1, "Priority":str_value2}
strCommit = "no" # set to no to validate user wants to take the action
strCommit = str(input("Do you want to make this change in the Dictionary? yes or no : "))
if (strCommit.strip () == 'yes'):
print(" This a a preview of your new dictionary row: ", dicNewRow)
add_todo.append(dicNewRow)
print(" Memory segment containing original dictionary was updated! : ", add_todo)
strWrite = str(input("Do you want to store this change in the text file? yes or no : "))
if (strWrite.strip () == 'yes'):
print("Writing all edits to text file: ", add_todo)
objfile = open("C:\\_PythonClass\\assignment05\\module05\\ToDo.txt", "w")
objfile.write(str(add_todo))
print(" New key:value pairs added! : ", add_todo)
break
else:
print(" Nothing changed!")
objfile.close()
except IOError:
print("Text File Could not be Opened!")
#Display current list of Key:Value Pairs
print('\n',"The text file contains the following Key:Value pairs . . .","\n")
print(objfile.read())
# Step 2
# Display a menu of choices to the user
# Step 3
# Display all todo items to user
# Step 4
# Add a new item to the list/Table
# Step 5
# Remove a new item to the list/Table
# Step 6
# Save tasks to the ToDo.txt file
# Step 7
# Exit program
# -------------------------------
objFileName = "C:\_PythonClass\Todo.txt"
strData = ""
dicRow = {}
lstTable = []
# Step 1 - Load data from a file
# When the program starts, load each "row" of data
# in "ToDo.txt" into a python Dictionary.
# Add each file "row" to a python list "table"
#Display the current List object contents
#print(objfile)
# Step 2 - Display a menu of choices to the user
while (True):
print("""
Menu of Options
1) Show current data
2) Add a new item.
3) Remove an existing item.
4) Save Data to File
5) Exit Program
""")
strChoice = str(input("Which option would you like to perform? [1 to 4] - "))
print() # adding a new line for console output spacing
# Step 3 -Show the current items in the table
if (strChoice.strip () == '1'):
print("Below is your List and Dictionary objects showing Key:Value pairs {'Key':'Value1','Value2'}")
LoadFileList()
LoadFileDict()
print("Above is a Multi-Dimension Table including unique Dictionary rows of Key,Value pairs!")
continue
# Step 4 - Add a new item to the list/Table
elif (strChoice.strip () == '2'):
print('You selected to add a new Dictionary Row to the larger Multi-Dimension List!')
AddItem()
continue
# Step 5 - Remove a new item to the list/Table
elif (strChoice == '3'):
print ('Not implemented...')
continue
# Step 6 - Save tasks to the ToDo.txt file
elif (strChoice == '4'):
print('Not implemented...')
continue
elif (strChoice == '5'):
objfile.close()
print ('See You Next Time...')
break # stop any loops and final exit the program
|
e57b325221d17e8abd6b44545967238017d2f616 | ARLbenjamin/PythonGames | /panecillos.py | 2,574 | 3.921875 | 4 | import random
def obtenerNumeroSecreto(digitosNum):
#retorna el numero secreto, el cual se crea al alzar
numeros = list(range(10))
random.shuffle(numeros)
numSecreto = ''
for i in range(digitosNum):
numSecreto += str(numeros[i])
return numSecreto
def obtenerPista(conjetura, numSecreto):
#regresa una palabra clave a manera de pista
if conjetura == numSecreto:
return 'Lo has adivinado!!'
pista = []
for i in range(len(conjetura)):
if conjetura[i] == numSecreto[i]:
pista.append('Fermi')
elif conjetura[i] in numSecreto:
pista.append('Pico')
if len(pista) == 0:
return 'Panecillos'
pista.sort()
return ' '.join(pista)
def esSoloDigitos(num):
#verifica si lo que se introduce es un numero
if num == '':
return False
for i in num:
if i not in '0 1 2 3 4 5 6 7 8 9'.split():
return False
return True
def jugarDeNuevo():
#verificar si el jugador desea jugar de nuevo
print('Deseas volver a jugar? (sí o no)')
return input().lower().startswith('s')
digitosNum = 3
MaxIntentos = 10
print(' ')
print('Estoy pensando en un número de %s digitos. Intenta adivinar cuál es' % (digitosNum))
print('Aqui hay algunas pistas: ')
print('Cuando digo: Eso significa:')
print(' Pico Un digito es correcto pero en la posición incorrecta.')
print(' Fermi Un digito es correcto y en la posición correcta.')
print(' Panecillos Ningún dígito es correcto.')
print(' ')
while True:
numSecreto = obtenerNumeroSecreto(digitosNum)
print('He pensado un número. Tienes %s intentos para adivinarlo.' % (MaxIntentos))
numIntentos = 1
while numIntentos <= MaxIntentos:
conjetura = ''
while len(conjetura) != digitosNum or not esSoloDigitos(conjetura):
print('Conjetura #%s (): ' % (numIntentos))
conjetura = input()
print(' ')
if len(conjetura) != digitosNum or not esSoloDigitos(conjetura):
print('Ingresó un valor inválido, por favor intente de nuevo.')
pistas = obtenerPista(conjetura, numSecreto)
print(pistas)
print(' ')
numIntentos += 1
if conjetura == numSecreto:
break
if numIntentos > MaxIntentos:
print('Te has quedado sin intetos. La respuesta era %s,' % (numSecreto))
if not jugarDeNuevo():
break
|
9d304c08122377649b4809d338a3388a93c85060 | Tdaycode/Data-structure-Algorithm-solutions | /binary-search-challenge.py | 425 | 3.890625 | 4 | import math
# Implementing binary search
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
def binary_search(array, item):
low = 0
high = len(array) - 1
while low <= high:
mid = low + high
guess = array[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
print(binary_search(arr, 89))
|
63fdb9f87bd84fab72406225ec083ea0f92427d4 | redhead520/LearningCode | /Design pattern/01.Factory Method(工厂方法).py | 3,561 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
' Factory Method'
__author__ = 'redhead'
# 定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method 使一个类的实例化延迟到其子类。
# 适用性:
#
# 当一个类不知道它所必须创建的对象的类的时候。
# 当一个类希望由它的子类来指定它所创建的对象的时候。
# 当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。
# 简单工厂模式
class LeiFeng():
def buy_rice(self):
pass
def sweep(self):
pass
class Student(LeiFeng):
def buy_rice(self):
print('大学生帮你买米')
def sweep(self):
print('大学生帮你扫地')
class Volunteer(LeiFeng):
def buy_rice(self):
print('社区志愿者帮你买米')
def sweep(self):
print('社区志愿者帮你扫地')
class LeiFengFactory():
def create_lei_feng(self, type):
map_ = {
'大学生': Student(),
'社区志愿者': Volunteer()
}
return map_[type]
if __name__ == '__main__':
leifeng1 = LeiFengFactory().create_lei_feng('大学生')
leifeng2 = LeiFengFactory().create_lei_feng('大学生')
leifeng3 = LeiFengFactory().create_lei_feng('大学生')
leifeng1.buy_rice()
leifeng1.sweep()
# 工厂方法模式
class LeiFeng():
def buy_rice(self):
pass
def sweep(self):
pass
class Student(LeiFeng):
def buy_rice(self):
print('大学生帮你买米')
def sweep(self):
print('大学生帮你扫地')
class Volunteer(LeiFeng):
def buy_rice(self):
print('社区志愿者帮你买米')
def sweep(self):
print('社区志愿者帮你扫地')
class LeiFengFactory():
def create_lei_feng(self):
pass
class StudentFactory(LeiFengFactory):
def create_lei_feng(self):
return Student()
class VolunteerFactory(LeiFengFactory):
def create_lei_feng(self):
return Volunteer()
if __name__ == '__main__':
myFactory = StudentFactory()
leifeng1 = myFactory.create_lei_feng()
leifeng2 = myFactory.create_lei_feng()
leifeng3 = myFactory.create_lei_feng()
leifeng1.buy_rice()
leifeng1.sweep()
# 工厂方法相对于简单工厂的优点:
#
# 1.
# 在简单工厂中,如果需要新增类,例如加一个中学生类(MiddleStudent),就需要新写一个类,同时要修改工厂类的map_,加入
# '中学生':MiddleStudent()。这样就违背了封闭开放原则中的一个类写好后,尽量不要修改里面的内容,这个原则。而在工厂方法中,需要增加一个中学生类和一个中学生工厂类(MiddleStudentFactory),虽然比较繁琐,但是符合封闭开放原则。在工厂方法中,将判断输入的类型,返回相应的类这个过程从工厂类中移到了客户端中实现,所以当需要新增类是,也是要修改代码的,不过是改客户端的代码而不是工厂类的代码。
#
# 2.
# 对代码的修改会更加方便。例如在客户端中,需要将Student的实现改为Volunteer,如果在简单工厂中,就需要把
#
# leifeng1 = LeiFengFactory().create_lei_feng('大学生')
# 中的大学生改成社区志愿者,这里就需要改三处地方,但是在工厂方法中,只需要吧
#
# myFactory = StudentFactory()
# 改成
#
# myFactory = VolunteerFactory()
# 就可以了 |
0f162bbed4a38ed2c2098cb823728ae115e2b218 | redhead520/LearningCode | /Algorithms/3.0数据结构-栈和队列.py | 2,491 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
' 3.00 数据结构:栈和队列'
# 栈:stack, 后进先出 last-in,first-out LIFO
# 队列:queue 先进先出 first-in,first-out FIFO
# 栈S
# S.push(), S.pop(), S.top, S.isempty()
# 栈下溢underflow, 栈上溢owerflow
class STACK():
def __init__(self, num=50, type=list):
if type == dict:
self.stacks = dict()
else:
self.stacks = [None] * num
self.top = -1
self.max = num
def push(self, item):
if self.top == self.max - 1:
raise OverflowError('stack was overflow!')
self.top = self.top + 1
self.stacks[self.top] = item
return self.stacks
def pop(self):
if self.isempty():
raise Exception('stack was underflow!')
self.top = self.top - 1
return self.stacks[self.top + 1]
def isempty(self):
if self.top < 0:
return True
return False
# S = STACK(5)
# print S.push('111')
# print S.push('222')
# print S.push('333')
# print S.push('444')
# print S.push('555')
# # print S.push('666')
# print S.pop()
# 队列:
class QUEUE():
def __init__(self, num=50, type=dict):
if type == dict:
self.Q = dict()
else:
self.Q = [None] * num
self.head = -1
self.tail = 0
self.max = num
def isempty(self):
if self.tail == self.head + 1:
return True
return False
def isfull(self):
if self.tail == self.head:
return True
return False
def enter(self, item):
if self.isfull():
raise OverflowError('Queue was full!')
if self.isempty():
self.head = 0
self.Q[self.tail] = item
self.tail = self.tail + 1
if self.tail == self.max:
self.tail = 0
return self.Q
def out(self):
if self.isempty():
raise Exception('Queue was empty!')
self.head = self.head + 1
if self.head == self.max:
self.head = 0 if self.tail != 0 else -1
return self.Q[self.head - 1]
# q = QUEUE(5)
# print q.isempty()
# print q.__dict__
# print q.enter('111')
# print q.enter('222')
# print q.enter('333')
# print q.enter('444')
# print q.enter('555')
# print '-'*10
# print q.__dict__
# print q.out()
# print '-'*10
# print q.__dict__
# print q.out()
# print '-'*10
# print q.__dict__
# print q.out()
# print q.enter('666')
|
fa1493d82201cb35e25484d00d21191a9e1322b2 | ZiHaoYa/1807-2 | /14day/01-计算器.py | 247 | 3.734375 | 4 | class student():
count = 0
def __init__(self,name):
self.name = name
self.count += 1
def add():
print("欢迎")
Student = student("美丽")
Student = student("狗威")
Student = student("高波")
Student = student("科林")
Student.add()
|
ba667451d2d80b621e1a5ae6f4166f148c4c0d74 | andyruwruw-old/coding-challenge-for-kids | /Labs_Python/2._Intermediate_Python/1._Strings/Tic-Tac-Toe/solution.py | 2,791 | 3.71875 | 4 | import math
board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
turn = 0
def printBoard(board):
for i in range(0, len(board)):
string = ""
for j in range(0, len(board[i])):
item = " "
if board[i][j] == 1:
item = "X"
elif board[i][j] == 2:
item = "O"
string += " " + item + " "
if j < (len(board[i]) - 1):
string += "|"
string += " "
for j in range(0, len(board[i])):
string += " " + str(j + (i * 3) + 1) + " "
if j < (len(board[i]) - 1):
string += "|"
print(string)
string = ""
if i < (len(board) - 1):
print("----------- -----------")
def resetBoard(board):
for i in range(0, len(board)):
for j in range(0, len(board[i])):
board[i][j] = 0
return board
def checkWin(board):
for i in range(0, 3):
if board[i][0] == board[i][1] and board[i][0] == board[i][2] and board[i][0] != 0:
return board[i][0]
if board[0][i] == board[1][i] and board[0][i] == board[2][i] and board[0][i] != 0:
return board[0][i]
if board[0][0] == board[1][1] and board[0][0] == board[2][2] and board[0][0] != 0:
return board[0][0]
if board[0][2] == board[1][1] and board[0][2] == board[2][0] and board[0][2] != 0:
return board[0][2]
return 0
def checkTie(board):
for row in board:
for block in row:
if block == 0:
return False
return True
print("Welcome to Tic-Tac-Toe.")
print("")
while True:
while True:
player = "O"
if turn == 0:
player = "X"
print(" -------It's " + player + "'s turn-------")
printBoard(board)
while True:
userInput = int(input("Choose a place to move: "))
row = math.floor((userInput - 1) / 3)
col = (userInput - 1) % 3
if userInput > 9 or userInput < 1:
print("Invalid Slot.")
elif board[row][col] != 0:
print("You can't move there.")
else:
board[row][col] = (turn + 1)
break
print("")
print("")
winner = checkWin(board)
if winner != 0:
print(player, "wins the game!")
printBoard(board)
print("")
break
elif checkTie(board):
print("Tie Game!")
print("")
break
if turn == 1:
turn = 0
else:
turn = 1
userInput = input("Play Again? (y/n): ")
if userInput == "n":
break
else:
board = resetBoard(board)
print("")
print("")
|
82c94fb9df5e8ae0628300f263ecbbe9da32e901 | andyruwruw-old/coding-challenge-for-kids | /Labs_Python/3._Advanced_Python/2._Input_and_Output_Files/Censored_Files/solution.py | 598 | 3.75 | 4 | inFile = open("input.txt", "r")
outFile = open("output.txt", "w")
badWords = []
while True:
badWord = input("What word would you like removed (/done to move on): ").lower()
if badWord == "/done":
break
badWords.append(badWord.lower())
for line in inFile:
words = line.split()
newLine = ""
for word in words:
if word.lower() in badWords:
for char in word:
newLine += "*"
else:
newLine += word
newLine += " "
newLine += "\n"
outFile.write(newLine)
outFile.close()
print("New File Created.")
|
ac52662a8ec3f30a9d706264a369cb71ae1d8834 | zephyrzth/FP-PemrogramanJaringan | /menu.py | 1,535 | 3.53125 | 4 | from tkinter import *
class Menu:
def __init__(self, master):
self.root = master
self.button_inputname = None
self.button_exit = None
self.generate_gui()
def generate_gui(self):
namalabel = Label(self.root, text = "")
namalabel.pack()
self.topframe = Frame(self.root)
self.topframe.pack()
self.bottomframe = Frame(self.root)
self.bottomframe.pack(side = TOP)
self.button_inputname = Button(self.bottomframe, text = "Finding Match ", fg= "black",command = self.printpesan)
self.button_inputname.pack(side = TOP)
self.button_exit = Button(self.bottomframe, text = "Exit Game", fg= "black",command = self.on_close)
self.button_exit.pack(side = TOP )
self.name_box()
def printpesan(self):
print("Masuk")
def on_close(self):
self.root.destroy()
exit(0)
def name_box(self):
frame = self.topframe
Label(frame, text='Enter username:', font=("Serif", 10)).pack(side='top', anchor='w')
self.enter_text_widget = Text(frame, width=20, height=2, font=("Serif", 10))
self.enter_text_widget.pack(side = BOTTOM, pady=15)
#self.enter_text_widget.bind('<Return>', self.on_enter_key_pressed)
frame.pack(side='top')
if __name__ == '__main__':
root = Tk()
root.title("Othello Menu")
root.geometry("320x220")
Gui = Menu(root)
root.protocol("WM_DELETE_WINDOW", Gui.on_close)
root.mainloop() |
f2277ac69ee272fee0239569dd7dbe406a5aa4c5 | zephyrzth/FP-PemrogramanJaringan | /logic-othello.py | 7,154 | 3.765625 | 4 | # array dengan value 0 brarti belum berisi
# array dengan value 1 terisi dengan bidak hitam
# array dengan value 2 terisi dengan bidak putih
class Othello:
board = [[0 for i in range(8)] for j in range(8)]
whitePieces = 0
blackPieces = 0
# Variabel untuk menghitung jumlah player yang gabisa gerak
cantMove = 0
def __init__(self):
# kondisi pertama kali permainan
# 2 bidak putih dan 2 bidak hitam saling bersilangan di tengah
self.board[4][3] = self.board[3][4] = 1
self.board[3][3] = self.board[4][4] = 2
self.turn = 1
def countPieces(self):
self.whitePieces = 0
self.blackPieces = 0
for i in range(8):
for j in range(8):
if(self.board[i][j] == 1):
self.blackPieces += 1
elif(self.board[i][j] == 2):
self.whitePieces += 1
def displayBoard(self):
# GUI mungkin ngubah disini nantinya
for row in self.board:
print("-----------------")
print("|", end="")
for element in row:
if(element == 0):
print(" |", end="")
elif(element == 1):
print("B|", end="")
else:
print("W|", end="")
print("")
print("-----------------")
def fillBoard(self):
# fungsi untuk ngisi bidaknya
# Beberapa hal yang harus di cek:
# 1. Papan masih kosong
# 2. Papan yang dipilih memiliki pasangan diantara bidak lawan
# Misal harus 1 2 2 2 (maka player 1 bisa naruh di samping bidak angka 2 tersebut)
# Kalau nomor 2 sudah terpenuhi, maka semua bidak diantara 1 tersebut akan menjadi sama warnanya
# Sebagai contoh tadi 1 2 2 2 1 maka akan berubah menjadi 1 1 1 1 1
if self.isValidMove(int(self.positionx), int(self.positiony), 1):
self.board[int(self.positionx)][int(self.positiony)] = self.turn
return True
else:
print("\nSorry, your move violate the rules, Please try another move!\n")
return False
def isOnBoard(self, x, y):
# Fungsi untuk mengecek apakah koordinat x,y berada dalam papan
return x >= 0 and x <= 7 and y >= 0 and y <=7
def isEmptyBoard(self, x, y):
# Fungsi untuk mengecek apakah koordinat x,y kosong atau tidak
return self.board[x][y] == 0
def isEnemyDisk(self, x, y):
# Fungsi untuk mengecek apakah koordinat x,y bidak lawan atau tidak
return self.board[x][y] != self.turn
def isValidMove(self, x, y, updateFlag):
# Fungsi untuk mengecek apakah valid dan apakah ada bidak yang perlu dialik warnanya
# Jika bidak yang dipilih diluar papan
if not self.isOnBoard(x,y):
return False
isValid = False
# Jika kotak yang dipilih masih kosong
if self.isEmptyBoard(x, y):
# Untuk mengecek 8 arah
ARRAY_DIRECTION=[
[-1 , 0], # Atas
[ 1 , 0], # Bawah
[ 0 , 1], # Kanan
[ 0 , -1], # Kiri
[-1 , 1], # Kanan Atas
[-1 , -1], # Kiri Atas
[ 1 , 1], # Kanan Bawah
[ 1 , -1], # Kiri Bawah
]
allDisktoFlip = []
for direction in ARRAY_DIRECTION:
disktoflip = []
iter_x = x+direction[0]
iter_y = y+direction[1]
# Lakukan looping selama pengecekan masih berada di dalam border
while self.isOnBoard(iter_x, iter_y):
# Jika papan yang dipilih masih kosong
if self.isEmptyBoard(iter_x, iter_y):
break
# Cek apakah bidak tetangganya adalah lawan
elif(self.isEnemyDisk(iter_x, iter_y)):
disktoflip.append([iter_x, iter_y])
else:
if(disktoflip):
isValid = True
for diskPos in disktoflip:
allDisktoFlip.append(diskPos)
break
iter_x += direction[0]
iter_y += direction[1]
if isValid and updateFlag:
self.updateBoard(allDisktoFlip)
return isValid
def updateBoard(self, diskToFlip):
# Fungsi untuk update board
# update koordinat board menjadi warna bidak player sekarang
for x in diskToFlip:
self.board[x[0]][x[1]] = self.turn
def isFinished(self):
# Fungsi untuk mengecek apakah game sudah selesai
isFull = True
for i in range(8):
for j in range(8):
# Jika ada kotak yang masih kosong maka belum selesai gamenya
if self.board[i][j] == 0:
# Jika player masih bisa melakukan sebuah move pada suatu turn maka belum selesai gamenya
if self.isValidMove(i, j, 0):
self.cantMove = 0
return False
isFull = False
# Jika board sudah penuh dengan bidak
if isFull:
return True
else:
self.cantMove += 1
# Jika kedua player tidak bisa bergerak
if self.cantMove == 2:
return True
else:
return False
def printResult(self):
# Fungsi untuk print hasil akhir game
self.displayBoard()
self.countPieces()
print("\nBlack Pieces (Player 1): " + str(self.blackPieces))
print("\nWhite Pieces (Player 2): " + str(self.whitePieces))
if self.blackPieces > self.whitePieces:
print("\nCongratulations!!! Player 1 win!\n")
elif self.whitePieces > self.blackPieces:
print("\nCongratulations!!! Player 2 win!\n")
else:
print("\nCongratulations!!! The result is draw!\n")
def play(self):
while(True):
if self.isFinished():
self.printResult()
break
if self.cantMove == 0:
while(True):
self.displayBoard()
self.positionx=input(">>Player 1 (Black) turn, choose x coordinate: ")
self.positiony=input(">>Player 1 (Black) turn, choose y coordinate: ")
if self.fillBoard():
break
self.turn = 2
if self.isFinished():
self.printResult()
break
if self.cantMove == 0:
while(True):
self.displayBoard()
self.positionx=input(">>Player 2 (White) turn, choose x coordinate: ")
self.positiony=input(">>Player 2 (White) turn, choose x coordinate: ")
if self.fillBoard():
break
self.turn = 1
ot = Othello()
ot.play() |
ca53b0e726e6c8f8f527739fc80c850bd05465e1 | agb32/aotools | /aotools/turbulence/turb.py | 1,960 | 3.578125 | 4 | """
General equations and definitions describing turbulence statistics
"""
import numpy
from scipy.special import gamma, kv
__all__ = ["phase_covariance","calc_seeing"]
def phase_covariance(r, r0, L0):
"""
Calculate the phase covariance between two points seperated by `r`,
in turbulence with a given `r0 and `L0`.
Uses equation 5 from Assemat and Wilson, 2006.
Parameters:
r (float, ndarray): Seperation between points in metres (can be ndarray)
r0 (float): Fried parameter of turbulence in metres
L0 (float): Outer scale of turbulence in metres
"""
# Make sure everything is a float to avoid nasty surprises in division!
r = numpy.float32(r)
r0 = float(r0)
L0 = float(L0)
# Get rid of any zeros
r += 1e-40
A = (L0 / r0) ** (5. / 3)
B1 = (2 ** (-5. / 6)) * gamma(11. / 6) / (numpy.pi ** (8. / 3))
B2 = ((24. / 5) * gamma(6. / 5)) ** (5. / 6)
C = (((2 * numpy.pi * r) / L0) ** (5. / 6)) * kv(5. / 6, (2 * numpy.pi * r) / L0)
cov = A * B1 * B2 * C
return cov
def calc_seeing(r0,lam,l0,r0IsAt500nm=1):
"""Compute seeing from r0, wavelength at which to compute seeing, and L0.
Note, L0 should be defined at lame.
Parameters:
r0 (float, ndarray): Frieds parameter in m.
lam (float, ndarray): Wavelength in nm.
l0 (float, ndarray): Outer scale in m.
r0IsAt500nm (int): Flag, defines where r0 is defined.
"""
lam=lam*1e-9#convert to m
if type(lam)==type(0.) and lam<1e-10:#probably in m already.
print( "Warning: Wavelength should be defined in nm")
if r0>2:#probably in cm. Convert to m.
print( "Warning - r0 might be defined in cm - needs to be in m")
if r0IsAt500nm:
r0*=(lam/500e-9)**(6./5)
seeing = 0.976* lam/r0*180/numpy.pi*3600
if l0!=0:#outer scale is defined...
seeing = seeing * numpy.sqrt(1-2.183*(r0/l0)**0.356)
return seeing
|
fd88cc6462b59a357c3d5612afe7ae334f651ccd | superxiangsx/python-ex | /ex17.py | 168 | 3.90625 | 4 | x = input("please input some words: ")
print(f"The words you input is {len(x)}")
y = input("please input some other words: ")
print(f"The words you input is {len(y)}")
|
731fca158d965092ca59f3f063d1e917fb56a84e | superxiangsx/python-ex | /test.py | 439 | 3.65625 | 4 |
#求绝对值的函数,即两点间距离的函数
'''def abs(x,y):
if x > y:
return x-y
else:
return y-x
'''
# y = |x-1| + 2*|x-2| + 3*|x-3| + 4*|x-4| + ...... + 100*|x-100|
#描述上述函数,min_x和max_x为区间的上下限
def jisuan(x,min_x,max_x):
j = min_x
z = 0
for j in range(min_x, max_x+1):
z = z + j * abs(x - j)
print(f"x = {x}, the result is {z}")
for i in range(1,101):
jisuan(i,1,100)
|
6b73ba38506e9fe8456532d627230062d9adbd16 | jstratman33/text-blackjack | /src/Player.py | 1,580 | 3.5 | 4 | '''
Created on Oct 5, 2017
@author: Jason
'''
import os
class Player:
def __init__(self, name):
"""
Builds the player object with name and sets the bank from file
Args:
None
Returns:
None
"""
self.name = name
self.bank = 0
self.setBank()
def setBank(self):
"""
Retrieves bank amount from file
Args:
None
Returns:
None
"""
bankFile = open("BankFile.txt", "r")
for line in bankFile:
pieces = line.split()
if pieces[0] == self.name:
self.bank = float(pieces[1])
break
bankFile.close()
if self.bank == 0:
bankFile = open("BankFile.txt", "a")
bankFile.write("\n" + self.name + " " + str(50))
self.bank = float(50)
bankFile.close()
def saveBank(self):
"""
Saves the bank amount back to the file
Args:
None
Returns:
None
"""
bankFile = open("BankFile.txt", "r")
tempFile = open("BankFile.tmp", "w")
for line in bankFile:
pieces = line.split()
if pieces[0] == self.name:
tempFile.write(self.name + " " + str(self.bank) + "\n")
else:
tempFile.write(line)
tempFile.close()
bankFile.close()
os.remove("BankFile.txt")
os.rename("BankFile.tmp", "BankFile.txt")
|
a24b998f495ff7e20561903ed543b09f54520a6a | SIDDHARTHSS93/Computer-Security-Assignments | /Siddharth_Shyamsunder_1802772/ass2.py | 5,069 | 3.78125 | 4 | import numpy
import random
import time
#We will store the values of private keys into private 1 and 2, private 1 and 2
#will be the output of combined congruential method.
#We will have alpha and q to obtain the public keys(x1 and x2) for the Diffie
#Hellman's Algorithm.
#we will use public keys x1 and x2 to generate secret key.
#variables y1 and y2 2 random numbers intermediate values in the combined
#congruential algorithm.
#variables a1,a2,m1 and m2 are used to generate y1, y2, and x.
#x holds the list of each generator value, or eachprivate key in this case.
private1=0
private2=0
alpha=3
q=353
x=numpy.zeros(3)
y1=numpy.zeros(3)
y2=numpy.zeros(3)
m1=2147483642
m2=2147483423
a1=450
a2=234
while True:
y1[0]=random.randint(1, 2147483641)
y2[0]=random.randint(1, 2147483422)
i=0
x[0]=0
for i in range(2):
y1[i+1]=(a1*y1[i])%m1
y2[i+1]=(a2*y2[i])%m2
x[i+1]=(y1[i+1]-y2[i+1])%(m1-1)
private1=int(x[1]%500)
private2=int(x[2]%500)
if private1<q and private2<q:
break
print("The first Private Key is:",private1)
print("The second Private Key is:",private2)
#Once the private keys are generated. We will use private keys in the formula
#X=a**privatekey mod q, where X is the public key x1 and x2,and
#the private keys are what we generated earlier.
x1=(alpha**private1)%q
x2=(alpha**private2)%q
#Once we generate public keys x1 and x2 we will use them to generate secret keys,
#we will use secret key=X**opp private mod q.
#where opp private key is the opposite private key used.
secretkey=(x2**private1)%q
print("The Secret Key is:",secretkey)
#Once Secret key is generate, we will divide it into its individual characters.
#This is going to be used to generate list T.
#We will ask user to enter a file name. This file will contain plain text which
#we will convert to cipher text.
#Also the 2nd user will enter the secret key, this is used to confirm that the
#2nd user is genuine.
l=len(str(secretkey))
count=0
f=input("Please Enter the file Name:")
secretkey=input("Please Enter the Secret Key:")
file=open(f,"r")
cont=file.read()
#We will take the plaintext from the block and divide it into 64 bit blocks
#In this case 8 characters, as each character is 8 bits in length.
#if all blocks are of equal sizes, we will take the last block, else we will take the 2nd last block.
for i in range(len(cont)):
count+=1
block=[]
count2=count/8-count//8
if count2>0:
count=(count//8)+1
else:
count=count//8
for i in range(count
):
block.append([])
i=0
block[i].append(cont[0])
for j in range(1,len(cont)):
if i<count:
block[i].append(cont[j])
if(j%8==0):
block[i]=''.join(block[i])
i+=1
if(j==(len(cont)-1)):
block[i]=''.join(block[i])
i+=1
while(j-1<8*i):
block[i-1]=block[i-1]+'0'
j+=1
if count2>0:
print("\n\nThe Block of plain text is:\n",block[i-2])
else:
print("\n\nThe Block of plain text is:\n",block[i-1])
#We will create list s contsining a range from 0-255, and t which will
#contain our secret key value as discussed earlier.
secretkeylist=numpy.zeros(l)
s=numpy.zeros(256)
t=numpy.zeros(256)
secretkey=str(secretkey)
for i in range(l):
secretkeylist[i]=int(secretkey[i])
for i in range(256):
s[i]=i
t[i]=secretkeylist[i%l]
j=0
#we will find j as a value of j+s[i]+t[i] mod 256 and swap s[i] and s[j]
for i in range(255):
j=int((j+s[i]+t[i])%256)
temp=s[i]
s[i]=s[j]
s[j]=temp
#In the end we get a new s array. Now we will give new values for i and j and again swap s[i] and s[j]
#we will take the last value as s[t] and store it in k. This k will be used to encrypt the block of plaintext
i=0
j=0
k=0
count3=0
while True:
i=int((i+1)%256)
if(i==0):
count3+=1
if(count3==2):
break
j=int((j+s[i])%256)
temp=s[i]
s[i]=s[j]
s[j]=temp
t=int(s[i]+s[j])%256
k=int(s[t])
if count2>0:
count=count-2
pt=block[count]
else:
count=count-1
pt=block[count]
#We will then take key k and xor with the ascii value of plain text, and convert the new integer list to a character string
#This new character String is the cipher text.
ptascii=numpy.zeros(len(pt))
ct=numpy.zeros(len(pt))
cipher=[]
for i in range(len(pt)):
ptascii[i]=ord(pt[i])
ct[i]=int(ptascii[i])^k
cipher.append(chr(int(ct[i]%26)+97))
cipher="".join(cipher)
print("The Encrypted Text is:",cipher)
cipher=input("Please enter the ciphertext:")
#We will ask the user to provide cipher text. We will use the cipher text to generatean integer matrix.
#We will use the key k to xor the cipher text back to plain text.
ctq=numpy.zeros(len(pt))
ctr=numpy.zeros(len(pt))
for i in range(len(pt)):
ctq[i]=ct[i]//26
ctr[i]=int((ord(cipher[i])-97)%26)
plain=[]
pt1=numpy.zeros(len(ct))
for i in range(len(ct)):
pt1[i]=ctq[i]*26+ctr[i]
pt1[i]=int(pt1[i])^k
plain.append(chr(int(pt1[i])))
plain="".join(plain)
print("The decrypted text is:",plain)
time.sleep(1000)
|
c9e7fd34fbbd2ae8fd3a81cfd08877310ffc88b0 | NagahShinawy/dev.to | /tips-tricks/3-python-tips-tricks-that-no-one-teach.py | 873 | 3.859375 | 4 | # https://dev.to/worldindev/6-python-tips-tricks-that-no-one-teaches-4j73
import random
import datetime
answers = ["A", "B", "C", "D", "E"]
books = ["Harry potter", "Don Quixote", "Learn Python", "Dracula"]
book = random.choice(books)
for _ in range(10):
answer = random.choice(answers)
print(answer)
# Unpacking elements with *
print(*answers, sep="")
name = "John"
chars = [*name] # [*iterable]
print(chars) # ['J', 'o', 'h', 'n']
# https://dev.to/jerrynsh/3-useful-python-f-string-tricks-you-probably-don-t-know-2o54
# 1. F-string for Debugging
now = datetime.datetime.now()
print(now)
# usual way
dt = now.strftime("%Y-%m-%d")
print(dt)
# using f-string
dt = f"{now:%y-%m-%d %H:%M:%S}"
print(dt)
# A repr() alternative with f-string
print(now)
print(
f"{now!r}"
) # !r: means use __rep__ ==> datetime.datetime(2021, 9, 9, 13, 50, 50, 247020)
|
4e070270f812ddd28e7a7d7453cd10397b16631c | Janarbek11/ifElse | /ifelse.py | 832 | 4.34375 | 4 | # Написать программу которая проверит число на несколько критериев:
# Чётное ли число?
# Делится ли число на 3 без остатка?
# Если возвести его в квадрат, больше ли оно 1000?
с = int(input("Введите число: "))
if с % 2 == 0:
print ("Четное число!")
else:
print("Нечетное число!")
o = int(input("Введите число: "))
g = o % 3
if g != 0:
print("Число делится на 3 с остатком = ", g)
else:
print("Число делится на 3 без остатка")
d = int(input("Возведенеие в 2\nВведите число: "))
e = d ** 2
if e > 1000:
print(e, "bolshe 1000")
else:
print(e, "menshe 1000") |
88dda3900d59832cd686572ace19c943c888dfd6 | dsweed12/My-Projects | /Project II - Python MITx/week2.py | 3,271 | 4.15625 | 4 | import math
def iter_power(base, exp):
"""
base: int or float
exp: int >= 0
returns: int or float, base^exp
"""
if exp == 0:
return 1
else:
result = base
while exp > 1:
result *= base
exp -= 1
return base
def recurPower(base, exp):
"""
base: int or float
exp: int >= 0
returns: int or float, base^exp
"""
if exp == 0:
return 1
elif exp == 1:
return base
else:
return base * recurPower(base, exp-1)
# Exercise 1:
iteration = 0
while iteration < 5:
count = 0
for letter in "hello, world":
count += 1
if iteration % 2 == 0:
break
print("Iteration " + str(iteration) + "; count is: " + str(count))
iteration += 1
# exercise 2:
x = 25
epsilon = 0.01
step = 0.1
guess = 0.0
while abs(guess**2-x) >= epsilon:
if guess <= x:
guess += step
else:
break
if abs(guess**2 - x) >= epsilon:
print('failed')
else:
print('succeeded: ' + str(guess))
#guess any number:
print("Please think of a number between 0 and 100")
low, high = 0, 100
mid = int((high +low)/2)
print("is your secret number "+ str(mid) +"?")
ans = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
while ans != "":
if ans == 'c':
break
elif ans =='h':
high = mid
elif ans == 'l':
low = mid
else:
print("Sorry, I did not understand your input.")
mid = int((low + high)/2)
print("is your secret number " + str(mid) + "?")
ans = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
print("Game over. Your secret number was:" + str(mid))
def printMove(fr, to, tree):
print("Tree "+str(tree)+": Move from "+str(fr)+" to "+str(to))
def towers(n, fr, to, spare, tree):
if n == 1:
printMove(fr, to, tree)
else:
towers(n-1, fr, spare, to, 1)
towers(1, fr, to, spare,2)
towers(n-1, spare, to, fr,3)
def gcdIter(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
guess = min(a, b)
while a % guess > 0 or b % guess > 0:
guess -= 1
return guess
def gcdRecur(a, b):
"""
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
"""
if b == 0:
return a
else:
return gcdRecur(b, a % b)
def isIn(char, aStr):
""""
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
"""
found = False
if aStr == "":
return False
else:
if aStr[0] == char or aStr[-1] == char:
return True
mid = aStr[len(aStr)//2]
if mid == char:
return True
elif mid > char:
return isIn(char, aStr[0:len(aStr)//2-1])
else:
return isIn(char, aStr[len(aStr) // 2:-1])
def polysum(n, s):
import math
area = (.25*n*s**2)/math.tan(math.pi/n)
perimeter = n*s
sum = area+perimeter**2
return round(sum, 4) |
c793c49002dae5ccb185c42dad3cddbc3bb8fcd6 | PolyMaG/python-project-lvl1 | /brain_games/games/gcd.py | 568 | 3.796875 | 4 | from random import randint
GREETING = 'Find the greatest common divisor of given numbers.'
def get_gcd(number1, number2):
max_number = max(number1, number2)
min_number = min(number1, number2)
gcd = 1
while gcd <= min_number:
if max_number % gcd == 0 and min_number % gcd == 0:
result = str(gcd)
gcd += 1
return result
def generate_data():
number1 = randint(1, 99)
number2 = randint(1, 99)
result = get_gcd(number1, number2)
question = '{} {}'.format(number1, number2)
return question, result
|
fe33826633b2348dc4fe943c9591c6737ff46416 | tracyyu/UCLA-CS-145-Cuisiner | /Cuisinier-Tracy/CuisinierClassifier.py | 3,860 | 3.609375 | 4 | from Cuisinier import Recipe, ClassifiedRecipe, Cuisinier
"""
Uses ingredients to categorize the cuisine of a recipe via the
One-Vs-All algorithm.
@author: Alan Kha
"""
class CuisinierOVA(Cuisinier):
def __init__(self):
super().__init__()
def preprocess(self):
super().preprocess()
self.cuisineRecipeClassification = {} # <cuisine, <ingredient, 1 or 0>>
def classifyRecipe(self, recipe: Recipe):
if not isinstance(recipe, Recipe):
raise TypeError("Cuisinier.classifyRecipe() takes a Recipe")
CuisineProb = {} # <cuisine, <ingredient, probability>>
possibleCusineChoices = [] # cuisines who have all the specified recipe
cuisineIngredCt = {} # <cuisine, <ingredient from recipe, frequency>
chosenCuisine = "" #correct Cuisine
chosenCuisineIngredFreq = 0
#loop through the databse of cuisine
for cuisine in self.cuisineCount:
cuisineRecipeClassification[cuisine] = {}
#loop through all the ingredients in the recipe we are given
for ingredient in recipe.ingredients:
#now mark whether ingredient exists in specific cusine
#1, for it does
#0, for it does not
if ingredient not in self.cuisineMatrix[cuisine]:
cuisineRecipeClassification[cuisine][ingredient] = 0
else:
if self.cuisineMatrix[cuisine][ingredient] > 0:
cuisineRecipeClassification[cuisine][ingredient] = 1
else:
cuisineRecipeClassification[cuisine][ingredient] = 0
#choose only the cuisine that has all the listed ingredients
for cuisine in cuisineRecipeClassification:
totalIngredCt = 0
#loop through all the ingredients in the recipe we are given
for ingredient in recipe.ingredients:
totalIngredCt += cuisineRecipeClassification[cuisine][ingredient]
#sum one the 1's must equal to # of ingredients in recipe
if totalIngredCt == (len(recipe.ingredients)):
possibleCusineChoices.append(cuisine)
#now to compare among the remaining cuisines
#if there exist only one possible Cusine choice, we have found it
if len(possibleCusineChoices) == 1:
chosenCuisine = possibleCusineChoices[0]
else:
recipeIngredCt = {} # <ingredient in recipe, frequency>
#now we will find the ingredient with lowest frequency out of all cuisines
for ingredient in recipe.ingredients:
recipeIngredCt[ingredient] = self.ingredientCount[ingredient]
ingredWithLowFreq = ""
for ingredient in recipeIngredCt:
if ingredWithLowFreq == "":
ingredWithLowFreq = ingredient
elif recipeIngredCt[ingredient] < recipeIngredCt[ingredWithLowFreq]:
ingredWithLowFreq = ingredient
#now find the cuisine with the highest frequency of the ingredients with lowest overall frequency
for cuisine in possibleCusineChoices:
cuisineIngredFreq = self.cuisineMatrix[cuisine][ingredWithLowFreq]
print(cuisine)
print(cuisineIngredFreq)
if chosenCuisine == "":
chosenCuisine = cuisine
chosenCuisineIngredFreq = cuisineIngredFreq
elif cuisineIngredFreq > chosenCuisineIngredFreq:
chosenCuisine = cuisine
chosenCuisineIngredFreq = cuisineIngredFreq
print(ingredWithLowFreq)
print(chosenCuisineIngredFreq)
return ClassifiedRecipe(recipe.id, chosenCuisine, recipe.ingredients)
|
9e47611cfa3d80554715e98da0f9f1c08b8331ff | tboydv1/project_python | /Python_book_exercises/chapter6/exercise_11/online_purchase.py | 1,288 | 4.25 | 4 | """Suppose you are purchasing something online on the Internet. At the website, you get
a 10% discount if you are a member. Additionally, you are also getting a discount of
5% on the item because its Father’s Day.
Write a function that takes as input the cost of the item that you are purchasing and
a Boolean variable indicating whether you are a member (or not), applies the discounts
appropriately, and returns the final discounted value of the item."""
def apply_discount():
try:
is_member = False
item_cost_str = input("Input cost of item purchased: ")
membership = input("Are you a member? [y/n]")
membership = membership.lower()
if membership == "y":
is_member = True
item_cost_float = float(item_cost_str)
except ValueError as a:
print(a)
if is_member == False:
percent = 5 / 100 * item_cost_float
dicount_value = item_cost_float - percent
return dicount_value
elif is_member == True:
percent = (15 / 100 * item_cost_float)
dicount_value = item_cost_float - percent
return dicount_value
def main():
discount = apply_discount()
print("Discounted value of item is: {}".format(discount))
if __name__ == '__main__':
main()
|
c5c23ee5b021fe7b7c6ee442ab3c32cece6831ff | tboydv1/project_python | /Python_book_exercises/chapter6/examples/word_search.py | 583 | 4 | 4 | # read through file one line at a time
def clean_word(word):
return word.strip().lower()
def get_vowel_in_word(words):
vowel = "aeiou"
vowel_in_word = ''
for char in words:
if char in vowel:
vowel_in_word += char
return vowel_in_word
# main program
# def main():
file_obj = open("dictionary.txt", "r")
word = ""
vowel_word = ""
vowels = "aeiou"
for line in file_obj:
word = clean_word(line)
if len(word) <= 6:
continue
vowel_word = get_vowel_in_word(word)
if vowel_word == vowels:
print(word)
|
2112a1c6e94348196d065f4748b6454345c2e112 | tboydv1/project_python | /Python_book_exercises/chapter2/exercise13.py | 331 | 4.125 | 4 | #Validate for and integer input
user_str = input("Input an integer: ")
status = True
while status:
if user_str.isdigit():
user_int = int(user_str)
print("The integer is: {}".format(user_int) )
status = False
else:
print("Error try again")
user_str = input("Input an integer: ")
|
6b0e05cdb97a6ca0eee0c64096017f46fd05cafe | tboydv1/project_python | /practice/circle.py | 223 | 4.3125 | 4 | from math import pi
tmp_radius = input("Enter radius of circle ")
radius = int(tmp_radius)
circumference = 2 * (pi * radius)
print("Circumference is: ", circumference)
area = pi * radius**2
print("Area is: ", area)
|
76bfd7b4ce465902718576aa06d26cc654c9e599 | tboydv1/project_python | /Python_book_exercises/chapter1/cosine.py | 1,060 | 4.34375 | 4 | from math import *;
print("Angles of triangle with lengths: 7, 3, 9", end = "\n\n")
##Find angle C when side a = 9, b = 3, c = 7
##formula= c**2 = a**2 + b**2 - 2 * a * b * Cos(c)
side_a, side_b, side_c = 9, 3, 7;
a_b = -(2 * side_a * side_b);
#Square all sides
pow_a = side_a**2
pow_b = side_b**2
pow_c = side_c**2
## add side a and b
sum_ab = pow_a + pow_b
pow_c -= sum_ab
angle_C = acos(pow_c / a_b)
#convert result to degrees
print("Angle C = ", degrees(angle_C))
#Find angle B when side a = 9, b = 3, c = 7
#Square all sides
pow_a = side_a**2
pow_b = side_b**2
pow_c = side_c**2
a_c = -(2 * side_a * side_c);
## add side a and b
sum_ac = pow_a + pow_c
pow_b -= sum_ac
angle_B = acos(pow_b / a_c)
print("Angle B = ", degrees(angle_B))
#Find angle A when side a = 9, b = 3, c = 7
#Square all sides
pow_a = side_a**2
pow_b = side_b**2
pow_c = side_c**2
b_c = -(2 * side_b * side_c);
## add side b and c
sum_bc = pow_b + pow_c
pow_a -= sum_bc
angle_A = acos(pow_a / b_c)
print("Angle B = ", degrees(angle_A))
|
682fa2b9c64d20165751d9a44a135dda1779f5be | tboydv1/project_python | /Python_book_exercises/chapter2/exercise11.py | 627 | 4.0625 | 4 | """Write a program that prompts for an integer—let’s call it X—and then finds the
sum of X consecutive integers starting at 1."""
value_str = input("Enter a value ")
sum = 0
count = 0
try:
#convert input to int
value_int = int(value_str)
print("Consecutive sums: ")
for i in range(1, value_int + 1):
# for j in range(1, i + 1):
sum += i
print(sum)
# sum = 0
if sum % len(range(1, value_int + 1)) == 0:
print("Total sum: ",sum, end=" ")
else:
print("Sum is not divisible by number")
# print(i)
except ValueError:
print("Invalid input")
|
42fe32b3336b638d54746970963d3a8dccf07171 | tboydv1/project_python | /Python_book_exercises/projectMatrix/matrix/matrix_program.py | 231 | 3.59375 | 4 | from matrix import Matrix
def main():
A = Matrix([[1,2,3], [2, 4, 4], [4, 4, 4]])
B = Matrix([[1,2,3], [2, 40, 4], [4, 4, 4]])
print(A)
print(B)
print(B.add(A))
if __name__ == '__main__':
main()
|
53c8eeb9ebc1c83debeecea5f0d5a42e7d365ba4 | tboydv1/project_python | /Python_book_exercises/chapter6/examples/program2.py | 346 | 3.796875 | 4 |
def func1 (str1, str2):
if str1 > str2:
result_str = str1[1:]
else:
result_str = str2[:-1]
return result_str
#main program
responses1_str = input("Enter a string:")
responses2_str = input("Enter a second string:")
dir(list)
print(func1(responses1_str, responses2_str))
print(func1(responses2_str, responses1_str))
|
f1d8cf960efa1ba7bafb12d84d48afc8b947d61c | tboydv1/project_python | /practice/factors.py | 284 | 4.125 | 4 | #get the input
num = int(input("Please type a number and enter: "))
#store the value
sum = 0
print("Factors are: ", end=' ')
#generate factors
for i in range(1, num):
if(num % i == 0):
print(i, end=' ')
#sum the factors
sum += i
print()
print("Sum: ",sum)
|
bbfc551d1ee571c9be6c68747b56ca85a56fcf4b | abaratif/code_examples | /sums.py | 813 | 4.34375 | 4 |
# Example usage of zip, map, reduce to combine two first name and last name lists, then reduce the combined array into a string
def combineTwoLists(first, second):
zipped = zip(first, second)
# print(zipped)
# [('Dorky', 'Dorkerton'), ('Jimbo', 'Smith'), ('Jeff', 'Johnson')]
# The list comprehension way
listComp = [x + " " + y for x, y in zipped]
# print(list(listComp))
# ['Dorky Dorkerton', 'Jimbo Smith', 'Jeff Johnson']
# The Map way
f = lambda a : a[0] + " " + a[1]
listComp = map(f, zipped)
f = lambda a,b: a + ", " + b
result = reduce(f, listComp)
# Dorky Dorkerton, Jimbo Smith, Jeff Johnson
# print(type(result))
# <type 'str'>
return result
def main():
first = ['Dorky', 'Jimbo', 'Jeff']
second = ['Dorkerton', 'Smith', 'Johnson']
print(combineTwoLists(first, second))
if __name__ == "__main__":
main() |
139af95efa48672d9d38ea31f30320e6fbdce184 | jonnysfarmer/python-learning | /webscraper/main.py | 1,077 | 3.8125 | 4 | from bs4 import BeautifulSoup
import requests
search = input('Search For: ')
params = {'q': search}
# does a request for first page of bing search resuls
r = requests.get('https://www.bing.com/search', params=params)
# uses beautiful soup to pass the html into text
soup = BeautifulSoup(r.text, 'html.parser')
# So it finds the 'ol' / ordered list with the id 'b_results'
results = soup.find('ol', {'id': 'b_results'})
# within results, we find ALL the 'li' with the class 'b_algo'
links = results.findAll('li', {'class': 'b_algo'})
# We iteratate of Links and set Item_text to the text within the linke
# and href as the arribute href of the 'a' tags
for item in links:
item_text = item.find('a').text
item_href = item.find('a').attrs['href']
# This is an example how you can look at parents etc of attributes
item_summary = item.find('a').parent.parent.find('p').text
# if both of these excist, then we print them
if item_text and item_href and item_summary:
print(item_text)
print(item_href)
print('Summary:', item_summary)
|
a54d2cbae58df936803b259917a95ed7f960f92b | sree-07/PYTHON | /escape_sequences.py | 1,829 | 4.25 | 4 | """sep & end methods"""
# a="python";b="programming"
# print(a,b,sep=" ") #python programming
# print(a,b,end=".") #python programming.
# print("sunday") #python programming.sunday
""" combination of end & str &sep """
# a="food"
# b="from swiggy"
# c="not available"
# print(a,b,end="." "its raining",sep=" ")
# print(c) #food from swiggy.its raining not available
""" escape seqences"""
# print("hello\tworld")
# print("hello\nworld")
# print("hello\bworld")
# print("hello\'world")
# print("hello\"world")
# print("hello\\world")
# print("hello\aworld") #helloworld
# print("hello\bworld") #hellworld
# print("hello\cworld")
# print("hello\dworld")
# print("hello\eworld")
# print("hello\fworld") #hello♀world
# print("hello\gworld")
# print("hello\hworld")
# print("hello\iworld")
# print("hello\jworld")
# print("hello\kworld")
# print("hello\lworld")
# print("hello\mworld")
# print("hello\nworld") #hello
# world
# print("hello\oworld")
# print("hello\pworld")
# print("hello\qworld")
# print("hello\rworld") #world
# print("hello\sworld")
# print("hello\tworld") #hello world
# print("hello\uworld") #SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes
# print("hello\vworld") #hello♂world
# print("hello\wworld")
# print("hello\xworld") #SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes
# print("hello\yworld")
# print("hello\zworld")
|
9cdf697a26228c198b2915a66ea9d32fae0fa091 | sree-07/PYTHON | /type_casting_convertion.py | 1,113 | 4.46875 | 4 | """int--->float,string"""
# a=7
# print(a,type(a)) #7 <class 'int'>
# b=float(a)
# print(b,type(b)) #7.0 <class 'float'>
# c=str(b)
# print(c,type(c)) #7.0 <class 'str'>
# x=10
# print("the value of x is",x) #the value of x is 10
# print("the value of x is %d"%x) #the value of x is 10
# z=str(x)
# print("the value of z is"+z) #the value of z is10
"""float---->int,string"""
# a=12.5
# print(a,type(a)) #12.5 <class 'float'>
# b=int(a)
# print(b,type(b)) #12 <class 'int'>
# c=str(b)
# print(c,type(c)) #12 <class 'str'>
"""string--->int,float"""
m="python"
print(m,type(m)) #python <class 'str'>
# n=int(m)
# print(n,type(n)) #ValueError: invalid literal for int() with base 10: 'python'
# o=float(m)
# print(o,type(o)) #ValueError: could not convert string to float: 'python'
# x="125"
# print(x,type(x)) #125 <class 'str'>
# y=int(x)
# print(x,type(y)) #125 <class 'int'>
# z=float(x)
# print(z,type(z)) #125.0 <class 'float'>
|
2127d708907ad975ca11a7ae89276e035dc84341 | bilakhiyaasif/SoloLearn_Project | /Python/C-46 Fibonacci series/Solution.py | 283 | 3.875 | 4 | #Fibonacci series
#Recursive Approach
#enter n any number
#like comment
def recu(x1,x2,n):
if n!=0:
z=x1+x2
print(z,end="\n")
x1=x2
x2=z
return recu(x1,x2,n-1)
n=int(input())
x1=0
x2=1
print(x1,end="\n")
print(x2, end="\n")
recu(x1,x2,n-2)
|
212723fd86585c17d19b8b4579e19b8f4d038a49 | mariantirlea/python-blackjack | /utilities/Line.py | 1,893 | 3.859375 | 4 | import re
from abc import ABC, abstractmethod
from colors import strip_color
class Line(ABC):
center_h = False
def __init__(self):
super().__init__()
def center(self, columns, text):
return text.rjust(int((columns - len(text)) / 2) + len(text))
@abstractmethod
def draw(self, columns):
pass
class OneColumnLine(Line):
def __init__(self, text = "", center_h = False):
self.text = text
self.center_h = center_h
def draw(self, columns):
col_width = len(strip_color(self.text))
colored_offset = len(self.text) - int(col_width)
return (self.text if not self.center_h else self.center(columns + colored_offset, self.text)) + "\n"
class TwoColumnsLine(Line):
def __init__(self, col1_text = "", col2_text = "", center_h = False):
self.col1_text = col1_text
self.col2_text = col2_text
self.center_h = center_h
def draw(self, columns):
col1_width = len(strip_color(self.col1_text))
col2_width = len(strip_color(self.col2_text))
colored_offset_1 = len(self.col1_text) - int(col1_width)
colored_offset_2 = len(self.col2_text) - int(col2_width)
if not self.center_h:
return self.col1_text.ljust(int(columns / 2 + colored_offset_1)) + self.col2_text.ljust(int(columns / 2 + colored_offset_2)) + "\n"
else:
return self.center(columns / 2 + colored_offset_1, self.col1_text).ljust(int(columns / 2 + colored_offset_1)) + self.center(columns / 2 + colored_offset_2, self.col2_text).ljust(int(columns / 2 + colored_offset_2)) + "\n"
class LineHelper:
@staticmethod
def draw_lines(columns, lines):
text = ""
for line in lines:
text = text + line.draw(columns)
return text |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.