blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
2c388737f42543942819ef22f8faac2098bff0c3 | SeanLau/leetcode | /problem_167.py | 1,444 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
class Solution(object):
def twoSum(self, numbers, target):
"""
时间复杂度,O(N*logN)
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
def binary_search(mlist, start, end, target):
while end >= start:
mid = (start + end) // 2
if mlist[mid] == target:
return mid
elif mlist[mid] > target:
end = mid - 1
elif mlist[mid] < target:
start = mid + 1
for i in range(len(numbers) - 1):
new_target = target - numbers[i]
res = binary_search(numbers, i + 1, len(numbers) - 1, new_target)
if res:
return i + 1, res + 1
def twoSum2(self, numbers, target):
""""
时间复杂度O(n)
"""
if numbers:
start = 0
end = len(numbers) - 1
while True:
if start == end:
return
temp = numbers[start] + numbers[end]
if temp == target:
return start + 1, end + 1
elif temp > target:
end -= 1
else:
start += 1
pass
if __name__ == '__main__':
l = [2,7,11,15]
s = Solution()
print(s.twoSum2(l, 9))
|
0b303dde589390cf6795a2fc79ca473349c5e190 | SeanLau/leetcode | /problem_104.py | 1,203 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# 此题可以先序遍历二叉树,找到最长的即可
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
depth = 0
if not root:
return depth
result = []
def preOrder(root, depth):
# return root
depth += 1
if root.left:
preOrder(root.left, depth)
if root.right:
preOrder(root.right, depth)
# yield depth
if not (root.left and root.right):
print("## depth in ===>", depth)
result.append(depth)
preOrder(root, depth)
return max(result)
if __name__ == '__main__':
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(2)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right.right = TreeNode(3)
root.right.left = TreeNode(4)
so = Solution()
print(so.maxDepth(root))
|
454512c0eacf9f9471ce330911247e85b5723d71 | SeanLau/leetcode | /problem_190.py | 733 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
class Solution(object):
"""
这里需要注意的是,切片使用的灵活性.
"""
def reverseBits(self, n):
"""
:param n:
:return:
"""
foo = bin(n)
foo_str = str(foo)[2:]
foo_str = foo_str.rjust(32, "0")
foo_str = list(foo_str)
foo_str.reverse()
return int(eval("0b" + "".join(foo_str)))
def reverseBits2(self, n):
s = bin(n)[-1:1:-1]
s += (32 - len(s)) * "0"
return int(s, 2)
def reverseBits3(self, n):
tmp = "{0:032b}".format(n)
return int(tmp[::-1], 2)
if __name__ == '__main__':
s = Solution()
print(s.reverseBits3(43261596)) |
6cfb4c27f0a897695d4b0bf229f64f5d0d5bb378 | SeanLau/leetcode | /problem_160.py | 3,348 | 3.75 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
采用边遍历边判断的方法,实现了功能,但是提交超时
:type head1, head1: ListNode
:rtype: ListNode
"""
if headA is None or headB is None:
return
cur1 = headA
while cur1:
cur2 = headB
while cur2:
if cur1 == cur2:
return cur1
else:
cur2 = cur2.next
cur1 = cur1.next
return
def getIntersectionNode2(self, headA, headB):
"""
采用先遍历后判断的逻辑,此种方法把链表的存储优势浪费了,使用庞大的列表,对空间的需求和遍历也是绝大的开支,仍超时
:param headA:
:param headB:
:return:
"""
listA= []
if headA is None or headB is None:
return
cur1 = headA
while cur1:
listA.append(cur1)
cur1 = cur1.next
cur2 = headB
while cur2:
if cur2 in listA:
return cur2
else:
cur2 = cur2.next
def getIntersectionNode3(self, headA, headB):
"""
两个链表,如果能同步遍历,则是寻找共同节点的最好办法.先找到共同长度
:param headA:
:param headB:
:return:
"""
cur1, cur2 = headA, headB
len1, len2 = 0, 0
while cur1 or cur2:
if cur1:
len1 += 1
cur1 = cur1.next
if cur2:
len2 += 1
cur2 = cur2.next
delta = abs(len1 - len2)
cur1, cur2 = headA, headB
if len1 > len2:
while delta > 0:
cur1 = cur1.next
delta -= 1
elif len2 > len1:
while delta > 0:
cur2 = cur2.next
delta -= 1
while cur1 and cur2:
if cur1 == cur2:
return cur1
cur1 = cur1.next
cur2 = cur2.next
def getIntersectionNode4(self, headA, headB):
"""
车轮战的方式匹配,这种匹配判断逻辑统一,没有程序跳转的过程,用时在提交代码中最短,代码也相对简洁
cur1 = headA + headB
cur2 = headB + headA
这样两者的长度就想相同了,next的步调也是一直的.妙!
:param headA:
:param headB:
:return:
"""
cur1, cur2 = headA, headB
while cur1 and cur2 and cur1 != cur2:
cur1 = cur1.next
cur2 = cur2.next
if cur1 is None:
cur1 = headB
if cur2 is None:
cur2 = headA
if cur1 == cur2:
return cur1
if __name__ == '__main__':
a = ListNode(1)
b = ListNode(3)
c = ListNode(4)
d = ListNode(5)
e = ListNode(6)
f = ListNode(7)
a.next = b
b.next = c
c.next = d
d.next = e
e.next = f
A = ListNode(100)
B = ListNode(200)
A.next = B
B.next = c
s = Solution()
print(s.getIntersectionNode3(a, A).val) |
ee7fb11021cb2d237d0dcc5409c8a91461956339 | vojtsek/tts-utils | /model/model.py | 3,216 | 3.59375 | 4 | '''
A linear regression learning algorithm example using TensorFlow library.
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''
import tensorflow as tf
import argparse
from dataset import Dataset, Utterance
import tensorflow.contrib.layers as tf_layers
ap = argparse.ArgumentParser()
ap.add_argument("-l", type=int)
ap.add_argument("-s", type=int)
ap.add_argument("-e", type=int)
ap.add_argument("--include_gold", action="store_true")
args = ap.parse_args()
no_classes = 4
d = Dataset(length=args.s, dataset_path="dataset.dump")
d.load_data(size=no_classes, include_gold=args.include_gold)
# Parameters
learning_rate = 0.01
training_epochs = args.e
display_step = 2
input_size = d.data_X.shape[1]
batch_size = 8
print(d.data_X.shape)
# batch x frames x order x engines
X = tf.placeholder("float", [None, input_size])
Y = tf.placeholder(tf.int64, [None])
# Set model weights
l1_size = args.l
# W1 = tf.Variable(initial_value=tf.random_uniform([input_size, l1_size], 0, 1), name="weights1", trainable=True)
# b1 = tf.Variable(initial_value=tf.random_uniform([l1_size], 0, 1), name="bias1", trainable=True)
# W2 = tf.Variable(initial_value=tf.random_uniform([100, no_classes], 0, 1), name="weights2", trainable=True)
# b2 = tf.Variable(initial_value=tf.random_uniform([no_classes], 0, 1), name="bias2", trainable=True)
l1 = tf.sigmoid(tf_layers.linear(X, l1_size))
logits = tf_layers.linear(l1, no_classes)
# softmax = tf.nn.softmax(logits)
pred = tf.argmax(logits, axis=1)
# Mean squared error
cost = tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(labels=tf.one_hot(Y, no_classes), logits=logits))
# Gradient descent
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)
# Initializing the variables
init = tf.global_variables_initializer()
# Launch the graph
with tf.Session() as sess:
sess.run(init)
# Fit all training data
# train_X, train_Y = d.get_data()
for epoch in range(training_epochs):
for x, y in d.next_batch():
sess.run([optimizer, cost], feed_dict={X: x, Y: y})
if d.batch_end():
break
# Display logs per epoch step
if (epoch+1) % display_step == 0:
predictions, c = sess.run([pred, cost], feed_dict={X: x, Y:y})
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), "pred=", predictions)
valid_X, valid_Y = d.get_valid()
train_X, train_Y = d.get_train()
predictions, c = sess.run([pred, cost], feed_dict={X: valid_X, Y: valid_Y})
print("Cost: {}, predictions: {}".format(c, predictions))
diff = abs((valid_Y - predictions) != 0)
print("Valid: ", 1 - ((sum(diff)) / len(diff)))
predictions, c = sess.run([pred, cost], feed_dict={X: train_X, Y: train_Y})
print("Cost: {}, predictions: {}".format(c, predictions))
diff = abs((train_Y - predictions) != 0)
print("Train: ", 1 - ((sum(diff)) / len(diff)))
print("Optimization Finished!")
#
# # Graphic display
# plt.plot(train_X, train_Y, 'ro', label='Original data')
# plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
# plt.legend()
# plt.show()
|
de483b8ac3b15b2472aac0ba7baf79f59c4bfb48 | Aromi-s/Assignment-function | /evnorodd.py | 129 | 4.1875 | 4 | num=int(input("Enter a number"))
mode=num%2
if mode>0:
print("This is an odd number")
else:
print("This is an even number") |
467a4efb5a3fde195fbf79387f3d3871f757a979 | Vishruth-S/Hack-CP-DSA | /Hackerrank/drawingbook/solution.py | 2,478 | 3.828125 | 4 | #!/bin/python3
import os
import sys
#
# Complete the pageCount function below.
#
def pageCount(n, p):
#
# Write your code here.
#
pages = []
count = 0
#For turing from page 1.
loop_run_one = 0
#For turning from page n.
loop_run_two = 0
#For storing count from page 1 and page n and then finding the min value from this array.
count_turns = []
#Appending the page numbers.
for i in range(0, n + 1):
pages.append(i)
#checking if total number of pages is odd.
if len(pages) % 2 != 0:
#checking if page to turn is odd.
if p % 2 != 0:
p = p - 1
#Checking and counting the page turns from page 1.
for j in range(0, len(pages), 2):
loop_run_one = loop_run_one + 1
#if pages array equals the page number then turns should be turns - 1. Suppose if we go to page 2 from page 1. Then the loop count will be 2 but we had only one turn so -1.
if j == p:
loop_run_one = loop_run_one - 1
count_turns.append(loop_run_one)
break
#Reversing the pages to start counting from page n.
pages.reverse()
for k in range(0, len(pages), 2):
loop_run_two = loop_run_two + 1
#if pages array equals the page number then turns should be turns - 1. Suppose if we go to page 2 from page 1. Then the loop count will be 2 but we had only one turn so -1.
if pages[k] == p:
loop_run_two = loop_run_two - 1
count_turns.append(loop_run_two)
break
else:
#Checking when page n is even.
if p % 2 != 0:
p = p - 1
for j in range(0, len(pages), 2):
loop_run_one = loop_run_one + 1
if j == p:
loop_run_one = loop_run_one - 1
count_turns.append(loop_run_one)
break
pages.reverse()
p = p + 1
for k in range(0, len(pages), 2):
loop_run_two = loop_run_two + 1
if pages[k] == p:
loop_run_two = loop_run_two - 1
count_turns.append(loop_run_two)
break
if len(count_turns) > 1:
#Checking for min turns required from the count_turns from back and front.
turns = min(count_turns)
else:
turns = 0
return turns
print(pageCount(6,2))
|
22bd9bc0d83a2d0390ad93812f48c6d8924ddee7 | sberen/uninterrupted | /summarizer.py | 2,179 | 3.53125 | 4 | import requests
def summary_from_url(url, sentences):
f = open("key.txt", "r")
querystring = {
"key":f.read(),
"sentences":sentences,
"url":url
}
return summary(querystring)
def summary_from_text(txt, sentences):
f = open("key.txt", "r")
querystring = {
"key":f.read(),
"sentences":sentences,
"txt":txt
}
return summary(querystring)
def summary(querystring):
url = "https://api.meaningcloud.com/summarization-1.0"
response = requests.request("Post", url, headers=None, params=querystring)
data = response.json()
print(data)
return(data["summary"])
#Uncomment for sample usage
# txt = """
# Joe Biden believes to his core that there’s no greater economic engine in the world than the hard work and ingenuity of the American people. Nobody has more respect for the working women and men who get up every day to build and sustain this country, or more confidence that they can meet the challenges we face.
# Make no mistake: America has been knocked down. The unemployment rate is higher than it was in the Great Recession. Millions have lost jobs, hours, pay, health care, or the small business they started, through no fault of their own.
# The pandemic has also laid bare some unacceptable truths. Even before COVID-19, the Trump Administration was pursuing economic policies that rewarded wealth over work and corporations over working families. Too many families were struggling to make ends meet and too many parents were worried about the economic future for their children. And, Black and Latino Americans, Native Americans, immigrants, and women have never been welcomed as full participants in the economy.
# Biden believes this is no time to just build back to the way things were before, with the old economy’s structural weaknesses and inequalities still in place. This is the moment to imagine and build a new American economy for our families and the next generation.
# An economy where every American enjoys a fair return for their work and an equal chance to get ahead. An economy more vibrant and more powerful precisely because everybody will be cut in on the deal.
# """
# print(summary_from_text(txt, 5)) |
c99bae5ac1bfa06c3796c5bb54a1d37d501a5a6a | srhternl/gaih-students-repo-example | /Homeworks/HW3.py | 731 | 3.609375 | 4 | def prime_first(number): # asal sayı hesaplayan 1. fonksiyonum.
if number !=1 and number !=0:
for i in range(2, number):
if number % i == 0:
break
else:
print("Prime numbers between 0-500:", number)
def prime_second(number): # asal sayı hesaplayan 2. fonksiyonum.
if number !=1 and number !=0:
for i in range(2, number):
if number % i == 0:
break
else:
print("Prime numbers between 500-1000:", number)
for i in list(range(1000)): # 0-500 ve 500-1000 arası asal sayıları hesaplayıp, ekrana yazdıran döngüm.
if i < 500:
prime_first(i)
else:
prime_second(i)
|
fb7f473982a26309c9ec086f0595c25ee1df5b2f | thoftheocean/project | /python/0homework/supplement/ascii.py | 226 | 3.984375 | 4 | # !/usr/bin/env python
# coding:utf-8
# author hx
#描述:将ascii码转化为对应的字符。如65
#ascii码转字母 chr()
for i in range(26):
print chr(i+65),
#字母转ascii码 ord()
print '\n', ord('a')
|
4ddcc55205d7213c9e5cc51275bc953053038784 | thoftheocean/project | /python/0homework/search_num.py | 649 | 3.875 | 4 | # !/usr/bin/env python
# coding:utf-8
# author:hx
'''
实现一个函数handler_num,输入为一个任意字符串,请将字符串中的数
字取出,将偶数放入一个列表,再将奇数放入一个列表,并将两个列表返回
'''
str = raw_input('输入一串字符:')
def search_num(str):
even = list()
odd = list()
result1 = dict()
for i in str:
if i.isdigit():
if int(i) % 2 == 0:
even.append(i)
else:
odd.append(i)
else:
continue
result1['even'] = even
result1['odd'] = odd
return result1
print search_num(str)
|
501275ca7933a25249bda2278eca0be3fefb59ea | WiktorSa/Operating-Systems | /OS4/algorithms/equal_algorithm.py | 1,895 | 3.609375 | 4 | import math
from algorithms.algorithm import Algorithm
class EqualAlgorithm(Algorithm):
def perform_simulation(self, processes: list):
original_no_of_frames = self.divide_frames_at_start(processes)
for i in range(len(processes)):
processes[i].lru.set_original_number_of_frames(original_no_of_frames[i])
no_page_errors = 0
# Perform simulation until all processes are finished
no_finished_processes = 0
while no_finished_processes < len(processes):
# Doing one iteration of lru algorithm for every process
for i in range(len(processes)):
if processes[i].state == 'Active':
no_page_errors += processes[i].use_lru()
# The process has finished
if processes[i].state == 'Finished':
no_finished_processes += 1
print("Equal algorithm - number of page errors: ", no_page_errors)
print("Number of page errors for every process: ")
for i in range(len(processes)):
print("Process number: {no} - {no_page_errors}".format(no=i+1, no_page_errors=processes[i].no_page_errors))
self.no_page_errors_process[i] += processes[i].no_page_errors
self.overall_no_page_errors += no_page_errors
# This algorithm will divide frames for every process equally
def divide_frames_at_start(self, processes: list):
# Distributing frames for every process
average_no_frames_per_process = math.floor(self.no_frames / len(processes))
no_frames_per_process = [average_no_frames_per_process] * len(processes)
# Assigning leftover frames
left_frames = self.no_frames - average_no_frames_per_process * len(processes)
for i in range(left_frames):
no_frames_per_process[i] += 1
return no_frames_per_process
|
ceaf75e59c51a4374dc12cc8adee3c3f663449a7 | skiranu/Python_ | /Interface_Abstract_Concrete_class.py | 548 | 3.96875 | 4 | from abc import *
#interface
class Vehicle(ABC):
@abstractmethod
def noOfWheels(self):
pass
def noOfDoors(self):
pass
def noOfExhaust(self):
pass
#abstract class
class Bus(Vehicle):
def noOfWheels(self):
return 7
def noOfDoors(self):
return 2
#concrete class
class Completebus(Bus):
def noOfExhaust(self):
return 2
#object creation and calling
a=Completebus()
print(a.noOfWheels())
print(a.noOfDoors())
print(a.noOfExhaust())
|
2f66a3dbe7423cbee94f32ee46a12af9262ca8d9 | skiranu/Python_ | /unzipping_disp.py | 288 | 3.796875 | 4 | from zipfile import *
f=ZipFile('zippedfiles.zip','r',ZIP_STORED)
content=f.namelist()
for eachfile in content:
k=open(eachfile,'r')
print(k.read())
print('the contents of {} are displayed above'.format(eachfile))
print('unzipping and displaying of files are accomplished!!')
|
7907ca619c61fadfc515d1081b96da4c274954cb | skiranu/Python_ | /Alpha_Ascii_Sequence_2.py | 330 | 3.953125 | 4 | a=input("enter the string:") #Input declaration.
s=k=d=s1=' ' #Variable for loop
for x in a: # loop to check the type of input(either alphabet or digit)
if x.isalpha():
s=x
else:
s1=x
k=k+s+chr(ord(s)+int(s1))
d=d+k
print(d) |
688be646bf564663c8cf00b9dac769a45d2e30fb | skiranu/Python_ | /Dict_Char_Count.py | 190 | 3.765625 | 4 | a=input("Enter the string:")
b={}
for x in a:
b[x]=b.get(x,0)+1
print(b) #dictionary form
for k,v in sorted(b.items()):
print("The number of occurances of : ",k,"is:",v)
|
bcab985c6af25defb7fa3bb752d2c8989f89466b | ardnahcivar/Python | /Learning python/LarryArray.py | 544 | 3.546875 | 4 | if __name__ == "__main__":
t = int(input())
for i in range(t):
inversion_count = 0
n = int(input())
a = [int(i) for i in input().split()]
#print(a)
b = sorted(a)
# print('sorted list is:', b)
for i, j in enumerate(a):
b = a[i+1:]
for k in b:
if k < j:
inversion_count = inversion_count+1
#print(inversion_count)
if(inversion_count%2 ==0):
print('YES')
else:
print('NO') |
8e304fd05a53a20ad9bc8576c4eb8b9dc85f73c2 | fly8764/LeetCode | /Tree/437 pathSum.py | 2,411 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# 题目说明,路径不一定包含根节点和叶子节点,所有,要遍历所有的可能
# 每个节点都可能 在或者不在路径中
# 单递归:从根节点遍历到每个节点时,从该节点往根节点遍历,必须包含该节点连续
# 路径中,其和满足要求的有多少条
# 双递归,包含该节点和不包含该节点,不包含该节点 又分为 左子树 右子树两种
# 其中用到的递归非常好,从符合要求的节点 返回的过程中,把所有的可能结果累加
class Solution(object):
def pathSum(self, root, target):
# 双递归
if not root:
return 0
def dfs(root,target):
if not root:
return 0
cnt = 0
if root.val == target:
cnt += 1
#这种递归循环非常好,从符合要求的节点往上返回,如果只有一种路径,则出栈到最后,结果为1
#在出栈的过程中,增量来自于 另外一个节点(eg右节点)的可能路径,最后得到所有的路径数
cnt += dfs(root.left,target - root.val)
cnt += dfs(root.right,target - root.val)
return cnt
# 这种return 就分为必须包含 根节点 和不包含根节点 两类
return dfs(root,target)+ self.pathSum(root.left,target)+ self.pathSum(root.right,target)
# def pathSum(self, root, target):
# #单递归
# """
# :type root: TreeNode
# :type sum: int
# :rtype: int
# """
# self.cnt = 0 #这里为什么非得要加个self
# path = [] #这里的path就不要加
# def dfs(root):
# if not root:
# return 0
# path.append(root.val)
# tmp = 0
# #这里要算到根节点,因为 可能出现中间几项和为0
# for i in range(len(path)-1,-1,-1):
# tmp += path[i]
# if tmp == target:
# self.cnt += 1
# dfs(root.left)
# dfs(root.right)
# # 别忘了把加入的这个节点 pop()
# path.pop()
# dfs(root)
#
# return self.cnt
|
67c0a68629883bbbc5b2ebe32f5ffb832e458008 | fly8764/LeetCode | /DP/121 maxProfit.py | 2,308 | 4.09375 | 4 | '''
思路:
方法一:
方法二:动态的选取 当前的最大收益 和当前的最小价格(为后面的服务)
当前最大收益 等于 max(当前收益,当前价格与之前最小价格差)
这个当前最大收益和当前最小价格 分别使用一个变量保存当前情况即可,
不需要保存之前的情况,保存了也用不到
'''
#second
class Solution:
def maxProfit(self, prices):
size = len(prices)
if size < 2:return 0
profit = 0
# min_price = float('-inf') #用负数来表示
# for i in range(size):
# profit = max(profit,prices[i] + min_price)
# min_price = max(min_price,-prices[i]) #绝对值最小
# return profit
min_price = float('inf') # 用整数来表示
for i in range(size):
profit = max(profit,prices[i] - min_price)
min_price = min(min_price,prices[i])
return profit
# def maxProfit(self, prices):
# size = len(prices)
# if size < 2:return 0
# dp = [0]*size
# #dp[i]:代表到prices[i]为止的最大收益
# for i in range(1,size):
# #这种方式里面的max() 和min()在数据量大时,容易超时
# #最小价格使用一个变量保存,实时更新即可,使用一个数组保存,查询时耗时
# dp[i] = max(max(dp[i-1]),prices[i]- min(prices[:i]))
# return dp[-1]
if __name__ == '__main__':
so = Solution()
print(so.maxProfit([7,1,5,3,6,4]))
print(so.maxProfit([7,6,4,3,1]))
# class Solution:
# def maxProfit(self, prices):
# length = len(prices)
#
# dp_0 = 0
# dp_1 = -999999
#
# for i in range(length):
# dp_0 = max(dp_0,dp_1 + prices[i])
# dp_1 = max(dp_1,-prices[i])
# return dp_0
#
#
# def maxProfit1(self, prices):
# length = len(prices)
#
# min_p = 99999
# profit = 0
#
# for i in range(length):
# if prices[i]< min_p:
# min_p = prices[i]
# elif prices[i]-min_p > profit:
# profit = prices[i] - min_p
# return profit
#
#
# if __name__ == '__main__':
# so = Solution()
# res = so.maxProfit([7,1,5,3,6,4])
# print(res)
#
|
5f94c757a6e5feee5379278fa951e69e1fbc48a4 | fly8764/LeetCode | /Tree/404 sumOfLeftLeaves.py | 1,160 | 3.859375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.ret = 0
def dfs(self,root):
if not root:
return
if root.left and not root.left.left and not root.left.right:
self.ret += root.left.val
self.dfs(root.left)
self.dfs(root.right)
def sumOfLeftLeaves(self, root):
self.dfs(root)
return self.ret
# def sumOfLeftLeaves(self, root):
# if not root:
# return 0
#
# ret = 0
# parent= [[root.left,root.right]]
# while parent:
# cur = []
# for node in parent:
# left,right = node[0],node[1]
# if left and (not left.left and not left.right):
# ret += left.val
#
# if left:
# cur.append([left.left,left.right])
# if right:
# cur.append([right.left, right.right])
# parent = cur[:]
# return ret
|
628bc364f43090ac70474469d2e708ffa27b02d8 | fly8764/LeetCode | /Tree/104 maxDepth.py | 683 | 3.90625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution1(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return 1+max(self.maxDepth(root.left),self.maxDepth(root.right))
'''
2020/12/8 1:19
深度优先搜索 递归
'''
class Solution:
def maxDepth(self, root):
if not root:
return 0
depth_l = self.maxDepth(root.left)
depth_r = self.maxDepth(root.right)
return max(depth_l,depth_r) + 1
|
9ba3bdd359faaa10341fdd3d8eb98f5b09022945 | fly8764/LeetCode | /Linked/61 rotateRight.py | 2,050 | 3.75 | 4 | # Definition for singly-linked list.
'''
注意点:
1. 空节点
2.k值的大小,k一般在长度范围内cnt,
如果大于长度范围cnt,要把k对cnt取余,使其在cnt范围内
取余要注意cnt = 1的特殊情况,取余无效,其实这时候就不用再算了,
长度为1的链表,怎么旋转都不会变化
3.cnt = 1,这个一上来要想到,不然后面就可能忘了
方法一:找到链表的长度,把后面k个节点一整串的拼接到开头
方法二:双指针法,也是先找到链表长度,再把后面k个节点使用双指针法 一个一个地
调换到前面
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def rotateRight1(self, head, k):
#双指针法
pass
def rotateRight(self, head, k):
if k == 0 or not head:
return head
dummy = ListNode(0)
cnt = 0
dummy.next = head
pre = dummy
while pre.next:
pre = pre.next
cnt += 1
if cnt == 1:
return head
#标记尾巴节点
end = pre
#k作为除数,要注意k=0的情况,
# if k > cnt:
# temp = k//cnt
# k = k - cnt*temp
# if k == 0:
# return head
# k = 1时,无效
k %= cnt
if k == 0:
return head
#找到倒数第k+1个节点,next置为空None,执行cnt - k次操作
node = dummy
for _ in range(cnt -k):
node= node.next
new_start = node.next
node.next = None
end.next = dummy.next
dummy.next = new_start
return dummy.next
if __name__ == '__main__':
so = Solution()
a = ListNode(1)
start = a
# for i in range(2,6):
# a.next = ListNode(i)
# a = a.next
# while start:
# print(start.val)
# start = start.next
res = so.rotateRight(start,k = 12)
while res:
print(res.val)
res = res.next
|
62538b8fd6f4befdbe1fbd8635f6ed884eb50716 | fly8764/LeetCode | /Tree/257 binaryTreePaths.py | 1,189 | 3.578125 | 4 | class Solution(object):
def binaryTreePaths(self, root):
if not root:
return []
if not root.left and not root.right:
return [str(root.val)]
left, right = [], []
if root.left:
left = [str(root.val) + '->' + x for x in self.binaryTreePaths(root.left)]
if root.right:
right = [str(root.val) + '->' + x for x in self.binaryTreePaths(root.right)]
return left + right
# def binaryTreePaths(self, root):
# """
# :type root: TreeNode
# :rtype: List[str]
# """
# if not root.left and not root.right:
# return [str(root.val)]
# left,right = [],[]
#
# if not root.left:
# for x in self.binaryTreePaths(root.left):
# left += [str(root.val)+ '->'+ str(x)]
# for x in self.binaryTreePaths(root.right):
# right += [str(root.val) + '->'+str(x)]
#
# # left = [str(root.val) + '->'+str(x) for x in self.binaryTreePaths(root.left)]
# # right = [str(root.val) + '->'+str(x) for x in self.binaryTreePaths(root.right)]
# return left + right |
5def0d595f79218e4cb62f249a1fa1a56dc4668d | fly8764/LeetCode | /Bit Manipulation/342 isPowerOfFour.py | 877 | 3.640625 | 4 | class Solution:
def isPowerOfFour(self, n):
#1.4的幂 最高位的1 都在奇数位上,所以判断最高位的1是否在奇数位,
#2.或者奇数位只有一个1
#1.0x5 0101 &(0100)(4)== 0100(num) 判断奇数位上的1
#2.16进制 a:1010 都在偶数位上,(0100)(4)&(1010)(a)== 0 表示在奇数位上
#0xaaaaaaaa&n == 0
# return n > 0 and not n&(n-1) and n&(0x55555555) == n
return n > 0 and not n&(n-1) and n&(0xaaaaaaaa) == 0
def isPowerOfFour0(self, n):
#4的幂 是1 左移 2n位的结果,
if n & (n-1):
return False
temp = 1
while temp < n:
temp <<= 2
if temp == n:
return True
else:
return False
if __name__ == "__main__":
so = Solution()
res = so.isPowerOfFour(16)
print(res)
|
19af6699431a5b3892d415b2941aa893a8c1bdea | fly8764/LeetCode | /Linked/92 reverseBetween.py | 7,775 | 4.15625 | 4 | # Definition for singly-linked list.
'''
方法一:递归法
问题:反转前N个节点
第N+1个节点,successor节点
递归解决,当N=1时,记录successor节点,successor = head.next
和全部反转不同,最后一个节点的next要指向 successor;head.next = successor
问题:反转第m到第n个节点
递归
一直到m= 1,则此时相当于反转前N个节点,
然后把之前的节点拼接起来
这里的递归返回的节点不像 全部反转或反转前N个节点,
这里返回的是正常的节点,相当于才重新拼接一下
方法二:双指针法
in-place
找到第m-1个节点pre,和第m个节点cur
从左往后遍历的过程中,更新 cur.next,pre.next,使得这两个节点反转,
并更新这两个节点,cur.next = temp.next在刚开始更新,pre.next = temp在最后更新
方法三:三指针法
类似于下面的双指针法,只不过这里把tail单独拎出来,并更新,
下面的双指针法,tail每次需要时生成,
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution1:
def __init__(self):
self.successor = None
def reverseBetween1(self, head, m, n):
# 这种方法没有在开头插入一个哑节点,所以当遇到m = 1时,
# 没有前面的头指针,即哑节点来拼接后面的反转链表
if m >= n or not head:
return head
start = head
idx = 1
while idx < m-1:
#先不直接到达第m个节点,因为后面要通过next把后面的拼接起来
head = head.next
idx += 1
#找到第n+1个节点,最后把其节点反转好的链表后面
new = head
new_idx = idx
while new_idx <n+1:
new = new.next
new_idx += 1
#为了保存head,后面要通过head.next把反转后的链表接上去
node = head.next
idx += 1
pre_node =None
p = ListNode(0)
while idx < n+1:
idx += 1
p = ListNode(node.val)
p.next = pre_node
pre_node = p
node = node.next
head.next = p
while head.next:
head = head.next
head.next = new
return start
def reverseBetween2(self, head, m, n):
if m >= n or not head:
return head
start = ListNode(0)
start.next = head
p = start
idx = 0
while idx < m-1:
#先不直接到达第m个节点,因为后面要通过next把后面的拼接起来
p = p.next
idx += 1
#找到第n+1个节点,最后把其接在反转好的链表后面
new = p
new_idx = idx
while new_idx <n+1:
new = new.next
new_idx += 1
#为了保存head,后面要通过head.next把反转后的链表接后面
#node 第m个节点
node = p.next
idx += 1
pre_node =None
point = ListNode(0)
while idx < n+1:
point = ListNode(node.val)
point.next = pre_node
pre_node = point
node = node.next
idx += 1
p.next = point
while p.next:
p = p.next
p.next = new
return start.next
def reverseBetween3(self, head, m, n):
#三指针法 哑光节点为m= 1考虑的 in-place 在原链表上改变
#类似于下面的双指针法,只不过这里把tail单独拎出来,并更新,
#下面的双指针法,tail每次需要时生成,
dummy = ListNode(0)
dummy.next = head
pre = dummy
#找到要反转的起始点的上一个节点,即第m-1个节点
for _ in range(m-1):
pre = pre.next
#使用三指针pre,start,tail
#cnt个节点,往前调换cnt-1次即可
start = pre.next
tail = start.next #tail紧接在start后面
for _ in range(n-m):
start.next = tail.next
tail.next = pre.next
pre.next = tail
tail = start.next
return dummy.next
def reverseBetween4(self, head, m, n):
#双指针法、哑节点 非常好 in-place 相比于三指针法 更简洁一些
dummy = ListNode(0)
dummy.next = head
pre = dummy
#pre始终是第m-1个节点
for _ in range(m-1):
pre = pre.next
cur = pre.next
#这里的循环,cur不改变
for _ in range(n-m):
temp = cur.next
cur.next = temp.next
# 下面只能用 pre.next,不能用cur,cur只在刚开始可以,后面就不行了,pre.next最准。
temp.next = pre.next
pre.next = temp
return dummy.next
def reverseList(self, node):
if not node:
return node
if not node.next:
return node
last = self.reverseList(node.next)
node.next.next = node
node.next = None
return last
def reverseN(self,head,n):
if not head:
return head
if n == 1:
self.successor = head.next
return head
last = self.reverseN(head.next,n-1)
head.next.next = head
head.next = self.successor
return last
def reverseBetween(self, head, m, n):
# 递归法
if m == 1:
return self.reverseN(head,n)
head.next = self.reverseBetween(head.next,m-1,n-1)
return head
'''
2020/12/13 16:40
第二次做,一上来就去找交界处左右两边的点,一共四个点,然后把m-n的节点反转,最后再重新连接到原链表上。
起始只要找到第m-1个节点即可,然后 in-place的方式直接在原链表上进行修改,比较间接。
注意:反转链表时注意细节,
cur = pre.next
for _ in (n-m):
tmp = cur.next
cur.next = tmp.next
# 下面只能用 pre.next,不能用cur,cur只在刚开始可以,后面就不行了,pre.next最准。
tmp.next = pre.next
pre.next = tmp
'''
class Solution:
# 常规做法
def reverseBetween1(self, head, m, n):
if not head or not head.next:
return head
dummy = ListNode(-1)
dummy.next = head
left,right = head,head
first = dummy
tail = head.next
l,r = 1,1
while r < n:
r += 1
right = right.next
tail = tail.next
while l < m:
l += 1
left = left.next
first = first.next
s,e = m,n
pre = None
mnode = None
mflag = True
while s <= e:
s += 1
node = ListNode(left.val)
if mflag:
mnode = node
mflag = False
node.next = pre
pre = node
left = left.next
first.next = pre
mnode.next = tail
return dummy.next
# 简便一些
def reverseBetween(self, head, m, n):
if not head or not head.next:
return head
dummy = ListNode(-1)
dummy.next = head
pre = dummy
for _ in range(m-1):
pre = pre.next
cur = pre.next
for _ in (n-m):
tmp = cur.next
cur.next = tmp.next
tmp.next = pre.next
pre.next = tmp
return dummy.next
if __name__ == '__main__':
so = Solution()
a = ListNode(3)
a.next = ListNode(5)
m= 1
n = 2
res = so.reverseBetween(a,m,n)
while res:
print(res.val)
res = res.next |
4d6575ccd0f71b77f94f037547af970f1d1a4ce4 | fly8764/LeetCode | /sort/386 lexicalOrder.py | 895 | 3.515625 | 4 | class Solution:
# def __init__(self):
# self.res = []
#
# def find(self,m,n):
# if m > n:
# return
# self.res.append(m)
#
# t = m*10
# for i in range(10):
# self.find(t+i,n)
#
# def lexicalOrder(self, n):
# res = []
# for i in range(1,10):
# self.find(i,n)
# return self.res
def __init__(self):
self.res = []
self.n = 0
def dfs(self,temp):
for i in range(10):
ans = temp*10 + i
if ans <= self.n:
if ans > 0:
self.res.append(ans)
self.dfs(ans)
else:return
def lexicalOrder(self, n):
self.n = n
self.dfs(0)
return self.res
if __name__ == '__main__':
so = Solution()
res = so.lexicalOrder(13)
print(res)
|
443f43d8573c1f93becc0c91150fcc81f5a82634 | fly8764/LeetCode | /sort/insert_sort.py | 9,983 | 3.5625 | 4 | class Solution1:
def __init__(self):
self.size = 0
def insetSort(self,nums):
#T(n) = n**2
#从前往后遍历
size = len(nums)
if size < 2:
return nums
for i in range(1,size):
j = i-1
temp = nums[i]
#扫描,从后往前扫描
while j > -1 and nums[j] > temp:
nums[j+1] = nums[j] #较大值往后挪
j -= 1
nums[j+1] = temp
return nums
def shellSort(self,nums):
#T(n) = n*logn
# 实际遍历时,不是 在一定间隔下,把一个子序列简单插入排序后,再对下一个子序列排序
# 而是 把所有的从前(nums[d])到后逐元素的进行,排序时找到前面间隔d的元素比较
# 一种子序列拍完了
size = len(nums)
if size < 2:
return nums
d = size//2
while d > 0:
for i in range(d,size):
temp = nums[i]
j = i - d
while j > -1 and nums[j] > temp:
#这里注意 nums[j] > temp而不是 nums[j]> nums[j+d](下面第一行会更行nums[j+d])
nums[j+d] = nums[j]
j -= d
nums[j+d] = temp
d //= 2
return nums
def bubbleSort(self,nums):
#T(n) = n**2
size = len(nums)
if size < 2:return nums
for i in range(1,size):
for j in range(i-1,-1,-1):
if nums[j] > nums[j+1]:
temp = nums[j+1]
nums[j+1] = nums[j]
nums[j] = temp
return nums
# def quickSort(self,nums):
#递归
#方法一:开辟新的数组
# size = len(nums)
# if size < 2:return nums
# temp = nums[0]
# left_sub = []
# right_sub = []
#
# for i in range(1,size):
# if nums[i] < temp:
# left_sub.append(nums[i])
# else:
# right_sub.append(nums[i])
# left = self.quickSort(left_sub)
# right = self.quickSort(right_sub)
# return left+[temp] + right
# def quickSort(self,nums,s,t):
#这里理解错了,
#实际上,每次swap 都是在调整 pivot的位置,当左右指针相等时,pivot的位置也调整好了,
#不用在最后再次调整 开头与i的位置元素,即 nums[left] = temp
# left = s
# right = t
# if s < t:
# temp = nums[s]
# while left < right: #从两边往中间扫描,直到left == right
# while right > left and nums[right] > temp:
# right -= 1
# if left < right: #看是上面哪个条件跳出来的
# 先不管 nums[left]的大小如何,先交换到右边的nums[right]再说,到那边再比较
# tmp = nums[left]
# nums[left] = nums[right]
# nums[right] = tmp
# left += 1
# while left < right and nums[left] < temp:
# left += 1
# if left < right:#先不管 nums[right]的大小如何,先交换到左边的nums[left]再说,到那边再比较
# tmp = nums[right]
# nums[right] = nums[left]
# nums[left] = tmp
# right -= 1
# nums[left] = temp #这一步不需要
# self.quickSort(nums,s,left-1)
# self.quickSort(nums,left+1,t)
def swap(self,nums,i,j):
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
def partition(self,nums,s,t):
#从左往右逐个扫描,而不是像上面那个解法,左右两边同时向中间扫描,直到相等
#这种方法 每次需要调整位置时,都要交换一次位置,操作数比较多
pivot = s
index = pivot + 1
temp = nums[pivot]
for i in range(pivot+1,t+1):
if nums[i] < temp:
self.swap(nums,i,index)
index += 1
self.swap(nums,pivot,index-1)
return index - 1
def quickSort(self,nums,s,t):
if s == t:return nums
elif s < t:
# 不要把partition写在里面,不然变量的作用范围容易受到影响;
# 最好写在外面
pivot = self.partition(nums, s, t)
self.quickSort(nums, s, pivot - 1)
self.quickSort(nums, pivot + 1, t)
def selectSort(self,nums):
#类似于冒泡排序,只不过,是在找到未排列 列表中的最小元素与 表头元素交换
size = len(nums)
def mergeSort(self,nums):
#递归,从上到下 递归,从下到上返回;
#递归题目:先假设 递归函数存在,拿过来直接用;然后,考虑如何处理边界情况
size = len(nums)
if size < 2:return nums
mid = size//2
left = nums[:mid]
right = nums[mid:]
return self.merge(self.mergeSort(left),self.mergeSort(right))
def merge(self,left,right):
res = []
while left and right:
if left[0] < right[0]:
res.append(left.pop(0))
else:
res.append(right.pop(0))
while left:
res.append(left.pop(0))
while right:
res.append(right.pop(0))
return res
def buildMaxheap(self,nums):
#这里从size//2开始往前遍历有两个好处
#1.类似于从完全二叉树的倒数第二层开始调整堆,2*i+1 2*i+2分别对应 节点i的左右子节点
#2.从后往前,从下往上,一层一层地“筛选”,保证最大的元素在堆顶。类似于冒泡
self.size = len(nums)
for i in range(self.size//2,-1,-1):
self.heapify(nums,i)
def heapify(self,nums,i):
left = 2*i + 1
right = 2*i + 2
largest = i
if left < self.size and nums[left] > nums[largest]: largest = left
if right < self.size and nums[right] > nums[largest]: largest = right
if largest != i:
#继续递归,使得上面调整后,下面的堆 仍然符合最大/小 堆的要求
self.swap(nums, i, largest)
self.heapify(nums, largest)
def heapSort(self,nums):
#最大堆排序
self.bubbleSort(nums)
for i in range(self.size-1,0,-1):
#把堆顶元素放到后面,最小元素放在堆顶,后面再重新调整堆;同时为处理的列表长度减1
self.swap(nums,0,i)
self.size -= 1
#从堆顶开始重新调整堆,原先的堆整体往上升了一层
self.heapify(nums,0)
return nums
def buildMinheap(self,nums):
self.size = len(nums)
for i in range(self.size//2,-1,-1):
self.heapifyMin(nums,i)
def heapifyMin(self,nums,i):
left = 2*i + 1
right = 2*i + 2
least = i
if left < self.size and nums[left] < nums[least]: least = left
if right < self.size and nums[right] < nums[least]:least = right
if least != i:
self.swap(nums,i,least)
self.heapifyMin(nums,least)
def heapSortMin(self,nums):
#T(n) = (n/2)logn + nlogn
#要保证 不改变 完全二叉树的 结构,因为在调整堆时,有 left = 2*i + 1 等的存在,要用到堆的结构
#因此,最小堆排序只能 额外申请一个数组,每次保存 堆顶的最小值,
#之后把右小角的值 交换到 堆顶,删除末尾元素,修改堆的长度,再次调整堆
res = []
self.buildMinheap(nums)
for i in range(self.size):
res.append(nums[0])
#把最大元素放到堆顶,之后删掉最后一个元素,修改堆的长度
self.swap(nums,0,self.size-1)
nums.pop()
self.size -= 1
self.heapifyMin(nums,0)
return res
def radixSort(self,nums):
maxx = max(nums)
bit = 0
while maxx:
bit += 1
maxx //= 10
mod = 10
dev = 1
for i in range(bit):
temp = {}
for j in range(len(nums)):
bucket = nums[j]%mod//dev
if bucket not in temp:
temp[bucket] = []
temp[bucket].append(nums[j])
cur = []
for idx in range(10):
if idx in temp:
cur.extend(temp[idx])
nums = cur[:]
mod *= 10
dev *= 10
return nums
class Solution:
def quickSort(self,nums,s,t):
if s >=t:
return
# 这里需要额外的变量保存边界索引,
l,r = s,t
temp = nums[l]
while l < r:
while r > l and nums[r] > temp:
r -= 1
if r > l:
nums[l] = nums[r]
l += 1
while l < r and nums[l] < temp:
l += 1
if l < r:
nums[r] = nums[l]
r -= 1
nums[l] = temp
self.quickSort(nums,s,l-1)
self.quickSort(nums,l+1,t)
def heapSort(self,nums):
pass
if __name__ == '__main__':
so = Solution()
nums = [4,1,5,3,8,10,28,2]
print(nums,'raw')
print(sorted(nums),'gt')
# res = so.insetSort(nums[:])
# print(res)
# res2 = so.shellSort(nums[:])
# print(res2)
# res3 = so.bubbleSort(nums[:])
# print(res3,'bubbleSort')
so.quickSort(nums,0,len(nums)-1)
print(nums)
# res = so.mergeSort(nums)
# print(res)
res = so.heapSort(nums[:])
print(res)
# res = so.heapSortMin(nums[:])
# print(res)
# res = so.radixSort(nums[:])
# print(res) |
c2d2c20ed5eab1db361735ead1d82573231ccdf5 | fly8764/LeetCode | /Tree/429 levelOrderN.py | 1,255 | 3.625 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution1:
def levelOrder(self, root):
if not root:
return []
res = []
parent = [root]
while parent:
child = []
cur = []
for _ in range(len(parent)):
node = parent.pop(0)
cur.append(node.val)
if node.children:
child.extend(node.children)
res.append(cur)
parent = child[:]
return res
'''
2020/12/7 22:40
node.children是个列表,需要注意
'''
class Solution:
def levelOrder(self, root):
if not root:
return []
res = []
parent = [root]
while parent:
children = []
tmp_res = []
# 有两种遍历方式
for node in parent:
# for _ in range(len(parent)):
# node = parent.pop(0)
tmp_res.append(node.val)
if node.children:
children.extend(node.children[:])
res.append(tmp_res)
parent = children[:]
return res |
911f7a55fcbe555fab00846892307a841e906bc5 | fly8764/LeetCode | /Linked/328 oddEvenList.py | 1,088 | 3.78125 | 4 | # Definition for singly-linked list.
'''
大致思路:
把奇偶位置的节点分开,各自串接自己一类的节点,最后在拼接起来
使用双指针,一个是奇数节点,一个是偶数节点
在开头别忘了使用一个临时节点,保存第一个偶数节点,后面把其拼接在奇数尾节点的后面
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def oddEvenList(self, head):
if not head or not head.next:
return head
odd = head
even = head.next
temp = head.next
#while循环里面的三个条件,有顺序要求
#首先判断even,其来自于head.next,有可能为空
#even不为空,则可以判断 even.next
#odd = head,在开头已经判断了,不为空,可以直接判断odd.next
while even and even.next and odd.next:
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
odd.next = temp
return head
|
22a46ad25d160525a0137a0ef1833d2845b89aff | AmrEsam0/HackerRank | /python3/2d_Array_DS.py | 709 | 3.609375 | 4 | #!/bin/python3
def list_sum(l):
total = 0
for i in range(len(l)):
total = total + l[i]
return total
def hourglassSum(arr):
max = -1000
s= []
sub_array = []
for m in range(4):
for col in range(4):
for row in range(3):
sub_array.append(arr[row + m][col: col + 3])
s = sub_array
hour_sum = list_sum(s[0]) + s[1][1] + list_sum(s[2])
if (max < hour_sum):
max = hour_sum
sub_array = []
return max
if __name__ == '__main__':
arr = [list(map(int, input().split())) for y in range(6)]
print(hourglassSum(arr))
|
e3fc26f817596ff52cf7a97933ea0c192c5cef42 | dsintsov/python | /labs/lab1/lab1-1_7.py | 989 | 4.125 | 4 | # № 7: В переменную Y ввести номер года. Определить, является ли год високосным.
"""
wiki: год, номер которого кратен 400, — високосный;
остальные годы, номер которых кратен 100, — невисокосные (например, годы 1700, 1800, 1900, 2100, 2200, 2300);
остальные годы, номер которых кратен 4, — високосные
"""
# Checking the user input
while True:
Y = input("Enter a year: ")
try:
if int(Y) > 0:
break # input is INT and greater than 0
else:
raise TypeError() # just call an exception
except:
print("ERR: \"{0}\" - it\'s NOT a valid year number, try again!".format(str(Y)))
Y = int(Y)
print(str(Y), end='')
if Y % 400 == 0 or Y % 4 == 0 and Y % 100 != 0:
print(" - is a leap year")
else:
print(" - isn't a leap year")
exit(0)
|
0d6c52bea723ecd9bd447f2b0962b4fb2f8876c5 | Kenjal1992/Kenjal_Python | /Assignment_6.py | 365 | 3.9375 | 4 | def CheckNumber(no):
if no>0:
print("{} is Positive Number".format(no))
elif no<0:
print("{} is Negative Number".format(no))
else:
print("{} is Zero".format(no))
def main():
print("Enter the number:")
n=int(input())
CheckNumber(n)
if __name__=="__main__":
main() |
61108fc4bf8d95401c043bf945d49567192ed9f3 | Kenjal1992/Kenjal_Python | /Assignment_7.py | 216 | 3.765625 | 4 | def Printstar(no):
for i in range (0,no):
print("*")
def main():
print("Enter the number:")
n=int(input())
Printstar(n)
if __name__=="__main__":
main()
|
c608249eb220babe22952f716e4c378ec3501ea4 | jjalomo93/Python-Analysis | /PyRamen/main.py | 5,151 | 3.921875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# import libraries
from pathlib import Path
import csv
# In[2]:
# Read in `menu_data.csv` and set its contents to a separate list object.
# (This way, you can cross-reference your menu data with your sales data as you read in your sales data in the coming steps.)
# set the file path for menu_csv
menu_path = Path("Resources/menu_data.csv")
# In[3]:
# Initialize an empty `menu` list object to hold the contents of `menu_data.csv`.
menu = []
# In[4]:
# Use a `with` statement and open the `menu_data.csv` by using its file path.
with open(menu_path, "r") as csvfile:
# Use the `reader` function from the `csv` library to begin reading `menu_data.csv`.
menu_reader = csv.reader(csvfile, delimiter=",")
# Use the `next` function to skip the header (first row of the CSV).
menu_header = next(menu_reader)
# Loop over the rest of the rows and append every row to the `menu` list object (the outcome will be a list of lists).
for row in menu_reader:
# add items to the menu list
menu.append(row)
# In[5]:
# Set up the same process to read in `sales_data.csv`. However, instead append every row of the sales data to a new `sales` list object
# set the file path for sales_data
sales_path = Path("Resources/sales_data.csv")
# In[6]:
# Initialize an empty 'sales' list object to hold the contents of 'sales_data.csv'
sales = []
# In[7]:
# Use a `with` statement and open the `sales_data.csv` by using its file path.
with open(sales_path, "r") as csvfile:
# Use the `reader` function from the `csv` library to begin reading `menu_data.csv`.
sales_reader = csv.reader(csvfile, delimiter=",")
# Use the `next` function to skip the header (first row of the CSV).
sales_header = next(sales_reader)
# Loop over the rest of the rows and append every row to the `menu` list object (the outcome will be a list of lists).
for row in sales_reader:
# add items to the menu list
sales.append(row)
# In[8]:
# Initialize an empty `report` dictionary to hold the future aggregated per-product results.
# The `report` dictionary will eventually contain the following metrics:
# * `01-count`: the total quantity for each ramen type
# * `02-revenue`: the total revenue for each ramen type
# * `03-cogs`: the total cost of goods sold for each ramen type
# * `04-profit`: the total profit for each ramen type
report = {}
# In[9]:
# Then, loop through every row in the `sales` list object.
for sales_data in sales:
# For each row of the `sales` data, set the following columns of the sales data to their own variables:
# * Quantity
# * Menu_Item
quantity = int(sales_data[3])
menu_item = sales_data[4]
# define variable for the record
record = {"01-count": 0, "02-revenue": 0, "03-cogs": 0, "04-profit": 0,}
# Perform a quick check if the `sales_item` is already included in the `report`.
if menu_item not in report:
# If not, initialize the key-value pairs for the particular `sales_item` in the report.
# Then, set the `sales_item` as a new key to the `report` dictionary and the values as a nested dictionary containing the record
report[menu_item] = record
# set the elif to add the "quantity" data to the count
if menu_item in report:
report[menu_item]["01-count"] += quantity
# In[11]:
# Create a nested loop by looping through every record in 'menu'
for sales_data in sales:
# set the values to compare against menu data
quantity = int(sales_data[3])
menu_item = sales_data[4]
for menu_data in menu:
# For each row of the `menu` data, set the following columns of the menu data to their own variables:
item = menu_data[0]
price = float(menu_data[3]) # float because there are decimals in price data
cost = int(menu_data[4])
# If the `sales_item` in sales is equal to the `item` in `menu`
# capture the `quantity` from the sales data and the `price` and `cost` from the menu data to calculate the `profit` for each item.
if menu_item == item:
report[item]["02-revenue"] += (quantity * price)
report[item]["03-cogs"] += (quantity * cost)
# else:
# print(f"{menu_item} does not equal {item}! NO MATCH!)
# In[14]:
# define and add the profit to the report (revenue - cogs)
# use nested for loop to calculate at the individual level
for menu_item, value_dict in report.items():
for key in value_dict:
# define the revenue, cogs, and profit variables
revenue = report[menu_item]["02-revenue"]
cogs = report[menu_item]["03-cogs"]
profit = (revenue - cogs)
# set the profit based on the "04-profit" key value
if key == "04-profit":
report[menu_item][key] = profit
# In[17]:
# print(report) to check values
# In[20]:
# set the output path for the text file
output_path = "pyramen_results.txt"
# In[21]:
# write the text file
with open(output_path, "w") as file:
for key in report:
file.write(f"{key} {report[key]}\n")
|
663b7ccb52e70b73824fe5f431fdc48c4e1e649a | MKerbleski/Data-Structures | /linked_list/linked_list.py | 2,989 | 3.75 | 4 | """
Class that represents a single linked
list node that holds a single value
and a reference to the next node in the list
"""
class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.next_node
def set_next(self, new_next):
self.next_node = new_next
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def add_to_tail(self, value):
new_node = Node(value)
if self.head == None:
self.head = new_node
self.tail = new_node
else:
self.tail.set_next(new_node)
# takes the current node 1 and points to new node
self.tail = new_node
# assigns the new node
self.tail.set_next(None)
pass
def remove_head(self):
# print("------------remove--------")
if self.head == None:
return None
else:
old = self.head.value
nextt = self.head.get_next()
if nextt == None:
self.head = None
self.tail = None
return old
else:
self.head = nextt
if old == None:
return None
else:
return old
pass
def contains(self, value):
# print("----------contains--------")
if self.head == None:
return False
else:
if self.head.value == value:
return True
else:
x = self.head.get_next()
while x != None:
if x.value == value:
return True
else:
x = x.get_next()
return False
pass
def get_max(self):
print("----------get_max--------")
if self.head == None:
return None
else:
global maxx
maxx = 0
x = self.head
while x!= None:
if x.value > maxx:
maxx = x.value
else:
x = x.get_next()
return maxx
pass
# notes
# def add_to_tail(self, value):
# print(self.tail, '-- self.tail A')
# print(self.head, '-- self.head A')
# new_node = Node(value)
# print(new_node.get_value(), '-- new_node value')
# if self.head == None:
# print('no head', new_node)
# self.head = new_node
# print(self.head, '-- self.head B')
# print(self.head.value, '-- self.head C')
# self.tail = new_node
# print(self.tail.value, '-- self.tail.value B')
# print(self.head.get_next(), '41')
# else:
# self.tail.set_next(new_node)
# # takes the current node 1 and points to new node
# self.tail = new_node
# # assigns the new node
# self.tail.set_next(None)
# print(self.tail.value, '-- self.tail B')
# print(self.tail.get_next(), '-- self.tail next B')
# print(self.head.get_next().value, '46')
# print(self.head.value, self.head.get_next(), self.head.get_next().get_next().value)
# pass
|
b263615206c83b6d159fa7e138052a007b3940b9 | billdonghp/Python | /variable.py | 514 | 3.8125 | 4 | '''
变量的作用域
'''
salary = 7000
def raiseSalary(salary): #salary形参
salary += salary * 0.08
raiseSalary(salary)
print("raiseSalary加薪后:%d"%(salary))
def raiseSalaryII(salary): #通过返回值影响
salary += salary * 0.08
return salary
salary = raiseSalaryII(salary)
print("raiseSalaryII加薪后:%d"%(salary))
def raiseSalaryIII():
global salary #使用全局变量
salary += salary * 0.1
raiseSalaryIII()
print("raiseSalaryIII加薪后:%d"%(salary))
|
24ef3ae3700fb03f7376673ee39067c362eee76a | billdonghp/Python | /stringDemo.py | 877 | 4.25 | 4 | '''
字符串操作符 + *
字符串的长度 len
比较字符串大小
字符串截取 [:] [0:]
判断有无子串 in not in
查找子串出现的位置 find() index() 不存在的话报错
encode,decode
replace(old,new,count)、count(sub,start,end)
isdigit()、startswith
split、join '-'.join('我爱你中国')
隔位截取str1[::2] = str1[0:-1:2] start 和end不写时为全部;step=2 如果 step为负数时,倒序截取;
'''
str1 = 'hello'
a = 'a'
b = 'b'
def stringEncode(str):
myBytes = str.encode(encoding='utf-8')
return myBytes
if __name__ == "__main__":
print(len(str1))
print(a < b)
print('中国' < '美国') #utf-8中 美比中大
print(str1[2:])
print(str1.upper())
sEncode = stringEncode('我爱你中国')
print(sEncode.decode(encoding='utf-8'))
print(str1.find('7'))
print(str1[::-1])
pass
|
a38739c2fa2c242811821ac1232993c8abf52047 | billdonghp/Python | /Person.py | 787 | 3.890625 | 4 | '''
封装人员信息
Person类
'''
class Person:
#属性
name = "林阿华"
age = 20
rmb = 50.0
#构造方法 外界创建类的实例时调用
#构选方法是初始化实例属性的最佳时机
def __init__(self,name,age,rmb):
print("老子被创建了")
self.name = name
self.age = age
self.rmb = rmb
#
def __str__(self):
return "{name:%s,age:%d,rmb:%s}"%(self.name,self.age,format(self.rmb,".2f"))
#方法或函数
#self 类的实例
#自我介绍方法
def tell(self):
print("我是%s,我%d岁了,我有%s元"%(self.name,self.age,format(self.rmb,".2f")))
if __name__ =='__main__':
p = Person("易中天",50,100000.0)
p.tell()
print(p)
|
79cae2d6bab2e3f3ae2bdd46882a0546c6f44b5e | izmailovpavel/gplib | /gplib/covfun/cov_base.py | 2,322 | 3.5 | 4 | import numpy as np
from abc import ABCMeta, abstractmethod
from .utility import pairwise_distance, stationary_cov
class CovarianceFamily:
"""This is an abstract class, representing the concept of a family of covariance functions"""
__metaclass__ = ABCMeta
@abstractmethod
def covariance_function(self, x, y, w=None):
"""
A covariance function
:param x: vector
:param y: vector
:param w: hyper-parameters vector of the covariance functions' family
:return: the covariance between the two vectors
"""
pass
@staticmethod
@abstractmethod
def get_bounds():
"""
:return: The bouns on the hyper-parameters
"""
pass
@abstractmethod
def set_params(self, params):
"""
A setter function for the hyper-parameters
:param params: a vector of hyper-parameters
:return: CovarianceFamily object
"""
pass
@abstractmethod
def get_params(self):
"""
A getter function for the hyper-parameters
:param params: a vector of hyper-parameters
:return: CovarianceFamily object
"""
pass
@abstractmethod
def get_derivative_function_list(self, params):
"""
:return: a list of functions, which produce the derivatives of the covariance matrix with respect to
hyper-parameters except for the noise variance, when given to the covariance_matrix() function
"""
pass
@abstractmethod
def covariance_derivative(self, x, y):
"""derivative wrt x"""
def get_noise_derivative(self, points_num):
"""
:return: the derivative of the covariance matrix w.r.t. to the noise variance.
"""
return 2 * self.get_params()[-1] * np.eye(points_num)
def __call__(self, x, y, w=None):
return self.covariance_function(x, y, w)
class StationaryCovarianceFamily(CovarianceFamily):
"""This is an abstract class, representing the concept of a family of stationary covariance functions"""
__metaclass__ = ABCMeta
def covariance_function(self, x, y, w=None):
return self.st_covariance_function(pairwise_distance(x, y), w)
@abstractmethod
def st_covariance_function(self, d, w=None):
pass
|
fbf161851509a46fda44a240008bbe87d399d90b | pythonmentor/charles-p3 | /maze.py | 1,854 | 3.734375 | 4 | #!/usr/bin/python3
# coding: utf-8
import pygame
from pygame.locals import *
from graphic_level import GraphicLevel
from level import Level
from inputs import inputs
def screen_loop(picture):
""" Welcome screen """
# Opening the Pygame window (660x600 corresponds
# to a maze of 15x15 squares of 40x40 pixels + tools banner)
fenetre = pygame.display.set_mode((660, 600))
# !!! quand je veux mettre cette ligne dans main(), ca ne marche pas ?!?
screen = pygame.image.load("images/" + picture).convert_alpha()
pygame.display.set_caption("OC python project n°3")
stay = True
while stay:
pygame.time.Clock().tick(100)
fenetre.blit(screen, (0, 0))
pygame.display.flip()
if inputs() == "end":
stay = False
def game_loop(level_num):
""" The game ! """
level_num.display()
pygame.display.flip()
stay = True
while stay:
move = inputs()
if move in list((K_LEFT, K_UP, K_RIGHT, K_DOWN)):
pos_current = level_num.mac_gyver.move(move)
level_num.tools.pick_up(pos_current)
stay = level_num.mac_gyver.fight(pos_current)
level_num.display()
pygame.display.flip()
if stay == "win":
screen_loop("free.png")
stay = False
elif stay == "defeat":
screen_loop("defeat.png")
stay = False
elif move == "end":
stay = False
def main():
""" Main frame """
pygame.init()
screen_loop("welcome_game.png")
# Can choose a level and the console mode (Level) or graphic mode
# (GraphicLevel) here
game_level = GraphicLevel("level_1")
# Setting up tools
game_level.tools.put(game_level)
game_loop(game_level)
if __name__ == "__main__":
main()
|
504efd209634a4f0c4b34995a7cdef6bc5dcdfe7 | namle-gamer/DP_CS_Code | /Tools Files/toolsNL.py | 2,832 | 3.96875 | 4 | '''
isEven takes a single integer paramenter a >= 0 returning True
if a is even then return true otherwise turn false
'''
def isEven(a):
if a % 2 == 0:
return True
return False
'''
missing_char will take a letter away from a word in a given position
'''
def missing_char(str, n):
newStr = "" #create an empty string
newStr = str[0:n] + str[n + 1: len(str)] #create limit of print
return newStr
'''
sumDigits takes a single positive integer paramenter and returns the sum of the digits
Parameters: i >= 0
return: returns sum of the digits
precondition: i is a valid integer greater than 0
'''
def sumDigits(a):
total = 0
#Casting is the change of type of variable
a = str(a)
#Looping through string
#Count, check, change
for i in range(0, len(a),1):
print(a[i])
total = total + int(a[i])
return total
#Trace Table:
#a = "1234"
# i | i < len(a)|
# 0 | 0 < 4| T RUN LOOP | total = 0 + a[0] = 1
# 1 | 1 < 4| T RUN LOOP | total = 1 + a[1] = 3
# 2 | 2 < 4| T RUN LOOP | total = 3 + a[2] = 6
# 3 | 3 < 4| T RUN LOOP | total = 6 + a[3] = 10
# 4 | 4 < 4| F EXIT LOOP
''' Different approach of sumDigits '''
def sumDigitsA(a):
total = 0
while (a > 0):
total = total + a % 10 #access the ones digit
a = a // 10 #cut down the ones digit from the number
return total
#Trace
# a = 57
# a | a > 0 |
# 57| 57 > 0 | TRUE RUN LOOP total = total + 57%10 = 7
# 5 | 5 > 0 | TRUE RUN LOOP total = total + 5%10 = 12
# 0 | 0 > 0 | FALSE EXIT LOOP
''' scaleElementsA takes an integer value a and a list reference b.
This function should scale each elemnt of b'''
def scaleElementA(int, b):
for i in range(0,len(int)):
int[i] = int[i]*b #Change value inside the array
''' scaleElementsB will create another list with the equal length of the previous
array.
For example if the list is [1,2,3,4] and the scale factor a = 2 then the returned array
should be [2,4,6,8]'''
def scaleElementB(int,b):
array = []
for i in range(0,len(int)):
int[i] = int[i]*b #Calculate new value
array.append(int[i]) #Insert value into new array
return array
'''addStringsSmallLarge will take two strings as arguements.
The function should return a new string consisting of the two strings
combined with the largest string first. If the strings are of equal length it
will return the first argument followed by the second argument'''
def addStringsSmallLarge(string1,string2):
string = ""#Empty string to combine 2 arguements later
string1 = str(string1)
string2 = str(string2)
a = len(string1)
b = len(string2)
if a > b or a == b:
string = string1 + " " + string2
elif a < b:
string = string2 + " " + string1
return string
|
962f447a73ebaa7f9c501e2acaca7dc2a71d6a58 | t0rx/friendly-schedule | /friendlyschedule/scheduleparser.py | 8,088 | 3.59375 | 4 | """Class to parse a textual schedule into a usuable structure."""
from datetime import date, datetime, time, timedelta
import re
from typing import List
from .schedule import Schedule
from .scheduletypes import ScheduleEntry, ScheduleEvent
class Invalid(Exception):
"""Raised when there is a parsing error."""
class ScheduleParser:
"""
Class providing facilities to parse schedule text.
The class may be run in one of two modes:
- Stateful (the default) allows schedules to specify on-off ranges or even
specifically named states (e.g. 'cold', 'warm', 'hot')
- Stateless means that the schedule consists purely of events and doesn't
allow state transitions.
In stateless mode, the schedule returned consists entirely of 'on' events.
"""
_day_map = {'Mon': 0, 'Tue': 1, 'Wed': 2,
'Thu': 3, 'Fri': 4, 'Sat': 5, 'Sun': 6}
_weekday_pattern = re.compile(r'^(?P<start>\w+)\s*\-\s*(?P<finish>\w+)$')
_time_pattern = re.compile(r'^\d?\d:\d\d$')
_time_seconds_pattern = re.compile(r'^\d?\d:\d\d:\d\d$')
_time_delta_pattern = re.compile(
r'^((?P<hours>\d+)h)?((?P<mins>\d+)m)?((?P<secs>\d+)s)?$')
def __init__(self, *, on_state: str = 'on',
off_state: str = 'off', stateless: bool = False) \
-> None:
"""
Initialise the parser.
Keyword arguments:
on_state -- the string to use to represent on (default 'on')
off_state -- the string to use to represent off (default 'off')
stateless -- if False then do not allow event states
"""
self.on_state = on_state
self.off_state = off_state
self.stateless = stateless
def parse_weekdays(self, text: str) -> List[int]:
"""
Parse a string of the form 'Mon-Wed,Fri' into a list of integers.
Note that the integers correspond to the Python day numbers of those
days, not ISO standard day numbers.
"""
parts = [p.strip() for p in text.split(',')]
result = [] # type: List[int]
for part in parts:
match = self._weekday_pattern.match(part)
if match:
# Range
start, finish = self.weekday(match.group(
'start')), self.weekday(match.group('finish'))
result += [start]
while start != finish:
start = (start + 1) % 7
result += [start]
else:
# Singleton
result += [self.weekday(part)]
return result
def weekday(self, text: str) -> int:
"""Convert a single day string into a Python day number."""
result = self._day_map.get(text)
if result is None:
raise Invalid('Bad weekday format: "{}"'.format(text))
return result
def parse_time(self, text: str) -> time:
"""Parse a string of the form H:M or H:M:S into a time object."""
text = text.strip()
if self._time_pattern.match(text):
return datetime.strptime(text, '%H:%M').time()
elif self._time_seconds_pattern.match(text):
return datetime.strptime(text, '%H:%M:%S').time()
else:
raise Invalid('Bad time format: "{}"'.format(text))
def parse_time_delta(self, text: str) -> timedelta:
"""
Parse a string of the form XhYmZx into a timedelta object.
All of the components of the string are optional, so you can do
things like '2h1s' or '1m'.
"""
text = text.strip()
match = self._time_delta_pattern.match(text)
if match:
hours = int(match.group('hours') or 0)
mins = int(match.group('mins') or 0)
secs = int(match.group('secs') or 0)
return timedelta(hours=hours, minutes=mins, seconds=secs)
else:
raise Invalid('Bad time delta format: "{}"'.format(text))
def parse_time_schedule_part(self, text: str) -> List[ScheduleEvent]:
"""
Parse a time range string into a list of events.
The string may be one of:
- Simple time: 11:15[:30] (in stateless mode only this is supported)
- On/off time range: 11:15-12:30
- On/off time range: 11:15+1h15m
- Time and state: 11:15=idle
"""
if self.stateless:
return [(self.parse_time(text), self.on_state)]
if '-' in text:
return self.parse_time_range(text)
elif '+' in text:
return self.parse_end_offset(text)
elif '=' in text:
return self.parse_explicit_state_change(text)
# Assume single time only
return [(self.parse_time(text), self.on_state)]
def parse_time_range(self, text: str) -> List[ScheduleEvent]:
"""Parse a string of the form 11:00-12:30 into an on/off pair."""
bits = text.split('-')
if len(bits) != 2:
msg = 'Bad time range format: "{}"'.format(text)
raise Invalid(msg)
start, finish = bits
start_time = self.parse_time(start)
finish_time = self.parse_time(finish)
if finish_time < start_time:
msg = 'Finish time cannot be before start: "{}"'.format(text)
raise Invalid(msg)
return [(start_time, self.on_state),
(finish_time, self.off_state)]
def parse_end_offset(self, text: str) -> List[ScheduleEvent]:
"""Parse a string of the form 11:00+2h30m into an on/off pair."""
bits = text.split('+')
if len(bits) != 2:
msg = 'Bad time range format: "{}"'.format(text)
raise Invalid(msg)
start, delta = bits
start_time = self.parse_time(start)
time_delta = self.parse_time_delta(delta)
# We can only apply a time delta to a datetime, not a time
base_date = date(2000, 1, 1)
start_datetime = datetime.combine(base_date, start_time)
end_datetime = start_datetime + time_delta
if end_datetime.date() != base_date:
msg = ('Cannot currently have time range going past end ' +
'of day: "{}"').format(text)
raise Invalid(msg)
return [(start_time, self.on_state),
(end_datetime.time(), self.off_state)]
def parse_explicit_state_change(self, text: str) -> ScheduleEvent:
"""Parse a state change of the form 11:00=state."""
bits = text.split('=')
if len(bits) != 2:
msg = 'Bad state change format: "{}"'.format(text)
raise Invalid(msg)
time_str, state = bits
return [(self.parse_time(time_str), state.strip())]
def parse_time_schedule(self, text: str) -> List[ScheduleEvent]:
"""
Parse a string into a list of time events.
Example: '10:00-11:15, 12:30-14:45'
"""
result = [] # type: List[ScheduleEvent]
for part in text.split(','):
result += self.parse_time_schedule_part(part)
return result
def parse_schedule_entry(self, text: str) -> ScheduleEntry:
"""
Parse a string into a ScheduleEntry structure.
Example: 'Mon-Fri: 10:00-11:15, 12:30-14:45'
"""
bits = text.split(':')
if len(bits) < 2:
raise Invalid('Bad schedule format: "{}"'.format(text))
days = bits[0]
times = ':'.join(bits[1:])
return (self.parse_weekdays(days), self.parse_time_schedule(times))
def parse_schedule_line(self, text: str) -> List[ScheduleEntry]:
"""
Parse a string separated with ';' into a list of ScheduleEntries.
Example: 'Mon-Fri: 10:00-11:15; Sat: 09:00-12:15'
"""
return [self.parse_schedule_entry(p) for p in text.split(';')]
def parse_schedule(self, text: str) -> Schedule:
"""
Parse a string separated with ';' into a Schedule object.
Example: 'Mon-Fri: 10:00-11:15; Sat: 09:00-12:15'
"""
return Schedule(self.parse_schedule_line(text), text)
|
33f20b00560ce5050b419684c709bec347aba42e | tymefighter/AI | /gridMDP/gridMDP2.py | 6,054 | 3.71875 | 4 | import numpy as np
import math
"""
0: (r-1, c): up
1: (r+1, c): down
2: (r, c-1): left
3: (r, c+1): right
"""
def print_mat(a):
for row in a:
s = ''
for x in row:
s += ' ' + str(x)
print(s)
def print_grid(grid):
for row in grid:
s = ''
for x in row:
s += x
print(s)
def reward(grid, r, c, a):
m = len(grid)
n = len(grid[0])
if grid[r][c] == '#':
return 0
if a == 0:
# up
if r-1 < 0 or grid[r-1][c] == '#':
return -100
if grid[r-1][c] == 'g':
return 100
elif a == 1:
# down
if r + 1 >= m or grid[r+1][c] == '#':
return -100
if grid[r+1][c] == 'g':
return 100
elif a == 2:
# left
if c - 1 < 0 or grid[r][c-1] == '#':
return -100
if grid[r][c-1] == 'g':
return 100
elif a == 3:
# right
if c + 1 >= n or grid[r][c+1] == '#':
return -100
if grid[r][c+1] == 'g':
return 100
return 0
def prob(p, grid, a, r, c, r_d, c_d):
m = len(grid)
n = len(grid[0])
if ((r_d == r and c_d == c) or (r_d == r-1 and c_d == c) or (r_d == r+1 and c_d == c) or (r_d == r and c_d == c-1) or (r_d == r and c_d == c+1)) == False:
return 0
count = 0
up = False
down = False
left = False
right = False
if r-1 < 0 or grid[r-1][c] == '#':
count += 1
up = True
if r+1 >= m or grid[r+1][c] == '#':
count += 1
down = True
if c-1 < 0 or grid[r][c-1] == '#':
count += 1
left = True
if c+1 >= n or grid[r][c+1] == '#':
count += 1
right += True
if r_d == r and c_d == c:
if grid[r][c] == 'g' or count == 4 or grid[r][c] == '#':
return 1
else:
return 0
if grid[r][c] == 'g' or count == 4 or grid[r][c] == '#':
return 0
#print(str(count) + " " + str(up) + " " +str(down)+" "+str(left) +" "+str(right))
if a == 0:
if up:
if r_d == r-1:
return 0
elif grid[r_d][c_d] == '#':
return 0
else:
return 1.0 / (4.0 - count)
else:
if r_d == r-1:
if count == 3:
return 1.0
else:
return p
elif grid[r_d][c_d] == '#':
return 0
else:
if count == 3:
return 0
else:
return (1.0 - p) / (3.0 - count)
elif a == 1:
if down:
if r_d == r+1:
return 0
elif grid[r_d][c_d] == '#':
return 0
else:
return 1.0 / (4.0 - count)
else:
if r_d == r+1:
if count == 3:
return 1.0
else:
return p
elif grid[r_d][c_d] == '#':
return 0
else:
if count == 3:
return 0
else:
return (1.0 - p) / (3.0 - count)
elif a == 2:
if left:
if c_d == c-1:
return 0
elif grid[r_d][c_d] == '#':
return 0
else:
return 1.0 / (4.0 - count)
else:
if c_d == c-1:
if count == 3:
return 1.0
else:
return p
elif grid[r_d][c_d] == '#':
return 0
else:
if count == 3:
return 0
else:
return (1.0 - p) / (3.0 - count)
else:
if right:
if c_d == c+1:
return 0
elif grid[r_d][c_d] == '#':
return 0
else:
return 1.0 / (4.0 - count)
else:
if c_d == c+1:
if count == 3:
return 1.0
else:
return p
elif grid[r_d][c_d] == '#':
return 0
else:
if count == 3:
return 0
else:
return (1.0 - p) / (3.0 - count)
def BellmanOp(Q, p, grid, gamma = 0.9):
TQ = np.zeros(Q.shape)
m = len(grid)
n = len(grid[0])
for r in range(m):
for c in range(n):
for a in range(4):
TQ[r][c][a] = reward(grid, r, c, a)
for r_d in range(m):
for c_d in range(n):
TQ[r][c][a] += gamma * prob(p, grid, a, r, c, r_d, c_d) * np.max(Q[r_d][c_d])
return TQ
def valueIter(p, grid, iters, gamma = 0.9):
m = len(grid)
n = len(grid[0])
Q = np.zeros((m, n, 4))
V = np.zeros((m, n))
pred = np.zeros((m, n))
for i in range(iters):
Q = BellmanOp(Q, p, grid, gamma)
for r in range(m):
for c in range(n):
V[r][c] = - math.inf
for a in range(4):
val = reward(grid, r, c, a)
for r_d in range(m):
for c_d in range(n):
val += gamma * prob(p, grid, a, r, c, r_d, c_d) * np.max(Q[r_d][c_d])
if val > V[r][c]:
pred[r][c] = a
V[r][c] = val
return V, pred
def main():
p = 0.8
with open('grid', 'r') as fl:
grid = []
for line in fl.readlines():
arr = []
for x in line:
if x != '\n':
arr.append(x)
grid.append(arr)
print_grid(grid)
V, pred = valueIter(p, grid, 20)
print_mat(V)
print_mat(pred)
#print(prob(p, grid, 3, 4, 2, 4, 3))
if __name__ == '__main__':
main() |
144aadab9b2167c896838ae99747d606b91834a3 | skad00sh/algorithms-specialization | /Divide and Conquer, Sorting and Searching, and Randomized Algorithms/0.4 week1 - bubble-sort.py | 691 | 4.21875 | 4 | def bubble_sort(lst):
"""
------ Pseudocode Steps -----
begin BubbleSort(list)
for all elements of list
if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for
return list
end BubbleSort
------ Doctests -----
>>> unsorted_list = [8,4,3,7,87,5,64,6,73]
>>> sorted_list = insertion_sort(unsorted_list)
>>> sorted_list
[3, 4, 5, 6, 7, 8, 64, 73, 87]
"""
for h in range(len(lst)):
for i in range(len(lst)-h-1):
if lst[i] > lst[i+1]:
lst[i], lst[i+1] = lst[i+1], lst[i]
return lst |
fbcb252e38b6a91f947100d88f8828802bec1856 | carmsanchezs/datacademy | /python_basic/diccionarios.py | 532 | 3.78125 | 4 | def main():
poblacion_paises = {
'Argentina': 44938712,
'Brasil': 210147125,
'Colombia': 50372424
}
print(poblacion_paises['Argentina']) # imprime 44938712
#print(poblacion_paises['Mexico']) # KeyError
for pais in poblacion_paises.keys():
print(pais)
for valor in poblacion_paises.values():
print(valor)
for key, value in poblacion_paises.items():
print('{} tiene {} habitantes'.format(key, value))
if __name__ == '__main__':
main()
|
b39e3d3e69f8a8452d6d5d4c8031a84d3b3b7c70 | carmsanchezs/datacademy | /python_basic/recorrer.py | 150 | 3.765625 | 4 | def main():
frase = input('Escribe una frase: ')
for letra in frase:
print(letra.upper())
if __name__ == '__main__':
main()
|
ada8e3b64923945dd7c82f9767b587ed40e377fb | abhyuday10/NEA-Intelligent-Car | /car.py | 9,189 | 3.65625 | 4 | """Car module to manage all data for one car. Each car represents a solution in the environment. Performance of car in environment determines the strength of that solution."""
import pygame
import math
import environment as env
import constants
class Car(pygame.sprite.Sprite):
"""Defining the car class which inherits properties from the Pygame sprite class"""
DELTA_ANGLE = 5.5 # Specifies the maximum rotation vector on each frame
SPEED = 5 # Specifies the maximum movement possible on each frame
def __init__(self, solution, x, y):
# Initialise the sprite masterclass
pygame.sprite.Sprite.__init__(self)
# Initialise images required for rendering
self.boom = pygame.image.load("images/explosion.png")
self.boom = pygame.transform.scale(self.boom, (50, 50))
if solution.fittest:
# Load image of different colour car if this member is the fittest from previous generation
self.image = pygame.image.load("images/car_fit.png")
else:
# Otherwise load default car
self.image = pygame.image.load("images/car.png")
# Scale the image for the environment
self.image = pygame.transform.scale(self.image, (30, 60))
self.orig_image = self.image
# Create mask from image. Mask contains each pixel overlapping the image in the environment.
# Required for pixel perfect collision detection at the cost of evaluation time.
self.mask = pygame.mask.from_surface(self.image)
# Create rectangle to store car coordinates
self.pos = [x, y]
self.rect = self.image.get_rect()
self.rect.center = (x, y)
# Store current angle car is facing.
self.angle = 0
# Boolean to store whether the car has collided in the environment.
self.crashed = False
# Store location of obstacles and screen boundary to check for collisions
self.obstacles = None
self.borders = None
# Store the solution representing this car
self.solution = solution
# Imputs and outputs for the neural network making decisions for this car.
self.inputs = None
self.output = None
def rotate_right(self):
"""Rotate car by maximum angle specified"""
self.angle = (self.angle - self.DELTA_ANGLE) % -360
def rotate_left(self):
"""Rotate car by maximum angle specified"""
self.angle = (self.angle + self.DELTA_ANGLE) % -360
def move_forward(self):
"""Trigonometric function to determine new position based on the angle car is facing."""
dx = math.cos(math.radians(self.angle + 90))
dy = math.sin(math.radians(self.angle + 90))
# Update position of car
self.pos = self.pos[0] + (dx * self.SPEED), self.pos[1] - (dy * self.SPEED)
self.rect.center = self.pos
def update(self):
"""Overriding the default Pygame update method
Update mask and collision state"""
self.mask = pygame.mask.from_surface(self.image)
self.crashed = self.check_if_crashed()
# Helper methods to get and set neural network values
def set_inputs(self, inputs):
self.solution.brain.set_inputs(inputs)
def feed_forward(self):
self.solution.brain.feed_forward()
def get_outputs(self):
return self.solution.brain.get_decision()
def calculate_fitness(self, time):
"""Simple algorithm to determine fitness from time spent in environment
Can be adjusted to make fitness increase exponentially with time"""
fitness = math.pow(time, 1)
self.solution.fitness = fitness
def draw(self):
"""Method to draw car data on this frame to the Pygame screen.
Rotate image to the angle the car is currently facing."""
self.image = pygame.transform.rotate(self.orig_image, self.angle)
self.rect = self.image.get_rect(center=self.rect.center)
# Rendering the image to the current coordinates of the car.
env.Environment.screen.blit(self.image, self.rect)
def check_if_crashed(self):
"""Algorithm to check if car has crashed by checking overlaps"""
sample_points = []
outline_points = self.mask.outline()
# Samples points by checking every tenth point in the car outline to reduce time required
for i in range(len(outline_points)):
if i % 10 == 0:
sample_points.append(outline_points[i])
# Points need to be offsetted as mask does not store absolute position
for point in sample_points:
offsetted_mask_point = [0, 0]
offsetted_mask_point[0] = point[0] + self.rect[0]
offsetted_mask_point[1] = point[1] + self.rect[1]
# Checks for overlaps between sampled points to check if crashed into object
if self.check_if_point_in_any_obstacle(offsetted_mask_point) or self.check_if_point_in_any_border(
offsetted_mask_point):
adjusted_rect = [offsetted_mask_point[0] - 25, offsetted_mask_point[1] - 25]
env.Environment.screen.blit(self.boom, adjusted_rect) # Display collision graphic if crashed
return True
return False
def get_arm_distance(self, arm, x, y, angle, offset):
"""Function to return sensor distance to objects"""
i = 0 # Used to count the distance.
# Look at each point and see if we've hit something.
for point in arm:
i += 1
# Move the point to the right spot.
rotated_p = self.get_rotated_point(
x, y, point[0], point[1], angle + offset
)
# Check if we've hit something. Return the current i (distance) if we did.
if rotated_p[0] <= 0 or rotated_p[1] <= 0 \
or rotated_p[0] >= env.Environment.width or rotated_p[1] >= env.Environment.height:
return i # Sensor is off the screen.
elif self.check_if_point_in_any_obstacle(rotated_p):
return i
elif constants.DRAW_SENSORS: # Only render sensor arms is specified
pygame.draw.circle(env.Environment.screen, constants.BLACK, rotated_p, 2)
# Return the distance for the arm.
return i
def check_if_point_in_any_border(self, point):
"""Method to check for border intersection with a point"""
for border in self.borders:
if self.check_inside_rect(point[0], point[1], border):
return True
return False
def check_if_point_in_any_obstacle(self, point):
"""Method to check for obstacle intersection with a point"""
for obstacle in self.obstacles:
if self.check_inside_circle(point[0], point[1], obstacle.pos[0], obstacle.pos[1], obstacle.radius):
return True
return False
# Static helper methods to check for point intersections with circles and rectangles
@staticmethod
def check_inside_rect(x, y, rect):
return (rect[0] + rect[2]) > x > rect[0] and (rect[1] + rect[3]) > y > rect[1]
@staticmethod
def check_inside_circle(x, y, a, b, r):
return (x - a) * (x - a) + (y - b) * (y - b) < r * r
def get_sensor_data(self):
"""Method to get sensors readings for the car"""
return self.get_sensor_readings(self.rect.center[0], self.rect.center[1], math.radians(abs(self.angle) - 90))
def get_sensor_readings(self, x, y, angle):
"""Return the values of each sensor in a list"""
readings = [] # List to store each sensor value
# Make our arms
arm_left = self.make_sensor_arm(x, y)
arm_middle = arm_left
arm_right = arm_left
# Rotate them and get readings.
readings.append(self.get_arm_distance(arm_left, x, y, angle, 0.75))
readings.append(self.get_arm_distance(arm_left, x, y, angle, 1.55))
readings.append(self.get_arm_distance(arm_middle, x, y, angle, 0))
readings.append(self.get_arm_distance(arm_left, x, y, angle, -1.55))
readings.append(self.get_arm_distance(arm_right, x, y, angle, -0.75))
return readings
@staticmethod
def make_sensor_arm(x, y):
"""Method to create array of points representing one arm of sensor."""
spread = 16 # Default spread between sensor points.
distance = 10 # Gap before first sensor point.
arm_points = []
# Make an arm.
for i in range(1, 15):
arm_points.append((distance + x + (spread * i), y))
return arm_points
@staticmethod
def get_rotated_point(x_1, y_1, x_2, y_2, radians):
"""Algorithm to rotate a point by an angle around another point.
Rotate x_2, y_2 around x_1, y_1 by angle."""
x_change = (x_2 - x_1) * math.cos(radians) + \
(y_2 - y_1) * math.sin(radians)
y_change = (y_1 - y_2) * math.cos(radians) - \
(x_1 - x_2) * math.sin(radians)
new_x = x_change + x_1
new_y = y_change + y_1
return int(new_x), int(new_y)
|
73b64affd060589fbe25c5a49efcf9e41ad81993 | DorianKucharski/big-data-vehicle-traffic | /Data/data_preparing.py | 2,800 | 3.53125 | 4 | """
Przygotowanie danych pobranych z Kaggle
"""
import random
import pandas
def generate_year(df_tmp: pandas.DataFrame, year: int) -> pandas.DataFrame:
"""
Generuje dane na zadany rok, posługując się przekazanymi danymi w obiekcie DataFrame. Generowanie obdywa się poprzez
kopiowanie wpisów z równoległych dat i nakładanie na nich niewielkiego szumu, bazując na odchyleniu standardowym.
Parameters
----------
df_tmp: pandas.DataFrame
Dane z wybranego roku
year: int
Rok który ma być wygenerowany
Returns
----------
pandas.DataFrame
Wygenerowane dane
"""
new_df = df_tmp.copy()
new_df = new_df[new_df["Year"] == 2020]
new_df["Year"].replace([2020], year, inplace=True)
sd = int(new_df["Volume"].std())
new_df["Volume"] = new_df["Volume"].apply(lambda x: x + int((random.randint(0, sd) * random.randint(0, 100)) / 100))
return new_df
if __name__ == '__main__':
# Wczytywanie danych z pliku csv do obiektu DataFrame
df = pandas.read_csv("Radar_Traffic_Counts.csv")
# Filtrowanie danych na podstawie lokalizacji w kolumnie location_name
df = df[df['location_name'] == " CAPITAL OF TEXAS HWY / WALSH TARLTON LN"]
# Usuwanie zbednych kolumn
df.drop('location_name', axis=1, inplace=True)
df.drop('location_latitude', axis=1, inplace=True)
df.drop('location_longitude', axis=1, inplace=True)
df.drop('Day of Week', axis=1, inplace=True)
df.drop('Time Bin', axis=1, inplace=True)
# Filtrowanie danych starszych niz te z 2018. Starsze dane byly niekompletne.
df = df[df["Year"] >= 2018]
# Usuwanie duplikatow bazujac na kolumnach okreslajacych czas
df = df.drop_duplicates(subset=['Year', 'Month', 'Day', 'Hour', 'Minute', 'Direction'], keep='first')
# Zmiana wartosci w kolumnie direction
df["Direction"].replace({"NB": "IN", "SB": "OUT"}, inplace=True)
# Zmiana lat na bardziej terazniejsze
df["Year"].replace([2019], 2021, inplace=True)
df["Year"].replace([2018], 2020, inplace=True)
# Generowanie i laczenie danych
years = [df]
for i in range(8):
years.append(generate_year(df, 2020 - (i + 1)))
df = pandas.concat(years)
# Utworzenie kolumny datatime na podstawie innych kolumn okreslajacych czas
df['Datetime'] = pandas.to_datetime(df[['Year', 'Month', 'Day', 'Hour', 'Minute']])
# Usuwanie niepotrzebnych kolumn
df = df[['Datetime', 'Direction', 'Volume']]
# Sortowanie
df = df.sort_values(by=['Datetime'])
# Konwersja danych w kolumnie Datetime na timestamp
df['Datetime'] = df['Datetime'].astype('int64') // 10 ** 9
# Zapis danych do pliku
df.to_csv("prepared_data.csv", index=False)
|
9fd432ad1b1ee73e07698c9ab1c83312bebfb922 | thinkphp/collatz | /collatz.py | 205 | 3.859375 | 4 | def Collatz(n):
while True:
yield n
if n == 1:
break
if n & 1:
n = 3 * n + 1
else:
n = n // 2
for j in Collatz(1780):
print(j, end = ' ')
|
379a186bc1a21dc591556d80a5298ceca9b77a80 | mfigand/start_with_python | /07 - Error handling/logic.py | 130 | 3.90625 | 4 | x = 206
y = 42
if x < y:
print(str(y) + ' is greater than ' + str(x))
else:
print(str(x) + ' is greater than ' + str(y))
|
650c122e59fe918a01e76c0a01f794432e621279 | shubh4197/Python | /PycharmProjects/day4/program1.py | 934 | 3.671875 | 4 | def outer(a):
print("This is outer")
def inner(*args, **kwargs): # inner function should be generic
print("This is inner")
for i in args:
if type(i) != str:
print("Invalid")
break
else:
for i in kwargs.values():
if type(i) != str:
print("Invalid")
break
else:
a(*args, **kwargs)
print("Inner finished")
return inner
@outer
def hello(name):
print("Hello" + name)
@outer
def sayhi(name1, name2):
print("Hello1 " + name1 + " " + name2)
# hello = outer(hello) This can be replaced by @wrapperfunctionname above the real function
# sayhi = outer(sayhi) This can be replaced by @wrapperfunctionname above the real function
hello("Sachin")
sayhi(name1="Sachin", name2="Rahul")
hello(1)
|
6179fa6cf1814016ab7b13e6cbb4dcf0d7e2833a | shubh4197/Python | /PycharmProjects/day4/program4.py | 500 | 3.671875 | 4 | class InvalidCredential(Exception):
def __init__(self, msg="Not found"):
Exception.__init__(self, msg)
try:
dict = {"Sachin": "ICC", "Saurav": "BCCI"}
username = input("Enter username:")
password = input("Enter password:")
if username not in dict:
raise InvalidCredential
else:
if dict[username] == password:
print("success")
else:
raise InvalidCredential
except InvalidCredential as e:
print(e)
|
52603c0b3bda574f3d6225bee89492e87df8b79e | EvanShui/interview_prep | /sort/selection_sort.py | 483 | 3.6875 | 4 | def selection_sort(A):
for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
print("swapping [idx: {}, val: {}] with [idx: {}, val: {}]".format(i,
A[i], min_idx, A[min_idx]))
A[i], A[min_idx] = A[min_idx], A[i]
def main():
A = [2, 42, 1, 94, 4, 3, 321]
selection_sort(A)
assert(A == [1, 2, 3, 4, 42, 94, 321])
if __name__ == '__main__':
main()
|
3bd6fa3a0e8d61e0fd0c10304a79d883c6471aae | deepakmatam/content_summary | /hack_gui.py | 2,534 | 3.625 | 4 | import Tkinter
from tkFileDialog import askopenfilename
m = Tkinter.Tk()
m.title('News categorizer ')
m.minsize(width=566, height=450)
def choosefile():
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
label = Tkinter.Label( m, text = filename )
label.pack()
def categorize():
input_list = []
with open('c:/python27/words.txt','r') as f:
for line in f:
for word in line.split():
chars_to_remove=['.',',','?','!','@','#','$','%','^','&','*',')','(','-','_','+','=','{','}','[','}','|','<','>',':',';','"']
r=word.translate(None, ''.join(chars_to_remove))
input_list.append(r) #print(word)
#print input_list
stop_words_list = []
with open('stop_words.txt','r') as f:
for line in f:
for word in line.split():
stop_words_list.append(word)
c_list = []
c_list = list(set(input_list) - set(stop_words_list))
c_list = list(set(c_list))
sports_list,entertainment_list,politics_list,business_list = [],[],[],[]
with open('sports.txt','r') as f:
for line in f:
for word in line.split(','):
sports_list.append(word)
with open('politics.txt','r') as f:
for line in f:
for word in line.split(','):
politics_list.append(word)
with open('entertainment.txt','r') as f:
for line in f:
for word in line.split(','):
entertainment_list.append(word)
with open('business_2.txt','r') as f:
for line in f:
for word in line.split(','):
business_list.append(word)
#print politics_list
sports_count,ent_count,politics_count,business_count,other_count = 0,0,0,0,0
for item in c_list:
if item in sports_list:
sports_count +=1
if item in entertainment_list:
ent_count +=1
if item in politics_list:
politics_count +=1
if item in business_list:
business_count +=1
#else:
# other_count +=1
dict = {'sports':sports_count,'Entertainment':ent_count,'politics':politics_count,'Business':business_count,'other':other_count}
print dict
result = max(dict,key = dict.get)
fresult = 'This news is about ',result
if result == 'other':
print "This content does not belong to any news"
else:
label = Tkinter.Label( m, text = fresult )
label.pack()
B_choose = Tkinter.Button(m, text ="choose a file", command = choosefile)
B_choose.place(x=250,y=130)
categorize = Tkinter.Button(m, text ="categorize", command = categorize)
categorize.place(x=255,y=170)
m.mainloop() |
b970b5e47e71e96495d5a7fef82af57309da2599 | jffist/pyfoo | /pyfoo/mathfun.py | 352 | 3.546875 | 4 | import numpy as np
def scale(x):
""" Centers the vector by subtracting it's mean and scales by the standart error
:param x: numeric vector
:type x: numpy.array or list of numbers
:returns: scaled vector of the same length with zero mean and deviation equal to 1
:rtype: numpy.array
"""
return (x - np.mean(x)) / np.std(x)
|
a2848e9c028940ce1147501710bef4dbcc147f59 | darshind/python_intermediate_project | /q03_create_3d_array/build.py | 230 | 3.90625 | 4 | # Default Imports
import numpy as np
# Enter solution here
def create_3d_array():
N = 28
random_array = np.arange(N-1)
reshaped_array = random_array.reshape((3,3,3))
return reshaped_array
print create_3d_array()
|
bf2cd8065542e92a19b392ab44b5bd8038077b07 | helani04/EulerProjects | /16/1_Multiples of 3 or 5 below 1000 .py | 87 | 3.640625 | 4 | a=1
s=0
while (a<1000):
if(a%3==0 ) or (a%5==0):
s = s+a
a=a+1
print (s)
|
d193d76fbd81a2e83bdbc76d62fc5f44726c4b55 | helani04/EulerProjects | /16/19-Counting Sundays.py | 482 | 3.734375 | 4 | import time
start = time.time()
year=1901
day=6
firsts=1
count=0
while year<=2000:
if year%400==0 or (year%4==0 and year%100!=0):
feb=29
else:
feb=28
months=0
NoOfDaysInMonths=[31,feb,31,30,31,30,31,31,30,31,30,31]
while months<12:
if day==firsts:
count+=1
if day-firsts>7:
firsts+=NoOfDaysInMonths[months]
months+=1
day+=7
year+=1
print(count)
end = time.time()
print(end - start)
|
5d9044a28fd1cbeeb0178f4be8abba86875ff2eb | marekhaba/addwidgets | /addwidgets/scrollable_frame.py | 2,629 | 3.671875 | 4 | import tkinter as tk
from tkinter import ttk
class ScrollableFrame(ttk.Frame):
"""
for adding widgets into the frame use .scrollable_frame, do NOT add widgets directly.
use width and height to enforce size. for modifing the forced size use change_size.
"""
#borroved from "https://blog.tecladocode.com/tkinter-scrollable-frames/" and modified a little bit.
def __init__(self, container, *args, y_scroll=True, x_scroll=True, **kwargs):
super().__init__(container, *args, **kwargs)
forced_width = kwargs.pop("width", None)
forced_height = kwargs.pop("height", None)
canvas = tk.Canvas(self, width=forced_width, height=forced_height)
self.canvas = canvas
if y_scroll:
scrollbar_y = ttk.Scrollbar(self, orient="vertical", command=canvas.yview)
if x_scroll:
scrollbar_x = ttk.Scrollbar(self, orient="horizontal", command=canvas.xview)
self.scrollable_frame = ttk.Frame(canvas)
self.scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(
scrollregion=canvas.bbox("all")
)
)
canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
if x_scroll and y_scroll:
canvas.configure(yscrollcommand=scrollbar_y.set, xscrollcommand=scrollbar_x.set)
elif x_scroll:
canvas.configure(xscrollcommand=scrollbar_x.set)
elif y_scroll:
canvas.configure(yscrollcommand=scrollbar_y.set)
if x_scroll:
scrollbar_x.pack(side="bottom", fill="x")
canvas.pack(side="left", fill="both", expand=True)
if y_scroll:
scrollbar_y.pack(side="right", fill="y")
def change_size(self, width=None, height=None):
"""
Changes the enforced size of the ScrollableFrame
"""
if width is not None:
#self.forced_width = width
super().configure(width=width)
self.canvas.configure(width=width)
if height is not None:
#self.forced_height = height
super().configure(height=height)
self.canvas.configure(height=height)
if __name__ == "__main__":
root = tk.Tk()
#ScrollableFrame
frame = ScrollableFrame(root, width=150, height=400, x_scroll=False)
frame.change_size(height=200)
for i in range(50):
ttk.Label(frame.scrollable_frame, text="Sample scrolling label").pack()
frame.pack()
root.mainloop() |
f7b532d7e46b5ffc609da81fcc795d85bbaadf19 | danielabar/python-practice | /solutions/pick_word.py | 414 | 3.578125 | 4 | #!/usr/bin/envn python
"""Pick a random word from text file.
Usage:
python pick_word
"""
import random
def pick_word():
with open('sowpods.txt', 'r') as sowpods:
lines = sowpods.readlines()
num_lines = len(lines)
some_line_num = random.randint(0, num_lines - 1)
print('Your random word is {}'.format(lines[some_line_num]))
if __name__ == '__main__':
pick_word()
|
9be81cae09ef9b0c9401efc4f9edbbe43758bd24 | mac912/python | /dictonary4.py | 242 | 3.875 | 4 | d={'d1':{'name':'zoro','age':21,'country':'japan'},'d2':{'name':'jerry','age':21,'country':'uk'},'d3':{}}
print(d)
print(d['d1'])
print(d['d1']['name'])
print(d['d2']['country'])
d['d3']['name']='henry'
d['d3']['age']=21
print(d)
|
60cff1227d0866a558d88df56dad871a8d189d9e | mac912/python | /calender.py | 1,021 | 4.3125 | 4 | # program to print calender of the month given by month number
# Assumptions: Leap year not considered when inputed is for February(2). Month doesn't start with specific day
mon = int(input("Enter the month number :"))
def calender():
if mon <=7:
if mon%2==0 and mon!=2:
for j in range(1,31):
print(j, end=' ')
if j%7==0:
print()
elif mon==2:
for j in range(1,29):
print(j, end=' ')
if j%7==0:
print()
elif mon<=7 and mon%2!=0:
for j in range(1,32):
print(j, end=' ')
if j%7==0:
print()
elif mon>7 and mon%2==0:
for j in range(1,32):
print(j, end=' ')
if j%7==0:
print()
elif mon>7 and mon%2!=0:
for j in range(1,31):
print(j, end=' ')
if j%7==0:
print()
calender()
|
e7921ad0ba8990d2dafb5c39d2804463820cb46d | mac912/python | /dictonary.py | 310 | 3.859375 | 4 | dict1 = {1:'start', 'name':'saini', 'age':10}
print(dict1)
print(dict1['name'])
#or
print(dict1.get('age'))
print(dict1.get(1))
print("After making some changes")
print()
dict1[1] = 'end'
dict1['name']= 'manish'
dict1['age'] = 20
print(dict1[1])
print(dict1['name'])
print(dict1['age'])
|
24e2224dd8d882665643ddaf11800f602e81027e | scarint/usingpython | /exercises/14 python-inventory-program.py | 2,075 | 4.03125 | 4 | # http://usingpython.com/python-lists/
# Write a program to store items in an inventory for an RPG computer game.
# Your character can add items (like swords, shields, and various potions)
# to their inventory, as well as 'use' an item, that will remove it from the
# inventory list.
# You could even have other variables like 'health' and 'strength', that are
# affected by 'finding' or 'using' items in the inventory.
health = 100
armor = 100
weight = 0
maxWeight = 100
def ReportStats(itemList, maxWeight):
health = 100
armor = 100
weight = 0
print("Equipment: ")
for item in itemList:
health = health + item[3]
armor = armor + item[4]
weight = weight + item[5]
print(item[0])
if weight > maxWeight:
print("\n!!!WARNING: Encumbered!!!\n")
print("Total health:\t" + str(health) + "\n"
"Total armor:\t " + str(armor) + "\n"
"Total weight:\t" + str(weight) + "\n")
# Item framework:
# item-type = ['name', #atk, #speed, #health, #armor, #weight]
# speed 1-10; 1 is fastest
weapon1 = ['sword', 50, 5, 0, 0, 20]
weapon2 = ['stick', 10, 1, 0, 0, 5]
weapon3 = ['axe', 70, 7, 0, 0, 50]
armor1 = ['helmet', 0, 0, 0, 5, 3]
armor2 = ['pauldron', 0, 0, 0, 10, 7]
armor3 = ['breastplate', 0, 0, 0, 30, 15]
armor4 = ['greaves', 0, 0, 0, 10, 8]
armor5 = ['shield', 0, 0, 0, 20, 10]
potion1 = ['smallHealth', 0, 0, 10, 0, 2]
potion2 = ['medHealth', 0, 0, 20, 0, 5]
potion3 = ['largeHealth', 0, 0, 50, 0, 10]
potion4 = ['smallArmor', 0, 0, 0, 10, 5]
potion5 = ['medArmor', 0, 0, 0, 20, 10]
potion6 = ['largeArmor', 0, 0, 0, 50, 15]
items_available = [weapon1, weapon2, weapon3, armor1, armor2, armor3, armor4, potion1, potion2, potion3, potion4, potion5, potion6]
itemList1 = [weapon1, armor1, armor2, potion3, potion4]
itemList2 = [weapon2, armor2, armor3, armor4, armor5]
itemList3 = [weapon3, armor1, armor2, armor3, armor4, armor5, armor5]
ReportStats(itemList1, maxWeight)
ReportStats(itemList2, maxWeight)
ReportStats(itemList3, maxWeight)
|
c4fd4291d7c6ff4ebe40d28579192478fb776e80 | bisharma/Binay_Seng560 | /converter.py | 622 | 4.03125 | 4 |
import math # This will import math module
# Now we will create basic conversion functions.
def decimal_to_binary(decimal_num):
result = bin(decimal_num)
return result
def binary_to_decimal(binary_num):
result = int(binary_num)
return result
def decimal_to_octal(decimal_num):
result = oct(decimal_num)
return result
def octal_to_decimal(octal_num):
result = int(octal_num)
return result
def decimal_to_hexa(decimal_num):
result = hex(decimal_num)
return result
def hexa_to_decimal(hexa_num):
result = int(hexa_num)
return result
|
b7fa421982e1756aca5ca2afc4c743d1bd7b7d0d | YuyangMiao/IBI1_2019-20 | /Practical5/collatz.py | 491 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 11 09:54:34 2020
@author: joe_m
"""
#import an integer n
n=7
#Judge if n=1
#If yes: print n and stop
#If no:
# print n
# Repeat:
# If n is even: n=n/2, print n
# If n is odd: n=3n+1, print n
# If n==1, stop
if n==1:
print (n)
else:
print (n)
while n!=1:
if n%2==0:
n=n/2
print (n)
else:
n=3*n+1
print (n)
if n==1:
break |
60363908ab9baed3f64f207efce46e44165d896f | Hyeeein/ClassLion_Python_2 | /Week_2_Q9.py | 532 | 3.546875 | 4 | # Q9. 첫 번째 줄에 사람 수 N을 입력받고, 두 번째 줄에 N개의 정수를 공백으로 구분되어 입력받음
# 마피아 1명을 찾기 위해 투표를 하게 되는데 참가하는 사람의 수는 N명, 두 번째 줄은 차례로 마피아 의심자 번호를 적음
# 표 많이 받은 사람 퇴장 / 표 많이 받은 사람 2명 이상이면 skipped / 무효표 > 많이 받은 사람인 경우, 표를 가장 많이 받은 사람 퇴장
N = int(input())
data = list(map(int, input().split()))
|
8edf41423eeb9a977ad8f378c0b325d415470459 | ryanbergner/nba-playoff-predictions | /Nba-Merge-df.py | 1,216 | 3.578125 | 4 | import pandas as pd
import numpy as np
# data from https://www.basketball-reference.com/leagues/NBA_2020.html
# First, we will rename the columns in the opponent dataframe so we can tell the difference between the columns in the team dataframe and the opponent dataframe
dfteam = pd.read_csv("NbaTeamData.csv")
dfopponent_unlabled = pd.read_csv("NbaOpponentData.csv")
# Create a dictionary to convert team column names to opponent stats column names for clarity (did not include team column because that would make no sense)
# We will also use team name
dict_to_opp = {'Rk' : 'opp_Rk', 'G' : 'opp_G', 'MP' : 'opp_MP', 'FG' : 'opp_FG', 'FGA' : 'opp_FGA', 'FG % ' : 'opp_FG %', '3P' : 'opp_3P', '3PA' : 'opp_3P', '3P % ' : 'opp_3P %', '2P' : 'opp_2P',
'2PA' : 'opp_2PA', '2P%' : 'opp_2P%', 'FT' : 'opp_FT', 'FTA' : 'opp_FTA', 'FT%' : 'opp_FT%', 'ORB' : 'opp_ORB', 'DRB' : 'opp_DRB' , 'TRB' : 'opp_TRB', 'AST' : 'opp_AST', 'STL' : 'opp_STL',
'BLK' : 'opp_BLK', 'TOV' : 'opp_TOV', 'PF' : 'opp_PF', 'PTS' : 'opp_PTS'}
dfopponent = dfopponent_unlabled.rename( columns = dict_to_opp , inplace = False)
df_nba = dfteam.merge(dfopponent, how = "right", on = ["Team"])
print(df_nba)
|
3c70d4ae169d4f9a4523648aae1ac89137ca0c74 | rakuishi/deep-learning-from-scratch | /ch04/error_functions.py | 627 | 3.59375 | 4 | # coding: utf-8
import numpy as np
# 2 乗和誤差
def mean_squared_error(y, t):
return 0.5 * np.sum((y-t)**2)
# 交差エントロピー誤差
def cross_entropy_error(y, t):
delta = 1e-7
return -np.sum(t * np.log(y + delta))
# 2 を正解とする
t = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
y1 = [0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0]
y2 = [0.1, 0.05, 0.1, 0.0, 0.05, 0.1, 0.0, 0.6, 0.0, 0.0]
print(mean_squared_error(np.array(y1), np.array(t)))
print(mean_squared_error(np.array(y2), np.array(t)))
print(cross_entropy_error(np.array(y1), np.array(t)))
print(cross_entropy_error(np.array(y2), np.array(t)))
|
76199c07a591052fa6309227c134850017f0fc5a | aomi/battlesnake-python | /app/astar.py | 3,227 | 3.6875 | 4 | #Determines distance via manhattan style
def manhattanWeight(current, goal):
return abs(current.x - goal.x) + abs(current.y - goal.y)
def astar(start, goal):
print("start: ", start.x, start.y)
print("goal: ", start.x, start.y)
start.netWeight = 0
lastTurnWeight = 0
openList = [start]
closedList = []
start.parent = 0
while(len(openList)>0):
centreNode = findSmallestWeightedNode(openList, lastTurnWeight)
openList.remove(centreNode)
successors = []
if (centreNode.up != 0) and (centreNode.up.content != "wall") and not (centreNode.up in closedList): successors.append(centreNode.up)
if (centreNode.down != 0) and (centreNode.down.content != "wall")and not (centreNode.down in closedList): successors.append(centreNode.down)
if (centreNode.left != 0) and (centreNode.left.content != "wall")and not (centreNode.left in closedList): successors.append(centreNode.left)
if (centreNode.right != 0) and (centreNode.right.content != "wall")and not (centreNode.right in closedList): successors.append(centreNode.right)
for successor in successors:
successor.parent = centreNode
successor.distance = manhattanWeight(successor, goal)
successor.netWeight = successor.weight + successor.distance
if (checkNodeEquality(successor, goal)): return goal
if (not(successor in openList and successor.netWeight < openList[openList.index(successor)].netWeight)):
if (not(successor in closedList and successor.netWeight < closedList[closedList.index(successor)].netWeight)):
openList.insert(0,successor)
closedList.insert(0,centreNode)
lastTurnWeight = centreNode.netWeight
def checkNodeEquality(nodeA, nodeB):
return nodeA.x == nodeB.x and nodeA.y == nodeB.y
def findSmallestWeightedNode(openNodeList, previousWeighting):
if (len(openNodeList)<=4):
return compareMinimums(openNodeList)
else:
smallestWeightedNode = compareMinimums(openNodeList[:4])
if (smallestWeightedNode.netWeight <= previousWeighting):
return smallestWeightedNode
else:
return compareMinimums(openNodeList)
def compareMinimums(openNodeList):
minimumWeight = 10000000
for openNode in openNodeList:
if openNode.netWeight < minimumWeight:
minimumWeight = openNode.netWeight
minimumWeightNode = openNode
return minimumWeightNode
def calculatePathWeight(start, goal):
totalWeight = 0
currentNode = astar(start, goal)
while (currentNode.parent != 0):
totalWeight += currentNode.netWeight
lastNode = currentNode
currentNode = currentNode.parent
totalWeight += currentNode.netWeight
print("currentNode: ", currentNode.x, currentNode.y)
print("lastNode: ", lastNode.x, lastNode.y)
if (currentNode.y - lastNode.y == 1): direction = "up"
elif (currentNode.y - lastNode.y == -1): direction = "down"
elif (currentNode.x - lastNode.x == 1): direction = "left"
elif (currentNode.x - lastNode.x == -1): direction = "right"
else: direction = "fail"
return [totalWeight, direction]
|
375c3c159d03fef9573d88b80e29b7bd532544a4 | c3forlive/uip-prog3 | /Tareas/Tarea2.py | 543 | 3.796875 | 4 | #Tarea2
#License by : Karl A. Hines
#Velocidad
#Crear un programa en Python que resuelva el siguiente problema
#de física:
#Una ambulancia se mueve con una velocidad de 120 km/h y
#necesita recorrer un tramo recto de 60km.
#Calcular el tiempo necesario, en segundos,
#para que la ambulancia llegue a su destino.
#La fórmula a utilizar es: velocidad = distancia / tiempo.
velocidad = 120
distancia = 60
tiempo = velocidad / distancia
print ('El tiempo a recorrer es '+str(tiempo))
print ('El tiempo en segundos es '+str((tiempo)*3600))
|
47e4b1b02962b4264cc9836d2733dd0c5ea674f6 | nixil/python_study | /insertion_sort.py | 340 | 3.984375 | 4 | def insertionSort(ar):
for j in range(1, len(ar)):
key = ar[j]
i = j - 1
while i >= 0 and ar[i] > key:
ar[i + 1] = ar[i]
i -= 1
print " ".join([str(x) for x in ar])
ar[i + 1] = key
print " ".join([str(x) for x in ar])
return ar
insertionSort([2, 4, 6, 8, 3]) |
6ba56f86733692c643f7c7e7e1808773a56d23f3 | nancypareta/Dice-Roll-Game | /dice roll game .py | 477 | 3.53125 | 4 | import tkinter
import random
root=tkinter.Tk()
root.geometry('600x600')
root.title('Roll Dice')
l1=tkinter.Label(root,text='',font=('Helvetica',260))
def rolldice():
dice=['\u2680','\u2681','\u2682','\u2683','\u2684','\u2685']
l1.configure(text=f'{random.choice(dice)}{random.choice(dice)}')
l1.pack()
b1=tkinter.Button(root,text="let's Roll dice...........",foreground='red',command=rolldice)
b1.place(x=330,y=0)
b1.pack()
root.mainloop() |
d332a00c6b70b60c577c65af2257d7bd6437c280 | ruben-fuertes/rosalind | /mmch.py | 595 | 3.703125 | 4 | from sys import argv
from math import factorial
file = open(argv[1])
seq = ''
for line in file:
line = line.rstrip().upper()
if not line.startswith('>'): seq+=line
# seq = 'CAGCGUGAUCACCAGCGUGAUCAC'
def maxmatches(sec):
'''This function takes a RNA sequence and
calculates the number of different max matches
that can be made'''
A = sec.count('A')
U = sec.count('U')
G = sec.count('G')
C = sec.count('C')
print(A,U,G,C)
return factorial(max(A,U))//factorial(max(A,U)-min(A,U)) * factorial(max(G,C))//factorial(max(G,C)-min(G,C))
print (maxmatches(seq))
|
ef81ba52131119c1e7052aa18f9cecda63883f1c | zhangdzh/GWC_Projects | /RandomMenu.py | 1,317 | 4.09375 | 4 | from random import *
entrees=["burger", "chicken", "steak", "pasta"]
sides=["macaroni and cheese", "salad", "fries", "biscuit", "coleslaw", "fruit"]
desserts=["sundae", "cheesecake", "strawberry shortcake", "pie"]
drinks=["soda", "smoothie", "milkshake", "water"]
print("Here's your random menu:")
EntreeIndex=randint(0, len(entrees)-1)
SidesIndex=randint(0, len(sides)-1)
SidesIndex2=randint(0, len(sides)-1)
DessertIndex=randint(0, len(desserts)-1)
DrinkIndex=randint(0, len(drinks)-1)
print("Your entree is", entrees[EntreeIndex])
print("Your sides are", sides[SidesIndex], "and", sides[SidesIndex2])
print("Your dessert is", desserts[DessertIndex])
print("Your drink is", drinks[DrinkIndex])
dessertprice=randint(3,7)
entreeprice=randint(7,12)
sidesprice=randint(3,6)
sidesprice2=randint(2,5)
drinkprice=randint(1,3)
'''if EntreeIndex==0 or 3:
entreeprice=9
else:
entreeprice=12
if SidesIndex==0 or 2 or 3:
sidesprice=3
else:
sidesprice=5
if SidesIndex2==0 or 2 or 3:
sidesprice2=3
else:
sidesprice2=5
if DessertIndex==0 or 1:
dessertprice=7
else:
dessertprice=5
if DrinkIndex==0 or 3:
drinkprice=1
else:
drinkprice=3'''
print("Your total cost is", entreeprice+sidesprice+dessertprice+sidesprice2+drinkprice, "dollars")
|
8e5865daf077399e2e57f53532c0600611a6f717 | dr2moscow/GeekBrains_Education | /I четверть/Основы языка Python (Вебинар)/Lesson-1/hw_1_6.py | 2,173 | 3.75 | 4 | '''
# 6
Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров.
Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего.
Требуется определить номер дня, на который результат спортсмена составит не менее b километров.
Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня.
Например: a = 2, b = 3.
Результат:
1-й день: 2
2-й день: 2,2
3-й день: 2,42
4-й день: 2,66
5-й день: 2,93
6-й день: 3,22
Ответ: на 6-й день спортсмен достиг результата — не менее 3 км.
'''
growth = 1.1
try:
a = float(input("Введите пожалуйста результат спортсмена в первый день: "))
except ValueError:
print('Число введено неверно. Будет заменено на 1.')
a = 1
try:
b = float(input("Введите пожалуйста желаемый результат спортсмена при текущем уровне улучшения: "))
except ValueError:
print('Число введено неверно. Будет заменено на 2.')
b = 2
if b <= a:
print(f'Число введено неверно. Будет заменено на {a + 1}.')
b = a + 1
# Итерационный метод
a_to_b = a
count = 1
while a_to_b < b:
a_to_b = a_to_b * growth
count += 1
print(f"Спортсмен достигнет результата через : {count} дня(-ей,-ь). (рассчитано в цикле)")
# Логичный метод
import math
period = int(-(-math.log(b/a, growth) // 1)) + 1
print(f"Спортсмен достигнет результата через : {period} дня(-ей,-ь). (рассчитано по формуле)")
|
01ed5a8e3395ce7ca90b82ee6d4a8c9f1d1ab67a | dr2moscow/GeekBrains_Education | /I четверть/Основы Python (Видеокурс)/Python_1_7/Task_1_7_1.py | 749 | 3.625 | 4 | # Задание # 1
#
# Даны два списка фруктов. Получить список фруктов, присутствующих в обоих исходных списках.
# Примечание: Списки фруктов создайте вручную в начале файла.
list_1 = ['Апельсин', 'Ананас', 'Манго', 'Маракуйя', 'Фейхуа', 'Банан', 'Помело', 'Апельсин']
list_2 = ['Апельсин', 'Яблоко', 'Груша', 'Грейпфрут', 'Гранат', 'Хурма', 'Манго', 'Апельсин']
list_common = [el for el in list_1 if list_2.count(el) > 0]
print(list_common)
list_common = [el for el in list_1 if el in list_2]
print(list_common)
|
839276f68d78539ebce39b5cbd8de329282fd68e | dr2moscow/GeekBrains_Education | /I четверть/Основы языка Python (Вебинар)/Lesson-2/homework_2.py | 4,143 | 4.0625 | 4 | # print("***********************************************************************")
# print(" Задание № 1")
# print("***********************************************************************")
# '''
# # 1
# Даны два произвольные списка. Удалите из первого списка элементы присутствующие во втором списке.
# '''
#
# my_list_1 = [2, 5, 8, 2, 12, 12, 4, 4, 4]
# my_list_2 = [2, 7, 12, 3]
#
# for number in my_list_1[:]:
# print(number)
# if number in my_list_2:
# my_list_1.remove(number)
# print('removing')
# print(my_list_1)
#
# my_list_1 = [2, 5, 8, 2, 12, 12, 4, 4, 4]
# my_list_2 = [2, 7, 12, 3]
# for list_val in my_list_2:
# while list_val in my_list_1:
# my_list_1.remove(list_val)
#
# print(my_list_1)
# print("***********************************************************************")
# print(" Задание № 2")
# print("***********************************************************************")
# '''
# # 2
# Дана дата в формате dd.mm.yyyy, например: 02.11.2013. Ваша задача — вывести дату в текстовом виде,
# например: второе ноября 2013 года. Склонением пренебречь (2000 года, 2010 года)
# '''
# date_dict = {'01':'первое','02':'второе','03':'третье','04':'четвертое','05':'пятое',
# '06':'шестое','07':'седьмое','08':'восьмое','09':'девятое','10':'десятое',
# '11':'одиннадцатое','12':'двенадцатое','13':'тринадцатое','14':'четырнадцатое','15':'пятнадцатое',
# '12':'шестнадцатое','17':'семнадцатое','18':'восемнадцатое','19':'девятнадцатое','20':'двадцатое',
# '21':'двадцать первое','22':'двадцать второе','23':'двадцать третье','24':'двадцать четвертое','25':'двадцать пятое',
# '26':'двадцать шестое','27':'двадцать седьмое','28':'двадцать восьмое','29':'двадцать девятое','30':'тридцатое',
# '31':'тридцать первое'}
#
# month_dict = {'01':'января','02':'февраля','03':'марта','04':'апреля','05':'мая',
# '06':'июня','07':'июля','08':'августа','09':'сентября','10':'октября',
# '11':'ноября','12':'декабря'}
#
# changed_date = '17.04.1979'
#
# dd = changed_date[:2]
# mm = changed_date[3:5]
# yyyy = changed_date[-4:]
# print(dd, mm, yyyy)
#
# changed_date_in_word = '{} {} {} года'.format(date_dict[dd], month_dict[mm], yyyy)
# print(f'Дата прописью: {changed_date_in_word}')
#
# print("***********************************************************************")
# print(" Задание № 3")
# print("***********************************************************************")
# '''
# # 3
# Дан список заполненный произвольными целыми числами.
# Получите новый список, элементами которого будут только уникальные элементы исходного.
# '''
#
# my_list_1 = [2, 2, 5, 12, 8, 2, 12]
# my_set_1 = set([])
# my_set_1_dublicates = set([])
#
# for list_val in my_list_1:
# if list_val in my_set_1:
# my_set_1_dublicates.add(list_val)
# else:
# my_set_1.add(list_val)
#
# my_list_2 = list(my_set_1 - my_set_1_dublicates)
#
# print(f'Новый список, который содержит только уникальные элементы: {my_list_2}')
print(type(10)) = <class 'int'>
type(10) == int - РАБОТАЕТ
print(type(None)) - <class 'NoneType'>
type(None) == NoneType - НЕ РАБОТАЕТ. Можно как-то обойти? |
44db1bec51190545210fd7565518ad602e33b937 | dr2moscow/GeekBrains_Education | /I четверть/Основы языка Python (Вебинар)/lesson-5/hw_5_5.py | 2,192 | 3.78125 | 4 | # Задание # 5
#
# Создать (программно) текстовый файл, записать в него программно набор чисел,
# разделенных пробелами. Программа должна подсчитывать сумму чисел в файле и выводить ее на экран.
from random import randint
def cat_numbers(file_object):
# Генератор, который считыват "слова" разделенные пробелами и, преобразовав их в числа, передает во внешний код.
str_var = ''
eof = False
while not eof:
symbol = file_object.read(1)
if symbol == '':
symbol = ' '
eof = True
if str_var == '':
break
if symbol != ' ':
str_var = str_var + symbol
else:
try:
current_number = float(str_var)
except ValueError:
current_number = 0
str_var = ''
yield current_number
if __name__ == '__main__':
# file_name = 'lesson_5_task_5_temporary_file.txt'
file_name = input(f'Введите имя файла, в котором будут записаны числа: ')
quantity = randint(10, 100)
numbers_sum = 0
numbers_count = 0
# Программное создание и запись файла с числами
with open(file_name, 'w', encoding='utf-8') as file_obj:
for el in range(quantity):
print(f'{randint(1000, 350000)/100}', file=file_obj, end=' ')
# Чтение файла и суммирование всех чисел из него происходит с помощью генератора
with open(file_name, 'r', encoding='utf-8') as file_obj:
for curr_number in cat_numbers(file_obj):
numbers_sum += curr_number
numbers_count += 1
print(f'{numbers_count}) {curr_number}. А сумма стала равной: {numbers_sum}')
print()
print(f'Сумма всех ({numbers_count} штук(-и, -а)) равна {numbers_sum}')
|
773d9211d4e6037aff180f87f135d11e0f660d7e | dr2moscow/GeekBrains_Education | /I четверть/Основы языка Python (Вебинар)/lesson-3/hw_3_3.py | 696 | 4.15625 | 4 | '''
Задание # 3
Реализовать функцию my_func(), которая принимает три позиционных аргумента, и
возвращает сумму наибольших двух аргументов.
'''
def f_max_2_from_3(var_1, var_2, var_3):
return var_1 + var_2 + var_3 - min(var_1, var_2, var_3)
my_vars = []
for count in range(3):
try:
var = float(input(f'Введите число # {count+1}: '))
except ValueError:
print('Должно быть число! По умолчанию подставлена 1')
var = 1
my_vars.append(var)
print(f'{f_max_2_from_3(my_vars[0], my_vars[1], my_vars[2])}')
|
a3c81c5b91daffbd7de1fbe55e2fce7eac26cd80 | dr2moscow/GeekBrains_Education | /I четверть/Основы языка Python (Вебинар)/lesson-3/hw_3_4.py | 1,434 | 4.125 | 4 | '''
Задание # 3
Реализовать функцию my_func(), которая принимает три позиционных аргумента, и
возвращает сумму наибольших двух аргументов.
'''
def f_my_power(base, power):
base__power = 1
for count in range(power*(-1)):
base__power *= base
return 1 / base__power
try:
var_1 = float(input('Введите действительное положительное: '))
except ValueError:
print('Должно быть число! По умолчанию подставлена 1')
var_1 = 1
try:
var_2 = int(input('Введите целое отрицательное число: '))
if var_2 > 0:
print('Число должно быть отрицательным. Поставим минус за Вас')
var_2 = 0 - var_2
elif var_2 == 0:
print('0 не подходит. Подставим -1')
var_2 = -1
except ValueError:
print('целое отрицательное число. А вы ввели что-то друге. Подставим вместо Вас -1')
var_2 = -1
print(f'Результат работы моей функции: {f_my_power(var_1, var_2)}')
print(f'Результат работы системной функции python: {var_1**var_2}. Для визуальной проверки результата')
|
c89455cedb014aca5fa8d634476fa9aedb2381c0 | mug-auth/ssl-chewing | /src/utilities/numpyutils.py | 2,600 | 4.03125 | 4 | from typing import Tuple, Optional, List
import numpy as np
from utilities.typingutils import is_typed_list
def is_numpy_1d_vector(x):
"""Check if ``x`` is a numpy ndarray and is a 1-D vector."""
return isinstance(x, np.ndarray) and len(x.shape) == 1
def is_numpy_2d_vector(x, column_vector: Optional[bool] = True):
"""
Check if ``x`` is a numpy ndarray and is a 1-2 vector.
:param x: The variable to check
:param column_vector: If True, vector should be a column vector, i.e. x.shape=(n,1). If False, vector should be a
row vector, i.e. x.shape=(1,n). If None, it can be any of the two.
"""
if not (isinstance(x, np.ndarray) and len(x.shape) == 2):
return False
if column_vector is None:
return True
if column_vector:
return x.shape[1] == 1
else:
return x.shape[0] == 1
def is_numpy_vector(x):
return is_numpy_1d_vector(x) or is_numpy_2d_vector(x, None)
def is_numpy_matrix(x, cols: int = None, rows: int = None):
if not isinstance(x, np.ndarray):
return False
if not len(x.shape) == 2:
return False
if rows is not None and x.shape[0] != rows:
return False
if cols is not None and x.shape[1] != cols:
return False
return True
def ensure_numpy_1d_vector(x: np.ndarray, force: bool = False):
assert isinstance(x, np.ndarray)
assert isinstance(force, bool)
shape: Tuple = x.shape
if len(shape) == 1:
return x
elif len(shape) == 2 and (shape[0] == 1 or shape[1] == 1):
return x.reshape((x.size,))
elif force:
return x.reshape((x.size,))
else:
raise ValueError("Cannot ensure 1D vector for matrices, unless force=True")
def ensure_numpy_2d_vector(x: np.ndarray, column_vector: bool = True):
assert isinstance(x, np.ndarray)
assert isinstance(column_vector, bool)
shp: Tuple = x.shape
dim: int = len(shp)
if dim == 1:
if column_vector:
return x.reshape((shp[0], 1))
else:
return x.reshape((1, shp[0]))
elif dim == 2:
if column_vector:
assert shp[1] == 1
else:
assert shp[0] == 1
return x
else:
raise ValueError("x.shape has " + str(dim) + ", expected 1 or 2 instead")
def setdiff1d_listint(set1: List[int], set2: List[int]) -> List[int]:
assert is_typed_list(set1, int)
assert is_typed_list(set2, int)
nset1: np.ndarray = np.array(set1)
nset2: np.ndarray = np.array(set2)
return np.setdiff1d(nset1, nset2).tolist()
|
229ae10428cfaa24615c9c329ee3258baa93943d | YuRen-tw/my-university-code | /cryptography/c2019-p4/maxima_interface.py | 807 | 3.578125 | 4 | '''
Interact with Maxima (a computer algebra system) via command line
'''
from subprocess import getoutput as CLI
def maxima(command):
command = 'display2d:false$' + command
output = CLI('maxima --batch-string=\'{}\''.format(command))
'''
(%i1) display2d:false$
(%i2) <CMD>
(%o2) <RESULT>
'''
return output[output.index('(%o2)')+5:].strip()
def primep(n):
output = maxima('primep({});'.format(n))
return output == 'true'
def factor(n):
output = maxima('factor({});'.format(n))
result = []
for prime_power in output.split('*'):
prime_power = (prime_power+'^1').split('^')[:2]
result.append(tuple(int(i) for i in prime_power))
return result
def next_prime(n):
output = maxima('next_prime({});'.format(n))
return int(output)
|
ef1ebb2ba1f95a2d8c09f3dc32af9d2ffec17499 | CyberTaoFlow/Snowman | /Source/server/web/exceptions.py | 402 | 4.3125 | 4 | class InvalidValueError(Exception):
"""Exception thrown if an invalid value is encountered.
Example: checking if A.type == "type1" || A.type == "type2"
A.type is actually "type3" which is not expected => throw this exception.
Throw with custom message: InvalidValueError("I did not expect that value!")"""
def __init__(self, message):
Exception.__init__(self, message) |
c61d5128252a279d1f6c2b6f054e8ea1ead7b2af | rup3sh/python_expr | /general/trie | 2,217 | 4.28125 | 4 | #!/bin/python3
import json
class Trie:
def __init__(self):
self._root = {}
def insertWord(self, string):
''' Inserts word by iterating thru char by char and adding '*"
to mark end of word and store complete word there for easy search'''
node = self._root
for c in string:
if c not in node:
node[c] = {}
node = node[c]
node['*'] = string
def printTrie(self):
node = self._root
print(json.dumps(self._root, indent=2))
##Utility methods
def isWord(self, word):
''' check if word exists in trie'''
node = self._root
for c in word:
if c not in node:
return False
node = node[c]
# All chars were seen
return True
#EPIP, Question 24.20
def shortestUniquePrefix(self, string):
'''shortest unique prefix not in the trie'''
prefix = []
node = self._root
for c in string:
prefix.append(c)
if c not in node:
return ''.join(prefix)
node = node[c]
return ''
def startsWithPrefix(self, prefix):
''' return suffixes that start with given prefix '''
# Simulating DFS
def _dfs(node):
stack = []
stack.append(node)
temp = []
while stack:
n = stack.pop()
for c in n.keys():
if c == '*': #Word end found
temp.append(n[c])
else: #Keep searching
stack.append(n[c])
return temp
##Position node to the end of prefix list
node = self._root
for c in prefix:
if c not in node:
break
node = node[c]
return _dfs(node)
def main():
t_list = "mon mony mont monty monday mondays tea ted teddy tom tony tori tomas tomi todd"
words = t_list.split()
trie = Trie()
for word in words:
trie.insertWord(word)
#trie.printTrie()
#Utility method test
target = 'teal'
#print(target, "Is in tree?", trie.isWord(target))
target = 'teddy'
#print(target, "Is in tree?", trie.isWord(target))
target = 'temporary'
#shortest_unique_not_in_trie = trie.shortestUniquePrefix(target)
#print("shortest_unique_not_in_trie is :", shortest_unique_not_in_trie)
suffixes = trie.startsWithPrefix('mon')
print("Words starting with prefix:", suffixes)
if __name__=="__main__":main()
|
08f9852f9cf2c1ac4a5b25899e4e0afb5f1d91ff | rup3sh/python_expr | /Recursion/palindrome | 493 | 3.890625 | 4 | #!/bin/python3
def isPalindrome(word):
def extractChars(word):
chars = []
for w in word.lower():
if w in 'abcdefghijklmnopqrstwxyz':
chars.append(w)
return ''.join(chars)
def isPalin(s):
if len(s)==1:
return True
else:
return s[0]==s[-1] and isPalin(s[1:-1])
chars = extractChars(word)
print(chars)
return isPalin(chars)
def main():
word = "Madam, I'm adam"
result = isPalindrome(word)
print(result)
if __name__=="__main__":main()
|
7cbfc86f3d6399973e6cd05e0a83bb4ad2f6e023 | rup3sh/python_expr | /generators/coroutine | 1,934 | 3.734375 | 4 | #!/bin/python3
import pdb
import sys
## Generators are somewhat opposite of coroutines.Generators produce values and coroutines consume value.
##Coroutines
## - consume value
## - May not return anything
## - not for iteration
## Technically, coroutines are built from generators.
## Couroutine does this -
## - Continually receives input, processes input, stops at yield statement
## - Coroutine have send method
## - Yield in coroutine pauses the flow and also captures values
## (Very powerful in data processing programs)
def main(argv):
coroutineDemo()
def barebones_coroutine():
while True:
x = yield # Essentially, control pauses here until send is invoked by caller.
print("In coroutine:" + str(x))
def mc_decorator(func):
def myfunc_wrapper(*args, **kwargs):
cr = func(*args, **kwargs)
next(cr)
return cr
return myfunc_wrapper
#Elaborate coroutine with decoratr to wrap it so that calling code does not have to call next
@mc_decorator
def message_checker(initial_list):
counter = 0
try:
while True:
received_msg = yield
if received_msg in initial_list:
counter+=1
print(counter)
except GeneratorExit: # This happens during closing the coroutine
print ("Final Count:" + str(counter))
def coroutineDemo():
try:
bbcor = barebones_coroutine()
## Have to initialize the internal generator
next(bbcor)
bbcor.send(25)
bbcor.send("This is how we do it!")
bbcor.close()
print("Closed barebones coroutine")
the_list = ["stanley", "ave", "fremont", "los angeles", "istanbul", "moscow", "korea", "india"]
mc = message_checker(the_list)
#next(mc) DUE TO DECORATOR, we do not have to do this
mc.send('japan')
mc.send('korea')
mc.send('usa')
mc.send('india')
mc.send('india')
mc.close()
except Exception as e:
sys.stderr.write("Exception:{}".format(str(e)))
if __name__ == "__main__":main(sys.argv[0:])
|
23f20f17dc25cc3771922706260d43751f2584c5 | rup3sh/python_expr | /generators/generator | 1,446 | 4.34375 | 4 | #!/bin/python3
import pdb
import sys
##Reverses words in a corpus of text.
def main(argv):
generatorDemo()
def list_of_even(n):
for i in range(0,n+1):
if i%2 == 0:
yield i
def generatorDemo():
try:
x = list_of_even(10)
print(type(x))
for i in x:
print("EVEN:" + str(i))
the_list = ["stanley", "ave", "fremont", "los angeles", "istanbul", "moscow", "korea"]
#Print the reverse list
print(the_list[::-1])
#list comprehension
new_list = [ item.upper() for item in the_list ]
print("NEWLIST:" + str(new_list))
#generator expression
gen_object = (item.upper() for item in the_list)
#You can also call next() on this generator object
# Generator would call a StopIteration Execepton if you cannot call next anymore
print(type(gen_object))
##This yields the items one by one toa list
newlist = list(gen_object)
print("YET ANOTHER NEWLIST:" + str(new_list))
# As you can see, generator objects cannot be reused
# So this would be empty
one_more_list = list(gen_object)
print("ONE MORE LIST:" + str(one_more_list))
# Capitalizes the word and reverses the word in one step
ultimate_gen = (item[::-1] for item in (item.upper() for item in the_list))
print("ULTIMATE LIST:" + str(list(ultimate_gen)))
except Exception as e:
sys.stderr.write("Exception:{}".format(str(e)))
if __name__ == "__main__":main(sys.argv[0:])
|
8fe1986f84ccd0f906095b651aa98ba62b2928b8 | rup3sh/python_expr | /listsItersEtc/listComp | 1,981 | 4.1875 | 4 | #!/bin/python3
import pdb
import sys
##Reverses words in a corpus of text.
def main(argv):
listComp()
def listComp():
the_list = ["stanley", "ave", "fremont", "los angeles", "istanbul", "moscow", "korea"]
print(the_list[0:len(the_list)])
#Slicing
#the_list[2:] = "paz"
#['stanley', 'ave', 'p', 'a', 'z'] # This replaces everything from indexs 2 onwards
#Everything except the last one
#print(str(the_list[:-1]))
#Prints 2, 3 only
#print(str(the_list[2:4]))
#Prints reverse -N onwards, but counting from 1 "los angeles", "istanbul", "moscow", "korea"]
#print(str(the_list[-4:]))
#Prints from start except last 4 ["stanley", "ave", "fremont",
#print(str(the_list[:-4]))
#Prints from start, skips odd positions ['ave', 'los angeles', 'moscow']
#print(str(the_list[1::2]))
#Prints from reverse at 1, skips odd positions (only 'ave')
#print(str(the_list[1::-2]))
#the_list[3:3] = "California"
#['stanley', 'ave', 'fremont', 'C', 'a', 'l', 'i', 'f', 'o', 'r', 'n', 'i', 'a', 'los angeles', 'istanbul', 'moscow', 'korea']
#Insert new list at a position
#the_list[3:3] = ["California"]
#['stanley', 'ave', 'fremont', 'California', 'los angeles', 'istanbul', 'moscow', 'korea']
# Modifies list to ['stanley', 'ave', 'fremont', 'California', 'moscow', 'korea']
#the_list[3:5] = ["California"]
# Delete middle of the list ['stanley', 'ave', 'fremont','moscow', 'korea']
#the_list[3:5] = []
##Add list to another list
add_this = ["africa", "asia", "antarctica"]
the_list.extend(add_this)
#Insert in the list
the_list.insert(4, 'alameda')
#Delete an element by index
x = the_list.pop(3)
#Delete an element by name
the_list.remove('moscow')
print(str(the_list))
#In-place reversal
the_list.reverse()
print(str(the_list))
print("Index of africa is: "+ str(the_list.index('africa')))
# Count occurrence
print(str(the_list.count('fremont')))
if __name__ == "__main__":main(sys.argv[0:])
|
c2aeb4bc202edaf3417d097408e5c680d0ffc1c0 | maksymshylo/statistical_pattern_recognition | /lab4/trws_algorithm.py | 9,184 | 3.5 | 4 | from numba import njit
import numpy as np
@njit
def get_right_down(height,width,i,j):
'''
Parameters
height: int
height of input image
width: int
width of input image
i: int
number of row
j: int
number of column
Returns
N: list
array of 2 neighbours coordinates
calculates 2 neighbours: Right and Down
(i,j)--(i,j+1)
|
(i+1,j)
examples:
>>> get_right_down(2,2,2,2.)
Traceback (most recent call last):
...
Exception: invalid indices values (not integer)
>>> get_right_down(-2,2,2,2)
Traceback (most recent call last):
...
Exception: height or width is less than zero
>>> get_right_down(2,2,2,2)
[]
>>> get_right_down(2,2,0,0)
[[0, 1], [1, 0]]
'''
if width <= 0 or height <= 0:
raise Exception('height or width is less than zero')
if type(i) is not np.int64 or type(j) is not np.int64:
raise Exception('invalid indices values (not integer)')
# i,j - position of pixel
# [Right, Down] - order of possible neighbours
# array of neighbour indices
nbs = []
# Right
if 0<j+1<=width-1 and 0<=i<=height-1:
nbs.append([i,j+1])
# Down
if 0<i+1<=height-1 and 0<=j<=width-1:
nbs.append([i+1,j])
return nbs
@njit
def get_neighbours(height,width,i,j):
'''
Parameters
height: int
height of input image
width: int
width of input image
i: int
number of row
j: int
number of column
Returns
N: tuple
neighbours coordinates, neighbours indices, inverse neighbours indices
calculates neighbours in 4-neighbours system (and inverse indices)
(i-1,j)
|
(i,j-1)--(i,j)--(i,j+1)
|
(i+1,j)
examples:
>>> get_neighbours(-1,1,1,1)
Traceback (most recent call last):
...
Exception: height or width is less than zero
>>> get_neighbours(3,3,-1,-1)
([], [], [])
>>> get_neighbours(3,3,0,0)
([[0, 1], [1, 0]], [0, 2], [1, 3])
>>> get_neighbours(3,3,0,1)
([[0, 0], [0, 2], [1, 1]], [1, 0, 2], [0, 1, 3])
>>> get_neighbours(3,3,1,1)
([[1, 0], [1, 2], [0, 1], [2, 1]], [1, 0, 3, 2], [0, 1, 2, 3])
'''
# i,j - position of pixel
# [Left, Right, Up, Down] - order of possible neighbours
# array of neighbour indices
if width <= 0 or height <= 0:
raise Exception('height or width is less than zero')
nbs = []
# neighbour indices
nbs_indices = []
# inverse neighbour indices
inv_nbs_indices = []
# Left
if 0<=j-1<width-1 and 0<=i<=height-1:
nbs.append([i,j-1])
inv_nbs_indices.append(1)
nbs_indices.append(0)
# Right
if 0<j+1<=width-1 and 0<=i<=height-1:
nbs.append([i,j+1])
inv_nbs_indices.append(0)
nbs_indices.append(1)
# Upper
if 0<=i-1<height-1 and 0<=j<=width-1:
nbs.append([i-1,j])
inv_nbs_indices.append(3)
nbs_indices.append(2)
# Down
if 0<i+1<=height-1 and 0<=j<=width-1:
nbs.append([i+1,j])
inv_nbs_indices.append(2)
nbs_indices.append(3)
N = (nbs, inv_nbs_indices, nbs_indices)
return N
@njit(fastmath=True, cache=True)
def forward_pass(height,width,n_labels,Q,g,P,fi):
'''
Parameters
height: int
height of input image
width: int
width of input image
n_labels: int
number of labels in labelset
Q: ndarray
array of unary penalties
g: ndarray
array of binary penalties
P: ndarray
array consist of best path weight for each direction (Left,Right,Up,Down)
fi: ndarray
array of potentials
Returns
P: ndarray
array consist of best path weight for each direction (Left,Right,Up,Down)
fi: ndarray
updated array of potentials
updates fi, according to best path for 'Left' and 'Up' directions
'''
# for each pixel of input channel
for i in range(1,height):
for j in range(1,width):
# for each label in pixel
for k in range(n_labels):
# P[i,j,0,k] - Left direction
# P[i,j,2,k] - Up direction
# calculate best path weight according to formula
P[i,j,0,k] = max(P[i,j-1,0,:] + (1/2)*Q[i,j-1,:] - fi[i,j-1,:] + g[i,j-1,1,:,k])
P[i,j,2,k] = max(P[i-1,j,2,:] + (1/2)*Q[i-1,j,:] + fi[i-1,j,:] + g[i-1,j,3,:,k])
# update potentials
fi[i,j,k] = (P[i,j,0,k] + P[i,j,1,k] - P[i,j,2,k] - P[i,j,3,k])/2
return (P,fi)
@njit(fastmath=True, cache=True)
def backward_pass(height,width,n_labels,Q,g,P,fi):
'''
Parameters
height: int
height of input image
width: int
width of input image
n_labels: int
number of labels in labelset
Q: ndarray
array of unary penalties
g: ndarray
array of binary penalties
P: ndarray
array consist of best path weight for each direction (Left,Right,Up,Down)
fi: ndarray
array of potentials
Returns
P: ndarray
array consist of best path weight for each direction (Left,Right,Up,Down)
fi: ndarray
updated array of potentials
updates fi, according to best path for 'Right' and 'Down' directions
'''
# for each pixel of input channel
# going from bottom-right to top-left pixel
for i in np.arange(height-2,-1,-1):
for j in np.arange(width-2,-1,-1):
# for each label in pixel
for k in range(n_labels):
# P[i,j,1,k] - Right direction
# P[i,j,3,k] - Down direction
# calculate best path weight according to formula
P[i,j,3,k] = max(P[i+1,j,3,:] + (1/2)*Q[i+1,j,:] + fi[i+1,j,:] + g[i+1,j,2,k,:])
P[i,j,1,k] = max(P[i,j+1,1,:] + (1/2)*Q[i,j+1,:] - fi[i,j+1,:] + g[i,j+1,0,k,:])
# update potentials
fi[i,j,k] = (P[i,j,0,k] + P[i,j,1,k] - P[i,j,2,k] - P[i,j,3,k])/2
return (P,fi)
def trws(height,width,n_labels,K,Q,g,P,n_iter):
'''
Parameters
height: int
height of input image
width: int
width of input image
n_labels: int
number of labels in labelset
K: ndarray
array of colors (mapping label->color)
Q: ndarray
array of unary penalties
g: ndarray
array of binary penalties
P: ndarray
array consist of best path weight for each direction (Left,Right,Up,Down)
n_iter: int
number of iteratations
Returns
output: ndarray
array of optimal labelling (with color mapping)
one iteration of TRW-S algorithm (forward and backward pass),
updates fi, according to best path for all directions
examples:
>>> trws('height','width','n_labels','K','Q','g','P',-1)
Traceback (most recent call last):
...
Exception: n_iter <=0
>>> trws('height','width',3,np.array([0,1]),'Q','g','P',2)
Traceback (most recent call last):
...
Exception: n_labels do not match with real number of labels
>>> trws('height','width',2,np.array([0,1]),[],'g','P',2)
Traceback (most recent call last):
...
Exception: unary or binary penalties are empty
'''
if n_iter <= 0:
raise Exception('n_iter <=0')
if len(K) != n_labels:
raise Exception('n_labels do not match with real number of labels')
if Q==[] or g ==[]:
raise Exception('unary or binary penalties are empty')
# initialise array of potentials with zeros
fi = np.zeros((height,width,n_labels))
# initialize Right and Down directions
P,_ = backward_pass(height,width,n_labels,Q,g,P,fi.copy())
for iteratation in range(n_iter):
P,fi = forward_pass(height,width,n_labels,Q,g,P,fi)
P,fi = backward_pass(height,width,n_labels,Q,g,P,fi)
# restore labelling from optimal energy after n_iter of TRW-S
labelling = np.argmax(P[:,:,0,:] + P[:,:,1,:] - fi + Q/2, axis = 2)
# mapping from labels to colors
output = K[labelling]
return output
def optimal_labelling(Q,g,K,n_iter):
'''
Parameters
Q: ndarray
updated unary penalties
g: ndarray
updated binary penalties
K: ndarray
set of labels
n_iter: int
number of iteratations
Returns
labelling: ndarray
array of optimal labelling (with color mapping)
for one channel in input image
initialize input parameters for TRW-S algorithm,
and returns best labelling
'''
height,width,_ = Q.shape
n_labels = len(K)
P = np.zeros((height,width,4,n_labels))
labelling = trws(height,width,n_labels,K,Q,g,P,n_iter)
return labelling
|
928c18324e7cfa1493ec890560c4adf3501a67f2 | jromero132/pyanimations | /animations/monte_carlo/pi.py | 5,178 | 3.546875 | 4 | from matplotlib import animation
import math
import matplotlib.pyplot as plt
import numpy as np
def is_in_circle(center: tuple, radius: float, point: tuple) -> bool:
return math.sqrt(sum((c - p) ** 2 for c, p in zip(center, point))) <= radius
class MonteCarloPiEstimation:
def __init__(self, display: "Display"):
self.display = display
@staticmethod
def expected_value():
return 3.1415
@property
def pi(self):
return 4 * self.cnt_in_points / self.cnt_all_points
def init(self):
self.cnt_in_points = 0
self.cnt_all_points = 0
def step(self):
in_points, out_points = [ [], [] ], [ [], [] ]
points = np.random.uniform(self.display.bottom_left_corner, self.display.top_right_corner, (self.display.points_per_iteration, 2))
for p in points:
if is_in_circle(self.display.center, self.display.radius, p):
in_points[ 0 ].append(p[ 0 ])
in_points[ 1 ].append(p[ 1 ])
else:
out_points[ 0 ].append(p[ 0 ])
out_points[ 1 ].append(p[ 1 ])
return in_points, out_points
def display_step(self, i: int):
in_points, out_points = self.step()
self.cnt_in_points += len(in_points[ 0 ])
self.cnt_all_points += len(in_points[ 0 ]) + len(out_points[ 0 ])
self.display.display_step(self, i, in_points, out_points)
def estimate(self):
self.init()
self.display.estimate(self.display_step)
class Display:
def __init__(self, iterations: int, points_per_iteration: int, bottom_left_corner: tuple, length: float):
self.iterations = iterations
self.points_per_iteration = points_per_iteration
self.bottom_left_corner = bottom_left_corner
self.top_right_corner = tuple(x + length for x in bottom_left_corner)
self.radius = length / 2
self.center = tuple(x + self.radius for x in self.bottom_left_corner)
class GraphicDisplay(Display):
def __init__(self, iterations: int, points_per_iteration: int, bottom_left_corner: tuple, length: float):
super(GraphicDisplay, self).__init__(iterations, points_per_iteration, bottom_left_corner, length)
def init(self):
self.fig, (self.monte_carlo_graph, self.pi_estimation_graph) = plt.subplots(1, 2)
self.fig.canvas.manager.set_window_title("Monte Carlo Pi Estimation")
self.monte_carlo_graph.set_aspect("equal")
self.monte_carlo_graph.set_xlim(self.bottom_left_corner[ 0 ], self.top_right_corner[ 0 ])
self.monte_carlo_graph.set_ylim(self.bottom_left_corner[ 1 ], self.top_right_corner[ 1 ])
self.monte_carlo_graph.set_xlabel(f"I = {self.iterations} ; N = {self.points_per_iteration}")
angle = np.linspace(0, 2 * np.pi, 180)
circle_x = self.center[ 0 ] + self.radius * np.cos(angle)
circle_y = self.center[ 1 ] + self.radius * np.sin(angle)
self.monte_carlo_graph.plot(circle_x, circle_y, color = "blue")
self.pi_estimation_graph.set_xlim(1, self.iterations)
self.pi_estimation_graph.set_ylim(0, 5)
self.pi_estimation_graph.set_title("Pi Estimation")
self.pi_estimation_graph.set_xlabel(f"Iteration")
expected_value = MonteCarloPiEstimation.expected_value()
self.pi_estimation_graph.set_ylabel(f"Pi Estimation (E = {expected_value})")
self.pi_estimation_graph.axhline(y = expected_value, color = "red", linestyle = "--")
self.fig.tight_layout()
self.estimations = [ [], [] ]
def display_step(self, obj: MonteCarloPiEstimation, i: int, in_points: list, out_points: list):
self.monte_carlo_graph.set_title(f"Iteration {i + 1} - Pi estimation: {obj.pi:.4f}")
self.monte_carlo_graph.scatter(*in_points, color = "blue", s = 1)
self.monte_carlo_graph.scatter(*out_points, color = "red", s = 1)
self.estimations[ 0 ].append(i + 1)
self.estimations[ 1 ].append(obj.pi)
self.pi_estimation_graph.plot(*self.estimations, color = "blue", linestyle = "solid", marker = '')
def estimate(self, func: "Function"):
self.init()
anim = animation.FuncAnimation(self.fig, func, frames = self.iterations, init_func = lambda: None, repeat = False)
# anim.save("demo.gif")
plt.show()
class ConsoleDisplay(Display):
def __init__(self, iterations: int, points_per_iteration: int, bottom_left_corner: tuple, length: int, *, log: bool = True):
super(ConsoleDisplay, self).__init__(iterations, points_per_iteration, bottom_left_corner, length)
self.log = log
def display_step(self, obj: MonteCarloPiEstimation, i: int, in_points: list, out_points: list):
if self.log:
print(f"Iteration {i + 1} - Pi estimation: {obj.pi:.4f}")
def estimate(self, func: "Function"):
for i in range(self.iterations):
func(i)
if __name__ == "__main__":
graph = MonteCarloPiEstimation(
display = GraphicDisplay(
iterations = 100,
points_per_iteration = 1000,
bottom_left_corner = (0, 0),
length = 1
)
)
graph.estimate()
# pi_estimation = MonteCarloPiEstimation(
# display = ConsoleDisplay(
# iterations = 1000,
# points_per_iteration = 1000,
# bottom_left_corner = (0, 0),
# length = 1,
# log = False
# )
# )
# pi_sum, trials = 0, 100
# for i in range(trials):
# pi_estimation.estimate()
# print(f"Iteration {i + 1} - Pi estimation: {pi_estimation.pi:.4f}")
# pi_sum += pi_estimation.pi
# print(f"After {trials} iterations, by the Law of Large Numbers pi estimates to: {pi_sum / trials:.4f}") |
6a13d6d6451f023372ed1583ef6d77c5ea9ca1fa | uribe-convers/Genomic_Scripts | /VCF-to-Tab_to_Fasta_IUPAC_Converter.py | 2,107 | 3.578125 | 4 | #!/usr/bin/python
def usage():
print("""
This script is intended for modifying files from vcftools that contain
biallelic information and convert them to fasta format. After the vcf file has
been exported using the vcf-to-tab program from VCFTools, and transposed in R,
or Excel, this script will change biallelic information at each site to only
one nucleotide using UIPAC conventions when the alleles are different
(heterozygous) or to the available nucleotide if both alleles are the same.
If one alle is present and the other one is missing, the script will change
the site to the available allele. All of these changes will be saved to a
new file in fasta format.
written by Simon Uribe-Convers - www.simonuribe.com
October 23rd, 2017
To use this script, type: python3.6 VCF-to-Tab_to_Fasta_IUPAC_Converter.py VCF-to-Tab_file Output_file
""")
import sys
import __future__
if __name__ == "__main__":
if len(sys.argv) != 3:
usage()
print("~~~~Error~~~~\n\nCorrect usage: python3.6 "+sys.argv[0]+" VCF-to-Tab file + Output file")
sys.exit("Missing either the VCF-to-Tab and/or the output files!")
filename = open(sys.argv[1], "r")
outfile = open(sys.argv[2] + ".fasta", "w")
# def IUPAC_converter(filename, outfile):
IUPAC_Codes = { "G/G" : "G", "C/C" : "C", "T/T" : "T", "A/A" : "A",
"-/G" : "G", "-/C" : "C", "-/T" : "T", "-/A" : "A", "G/-" : "G",
"C/-" : "C", "T/-" : "T", "A/-" : "A", "G/T" : "K", "T/G" : "K",
"A/C" : "M", "C/A" : "M", "C/G" : "S", "G/C" : "S", "A/G" : "R",
"G/A" : "R", "A/T" : "W", "T/A" : "W", "C/T" : "Y", "T/C" : "Y",
"./." : "N", "-/-" : "N", "N/N" : "N", "-/N" : "N", "N/-" : "N",
"N/." : "N", "./N" : "N"
}
for line in filename:
species_name = line.strip().split(" ")[0]
data = line.strip().split(" ")[1:]
new_data = [IUPAC_Codes[i] for i in data]
# print(new_data)
new_data2 = "".join(new_data)
outfile.write(">" + species_name + "\n" + new_data2 + "\n")
print("\n\n~~~~\n\nResults can be found in %s.fasta\n\n~~~~" %sys.argv[2])
sys.exit(0)
|
af559157ebe1d11b16c38556ed60da92a9694098 | bryanluu/AdventOfCode2020 | /Day11/Day11.py | 4,326 | 3.71875 | 4 | #!/bin/python3
import sys
import numpy as np
filename = sys.argv[1] if len(sys.argv) > 1 else "input"
part = (int(sys.argv[2]) if len(sys.argv) > 2 else None)
while part is None:
print("Part 1 or 2?")
reply = input("Choose: ")
part = (int(reply) if reply == "1" or reply == "2" else None)
# characters in problem statement
FLOOR = "."
EMPTY = "L"
OCCUPIED = "#"
# Show numpy grid
def show_grid(grid):
for row in grid:
print(" ".join(map(str, row)))
# Gets the adjacent surrounding seats of seat at r, c
def get_adjacent(seats, r, c):
neighbors = np.zeros(seats.shape, dtype=bool)
rows, cols = seats.shape
adjacent = np.array([(r+i, c+j) for i in range(-1, 2) for j in range(-1, 2)
if 0 <= r+i < rows and 0 <= c+j < cols and not (i == 0 and j == 0)])
for nr, nc in adjacent:
neighbors[nr, nc] = True
return adjacent, neighbors
# Gets visible seats from seat at r, c
def get_visible_chairs(seats, r, c):
neighbors = np.zeros(seats.shape, dtype=bool)
rows, cols = seats.shape
valid = lambda row, col: (0 <= row < rows and 0 <= col < cols and not (row == r and col == c)
and seats[row, col] != FLOOR)
first = lambda x: np.array(x[0], dtype=int) if len(x) > 0 else np.array([-1, -1], dtype=int)
W = np.array([(r, c-i) for i in range(cols) if valid(r, c-i)], dtype=int)
E = np.array([(r, c+i) for i in range(cols) if valid(r, c+i)], dtype=int)
N = np.array([(r-i, c) for i in range(cols) if valid(r-i, c)], dtype=int)
S = np.array([(r+i, c) for i in range(cols) if valid(r+i, c)], dtype=int)
NW = np.array([(r-i, c-i) for i in range(cols) if valid(r-i, c-i)], dtype=int)
NE = np.array([(r-i, c+i) for i in range(cols) if valid(r-i, c+i)], dtype=int)
SW = np.array([(r+i, c-i) for i in range(cols) if valid(r+i, c-i)], dtype=int)
SE = np.array([(r+i, c+i) for i in range(cols) if valid(r+i, c+i)], dtype=int)
visible = np.stack((first(W), first(E), first(N), first(S),
first(NW), first(NE), first(SE), first(SW)))
ok = np.all(visible >= 0, axis=1)
for nr, nc in visible[ok]:
neighbors[nr, nc] = True
return visible[ok], neighbors
def initialize_neighbors(seats, positions):
neighbors = {}
for r, c in positions[seats != FLOOR]:
neighbors[r, c] = (get_adjacent(seats, r, c) if part == 1 else get_visible_chairs(seats, r, c))
return neighbors
# Simulate one round of seating
def simulate_round(seats, positions, neighbors):
limit = (4 if part == 1 else 5)
simulation = seats.copy()
flipped = np.where(seats == EMPTY, np.full(seats.shape, OCCUPIED),
np.where(seats == OCCUPIED, np.full(seats.shape, EMPTY), np.full(seats.shape, FLOOR)))
changed = np.zeros(seats.shape, dtype=bool)
occupied = np.zeros(seats.shape, dtype=int)
if np.all(seats != OCCUPIED): # if no seats are occupied
chairs = (seats == EMPTY)
simulation[chairs] = OCCUPIED
changed[chairs] = True
else: # else check each position that might change
for r, c in positions[seats != FLOOR]:
_, isneighbor = neighbors[r, c]
occupied[r, c] = np.sum((seats[isneighbor] == OCCUPIED))
changed = (((seats == EMPTY) & (occupied == 0)) | ((seats == OCCUPIED) & (occupied >= limit)))
simulation = np.where(changed, flipped, seats)
return changed, simulation
def solve(filename):
seats = []
with open(filename) as file:
for line in file:
line = line.rstrip()
seats.append([c for c in line])
seats = np.array(seats)
rows, cols = seats.shape
positions = np.array([[(r, c) for c in range(cols)] for r in range(rows)])
round = 0
print("---Initial Layout---")
show_grid(seats)
print("Building neighbor list...")
neighbors = initialize_neighbors(seats, positions)
print("===Simulation Begin===")
while True:
changed, simulation = simulate_round(seats, positions, neighbors) # simulate round
if np.any(changed): # if any seat changed, continue, otherwise, finish
round += 1
print(f"---Round {round}---")
seats = simulation
show_grid(seats)
else:
break
print(f"===Simulation Ended after {round} rounds===")
print(f"Part {part} # occupied: {np.sum(seats == OCCUPIED)}")
if __name__ == '__main__':
print(f"Input file: {filename}")
import time
start = time.time()
solve(filename)
end = time.time()
print(f"Solve time: {end-start} seconds") |
bf9c44aa4e028f2c736743cdc88956637a73a7c7 | GuoZhouBoo/python_study | /basics/container.py | 1,605 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : container.py
# Author: gsm
# Date : 2020/5/6
def test_list():
list1 = [1, 2, 3, 4, '5']
print list1
print list1[0] # 输出第0个元素
print list1[0:3] # 输出第1-3个元素
print list1[0:] # 输出从0到最后的元素
print list1[0:-1] # 输出从0到最后第二元素
list1.append(6) # 更新列表
print list1
del list1[1] # 删除指定位置的元素
print list1
list1.reverse() # 逆置列表
print list1
print '-----------------'
def test_tuple():
# 元组无法被二次赋值,相当于一个只读列表
tuple1 = ('runoob', 786, 2.23, 'john', 70.2)
tinytuple = (123, 'john')
print tuple1 # 输出完整元组
print tuple1[0] # 输出元组的第一个元素
print tuple1[1:3] # 输出第二个至第四个(不包含)的元素
print tuple1[2:] # 输出从第三个开始至列表末尾的所有元素
print tinytuple * 2 # 输出元组两次
print tuple1 + tinytuple # 打印组合的元组
print '-----------------'
def test_dict():
dict1 = {}
dict1['one'] = "This is one"
dict1[2] = "This is two"
tinydict = {'name': 'john', 'code': 6734, 'dept': 'sales'}
print dict1['one'] # 输出键为'one' 的值
print dict1[2] # 输出键为 2 的值
print tinydict # 输出完整的字典
print tinydict.keys() # 输出所有键
print tinydict.values() # 输出所有值
print '-----------------'
if __name__ == '__main__':
test_list()
test_tuple()
test_dict()
|
283ce2bf5201efde8d0b6998758be87d8b06db3d | shamoons/Reinforcement_Learning_Textbook_Exercises | /Chapter_5/Exercise_12/env.py | 4,713 | 3.546875 | 4 | '''
This will build the enviroment of the racetrack
'''
import numpy as np
import random
class RaceTrack():
def __init__(self):
super(RaceTrack, self).__init__()
print("Environment Hyperparameters")
print("===============================================================================")
# Initalize possible starting states
self.starting_states = [[] for i in range(6)]
for i in range(6):
self.starting_states[i] = [31, i+3]
print("Starting States: \n",self.starting_states)
# Initalize terminal states
self.terminal_states = [[] for i in range(6*4)]
for i in range(6):
for j in range(4):
self.terminal_states[(i*4) + j] = [i, 16 + j]
print("Terminal States: \n",self.terminal_states)
# Generate a set representing a square grid 32x17
self.states = [[] for i in range((32*17))]
for i in range(17):
for j in range(32):
self.states[(i*32) + j] = [j,i]
#print("States: \n",self.states)
# Make sets of locations not in possible states
bound1 = [[] for i in range(4)]
for i in range(4):
bound1[i] = [i,0]
bound2 = [[] for i in range(18)]
for i in range(18):
bound2[i] = [i + 14,0]
bound3 = [[] for i in range(3)]
for i in range(3):
bound3[i] = [i,1]
bound4 = [[] for i in range(10)]
for i in range(10):
bound4[i] = [i + 22,1]
bound5 = [[0,2]]
bound6 = [[] for i in range(3)]
for i in range(3):
bound6[i] = [i + 29,2]
bound7 = [[] for i in range(25)]
for i in range(25):
bound7[i] = [i + 7,9]
bound8 = [[] for i in range(182)]
for i in range(26):#rows
for j in range(7):#cols
bound8[(i*7) + j] = [i + 6, j +10]
bounds = bound1 + bound2 + bound3 + bound4 + bound5 + bound6 + bound7 + bound8
#print("Bounds: \n", bounds)
# Remove states in the square grid that are out of bounds
for state in bounds: self.states.remove(state)
print("===============================================================================\n")
def step(self, state, action, velocity):
'''
Given the current state, chosen action and current velocity
this function will compute the next state, velocity and whether
the episode reached its terminal state
'''
print("Step Results")
print("==========================")
print("Inital State: ", state)
print("Intial Velocity: ", velocity)
print("Action ", action)
print("--------------------------")
# Compute new velocity given action
intial_velocity = velocity
velocity = list(np.asarray(velocity) + np.asarray(action))
# Ensure velocity is within bounds
self.fix_velocity(velocity, intial_velocity, state)
# The way the gridworld is set up a negative velocity is needed to move forward
# so this just flips the sign of the vertical velocity for calculating next state
mirror_effect = [-1*velocity[0], velocity[1]]
# Calculate new state
state = list(np.asarray(state) + mirror_effect)
# Determine if the new state is out of bounds
if state not in self.states:
state = random.choice(self.starting_states)
velocity = [0,0]
# Determine if episode is over
terminate = False
if state in self.terminal_states:
terminate = True
print("Final State: ", state)
print("Final Velocity: ", velocity)
print("Episode Terminated: ", terminate)
print("==========================\n")
return state, velocity, terminate
def fix_velocity(self,velocity, intial_velocity, state):
'''
This function will limit the velocity to its max and min value and
prevent the car from coming to a stop at any point
'''
if velocity[0] > 3:
velocity[0] = 3
if velocity[0] < -3:
velocity[0] = -3
if velocity[1] > 3:
velocity[1] = 3
if velocity[1] < -3:
velocity[1] = -3
if velocity == [0,0] and state not in self.starting_states:
velocity = intial_velocity
if velocity == [0,0] and state in self.starting_states:
velocity = [1,0]
return velocity
|
86643d87a3010f92442c579b7a6fd3f7154af55f | scottfoltz/pythonpractice | /password-gen.py | 1,419 | 4.03125 | 4 | import random
print ('**********************************************')
print ('Welcome to the Welcome to the Password Generator!')
print ('**********************************************')
#define an array that will hold all of the words
lineArray = []
passwordArray = []
#prompt user
filename = input('Enter the name of the file to analyze: ')
#read in the file one line at a time without newlines
with open(filename) as my_file:
lineArray = my_file.read().splitlines()
print(*lineArray)
#we loop based on the value of numPasswords
for i in range(numPasswords):
#get first word
word1 = random.choice(wordArray)
#get second word and capitalize it
word2 = random.choice(wordArray).upper()
#get second word
word3 = random.choice(wordArray)
#get the random number within respected range
num = random.randint(1000,9999)
#find and replace I, S, O in word2
word2 = word2.replace('I','1')
word2 = word2.replace('S','$')
word2 = word2.replace('O','0')
#concantenate the final string and make sure to change num to a string
finalPassword = word1 + word2 + word3 + str(num)
#add that password to our passwordArray
passwordArray.append(finalPassword)
#Here is where we print our results
print('Here are the passwords:')
#using a for loop iterating through our passwords
for i in passwordArray:
#print each password in the list
print(i)
|
3b597cae9208d703e6479525625da55ddc18b976 | DahlitzFlorian/python-zero-calculator | /tests/test_tokenize.py | 1,196 | 4.1875 | 4 | from calculator.helper import tokenize
def test_tokenize_simple():
"""
Tokenize a very simple function and tests if it's done correctly.
"""
func = "2 * x - 2"
solution = ["2", "*", "x", "-", "2"]
assert tokenize.tokenize(func) == solution
def test_tokenize_complex():
"""
Tokenize a more complex function with different whitespaces and
operators. It also includes functions like sin() and con().
"""
func = "x*x- 3 /sin( x +3* x) + cos(9*x)"
solution = [
"x",
"*",
"x",
"-",
"3",
"/",
"sin",
"(",
"x",
"+",
"3",
"*",
"x",
")",
"+",
"cos",
"(",
"9",
"*",
"x",
")",
]
assert tokenize.tokenize(func) == solution
def test_tokenize_exponential_operator():
"""
Test if tokenizing a function including the exponential operator **
works as expected and that it does not add two times the multiplication
operator to the final list.
"""
func = "2 ** 3 * 18"
solution = ["2", "**", "3", "*", "18"]
assert tokenize.tokenize(func) == solution
|
56f1c9051a35ef64d3eb05510e2025089fb30315 | potsawee/py-tools-ged | /gedformatconvert.py | 1,861 | 3.671875 | 4 | import sys
def one_word_to_one_sentence(input, output):
with open(input, 'r') as f1:
with open(output, 'w') as f2:
newline = []
for line in f1:
if line == '\n':
if len(newline) > 0:
f2.write(' '.join(newline) + '\n')
newline = []
else:
word = line.strip().split()[0]
# ----------- Filter ----------- #
# for swb work - 8 Feb 2019
# disf = line.strip().split()[1]
# if disf != 'O':
# continue
# ------------------------------ #
newline.append(word)
print('convert one_word_to_one_sentence done!')
def one_sentence_to_one_word(input, output):
with open(input, 'r') as f1:
with open(output, 'w') as f2:
newline = []
for line in f1:
# if line == '\n':
# if len(newline) > 0:
# f2.write(' '.join(newline) + '\n')
# newline = []
# else:
# word = line.strip().split()[0]
# newline.append(word)
words = line.split()
for word in words:
f2.write(word + '\n')
f2.write('\n')
print('convert one_sentence_to_one_word done!')
def main():
if len(sys.argv) != 4:
print("Usage: python3 gedformatconvert.py [1/2] input output")
return
convert_type = sys.argv[1]
input = sys.argv[2]
output = sys.argv[3]
if convert_type == '1':
one_word_to_one_sentence(input, output)
elif convert_type == '2':
one_sentence_to_one_word(input, output)
if __name__ == '__main__':
main()
|
bf3e0d3733919a06c12fdbb8fede6596bd237db3 | potsawee/py-tools-ged | /assertdata.py | 1,286 | 3.59375 | 4 | #!/usr/bin/python3
'''
Count how many lines in the target files have zero, one, two, ... field
Args:
path: path to the target file
Output:
print the output to the terminal e.g.
linux> python3 assertdata.py clctraining-v3/dtal-exp-GEM4-1/output/4-REMOVE-DM-RE-FS.tsv
zero: 3649
one: 0
two: 0
three: 0
four: 0
five+: 69248
'''
import sys
def main():
# path = '/home/alta/BLTSpeaking/ged-pm574/artificial-error/lib/tsv/ami1.train.ged.tsv'
if len(sys.argv) != 2:
print('Usage: python3 assertdata.py path')
return
path = sys.argv[1]
zero = 0
one = 0
two = 0
three = 0
four = 0
fivemore = 0
with open(path) as file:
for line in file:
n = len(line.split())
if n == 0:
zero += 1
elif n == 1:
one += 1
elif n == 2:
two += 1
elif n == 3:
three += 1
elif n == 4:
four += 1
else:
fivemore += 1
print("zero: ", zero)
print("one: ", one)
print("two: ", two)
print("three: ", three)
print("four: ", four)
print("five+: ", fivemore)
if __name__ == "__main__":
main()
|
3d3306cf4afef96d48911f7bda81ff98f595be84 | jvcampbell/py-bits-n-bobs | /Udemy-Python-Bootcamp/Capstone Project/Caesar Cipher/Caesar Cipher.py | 2,877 | 4.03125 | 4 | # Encode/Decode text to caesar cipher. Includes a brute force method when the key is not known
import os
class CaesarCipherSimple(object):
alphabet = 'abcdefghijklmnopqrstuvwxyz '
def __init__(self):
pass
def encode(self,input_text,cipher_key = 1):
'''Encodes text by receiving an integer and shifting the letter position that number of letters to the right '''
try:
return self.__shift_letter(input_text,cipher_key)
except:
print('Error encoding')
def decode(self,input_text,cipher_key = 1):
'''Encodes text by receiving an integer and shifting the letter position that number of letters to the right '''
try:
return self.__shift_letter(input_text,cipher_key*-1)
except:
print('Error decoding')
def brute_decode(self,input_text):
'''Encodes text by receiving an integer and shifting the letter position that number of letters to the right '''
try:
decode_list = []
for cipher_key in range(1,27):
decode_list.append(str(cipher_key) + ': ' + self.__shift_letter(input_text,cipher_key*-1))
return decode_list
except:
print('Error decoding')
def __shift_letter(self,input_text,shift_nb):
new_text = ''
for text_letter in input_text:
letter_position = CaesarCipherSimple.alphabet.find(text_letter)
letter_position += shift_nb
# Handle letters that shift off the 0-26 position spectrum of the alphabet
if shift_nb > 0:
if letter_position > 27:
letter_position -= 27
else:
pass
else:
if letter_position < 0:
letter_position += 27
new_text += self.alphabet[letter_position]
return new_text
#-----------------------------------------------#
os.system('cls')
print('-------------------------Caesar Cypher--------------------------')
action = input('Are you encoding a message or decoding a cypher? (e/d):').lower()
input_text = input('Enter the text you want to work on:').lower()
try:
input_key = int(input('Enter an integer cypher key (press Enter if you don''t know):'))
except:
input_key = None
if action == 'd' and (input_key == 0 or input_key is None):
print('\n!!! Time to brute force this thing !!!')
action = 'bd'
cypherMachine = CaesarCipherSimple()
print('\n----------OUTPUT----------------')
if action == 'e':
print(cypherMachine.encode(input_text,input_key))
elif action == 'd':
print(cypherMachine.decode(input_text,input_key))
elif action =='bd':
for attempt in cypherMachine.brute_decode(input_text):
print(attempt)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.