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 |
|---|---|---|---|---|---|---|
6eff70e2d978b89ddd53e28c4e16a70fce9b43d7 | Lobo2008/LeetCode | /113_Path_Sum_II.py | 3,895 | 3.890625 | 4 | """
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
[
[5,4,11,2],
[5,8,4,5]
]
"""
# 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, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
"""
root-to-leaf ,sum = 20
5
/ \
4 8
/ / \
11 13 7
root=5, sum=20
left=(5.left=4,20-5=15) => left(4,15)
root=4,sum=15
left=(4.left=11,15-4=11) => left(11,11)
root=11,sum=11
root.left=root.rigt=none and root.val=sum,所以返回[[sum]] = [[11]]
所以rs=[4]+[11]=[4,11]
rigt=(4.rigt=none) => rigt(none),为空,所以返回[]
因为rigt为空,所以两个for循环以后rs还是[4,11]
所以返回[4,11]
所以rs=[5]+[4,11]=[5,4,11]
rigt=(5.rigt=8,20-5=15) => rigt(8,15)
root=8,sum=15
left=(8.left=13,15-8=7) => left(13,7)
root=13,sum=7
root.left=root.rigt=none and root.val!=sum,所以返回[]
rigt=(8.rigt=7 ,15-8=7) => rigt(7,7)
root=7,sum=7
root.left=root.rigt=none and root.val=sum,收益以返回[[7]]
所以for循环以后rs=[8] + [7] =[8,7]
所以rs=[5]+[8]+[7] =[5,8,7]
"""
#ref:https://www.cnblogs.com/chruny/p/5258576.html
rs = []
if not root:
return rs
if not root.left and not root.right:
if root.val == sum:
return [[sum]]
else:
return []
left = self.pathSum(root.left, sum-root.val)
right = self.pathSum(root.right, sum-root.val)
for item in left:
rs.append([root.val] + item)
for item in right:
rs.append([root.val] + item)
return rs
#ref:https://blog.csdn.net/u013291394/article/details/50740194
def pathSum2(self, root, sum):
rs = []
self.helper2(root,sum,[], rs)
return rs
"""
5
/ \
4 8
/ / \
11 13 7
这种方法,在helper里面没有直接返回rs,而是在调用helper的那个方法里面返回的
"""
def helper2(self, root, sum, currRs, rs):
if not root:
return
sum -= root.val
"""
到达叶子节点,切叶子节点的值等于当前sum的值,就放到rs里面
"""
if sum == 0 and not root.left and not root.right:
rs.append(currRs + [root.val])
if root.left:
self.helper2(root.left, sum, currRs+[root.val], rs)
if root.right:
self.helper2(root.right, sum, currRs+[root.val], rs)
"""
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
"""
so = Solution()
l1 = TreeNode(5)
l21 = TreeNode(4)
l22 = TreeNode(8)
l31 = TreeNode(11)
l32 = TreeNode(13)
l33 = TreeNode(4)
l41 =TreeNode(7)
l42 = TreeNode(2)
l43 = TreeNode(5)
l44 = TreeNode(1)
root = l1
l1.left = l21; l1.right = l22
l21.left = l31; l22.left= l32; l22.right = l33
l31.left = l41; l31.right = l42; l33.left = l43; l33.right = l44
sum = 22
print(so.pathSum(root,sum))
print(so.pathSum2(root,sum))
|
08279e371c560a93d448f36f57f203cc0b194688 | Lobo2008/LeetCode | /212_Word_Search_II.py | 3,190 | 3.90625 | 4 | """
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example:
Input:
words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
Output: ["eat","oath"]
Note:
You may assume that all inputs are consist of lowercase letters a-z.
"""
class Solution:
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
"""
第一代的变体,遍历每个word,把符合要求的word存下即可
to be continue:
still TLE, pls ref this https://leetcode.com/problems/word-search-ii/discuss/59864/Python-code-use-trie-and-dfs-380ms
"""
rs = []
words = list(set(words))
for word in words:
if self.wordSearch(board, word):
rs.append(word)
return rs
"""
查找board中是否存在word ,也就是lc79的源代码
"""
def wordSearch(self, board, word):
if len(word) == 0: return True
if len(board) == 0 or len(board[0]) == 0: return False
if not self._hasEnoughChar(board, word): return False
for i in range(len(board)):
for j in range(len(board[0])):
if self.dfs(i,j, board, word):
return True
"""
dfs搜索
"""
def dfs(self, i, j, board, word):
if len(word) == 0: return True
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] != word[0]:
return False
visited = board[i][j]
board[i][j] = ' '
# rs =(self.dfs(i-1,j,board,word[1:]) or \
# self.dfs(i+1,j,board,word[1:]) or \
# self.dfs(i,j-1,board,word[1:]) or\
# self.dfs(i,j+1,board,word[1:]))
# board[i][j] = visited
# return rs
if self.dfs(i-1,j,board,word[1:]):
board[i][j] = visited
return True
if self.dfs(i+1,j,board,word[1:]):
board[i][j] = visited
return True
if self.dfs(i,j-1,board,word[1:]):
board[i][j] = visited
return True
if self.dfs(i,j+1,board,word[1:]):
board[i][j] = visited
return True
return False
"""
判断word里的元素的个数是否少于board里面的对应元素的个数,对提升速度有很大的影响
"""
def _hasEnoughChar(self, board, word):
from collections import Counter
c_w = Counter(word)
c_board = Counter([c for row in board for c in row])
for k,v in c_w.items():
if c_board[k] < v:
return False
return True
so = Solution()
board =\
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
words = ["oath","pea","eat","rain"]
print(so.findWords(board,words))
|
a0bfc34b5087331432998cb698a7dec6cc9a843a | Lobo2008/LeetCode | /16_3Sum_Closest.py | 10,353 | 3.90625 | 4 | """
Given an array nums of n integers and an integer target,
find three integers in nums such that the sum is closest to target.
Return the sum of the three integers. You may assume that each input would have exactly one solution.
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
"""
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
"""
#ref https://leetcode.com/problems/3sum-closest/discuss/7871/Python-O(N2)-solution/8988
#[-20, -4, -1, -1, 0, 1, 2, 7, 20] ,target= 15
先排序,然后固定一个数,然后每次从这个数后面的数开始找,用两个指针
比如,固定 -4(下标index=1),然后从剩下的元素newnum=[-1, -1, 0, 1, 2, 7, 20] 中开始找
两个指针,一个指针指向newnums的最左边,一个指向最右边(还原到nums里的下标就是left=index+1,right=len(nums)-1)
然后求三个数的和 sum = index + left + right ,注意,index是固定的,所以内循环每次更新 l 和r即可
如果 sum与target的差距(sum-target)小于 上一次的差距 (rs-tagget),则更新结果
sum每次和target比较,如果小于target,则左指针右移,反之右指针左移,相等的时候就是结果
"""
if len(nums) < 3:return
nums.sort()
rs = nums[0] + nums[1] + nums[2]
for i in range(len(nums) - 2):
l = i + 1
r = len(nums) - 1
while l < r:
tmpsum = nums[i] + nums[l] + nums[r]
if tmpsum == target:
return tmpsum
if abs(tmpsum - target) < abs(rs - target):
rs = tmpsum
if tmpsum < target:
l += 1
if tmpsum > target:
r -= 1
return rs
def threeSumClosest_old(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
"""
先找出threesum的组合,然后sum每个组合,遍历一遍就可以了?
a+b+c-target = x
min(x)
[-20,-4, -1, -1, 0, 1, 2,7,20] target = 13
=> [-4,-1,20] -4-1+20=15 最接近13
先找 target-a最小的,然后(target-a)-b最小的,最后(target-a-b)-c最小的
设置初始的最小最近值是前三个数相加,即min(x0)=clo =(-20)+(-4)+(-1) - 13 = -38
先固定一个元素a,比如-20,然后从[-4,-1, -1, 0, 1, 2,7,20]中找离新目标 newTarget=13-(-20)=33最近的元素
两个数初始最小值 clo2 = (-4)+(-1)=-5-target = -38
最边上两个数字和,(-4)+20 = 16 -> 16-newtarget(33) = -17
abs(-17)< abs(-38),距离比clo2更近,则当前最近就是 -17,
同时这两个和小于newtarget,所以从右边往左逼近 <--
vice versa
最后可以找到固定-20的时候[-4,-1, -1, 0, 1, 2,7,20]距离newtarget最近的值
如果这个值小于三元素的clo,则对clo进行更新,遍历万以后可以找到全局最小的那一个
用夹逼的方法,如果从两边迫近,
如果nums[low]+nums[high]= newtarget,则已经找到
如果nums[low]+nums[high] > newtarget,说明数字太大,右边往左逼近
如果nums[low]+nums[high] < newtarget,说明数字太小,左边往右逼近
每次nums[low]+nums[high] - newtarget的值都要进行判断
"""
nums.sort()
if len(nums) <=3: return sum(nums)
print('-----ori:',nums,',target=',target)
closet = nums[0] + nums[1] + nums[3] - target
i = 0
while i <= len(nums)-3:
newTarget = target -nums[i]
if i >= 1 and nums[i] == nums[i-1] and i < (len(nums)-3):
while nums[i] == nums[i-1] and i <(len(nums)-3) :
i += 1
continue
low, high = i+1, len(nums)-1
closet2 = nums[low] + nums[low+1] - newTarget
while low <high:
diff = nums[low] + nums[high] - newTarget
if diff == 0:#差值为0,说明找到了直接返回
return target
elif diff > 0:#太大了,所以往左逼近
high -= 1
while low < high and nums[high] == nums[high+1] and high > 2:
high -= 1
else:#太小了,所以往右逼近
low += 1
while low < high and nums[low] == nums[low-1] and low < len(nums)-2:
low += 1
closet2 = diff if abs(diff) < abs(closet2) else closet2
closet = closet2 if abs(closet2) < abs(closet) else closet
i += 1
return closet+target
"""
有更多注释、打印的代码
"""
def threeSumClosest1(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
"""
先找出threesum的组合,然后sum每个组合,遍历一遍就可以了?
a+b+c-target = x
min(x)
[-20,-4, -1, -1, 0, 1, 2,7,20] target = 13
=> [-4,-1,20] -4-1+20=15 最接近13
先找 target-a最小的,然后(target-a)-b最小的,最后(target-a-b)-c最小的
设置初始的最小最近值是前三个数相加,即min(x0)=clo =(-20)+(-4)+(-1) - 13 = -38
先固定一个元素a,比如-20,然后从[-4,-1, -1, 0, 1, 2,7,20]中找离新目标 newTarget=13-(-20)=33最近的元素
两个数初始最小值 clo2 = (-4)+(-1)=-5-target = -38
最边上两个数字和,(-4)+20 = 16 -> 16-newtarget(33) = -17
abs(-17)< abs(-38),距离比clo2更近,则当前最近就是 -17,
同时这两个和小于newtarget,所以从右边往左逼近 <--
vice versa
最后可以找到固定-20的时候[-4,-1, -1, 0, 1, 2,7,20]距离newtarget最近的值
如果这个值小于三元素的clo,则对clo进行更新,遍历万以后可以找到全局最小的那一个
用夹逼的方法,如果从两边迫近,
如果nums[low]+nums[high]= newtarget,则已经找到
如果nums[low]+nums[high] > newtarget,说明数字太大,右边往左逼近
如果nums[low]+nums[high] < newtarget,说明数字太小,左边往右逼近
每次nums[low]+nums[high] - newtarget的值都要进行判断
"""
nums.sort()
if len(nums) <=3:return sum(nums)
print('-----ori:',nums,',target=',target)
closet = nums[0] + nums[1] + nums[3] - target
i = 0
# for i in range(len(nums)-2):
while i <= len(nums)-3:
a = nums[i]
newTarget = target - a
"""
如果固定的元素一样,前一个处理了以后,直接跳过,比如[-4,-1,-1,0,1,1,1],
固定了-4,然后是-1 ,再接着一个-1,而第二个-1可以不用处理了,直接跳过到0
因为要留给low和high至少各一个元素,所以最多能跳到倒数第3个
跳过重复元素的优化,可以将耗时从171ms降到121ms
"""
if i >= 1 and nums[i] == nums[i-1] and i < (len(nums)-3):
print('~~~~~~~~~~~~~~~~~~',nums[i],' - ',nums[i-1])
print('**** before i=',i)
while nums[i] == nums[i-1] and i <(len(nums)-3) :
i += 1
print('**** i=',i)
continue
print(' i=',i)
print('先固定 ',a,',然后从 ',nums[i+1:],'中找离 ',newTarget,'最近的元素')
low = i+1
high = len(nums)-1
closet2 = nums[low] + nums[low+1] - newTarget
while low <high:
#twosum的 初始最小差值
print(' ',nums[low],' + ',nums[high],' = ',nums[low] + nums[high],' VS ',newTarget,' min=',closet2)
diff = nums[low] + nums[high] - newTarget
print(' diff=',diff)
if nums[low] + nums[high] == newTarget:#差值为0,说明找到了直接返回
print('****BINGO****')
return target
elif nums[low] + nums[high] > newTarget:#太大了,所以往左逼近
print(' 太大了,所以往 <-- 逼近')
high -= 1
print('high before=',high)
"""
[1,1,1,1,1,1]这种,因为固定元素占了一个,low占了一个,所以high最多能降到第3个元素,所以下标大于2的时候才能减一
"""
while low < high and nums[high] == nums[high+1] and high > 2:
high -= 1
print('high=',high)
else:#太小了,所以往右逼近
low += 1
print(' 太小了,所以往 --> 逼近')
"""
[1,1,1,1,1,1]这种,因为固定元素占了一个,high占了一个,所以low最多能升到倒数第2个元素
"""
while low < high and nums[low] == nums[low-1] and low < len(nums)-2:
low += 1
if abs(diff) < abs(closet2):#更新差值
print(' 更新差值为,',diff)
closet2 = diff#固定元素nums[i]时的min(x)
print('-----所以最小差值为 ',closet2)
if abs(closet2) < abs(closet):#全局min(x)
closet = closet2
i += 1
return closet+target
so = Solution()
nums = [-1, 2, 1, -4]; target = 1
nums = [-20,-4, -1, -1, 0, 1, 2,7,20] ;target = 15
# nums = [1,1,1,1,1,1,1,1]; target=0
# print(so.threeSumClosest1(nums, target))
print(so.threeSumClosest(nums, target))
|
5e8afcd27ad33b1f3ff0e83fd6d0227cde78f8ce | Lobo2008/LeetCode | /172_Factorial_Trailing_Zeroes.py | 2,130 | 3.640625 | 4 | """
Given an integer n, return the number of trailing zeroes in n!.
Example 1:
Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.
大概是,阶乘结果的0的数量?
5 = 5x4x3x2x1 = 120
10 = 10x9x8x7x6x5x4x3x2x1=3628800
方法一:
如果我们要判断出0的个数,如果我们直接求N!那么数据会很大,数据可能溢出,,
那么为了得到0的个数我们知道可以从10的角度进行判断,如果我们知道N!中10的个数,
我们就可以判断出0的个数,
如果N!=K*10^n,K是不能被10整除的数,那么我们可以根据n就可以得到0的个数,
考虑10的个数,我们必须对N!进行质因数的分解,N!=(2^x)*(3^y)(5^z)...........,由于2*5=10,
所以n只与x和z相关,
于是n=min(x,z),我们可以判断出x的个数必然大于z的个数,因为被2整除的数的频率大于被5整除的数的频率高,
所以n=z;
下面我们要判断出N1中5的个数,
因为N!=N*N-1*N-2*N-3.......................................
所以我们要判断出5的个数,我们可以对每个N,N-1,N-2,进行判断,就可以得到5的个数了
方法二:递归
if n >= 5:
return int(n/5) + int(self.trailingZeroes(n/5))
else:
return 0
因为0的数量只跟2x5有关,而5的数量必定比2的少,所以求5的个数即可
"""
class Solution(object):
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
#z=N/5+N/25+N/5^3+....................
count = 0
while n != 0:
count += int(n /5)
n = int(n/5)
return count
"""
recurssive
"""
def trailingZeroes2(self,n):
if n >= 5:
return int(n/5) + int(self.trailingZeroes(n/5))
else:
return 0
n = 668
n = 3322
so = Solution()
rs = so.trailingZeroes(n)
# rs = so.factorialX(n)
print(rs)
# for i in range(5,31,1):
# rs = so.factorialX(i)
# times = so.trailingZeroes(i)
# print(i,'=>',rs,':',times) |
3ac89a123fd5bd63ef80f404d8a3a13641faf047 | Lobo2008/LeetCode | /221_Maximal_Square.py | 1,840 | 3.625 | 4 | """
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Example:
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4
"""
class Solution:
def maximalSquare(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
"""
又是数组,应该是回溯+dfs
遍历每行每列,当找到一个1的时候,开始递归查找这个1右边和边的元素(因为遍历是从左往右从上往下的,所以不用再找左边和下边)
假设是这样,然后i=1,j=1,即处理到了x元素
1 1
1 x
此时,如果x元素是0,进行下一个判断
如果x元素是1,则此时的的正方形由x的左边[i][j-1],上边[i-1][j],左上边[i-1][j-1]决定,
如果这三个元素中有一个为0,则当前的最大面积只为1,即x元素本身
如果这三个元素都为1的时候,元素才是2,所以,此时dp[i][j] 等于2,
当判断到i=3,j=3的时候,也是一样的
"""
if len(matrix) == 0 or len(matrix[0]) == 0: return 0
h, w = len(matrix), len(matrix[0])
dp = [[0]*(w+1) for i in range(h+1)]
rs = 0
for i in range(1,h+1):
for j in range(1,w+1):
if matrix[i-1][j-1] == '0': continue
dp[i][j] = 1 + min(dp[i-1][j-1], dp[i][j-1], dp[i-1][j])
rs = max(rs, dp[i][j]**2)
return rs
"""
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4
"""
so = Solution()
matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
for item in matrix:
print(item)
print(so.maximalSquare(matrix))
|
4037956b9303d8030bf8e6dc550d3ea5dee51e7e | sureindia-in/contrastiveExplanation | /contrastiveRegressor/generate_Gompertz_sales.py | 2,749 | 3.765625 | 4 | '''
Generate sales for toy example (Experiment #2)
carlos.aguilar.palacios@gmail.com
'''
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import scipy
from sklearn.preprocessing import MinMaxScaler
import pandas as pd
def Gompertz_distribution(t=np.linspace(0, 5, 50), b_scale=1, eta_shape=0.2):
# https://www.wikiwand.com/en/Gompertz_distribution
return b_scale*eta_shape*np.exp(eta_shape)*np.exp(b_scale*t)*np.exp(-eta_shape*np.exp(b_scale*t))
def shifted_Gompertz_distribution(t=np.linspace(0, 5, 50), b_scale=0.4, eta_shape=10):
# https://www.wikiwand.com/en/Shifted_Gompertz_distribution
e_bt = np.exp(-b_scale*t)
return b_scale*e_bt*np.exp(-eta_shape*e_bt)*(1+eta_shape*(1-e_bt))
def generate_Gompertz_sales(num_samples,
mu_sales, sigma_sales,
price_mu,
discount_sigma,
shelf_capacity, shelf_impact,
b_scale, eta_shape):
'''Generate sales for toy example.
The discount effect on the sales is modelled as a shifted
Gompertz distribution.
The baseline sales are modelled as a Gaussian curve.
Parameters
----------
num_samples: integer
mu_sales: float
sigma_sales: float
discount_sigma: float
shelf_capacity: integer
shelf_impact: float
'''
# 1 - Baseline sales
baseline_sales = np.random.normal(mu_sales, sigma_sales, num_samples)
# 3 - Discount
# Let's assume that we are working with price cut promos, so the discount
# is always GE 0
# Half-normal distribution
discount_mu = 0.0
discount = np.abs(np.random.normal(discount_mu, discount_sigma, num_samples))
price = price_mu - discount
# 4 - Sales-gain due to the discount
# The impact of the price/discount on sales is modelled as a shifted Gompertz response.
# Tweak the Gompertz dist and scale the baseline sales
sales_response = lambda t: 1.0+(2.2*shifted_Gompertz_distribution(t, b_scale, eta_shape))
sales_driven_by_discount = np.multiply(sales_response(discount), baseline_sales)
# 4- Shelves
# Easy-peasy: A curve to map the increment per shelf
# This is fixed up to a 12% gain. This value is then multiplied by the shelf_impact
max_gain = 0.12
min_shelf_size = 0.0
max_shelf_size = 25
# Randomly pick the capacities from the list
shelves = np.random.choice(shelf_capacity, num_samples, replace=True)
shelves_gain = shelf_impact*max_gain*(shelves-min_shelf_size) \
/ (max_shelf_size-min_shelf_size)
shelf_sales = np.multiply(shelves_gain, sales_driven_by_discount)
product_sales = sales_driven_by_discount + shelf_sales
# Stick the data into a DF
df = pd.DataFrame({'price': price,
'discount': discount,
'baseline_sales': baseline_sales,
'shelves': shelves,
'shelf_sales': shelf_sales,
'product_sales': product_sales})
return df
|
4b3fe35e32f2184441be0ef7d9ced13a25f0e9b6 | TudorCovaci/FP | /Student management/Repos/GradeRepo.py | 1,574 | 3.828125 | 4 |
class GradeRepo:
"""
Class for grade repositories
"""
def __init__(self):
"""
Constructor
"""
self._data = []
def __len__(self):
"""
Returns the length of the repository
"""
return len(self._data)
def __str__(self):
"""
String format of repository
"""
string = ""
for grade in self._data:
string = string + str(grade) + "\n"
return string
def add(self, grade):
"""
Adds a grade to the repoistory
"""
self._data.append(grade)
def remove(self, grade):
"""
Removes a grade from repoistory
"""
self._data.remove(grade)
return True
def getAll(self):
"""
Returns the data
"""
return self._data
def findAllGradesForStudent(self, studID):
"""
Returns the list of student's grades
"""
listOfGrades = []
for grade in self._data:
if grade.studID == studID:
listOfGrades.append(grade)
return listOfGrades
def clear(self):
"""
Clears the repository
"""
return self._data.clear()
def findAllGradesForDiscipline(self, disciplineID):
"""
Return the list of the grades at the given discipline
"""
listOfGrades = []
for grade in self._data:
if grade.disciID == disciplineID:
listOfGrades.append(grade)
return listOfGrades
|
4657d0953674309d7f531e7a30c978894864ca4e | ezefranca/tob-stt | /rasa-bot/utils.py | 935 | 3.546875 | 4 | def write_story(intent, utter, file, iterations=1):
result_string = ''
for i in range(iterations):
name = input("What concept: ").strip('\n')
utter_name = name.replace(' ', '_')
result_string += f'\n## {intent} {name}\n' + \
f'* {intent}\n' + \
' - slot{"concept": ' + f'"{name}"' + '}\n' + \
f' - utter_{utter}_{utter_name}\n'
with open(file, 'a') as fp:
fp.write(result_string)
def write_response(utter, file, iterations=1):
result_string = '\n'
for i in range(iterations):
name = input("What concept: ").strip('\n')
response = input("What answer: ").strip('\n')
utter_name = name.replace(' ', '_')
result_string += f'utter_{utter}_{utter_name}:\n' + \
f' - text: "{response}"\n'
with open(file, 'a') as fp:
fp.write(result_string)
|
9e54b2d6778065c6077e094dae2720ee4d9f0063 | jrpresta/FantasyTrades | /entites.py | 896 | 3.78125 | 4 |
class User:
def __init__(self, user, objs):
self.user = user
self.players = objs
self.preferences = []
def add_obj(self, new_obj):
self.players += new_obj
def add_preferences(self, preferences):
"""Trying an ordered list of preferences"""
self.preferences = preferences
def __repr__(self):
return f'User: {self.user}\nPlayers: {[p.name for p in self.players]}'
def __str__(self):
return self.__repr__()
class Player:
def __init__(self, name):
self.name = name
self.is_available = True
self.preference = None
def add_preference(self, preference):
self.preference = preference
def __repr__(self):
return f'"{self.name}"'
def __str__(self):
return self.__repr__()
if __name__ == '__main__':
en_1 = User('Jon-Ross', [])
print(en_1)
|
3569b04b976c954b03aaa668ed19f2f0dcfa32be | bkp2/Lesson3 | /07_wall.py | 532 | 3.703125 | 4 | # -*- coding: utf-8 -*-
# (цикл for)
import simple_draw as sd
# Нарисовать стену из кирпичей. Размер кирпича - 100х50
# Использовать вложенные циклы for
# TODO здесь ваш код
for x in range(1200, 0, -100):
for y in range(0, 1200, 50):
x -= 50
point_left = sd.get_point(x,y)
point_right = sd.get_point(x+100,y+50)
sd.rectangle(left_bottom=point_left, right_top=point_right, color=sd.COLOR_RED, width=2)
sd.pause()
|
252a87d8a7dbe9766c4a0267abc893cd6dbbd480 | moon729/PythonAlgorithm | /5. 재귀 알고리즘/gcd.py | 268 | 4.03125 | 4 | #euclidean algorithm
def gcd(x:int, y:int) -> int:
if x < y:
x, y = y, x
if y == 0: return x
else:
return gcd(y, x%y)
if __name__ == '__main__':
x = int(input('x : '))
y = int(input('y : '))
print(f'gcd(x,y) = {gcd(x,y)}')
|
12d523ff33e120c1acc810313d9077697c40390d | moon729/PythonAlgorithm | /6.정렬 알고리즘/quick_sort1.py | 900 | 3.796875 | 4 | #퀵 정렬 알고리즘 구현
from typing import MutableSequence
def qsort(a: MutableSequence, left: int, right: int) -> None:
pl = left #왼쪽 커서
pr = right #오른쪽 커서
x = a[(left + right) // 2] #피벗(가운데 원소)
while pl <= pr:
while a[pl] < x: pl += 1
while a[pr] > x : pr -= 1
if pl <= pr:
a[pl], a[pr] = a[pr], a[pl]
pl += 1
pr -= 1
if left < pr: qsort(a, left, pr)
if right > pl: qsort(a, pl, right)
def quick_sort(a: MutableSequence) -> None:
qsort(a, 0, len(a) -1)
if __name__ == '__main__' :
print('퀵 정렬 수행')
num = int(input('원소 개수 입력 : '))
x = [None] * num
for i in range(num):
x[i] = int(input(f'x[{i}] : '))
quick_sort(x)
print('오름차순 정렬 완료')
for i in range(num):
print(f'x[{i}] = {x[i]}')
|
7daa3469d5686be5fde9a5e512c5463c13d984cd | hexmaster111/ll | /hexto10.py | 571 | 3.90625 | 4 | num = raw_input("Enter your number: ")
option = raw_input(" hex to binary(1)\n binary to hex(2)\n hex to decimal(3)\n binary to decimal(4)\n decimal to binary(5)\n decimal to hex(6)\n")
if option == str("1"):
print(bin(int(num, 16)))
elif option == str("2"):
print(hex(int(num, 2)))
elif option == str("3"):
print(int(num, 16))
elif option == str("4"):
print(int(num, 2))
elif option == str("5"):
print(bin(int(num)))
elif option == str("6"):
print(hex(int(num)))
elif option == str("7"):
print(int(num, 8))
else:
print("Oops! You made a mistake.")
|
7d6aa86ccbe11b0c93c7aa678c30390735d07983 | IUL1AN27/Instructiunea-String | /Problema 5 string.py | 163 | 3.5625 | 4 | cnp=str(input('Introduceti CNP-ul persoanei: '))
if cnp.isnumeric() and len(cnp) == 13:
print('CNP-ul este corect')
else:
print('CNP-ul este gresit')
|
175dde5385d04b42e6d2621a174e98b011fb7762 | ImaniLargin1996/Hangman | /Main | 490 | 3.78125 | 4 | #!python
import random
###############################################
#PART 4
#show previously guessed letters,
part3 = ['ocean', 'jump', 'computer', 'chair', 'rope']
selected_word = random.choice(part3)
letters = list(selected_word)
#print(letters)
characters = len(letters)
#print(characters)
def printblanks(num):
for x in range(num):
print('_', end=' ')
print()
printblanks(characters)
def checkletters(num):
if (num > 1):
print('Please enter only one letter!')
tries = 15
|
80dc0a675b980a943ed09d24bbe69361fd920b5c | sayantanHack/Product-from-given-list | /list of num 2.py | 335 | 3.8125 | 4 | listofnum = [2,4,1,5,6,40,-1]
num = int(input("Which number you want as a product : "))
i=None
j = None
for i in range(len(listofnum)):
if num%listofnum[i]==0:
if num/listofnum[i] in listofnum:
print('The numbers multiplied are : ',listofnum[i],'and',int(num/listofnum[i]))
|
343973f2294a73e3ab24a9f9cf55ed005409303d | dheerajthodupunoori/problem-solving | /directed-acyclic-graph-clone.py | 2,357 | 3.78125 | 4 | #directed graph
from collections import deque
class GraphNode:
def __init__(self,value):
self.val = value
self.adjacent = []
class GraphOperations:
def __init__(self):
print("Graph operations classe is initialized")
self.graph = set()
def addEdge(self,source,destination):
# print("Adding edge from {source} to {destination}".format(source=source.val,destination=destination.val))
if source not in self.graph:
self.graph.add(source)
source.adjacent.append(destination)
# print("Edge added from {source} to {destination}".format(source=source.val,destination=destination.val))
def printGraph(self,graph):
for node in graph:
print("Parent - {value} and {object}".format(value=node.val,object=node))
for adjacent in node.adjacent:
print(" ------>{value} and {object}".format(value=adjacent.val,object=adjacent))
def cloneDAG(self,source,visited):
queue = deque()
queue.append(source)
clone = GraphNode(source.val)
visited[source] = clone
while len(queue) > 0:
popped = queue.popleft()
root = visited[popped]
for adjacent in popped.adjacent:
adjacent_clone = None
if adjacent not in visited:
adjacent_clone = GraphNode(adjacent.val)
visited[adjacent] = adjacent_clone
else:
adjacent_clone = visited[adjacent]
queue.append(adjacent)
root.adjacent.append(adjacent_clone)
if __name__=="__main__":
# print("Directed Acyclic Graph Cloning.")
graph = GraphOperations()
one = GraphNode(1)
two = GraphNode(2)
three = GraphNode(3)
four = GraphNode(4)
nodes = [one,two,three,four]
graph.addEdge(one,two)
graph.addEdge(three,two)
print("Graph before cloning")
graph.printGraph(nodes)
visited = dict()
for node in nodes:
if node not in visited:
graph.cloneDAG(node,visited)
print("*************************************")
print("Graph after cloning")
print(len(visited.values()))
cloned_graph =visited.values()
graph.printGraph(cloned_graph)
|
8e4d614f8aa1fd2dca9865c0ce93d31e8c6bf38d | dheerajthodupunoori/problem-solving | /indeed-karat/single_rectangle.py | 1,511 | 3.875 | 4 | # https://leetcode.com/discuss/interview-question/1062462/Indeed-Karat-Questions
# https://leetcode.com/discuss/interview-question/1063081/Indeed-or-Karat-(Video-Screen)-or-Find-Rectangles
# Given a 2D array of 0s and 1s, return the position of the single rectangle made up of 1s.
#
# # Example input
grid1 = [[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
grid3 = [[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]]
# # you should return the
# # (start_row, start_col, end_row, end_col)
# [ 1, 1, 2, 3 ]
def get_rectangle_position(grid):
start_row = 0
start_col = 0
end_row = 0
end_col = 0
row_length = len(grid)
col_length = len(grid[0])
is_one_found = False
for i in range(row_length):
for j in range(col_length):
if grid[i][j] == 1:
# print(i, j)
start_row = i
start_col = j
is_one_found = True
break
if is_one_found:
break
# print(start_row, start_col)
for row in range(start_row, row_length):
if grid[row][start_col] == 1:
end_row = row
for col in range(start_col, col_length):
if grid[start_row][col] == 1:
end_col = col
print(start_row, start_col, end_row, end_col)
get_rectangle_position(grid1)
get_rectangle_position(grid3)
|
bf37a1b14897908681734a83eaf4ad44876586c2 | dheerajthodupunoori/problem-solving | /grid-word-search.py | 1,462 | 3.75 | 4 | class WordSearch:
def __init__(self,grid):
self.grid=grid
self.directions = [[0,-1],[-1,0],[0,1],[1,0]]
self.R = len(grid)
self.C = len(grid[0])
print(self.grid)
def searchWord(self,word,row,col,position):
# print(word,position,word[position],row,col)
if row<0 or row>=self.R or col<0 or col>=self.C:
return False
if position == len(word):
return True
if word[position] == self.grid[row][col]:
result = (self.searchWord(word,row,col-1,position+1) or
self.searchWord(word,row-1,col,position+1) or
self.searchWord(word,row,col+1,position+1) or
self.searchWord(word,row+1,col,position+1))
return result
else:
return False
return True
if __name__=="__main__":
grid = [['a','x','m','y'],
['b','e','e','f'],
['x','e','e','f'],
['r','a','k','s']]
search = WordSearch(grid)
word = input()
wordFound = False
for i in range(len(grid)):
for j in range(len(grid[0])):
if word[0] == grid[i][j]:
if search.searchWord(word,i,j,0):
print("Word found at {i},{j}".format(i=i,j=j))
wordFound = True
break
if not wordFound:
print("Word not found")
|
fa18a5a720dfda793bf43408392742fd3ce420db | dheerajthodupunoori/problem-solving | /indeed-karat/find_word_from_string.py | 2,069 | 4.0625 | 4 | # You are running a classroom and suspect that some of your students are passing around the answers to multiple
# choice questions disguised as random strings.
#
# Your task is to write a function that, given a list of words and a string, finds and returns the word in the list
# that is scrambled up inside the string, if any exists. There will be at most one matching word. The letters don't
# need to be contiguous.
#
# Example:
# words = ['cat', 'baby', 'dog', 'bird', 'car', 'ax']
# string1 = 'tcabnihjs'
# find_embedded_word(words, string1) -> cat
#
# string2 = 'tbcanihjs'
# find_embedded_word(words, string2) -> cat
#
# string3 = 'baykkjl'
# find_embedded_word(words, string3) -> None
#
# string4 = 'bbabylkkj'
# find_embedded_word(words, string4) -> baby
#
# string5 = 'ccc'
# find_embedded_word(words, string5) -> None
#
# string6 = 'nbird'
# find_embedded_word(words, string6) -> bird
#
# n = number of words in words
# m = maximal string length of each word
def find_embedded_word(words_, data):
for word in words_:
hashed = get_hash_map_data(data)
is_found = True
for char in word:
if char not in hashed or hashed[char] == 0:
is_found = False
break
elif char in hashed:
hashed[char] -= 1
if is_found:
return word
return None
def get_hash_map_data(data):
data_hashed = {}
for char in data:
if char not in data_hashed:
data_hashed[char] = 1
else:
data_hashed[char] += 1
return data_hashed
words = ['cat', 'baby', 'dog', 'bird', 'car', 'ax']
string1 = 'tcabnihjs'
print(find_embedded_word(words, string1)) # -> cat
string2 = 'tbcanihjs'
print(find_embedded_word(words, string2)) # -> cat
string3 = 'baykkjl'
print(find_embedded_word(words, string3)) # -> None
string4 = 'bbabylkkj'
print(find_embedded_word(words, string4)) # -> baby
string5 = 'ccc'
print(find_embedded_word(words, string5)) # -> None
string6 = 'nbird'
print(find_embedded_word(words, string6)) # -> bird |
5cd5a6757593631413b06660993ab63c23614d80 | BonoboJan/M03-Ofim-tica | /multiplode.py | 434 | 4 | 4 | #coding:utf8
#Jandry Joel
#23/02/18
num1=input("Introduzca el primer valor: ")
num2=input("Introduzca el segundo valor: ")
if (num1==0) or (num2==0) :
print "Introduzca valores diferentes a 0."
else:
if num1>num2 :
mayor=num1
menor=num2
else:
mayor=num2
menor=num1
if mayor%menor==0:
print mayor,"es múltiplo de ", menor
else:
print mayor,"no es múltiplo de ", menor
|
4139ad8790694f9b950b29fccddd249c06ddcee7 | BonoboJan/M03-Ofim-tica | /Bucles/ejercicio-bucle-informes.py | 266 | 3.671875 | 4 | #coding:utf8
# Inicializaciones
salir = "N"
anyo=2001
while ( salir=="N" ):
# Hago cosas
print "Informes año", anyo
# Incremento
anyo= anyo +1
# Activo indicador de salida si toca
if ( anyo>2016 ): # Condición de salida
salir = "S"
|
6ef2ad7e067cc031fdddf6134e86f5263f369f87 | PehhViny/aulaslpoo2sem21 | /aula2.py | 159 | 3.796875 | 4 | def main ():
nota1 = int(2)
nota2 = int(8)
soma = nota1 + nota2
media = soma / 2
if media >= 5:
print ("passou")
else:
print ("Bombou")
main()
|
eff175292e48ca133ae5ca276a679821ebae0712 | soumilshah1995/Data-Structure-and-Algorithm-and-Meta-class | /DataStructure/Deque/DEQChallenge.py | 1,505 | 4.15625 | 4 | """
DEQUE Abstract Data Type
DEQUE = Double ended Queue
High level its combination of stack and queue
you can insert item from front and back
You can remove items from front and back
we can use a list for this example. we will use methods
>----- addfront
>----- add rear
>----- remove front
>----- remove rear
we want to check Size, isempty
QUEUE - FIFO
STACK - LIFO
DEQUE - can use both LIFO or FIFO
any items you can store in list can be stored in DEQUE
Most common Questions is Palindrone
using DEQUE Datastructure
"""
class Deque(object):
def __init__(self):
self.items = []
def add_front(self, item):
self.items.insert(0, item)
def add_rear(self, item):
self.items.append(item)
def remove_front(self):
return self.items.pop(0)
def remove_rear(self):
return self.items.pop()
def size(self):
return len(self.items)
def isempty(self):
if(self.items) == []:
return True
else:
return False
def peek_front(self):
return self.items[0]
def peek_rear(self):
return self.items[-1]
def main(data):
deque = Deque()
for character in data:
deque.add_rear(character)
while deque.size() >= 2:
front_item = deque.remove_front()
rear_item = deque.remove_rear()
if rear_item != front_item:
return False
return True
if __name__ == "__main__":
print(main("nitin"))
print(main("car")) |
5d37cc5141b7f47ec6991ffa4800055fef50eab8 | soumilshah1995/Data-Structure-and-Algorithm-and-Meta-class | /DataStructure/Queue/Queue.py | 786 | 4.125 | 4 |
class Queue(object):
def __init__(self):
self.item = []
def enqueue(self, item):
self.item.insert(0, item)
def dequeue(self):
if self.item:
self.item.pop()
else:
return None
def peek(self):
if self.item:
return self.item[-1]
def isempty(self):
if self.item == []:
return True
else:
return False
def size(self):
return len(self.item)
if __name__ == "__main__":
queue = Queue()
queue.enqueue(item=1)
queue.enqueue(item=2)
print("Size\t{}".format(queue.size()))
print("Peek\t{}".format(queue.peek()))
queue.dequeue()
print("Size\t{}".format(queue.size()))
print("Peek\t{}".format(queue.peek()))
|
2bb127606086c19cfbc3309b0adb8a43fdd4955d | mcfee-618/FluentAlgorithm | /01linkedlist/src/reverse.py | 347 | 3.953125 | 4 | # 反转链表
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
p1 = head
p2 = None
while p1 != None:
p3 = p1.next
p1.next = p2
p2 = p1
p1 = p3
return p2
|
e69ecf21f161fdbfc6ffb31b1519bc03b7c76d4c | KevinBXu/GrapheneImages | /helper.py | 4,833 | 3.5 | 4 | import gmsh
import matplotlib.pyplot as plt
import math
#find the distance between two (x, y) coordinates using the max metric
def distance(p1, p2):
x = abs(p1[0]-p2[0])
y = abs(p1[1]-p2[1])
return max(x,y)
#find the distance between two (x, y) coordinates using the euclidean metric
def euclidean(p1, p2):
return (math.sqrt((p1[0]-p2[0]) ** 2 + (p1[1]-p2[1]) ** 2))
#add two cartesian coordinates
def add(p1, p2):
x = p1[0]+p2[0]
y = p1[1]+p2[1]
return (x,y)
#divide a cartesian coordinate by a scalar
def div(p, c):
x = round(p[0] / c)
y = round(p[1] / c)
return (x,y)
#print the lines using pyplot
# l - list containing lists of points (lines)
def print_lines(l):
for line in l:
plt.scatter(*zip(*(line)), s=0.25)
plt.show()
#functions similarly to print_lines but uses xs, ys for the axes
def print_lines_window(l, xs, ys):
for line in l:
plt.scatter(*zip(*(line)), s=0.25)
plt.xlim([0, xs])
plt.ylim([0, ys])
plt.show()
#return the points above, below, left, and right of p
def get_circle(p):
return [(p[0] - 1, p[1]), (p[0] + 1, p[1]), (p[0], p[1] - 1), (p[0], p[1] + 1)]
#returns segment sorted from one endpoint to the other
def sort_line(segment):
#determines one endpoint by using breadth first search starting from an arbitrary point
check = [segment[0]]
visited = check[:]
while len(check) != 0:
for point in get_circle(check.pop(0)):
if point in segment and point not in visited:
visited.append(point)
check.append(point)
#the point visited last should be an endpoint
endpoint = visited.pop()
#visits every point starting from the endpoint using bf search
#the resulting list has the points in order from one endpoint to the other
check = [endpoint]
visited = check[:]
while len(check) != 0:
for point in get_circle(check.pop(0)):
if point in segment and point not in visited:
visited.append(point)
check.append(point)
return visited
#create the mesh
#segments - list of the segments (as dictionaries)
#lines - list of the lines
#points - list of all knots and nodes
#xs, ys - dimensions of the image
#mesh_name - name of the resulting file
#cLC - size of the generated mesh triangles
def create_mesh(segments, lines, points, xs, ys, mesh_name, cLC):
#map each point in points to an index
point_dict = {}
count = -1
for point in points:
point_dict[point] = (count := count + 1)
gmsh.initialize()
gmsh.option.setNumber("General.Terminal", 1)
gmsh.model.add("Moire")
#generate the boundary of the mesh
boundary_points = [(-10, -10), (-10, ys + 10), (xs + 10, ys + 10), (xs + 10, -10)]
for key in point_dict:
gmsh.model.geo.addPoint(key[1], ys - key[0], 0, cLC, point_dict[key])
boundary = []
loop = 0
for i in range(len(boundary_points)):
if i == 0:
loop = gmsh.model.geo.addPoint(boundary_points[i][0], boundary_points[i][1], 0, cLC)
boundary.append(loop)
else:
boundary.append(gmsh.model.geo.addPoint(boundary_points[i][0], boundary_points[i][1], 0, cLC))
boundary.append(loop)
tags = [None] * (len(boundary) - 1)
for i in range(len(boundary) - 1):
tags[i] = gmsh.model.geo.addLine(boundary[i], boundary[i+1])
btag = gmsh.model.geo.addCurveLoop(tags, len(boundary))
dtag = gmsh.model.geo.addPlaneSurface([btag])
gmsh.model.geo.synchronize()
gmsh.model.addPhysicalGroup(1, tags, 1)
gmsh.model.setPhysicalName(1, 1, "boundary")
gmsh.model.addPhysicalGroup(2, [dtag], 1)
gmsh.model.setPhysicalName(2, 1, "domain")
#add the lines to the image
for line in lines:
if "value" not in line:
continue
spline_tags = []
#splines cannot cross so segments have to be added individually
for segment in segments:
if segment["line"] != line:
continue
knot_indexes = []
for point in segment["knots"]:
knot_indexes.append(point_dict[point])
spline_tags.append(gmsh.model.geo.addBSpline(knot_indexes))
gmsh.model.geo.synchronize()
ltag = gmsh.model.addPhysicalGroup(1, spline_tags)
gmsh.model.setPhysicalName(1, ltag, line["color"] + " " + str(line["value"]))
gmsh.model.mesh.embed(1, spline_tags, 2, dtag)
gmsh.model.mesh.setAlgorithm(2, dtag, 1)
gmsh.model.mesh.generate(2)
gmsh.model.mesh.optimize("")
gmsh.write(mesh_name + ".msh")
gmsh.write(mesh_name + ".vtk")
gmsh.finalize() |
8acb397fd77fe9ce1478a5ba99452d2b60072cb4 | Pygame-Tetris-2020/tetris-2020 | /Buttons.py | 3,562 | 3.75 | 4 | # -*- coding: cp1252 -*-
# /usr/bin/env python
# Simon H. Larsen
# Buttons
# Project started: d. 26. august 2012
import pygame
from pygame.locals import *
import sett
from music import *
pygame.init()
class Button:
def create_button(self, surface, color, x, y,
length, height, width,
text, text_color):
"""Responsible for creating the button.
Accepts the following arguments:
surface - defines the drawing surface
color - defines the drawing color
x - x-coord of left upper angle
y - y-coord of left upper angle
length - defines the length of button
height - defines the height of button
width - defines the width of button
text - text in button
text_color - color of the text on the button
"""
surface = self.draw_button(surface, color,
length, height, x, y, width)
surface = self.write_text(surface, text,
text_color, length, height, x, y)
self.rect = pygame.Rect(x, y, length, height)
return surface
def write_text(self, surface, text, text_color, length, height, x, y):
"""Responsible for writing the text on the button.
Accepts the following arguments:
surface - defines the drawing surface
text - text in button
text_color - color of the text on the button
x - x-coord of left upper angle
y - y-coord of left upper angle
length - defines the length of button
height - defines the height of button
"""
font_size = int(length // len(text))
myFont = pygame.font.Font('tetris-font.ttf', font_size)
myText = myFont.render(text, 1, text_color)
surface.blit(myText, ((x + length / 2) - myText.get_width() / 2,
(y + height / 2) - myText.get_height() / 2))
return surface
def draw_button(self, surface, color, length, height, x, y, width):
"""Responsible for drawing the button.
Accepts the following arguments:
surface - defines the drawing surface
color - defines the drawing color
x - x-coord of left upper angle
y - y-coord of left upper angle
length - defines the length of button
height - defines the height of button
width - defines the width of button
"""
for i in range(1, 10):
s = pygame.Surface((length + (i * 2), height + (i * 2)))
s.fill(color)
alpha = (255 / (i + 2))
if alpha <= 0:
alpha = 1
s.set_alpha(alpha)
pygame.draw.rect(s, color, (x - i, y - i, length + i,
height + i), width)
surface.blit(s, (x - i, y - i))
pygame.draw.rect(surface, color, (x, y, length, height), 0)
pygame.draw.rect(surface, sett.BLACK, (x, y, length, height), 1)
return surface
def pressed(self, mouse):
if mouse[0] > self.rect.topleft[0]:
if mouse[1] > self.rect.topleft[1]:
if mouse[0] < self.rect.bottomright[0]:
if mouse[1] < self.rect.bottomright[1]:
curr_sound.play('butt_click')
return True
else:
return False
else:
return False
else:
return False
else:
return False
|
248b3fd83910de6de72e29571472a7bf20e6bbdb | hyunillkang/Path-Finding-Algorithms-Maze-Solving | /create_maze.py | 3,912 | 3.78125 | 4 | import os
import msvcrt
class Maze:
def __init__(self, rows, cols):
self.rows = rows
self.cols = cols
self.contents = []
class Cursor:
def __init__(self, row, col):
self.row = row
self.col = col
def createMazeFrame(rows, cols):
maze = Maze(rows, cols)
for i in range(rows):
temp = []
for j in range(cols):
if i == 0 or j == 0 or i == rows-1 or j == cols-1: # fills the edges of the maze with obsticles
temp.append('#')
else:
temp.append(' ')
maze.contents.append(temp)
return maze
def controlCursor(maze, cursor, key): # cursor moves according to pressed keyboard arrows
if(key == 'up'):
if(cursor.row == 0):
return
cursor.row -= 1
elif(key == 'down'):
if(cursor.row == maze.rows-1):
return
cursor.row += 1
elif(key == 'left'):
if(cursor.col == 0):
return
cursor.col -= 1
elif(key == 'right'):
if(cursor.col == maze.cols-1):
return
cursor.col += 1
elif(key == 'space'):
if(maze.contents[cursor.row][cursor.col] == ' ' or
maze.contents[cursor.row][cursor.col] == 'S' or
maze.contents[cursor.row][cursor.col] == 'D'): # fills the spot where the cursor is on with an obsticle
maze.contents[cursor.row][cursor.col] = '#'
elif(maze.contents[cursor.row][cursor.col] == '#'): # or replaces the obsticle to empty space
maze.contents[cursor.row][cursor.col] = ' '
elif(key == 'start'):
for row in range(0, maze.rows):
for col in range(0, maze.cols):
if(maze.contents[row][col] == 'S'): # sets the start point
maze.contents[row][col] = ' '
break
maze.contents[cursor.row][cursor.col] = 'S'
elif(key == 'destination'):
for row in range(0, maze.rows):
for col in range(0, maze.cols):
if(maze.contents[row][col] == 'D'): # sets the destination point
maze.contents[row][col] = ' '
break
maze.contents[cursor.row][cursor.col] = 'D'
def printMaze(maze, cursor):
os.system('cls')
for row in range(0, maze.rows):
for col in range(0, maze.cols):
if(row == cursor.row and col == cursor.col):
print('O',end=' ')
else:
print(maze.contents[row][col], end=' ')
print()
print("Arrow keys: move cursor")
print("Space: create/remove obstacle")
print("S/D: set start/destination point")
print("O: output the current maze file")
print("ESC: exit")
def outputMazeFile(maze):
f = open('mazefile.txt', "w")
for row in range(0, maze.rows):
for col in range(0, maze.cols):
f.write(maze.contents[row][col])
f.write('\n')
print("mazefile.txt is created successfully.")
def getKeyboardArrow():
key = ord(msvcrt.getch())
if (key == 72):
key = 'up'
elif (key == 80):
key = 'down'
elif (key == 75):
key = 'left'
elif (key == 77):
key = 'right'
elif (key == 32):
key = 'space'
elif(key == 115 or key == 83):
key = 'start'
elif(key == 100 or key == 68):
key = 'destination'
elif(key == 111 or key == 79):
key = 'output'
elif (key == 27):
exit()
return key
rows = int(input("Input the rows of the maze size: "))
cols = int(input("Input the cols of the maze size: "))
cursor = Cursor(1, 1)
maze = createMazeFrame(rows, cols)
while True:
printMaze(maze, cursor)
key = getKeyboardArrow()
if(key == 'output'):
outputMazeFile(maze)
key = getKeyboardArrow()
controlCursor(maze, cursor, key)
|
4d3404edff3a1c83505fcff636da20ba887d0c5d | AncientAbysswalker/Projekt-Euler | /Euler Projekt 004 - Largest Palindrome Product/EulerProjekt_4.py | 907 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 8
@author: Ancient Abysswalker
"""
from math import floor
def isPalindrome(number):
number=str(number)
for digit in range(0,floor(len(number)/2)):
if number[digit] != number[-1-digit]:
return False
return True
#Problem definition
maxMult=999
maxPalindrome=0
multiples=[0,0]
#Check largest products for first palindrome
for i in reversed(range(80,maxMult+1)):
#Centric Diagonal
if (i)*(i)<maxPalindrome:
print(maxPalindrome,multiples)
break
for j in range(0,maxMult-i+1):
if isPalindrome((i+j)*(i-j)):
maxPalindrome=(i+j)*(i-j)
multiples=[(i+j),(i-j)]
#Off-Centric Diagonal
if (i)*(i-1)<maxPalindrome:
print(maxPalindrome,multiples)
break
for j in range(0,maxMult-i+1):
if isPalindrome((i+j)*(i-j-1)):
maxPalindrome=(i+j)*(i-j-1)
multiples=[(i+j),(i-j-1)] |
470f6de5fff526bc52c8d3290a2c0ae2e4349f09 | AncientAbysswalker/Projekt-Euler | /Euler Projekt 020 - Factorial digit sum/EulerProjekt_20.py | 165 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Jul 26
@author: Abysswalker
"""
from math import factorial
print(sum(int(digit) for digit in str(factorial(100)))) |
103e2d92ddd591cfbdac2b546f36bf13c2c8abbb | AncientAbysswalker/Projekt-Euler | /Euler Projekt 041 - Pandigital prime/EulerProjekt_41.py | 997 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 24
@author: Abysswalker
"""
from os import path
#Import Primes from file
def primeFile():
filepath = path.join(path.dirname(__file__),"primes.txt")
primes=set()
print("Checking existance of generated prime file")
if not path.exists(filepath):
raise ValueError("File does not exist, error...")
else:
print("File exists, parsing...")
f=open(filepath, 'r')
for num in f.read().split():
primes.add(int(num))
print("Parsing complete!")
f.close()
return primes
#Is the number pandigital?
def isPandigital(number):
check=len(str(number))
if check>9:
raise ValueError('A number cannot exceed 9 pandigital by definition')
if set(str(number)) == set(str(i) for i in range(1,check+1)):
return True
return False
#Generate Sets
primes=primeFile()
maxPan=0
#Search primes for L/R trunkable
for p in primes:
if isPandigital(p) and p>maxPan:
maxPan=p
print(maxPan)
|
193a157b59d30a240f7f2a937b06627bc5394398 | svaishn/ImageManipulationAlgorithms | /SingleColor-B-BW.py | 682 | 3.515625 | 4 | # Author Bhargav K
# Email bhargav.gamit@gmail.com
# Single Color Channel using blue
# gray = blue
from PIL import Image
i = Image.open("input.png")
#pixel data is stored in pixels in form of two dimensional array
pixels = i.load()
width, height = i.size
j=Image.new(i.mode,i.size)
#cpixel[0] contains red value cpixel[1] contains green value
#cpixel[2] contains blue value cpixel[3] contains alpha value
for image_width_iterator in range(width):
for image_height_iterator in range(height):
cpixel = pixels[image_width_iterator, image_height_iterator]
gray = cpixel[2]
j.putpixel((image_width_iterator,image_height_iterator),(gray,gray,gray))
j.save('output.png')
|
67c68086d85a19377908e5f5d32b27bb3087f0bd | svaishn/ImageManipulationAlgorithms | /ColourInversionAlgo.py | 874 | 3.890625 | 4 | # Author Sri Vennela Vaishnapu
# Email vennelavaishnapu2003@gmail.com
# Inversion algorithm
# colour = GetPixelColour(x, y)
# invertedRed = 255 - Red(colour)
# invertedGreen = 255 - Green(colour)
# invertedBlue = 255 - Blue(colour)
# PutPixelColour(x, y) = RGB(invertedRed, invertedGreen,invertedBlue)
from PIL import Image
i = Image.open("input.png")
#pixel data is stored in pixels in form of two dimensional array
pixels = i.load()
width, height = i.size
j=Image.new(i.mode,i.size)
for x in range(width):
for y in range(height):
cpixel = pixels[x, y]
#cpixel[0] contains red value cpixel[1] contains green value
#cpixel[2] contains blue value cpixel[3] contains alpha value
invertedRed = 255 - cpixel[0]
invertedGreen = 255 - cpixel[1]
invertedBlue = 255 - cpixel[2]
j.putpixel((x, y),(invertedRed, invertedGreen, invertedBlue))
j.save('output.png')
|
6e3361a86bea6a371d31e1f2fba02beeda2ed26e | rylan-michael/virtual-memory-problems | /main.py | 8,089 | 3.78125 | 4 | import random
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from collections import deque
import time
def rand_page_ref_str(page_numbers, reference_length):
"""Generate a random reference string.
A reference string is used for evaluating performance of page replacement
algorithms. We test the algorithm by running it on a particular string of
memory references called a reference string. (see pg. 412)
The reference string is 10 characters long with each character representing
a frame number.
"""
return [random.choice(range(page_numbers)) for i in range(reference_length)]
def counter_lru_page_replacement(reference_string, memory_size):
"""Counter-based LRU page-replacement algorithm.
Use the recent past as an approximation for the near future. Replace the
page that has not been used for the longest period of time. Associates a
page with time of its last use.
We use counters to implement the algorithm. The clock is incremented for
every memory reference. Whenever a reference to a page is made, the contents
of the clock register are copied to the time-of-use filed in the page-table
entry for that page. (see pg. 416)
:return: tuple of reference_string length, allocated memory space for page
frames and the number of page fault occurrences.
"""
class LRUClock:
"""Counter for keeping time inside of the LRU page-replacement algorithm.
tick: keeps track of how much time has passed.
increment(): increases tick by 1.
"""
def __init__(self):
self.tick = 0
def increment(self):
self.tick += 1
page_fault_count = 0
memory = [None for x in range(memory_size)]
clock = LRUClock()
for c in reference_string:
frame = {"#": c, "TOU": clock.tick} # Frame number, time of use
clock.increment()
# Would be easiest to check if frame were already in memory by using
# if frame in memory:, but we need to ignore age comparison.
# Check if the frame is already loaded into memory. Since frames are
# loaded serially, if we hit a None element then that means the array
# is empty moving forward and won't contain the frame we are looking for.
if None in memory:
# Checks for page faults when the memory isn't full.
# The frame could already be loaded.
for f in memory:
if f is None: # Frame isn't loaded into memory
page_fault_count += 1
memory[memory.index(None)] = frame
break
elif f["#"] is frame["#"]: # Frame is loaded
# Since frame is already loaded, update the time value.
index = memory.index(f)
memory[index] = frame
break
else:
loaded = False
for f in memory:
if f["#"] is frame["#"]: # If frame in memory
memory[memory.index(f)] = frame
loaded = True
if not loaded:
# find the oldest frame and replace it with the current frame
oldest_frame = None
index = 0
for f in memory:
if oldest_frame is None:
oldest_frame = f
elif f["TOU"] < oldest_frame["TOU"]:
oldest_frame = f
index = memory.index(oldest_frame)
memory[index] = frame
page_fault_count += 1
return len(reference_string), memory_size, page_fault_count
def stack_lru_page_replacement(reference_string, memory_size):
frame_stack = deque(maxlen=memory_size)
page_fault_count = 0
for c in reference_string:
if c in frame_stack:
# If the frame is in stack, move to top of stack.
frame_stack.remove(c)
frame_stack.append(c)
elif len(frame_stack) < memory_size:
# There is room on the stack to add frame.
frame_stack.append(c)
page_fault_count += 1
else:
# There is no room on stack, replace frame.
frame_stack.popleft()
frame_stack.append(c)
page_fault_count += 1
return len(reference_string), memory_size, page_fault_count
def opt_page_replacement(reference_str, memory_size):
"""Optimal page-replacement algorithm.
Replace the page that will not be used for the longest period of time. Use
of this page-replacement algorithm guarantees the lowest possible page-fault
rate for a fixed number of frames. (see pg. 414)
"""
memory = [None for x in range(memory_size)]
# Check loaded frames for page existence.
# If page not in a loaded frame then load in frame
# If available memory, load frame
# Else replace frame that wont be used longest time
page_fault_count = 0
unmodified_ref_str = reference_str
for page in reference_str:
reference_str = reference_str[1:]
if page in memory: # Frame exists.
pass
elif None in memory: # Load frame.
page_fault_count += 1
index = memory.index(None)
memory[index] = page
else: # Replace frame.
page_fault_count += 1
rank_dict = {}
loaded = False
for p in memory: # Is there any page in memory that won't be used again?
if p not in reference_str:
loaded = True
index = memory.index(p)
memory[index] = page
break
else: # Give each loaded frame a rank.
index = reference_str.index(p)
rank_dict[p] = index
if not loaded:
least_active = max(rank_dict)
index = memory.index(least_active)
memory[index] = page
return len(unmodified_ref_str), memory_size, page_fault_count
def analyze_page_replacement_performance():
ref_str = rand_page_ref_str(page_numbers=10, reference_length=10)
data_set = {"LRU": [], "OPT": []}
index = []
for i in range(1, 8):
(ref_len, mem_size, page_fault_count) = counter_lru_page_replacement(ref_str, i)
data_set["LRU"].append(page_fault_count)
(ref_len, mem_size, page_fault_count) = opt_page_replacement(ref_str, i)
data_set["OPT"].append(page_fault_count)
index.append(i)
df = pd.DataFrame(data=data_set, index=index)
ax = df.plot.bar(rot=0)
plt.suptitle(f"Page Replacement Algorithm Performance")
ax.text(4, 7, "ref_str: {0}".format(ref_str),
bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10})
ax.set_xlabel("Number of Frames")
ax.set_ylabel("Number of Page Faults")
plt.show()
def analyze_lru_runtime_performance():
reference_string = rand_page_ref_str(page_numbers=20, reference_length=50000)
data_set = {"counter": [], "stack": []}
index = []
for i in range(1, 11):
index.append(i)
time_start = time.time()
counter_lru_page_replacement(reference_string, i)
time_end = time.time()
data_set["counter"].append(time_end - time_start)
time_start = time.time()
stack_lru_page_replacement(reference_string, i)
time_end = time.time()
data_set["stack"].append(time_end - time_start)
df = pd.DataFrame(data=data_set, index=index)
lines = df.plot.line()
lines.set_xlabel("Number of Frames")
lines.set_ylabel("Running Time")
lines.set_yticklabels([])
plt.suptitle(f"LRU Runtime Performance Comparison")
plt.show()
analyze_page_replacement_performance()
analyze_lru_runtime_performance()
|
6b1fa7ff2a58e8234123622bda5f0fde81e3af8b | kiddliao/lh_CODE | /lh_algorithm/lh_algorithm_binary_tree.py | 3,271 | 3.90625 | 4 | class TreeNode:
def __init__(self,x):
self.val=x
self.left=None
self.right=None
#非递归的前序遍历,进栈顺序是前序遍历,出栈顺序中序遍历
#https://blog.csdn.net/monster_ii/article/details/82115772
class newTree:
def __init__(self,x):
self.head=self.new(None,x,0)
self.pre,self.mid,self.post=[],[],[]
self.pre2,self.mid2,self.post2=[],[],[]
self.ceng=[]
def new(self,tree,x,i):
if i<len(x):
if x[i]==None:return TreeNode(None)
else:
tree=TreeNode(x[i])
tree.left=self.new(tree.left,x,2*i+1)
tree.right=self.new(tree.right,x,2*i+2)
return tree
return tree
def preOrderTraverse(self,node):
if node==None:
return
self.pre.append(node.val)
self.preOrderTraverse(node.left)
self.preOrderTraverse(node.right)
def preOrderTraverse2(self,node):
stack=[]
cur=node
while(cur!=None or len(stack)!=0):
while(cur!=None):
stack.append(cur)
self.pre2.append(cur.val)
cur=cur.left
top=stack[-1]
stack.pop()
cur=top.right
def midOrderTraverse(self,node):
if node==None:
return
self.midOrderTraverse(node.left)
self.mid.append(node.val)
self.midOrderTraverse(node.right)
def midOrderTraverse2(self,node):
stack=[]
cur=node
while(cur!=None or len(stack)!=0):
while(cur!=None):
stack.append(cur)
cur=cur.left
top=stack[-1]
self.mid2.append(top.val)
stack.pop()
cur=top.right
def postOrderTraverse(self,node):
if node==None:
return
self.postOrderTraverse(node.left)
self.postOrderTraverse(node.right)
self.post.append(node.val)
def postOrderTraverse2(self,node):
stack=[]
cur=node
last=None
while(cur!=None or len(stack)!=0):
while(cur!=None):
stack.append(cur)
cur=cur.left
top=stack[-1]
if top.right==None or top.right==last:
self.post2.append(top.val)
stack.pop()
last=top
else:
cur=top.right
def cengOrderTraverse(self,node):
queue=[]
cur=node
if cur:
queue.append(cur)
while(queue):
top=queue[0]
self.ceng.append(top.val)
queue.pop(0)
if top.left:
queue.append(top.left)
if top.right:
queue.append(top.right)
# a=newTree([1,2,3,4,5])
# a.preOrderTraverse(a.head)
# a.midOrderTraverse(a.head)
# a.postOrderTraverse(a.head)
# print(a.pre)
# print(a.mid)
# print(a.post)
# a.preOrderTraverse2(a.head)
# a.midOrderTraverse2(a.head)
# a.postOrderTraverse2(a.head)
# print(a.pre2)
# print(a.mid2)
# print(a.post2)
# a.cengOrderTraverse(a.head)
# print(a.ceng)
|
46c7075a38738a5ead62a7e751700bcf98762d6c | ArthMx/AdamANN | /Old/DeepNN.py | 10,384 | 3.515625 | 4 | '''
Created 02/05/2018
ANN with N layers and Softmax or sigmoid as the last layer.
Architecture of the NN :
(Tanh or ReLU) x N-1 times + (Softmax or sigmoid) for output
'''
import numpy as np
import matplotlib.pyplot as plt
import time
def ReLU(Z):
'''
Compute the ReLU of the matrix Z
'''
relu = np.maximum(0, Z)
return relu
def Sigmoid(Z):
'''
Compute the sigmoid of the matrix Z
'''
sigmoid = 1/(1+np.exp(-Z))
return sigmoid
def Softmax(Z):
'''
Compute the Softmax of the matrix Z
'''
exp_Z = np.exp(Z)
softmax = exp_Z/np.sum(exp_Z, axis=0)
return softmax
def InitializeParameters(n_units_list):
'''
Initialize the parameters values W and b for each layers.
--------
Input
- n_units_list : list of number of units for each layers, input and
output included.
Output
- parameters : dictionnary of the parameters W and b
for each layers
'''
L = len(n_units_list) -1 # number of layers
parameters = {}
for l in range(1, L+1):
n_l_prev = n_units_list[l-1] # number of units in layer l-1
n_l = n_units_list[l] # number of units in layer l
# initialize the parameters values randomly for W and 0 for b
parameters['W' + str(l)] = np.random.randn(n_l, n_l_prev)*0.01
parameters['b' + str(l)] = np.zeros((n_l, 1))
return parameters
def ForwardProp(X, parameters, hidden_func, output_func):
'''
Compute the prediction matrix A3.
--------
Input
- X : Matrix of input (n_x, m)
- parameters : dictionnary of parameters W and b, for each layers
- hidden_func : Activation function to be used for the hidden layers
- output_func : Activation function to be used for the last layer
Output
- AL : Output matrix of last layer (n_y, m)
- cache : Dictionnary of the A and Z, to use them during backprop
'''
L = len(parameters)//2
cache = {}
Al_prev = X
for l in range(1,L):
# get the parameters from the parameters dict
Wl = parameters['W' + str(l)]
bl = parameters['b' + str(l)]
# compute forward propagation
Zl = Wl.dot(Al_prev) + bl
if hidden_func=='tanh':
Al = np.tanh(Zl)
if hidden_func=='relu':
Al = ReLU(Zl)
# write into the cache dict the Z and A
cache['Z' + str(l)] = Zl
cache['A' + str(l)] = Al
# set Al_prev for next iter
Al_prev = Al
# compute forward prop for last layer
WL = parameters['W' + str(L)]
bL = parameters['b' + str(L)]
ZL = WL.dot(Al_prev) + bL
if output_func=='softmax':
AL = Softmax(ZL)
if output_func=='sigmoid':
AL = Sigmoid(ZL)
return AL, cache
def ComputeCost(Y, AL, output_func):
'''
Compute the cost function.
--------
Input
- Y : Target matrix (n_y, m)
- AL : Output matrix of last layer (n_y, m)
- output_func : Activation function to be used for the last layer
Output
- cost : the cost function computed for Y and AL
'''
n_y, m = Y.shape
if output_func=='sigmoid':
loss = - Y * np.log(AL) - (1-Y) * np.log(1 - AL)
# sum the loss through the m examples
cost = np.sum(loss)/m
if output_func=='softmax':
loss = - Y * np.log(AL)
# sum the loss through the m examples
cost = np.sum(loss)/(n_y*m)
return cost
def BackProp(X, Y, AL, parameters, cache, hidden_func, output_func):
'''
Compute the gradients of the cost for the parameters W, b of each layers
--------
Input
- X : Training data matrix of shape (n_x, m)
- Y : Target data matrix of shape (n_y, m)
- AL : Output from last layer
- parameters : Parameters of the model W and b
- cache : Cache data of Z and A
- hidden_func : Activation function to be used for the hidden layers
- output_func : Activation function to be used for the last layer
Output
- grads : dictionnary of the derivatives of the cost function
for each parameters
'''
m = X.shape[1] # m = number of training examples
L = len(parameters)//2 # L number of layer
grads = {}
# last layer
# get dZL, depending of last layer activation fuction
if output_func=='sigmoid':
dZL = AL - Y
if output_func=='softmax':
dZL = AL - Y #(AL - 1) * Y
# get AL_prev to compute the gradients
AL_prev = cache['A'+str(L-1)]
dWL = (1/m) * dZL.dot(AL_prev.T)
dbL = (1/m) * np.sum(dZL, axis=1, keepdims=True)
# write the gradients in grads dictionnary
grads['dW'+str(L)] = dWL
grads['db'+str(L)] = dbL
# set dZl to dZL to be use as dZl_next for the first iter of the loop
dZl = dZL
# layer L-1 to 1
for l in range(L-1,0,-1):
# compute dAl
Wl_next = parameters['W'+str(l+1)]
dZl_next = dZl
dAl = Wl_next.T.dot(dZl_next)
# compute dZl
Zl = cache['Z' + str(l)]
if hidden_func=='tanh':
dZl = (1 - np.tanh(Zl)**2) * dAl
if hidden_func=='relu':
dZl = (Zl > 0)*1
# get Al_prev
if l>1:
Al_prev = cache['A'+str(l-1)]
if l == 1:
Al_prev = X
# compute the gradients
dWl = (1/m) * dZl.dot(Al_prev.T)
dbl = (1/m) * np.sum(dZl, axis=1, keepdims=True)
# write the gradients in grads dictionnary
grads['dW'+str(l)] = dWl
grads['db'+str(l)] = dbl
return grads
def UpdateParameters(parameters, grads, learning_rate):
'''
Update the parameters by gradient descent
---------
Input
- parameters : dictionnary of parameters W, b of each layer
- grads : dictionnary of gradient of the cost function
for each parameters W, b of each leayer
- learning_rate : learning rate to use for updating the parameters
Output
- parameters : parameters updated after gradient descent
'''
L = len(parameters)//2 # L number of layer
for l in range(1, L+1):
parameters['W' + str(l)] -= learning_rate * grads['dW' + str(l)]
parameters['b' + str(l)] -= learning_rate * grads['db' + str(l)]
return parameters
def PreProcess_X_Y(X,y):
'''
Preprocess the data.
----------
Input
- X : Input data of shape (m, n_x)
- Y : Input target of shape (m,)
Output
- X : New input data of shape (n_x, m)
- Y : New input target of shape (n_y, m)
'''
# get the number of features n_x and number of examples m of X
m = X.shape[0]
# transform Y to a 2 dim array (m, n_y)
K = len(np.unique(y)) # get number of classes
if K==2:
Y = y.reshape(-1,1) # reshape Y into (m,1)
if K>2:
Y_dummy = np.zeros((m, K))
for i in range(len(y)):
Y_dummy[i, int(y[i])] = 1 # Y_dummy : (m, K)
Y = Y_dummy
X, Y = X.T, Y.T
return X, Y
def NN_model(X, y, hidden_units, hidden_func='tanh', output_func='sigmoid', \
epoch=10000, learning_rate=0.01, verbose=True):
'''
Train a Neural Network of 3 layers (2 layers ReLU and 1 sigmoid for the output).
----------
Input
- X : input training dataset (m, n_x)
- y : target of the training dataset (m,)
- hidden_units : list of number of units for the hidden layers
- hidden_func : Activation function to be used for the hidden layers
- output_func : Activation function to be used for the last layer
- epoch : number of iteration
- learning_rate : learning rate for the gradient descent
- verbose : if True, print cost function value every 100 epoch
Output
- parameters : dictionnary of the trained parameters W, b for each layers
'''
t0 = time.time()
# reshape and transform X and y
X, Y = PreProcess_X_Y(X,y)
# get architecture of the NN
n_x = X.shape[0]
n_y = Y.shape[0]
n_units_list = [n_x] + hidden_units + [n_y]
# initialize the parameters
parameters = InitializeParameters(n_units_list)
# initialize a list to plot the evolution of the cost function
cost_list = []
for i in range(epoch):
# compute the forward propagation
AL, cache = ForwardProp(X, parameters, hidden_func, output_func)
# compute the back propagation
grads = BackProp(X, Y, AL, parameters, cache, hidden_func, output_func)
# update the parameters
parameters = UpdateParameters(parameters, grads, learning_rate)
if i%100 == 0:
# compute the cost function
cost = ComputeCost(Y, AL, output_func)
cost_list.append(cost)
if verbose and (i%1000 == 0):
print('Cost function after epoch {} : {}'.format(i, cost))
print('Cost function after epoch {} : {}'.format(epoch, cost))
print('Time : %.3f s' % (time.time()-t0))
# print the cost function for each iterations
plt.figure()
plt.plot(cost_list)
plt.title('Cost function')
plt.xlabel('Number of iterations, by hundreds')
plt.ylabel('Cost Function')
return parameters
def MakePrediction(X, parameters, hidden_func, output_func):
'''
Make prediction of the data X
---------
Input
- X : Input data (m, n_x)
- parameters : parameters W, b of each layers of the NN model
Output
- Y_pred : Predicted labels for X (m, n_y)
'''
X = X.T
A3, _ = ForwardProp(X, parameters, hidden_func, output_func)
if output_func=='softmax':
Y_pred = np.argmax(A3, axis=0)
if output_func=='sigmoid':
Y_pred = ((A3 >0.5)*1).reshape(-1)
return Y_pred |
595ed88dcc47f971db5e50291b398318bb41d94c | Oldby141/learning | /function/isnot.py | 707 | 3.9375 | 4 | x = []
y = None
print(not x is None)####################true
print(not y is None)#F
print(not x)#################true
print(not y)#True
print(x is None)#flase
print(y is None)#true
print(y == None)#true
x = 1
y = [0]
print(not x)#f
print(not y)#f
print(x is None)#f
print(y is None)#f
print(y == None)#f
x = 0
y = [1]
print(not x is None)#############################t
print(not y is None)#t
print(not x)#################true
print(not y)#f
print(x is None)#flase
print(y is None)#f
print(x == None)#f
print(True is None)#f
class foo(object):
def __eq__(self, other):
return True
f = foo()
print(f==None)#f
print(f is None)#f
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list1==list2#t
list1 is list#f
|
45445aa84587ad80f81ce639b1a9e41fa79921f0 | Oldby141/learning | /day3/装饰器.py | 867 | 3.671875 | 4 | import time
def timer(func):
def deco():
start_time=time.time()
func()
end_time = time.time()
print("run time%s"%(end_time-start_time))
return deco
@timer
def test1():
time.sleep(2)
print("in the test1")
def test2():
time.sleep(2)
print("in the test2")
#test1=timer(test1)
test1()
test2()
#https://blog.51cto.com/egon09/1836763?tdsourcetag=s_pctim_aiomsg装饰器详解
#迭代器
from collections import Iterable
from collections import Iterator
print(isinstance([],Iterable))#这些可以直接作用于for循环的对象统称为可迭代对象:Iterable
print(isinstance((i for i in range(10)),Iterator))#*可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。
print(isinstance("ada",Iterator))#把list、dict、str等Iterable变成Iterator可以使用iter()函数 |
c9e1cdd80a02af2a839e1ca7a9df489a7c99faa6 | Oldby141/learning | /day2/文件修改.py | 533 | 3.6875 | 4 | f = open("yesterday",'r',encoding="UTF-8")
#f_new = open("yesterday2","w",encoding="UTF-8")
for line in f:
if "肆意的快乐" in line:
print('s')
line=line.replace("肆意的快乐","s")#########888888888888******
print(line)
f.close()
#f_new.close()
line="肆意的快乐"
print(line.replace("肆意的快乐","s"))
s=line.replace #s发生变化
print(line)##line没有发生变化
with open("yesterday","r",encoding="UTF-8") as f:
for line in f:
print(line.strip())
print(f.tell()) |
c4765e62289e7318c56271e9f27942544b572842 | Oldby141/learning | /day6/继承.py | 1,397 | 4.375 | 4 | #!_*_coding:utf-8_*_
# class People:#经典类
class People(object):#新式类写法 Object 是基类
def __init__(self,name,age):
self.name = name
self.age = age
self.friends = []
print("Run in People")
def eat(self):
print("%s is eating...."%self.name)
def talk(self):
print("%s is talking...." % self.name)
def sleep(self):
print("%s is sleeping...." % self.name)
class Relation(object):
def __init__(self,name,age):
print("Run in Relation")# 多继承先左后右
def make_friend(self,obj):
print("%s is making friends with %s"%(self.name,obj.name))
#self.friends.append(obj.name)
self.friends.append(obj)
class Man(Relation,People):
def __init__(self,name,age,money):
#People.__init__(self,name,age)
super(Man,self).__init__(name,age)#新式类写法
self.money = money
print("出生的钱数目:%s"%self.money)
def p(self):
print("%s "%self.name)
def sleep(self):
People.sleep(self)
print("man is sleeping")
class Woman(People,Relation):
def get_birth(self):
print("%s get birth"%self.name)
m1 = Man("byf",23,10)
# print(m1.name)
# m1.sleep()
w1 = Woman("gg",23)
# w1.get_birth()
#m1.make_friend(w1)
#print(m1.friends)
#print(m1.friends[0].name)
w1.name = "GG"
#print(m1.friends[0].name) |
1ccf0eaf6041212bfe68e638106f25a7ad542014 | Oldby141/learning | /day7/__new__.py | 497 | 3.78125 | 4 | #!_*_coding:utf-8_*_
# class Foo(object):
# def __init__(self, name):
# self.name = name
#
#
# f = Foo("alex")
# print(type(f))
# print(type(Foo))
def func(self):
print('hello %s'% self.name)
def __init__(self,name,age):
self.name = name
self.age = age
Foo = type('Foo',(object,),{'talk':func,'__init__':__init__})#
# #type第一个参数:类名
#type第二个参数:当前类的基类
#type第三个参数:类的成员
f = Foo('Chrn',22)
f.talk()
print(type(Foo)) |
5f50045fadf52e7e1cd0055939d51eda7bbdfea0 | smahmud5949/age_calc | /age calculator demo.py | 412 | 3.859375 | 4 | import datetime
#import arrow
#utc = arrow.utcnow()
date_in = int(input("Input date : "))
month_in = int(input("Input Month : "))
year_in = int(input("Input year : "))
year = datetime.datetime.now().year
#month = datetime.datetime.now().month
#date = datetime.datetime.now().date()
print ("You're "+ str(year-int(year_in))+" old")
print("Enter to exit")
#print(month-int(month_in))
|
a93ea52f80a206de46fe65cfdabec30969e9af62 | zooee/PyDevtest1 | /PythonFirst/Gui.py | 611 | 3.53125 | 4 | #coding=utf-8
'''
Created on 2016年4月27日
@author: Administrator
'''
#from PIL import Image
from tkinter import *
class Application(Frame):
def __init__(self,master=None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
self.helloLabel = Label(self, text='Yeap!Say say say hello~~~')
self.helloLabel.pack()
self.quitButton = Button(self, text='Quit', command=self.quit())
self.quitButton.pack()
app = Application()
app.master.title('Rolling in the deep')
app.mainloop() |
321ca3270dd210a1765db6af8c49ae749a7ed928 | Bobslegend61/python_sandbox | /string.py | 625 | 3.828125 | 4 | # single line strig
name = 'Alabi'
print(name)
# multiline string
sentence = '''This is a sentense
and the sentences
continues from
here.
'''
print(sentence)
# Strings are arrays
a = 'Hello, World'
print(a[0])
# slice syntax
print(a[2:5])
print(a[-5:-2])
# length
print(len(a))
# STRING METHODS
# strip - acts like trim in JS
print(a.strip())
# lowercase
print(a.lower())
# uppercase
print(a.upper())
# Replace
print(a.replace('H', 'J'))
# Split
print(a.split(','))
# check string
print('o' in a)
print('h' not in a)
user = 'Brad'
age = 37
print(f'The name of my mentor is {user} and he is {age} years old') |
67646a311652dff6d31d4f26b778218b52162f5e | sophia1215/pyCollection | /json-douban.py | 2,000 | 3.578125 | 4 | import json
import requests
class Douban(object):
def __init__(self):
self.start_url = "https://movie.douban.com/j/search_subjects?type=movie&tag=%E7%83%AD%E9%97%A8&sort=recommend&page_limit=20&page_start={}"
# 存放所有電影的 url
self.url = []
self.headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
}
for i in range(16):
url = self.start_url.format(i*20)
self.url.append(url)
print (self.url)
with open('douban.csv', 'a') as f:
f.write('電影名稱, 評分, url, 圖片地址' + '\n')
def get_json(self, url):
result = requests.get(url, headers=self.headers)
jsonDict = json.loads(result.text)
content_list = [] # [{},{},{},{},{}]
for i in jsonDict['subjects']:
content = {} # 創建一個 dictionary
content['電影名稱'] = i['title']
content['評分'] = i['rate']
content['url'] = i['url']
content['img'] = i['cover']
content_list.append(content)
print(content_list)
return content_list
def save(self, content_list):
# pass # Suppose you are designing a new class with some methods that you don't want to implement, yet.
with open('douban.csv', 'a') as f:
for content in content_list:
f.write(content['電影名稱'] + ',' +
content['評分'] + ',' +
content['url'] + ',' +
content['img'] + '\n')
def run(self):
for url in self.url :
content_list = self.get_json(url)
self.save(content_list)
if __name__ == '__main__':
douban = Douban()
douban.run()
|
2ab7daef2997c1ebbc28e1c89a469c0176a18844 | seannich/RatVenture_ETI_Assignment | /ratventure/ratventure_functions.py | 11,308 | 3.875 | 4 | import os
import sys
import pickle
import random
class Player:
"""
Player class for when the player first starts the game
"""
def __init__(self):
self.name = 'The Hero'
self.damage = '2-4'
self.minDamage = 2
self.maxDamage = 4
self.defence = 1
self.hp = 20
self.day = 1
self.position = 1
self.location = 'You are in a Town'
self.locationTag = 'H'
self.combat = False
def herostats(self):
'''
This function prints out the player's name, damage, defence and HP.
Expected Output:
The Hero
Damage: 2-4
Defence: 1
HP: 20
'''
stats = self.name + "\nDamage: {}\nDefence: {}\nHP: {}".format(self.damage,self.defence,self.hp)
print(stats)
return stats
def herorest(self):
'''
This function restores the player to 20, adds 1 day to the day count and prints out "You are fully healed".
Expected Output:
20 2
'''
self.hp = 20
self.day += 1
print("You are fully healed.")
return self.hp, self.day
def playerMovement(self):
"""
This function shows the map UI and allows player to move their character.
Player postion starts at 1.
W: player.postion -8
A: player.postion -1
S: player.postion +8
D: player.postion +1
If player goes outside of map: How about we explore the area ahead of us later.
If player chooses something other than wasd: Please select a valid option.
If player chooses acceptable choice: return player postition
"""
position = self.position
topWall = [1,2,3,4,5,6,7,8]
leftWall = [1,9,17,25,33,41,49,57]
bottomWall = [57,58,59,60,61,62,63,64]
rightWall = [8,16,24,32,40,48,56,64]
posibleChoice = ["w", "a", "s", "d"]
errorMsg = "How about we explore the area ahead of us later."
invalidChoice = "Please select a valid option."
invalidMovement = True
while invalidMovement:
mapUI(position)
print("W = up; A = left; S = down; D = right")
choice = input("Your move: ")
if choice not in posibleChoice:
print(invalidChoice)
return invalidChoice
else:
if choice == "w":
if position in topWall:
print(errorMsg)
else:
position -= 8
invalidMovement = False
self.position = position
mapUI(self.position)
if choice == "a":
if position in leftWall:
print(errorMsg)
else:
position -= 1
invalidMovement = False
self.position = position
mapUI(self.position)
if choice == "s":
if position in bottomWall:
print(errorMsg)
else:
position += 8
invalidMovement = False
self.position = position
mapUI(self.position)
if choice == "d":
if position in rightWall:
print(errorMsg)
else:
position += 1
invalidMovement = False
self.position = position
mapUI(self.position)
if invalidMovement :
return errorMsg
else:
return self.position
class Enemy:
"""
Enemy class to create an enemy for player to fight when they enter combat
Example of how to create object:
rat = Enemy('Rat', 1, 3, 1, 10)
"""
def __init__(self, name, minDamage, maxDamage, defence, maxHp):
self.name = name
self.minDamage = minDamage
self.maxDamage = maxDamage
self.defence = defence
self.maxHp = maxHp
self.hp = self.maxHp
self.alive = True
def run(player, enemy):
'''
This function sets the player's combat state to False, restores the Enemy's HP to maximum and prints out "You run and hide".
Expected Output:
False, Enemy HP restored to max
'''
player.combat = False
enemy.hp = enemy.maxHp
print("You run and hide.")
def spawnorb(townPosition):
"""
Spawns the Orb of Power in a random town except the first town (the town that the player spawns in) and returns the town position that the orb is in
"""
orbPossiblePosition = townPosition[1:-1]
orbPosition = random.choice(orbPossiblePosition)
return orbPosition
def mapUI(position):
"""
Displays UI for map
+---+---+---+---+---+---+---+---+
| T | | | | | | | |
+---+---+---+---+---+---+---+---+
| | | | T | | | | |
+---+---+---+---+---+---+---+---+
| | | | | | T | | |
+---+---+---+---+---+---+---+---+
| | T | | | | | | |
+---+---+---+---+---+---+---+---+
| | | | | | | | |
+---+---+---+---+---+---+---+---+
| | | | | | | | |
+---+---+---+---+---+---+---+---+
| | | | | T | | | |
+---+---+---+---+---+---+---+---+
| | | | | | | | K |
+---+---+---+---+---+---+---+---+
"""
map = "+---+---+---+---+---+---+---+---+\n"
townPosition = [1,12,22,26,53]
orbposition = spawnorb(townPosition)
for x in range(1,65):
if (x % 8) == 0 and x != 64:
map += "| |\n+---+---+---+---+---+---+---+---+\n"
elif x in townPosition:
if x == position:
map += "|H/T"
elif x == orbposition:
map += "|T/O"
else:
map += "| T "
elif x == 64:
if x == position:
map += "|H/K|\n+---+---+---+---+---+---+---+---+\n"
else:
map += "| K |\n+---+---+---+---+---+---+---+---+\n"
elif x == position and x != townPosition and x != 64:
map += "| H "
else:
map += "| "
print(map)
return(map)
def mainMenuUI():
"""
Displays UI for main menu
Welcome to Ratventure!
----------------------
1) New Game
2) Resume Game
3) Exit Game
"""
os.system('cls')
menuUI = "Welcome to Ratventure!\n----------------------\n1) New Game\n2) Resume Game\n3) Exit Game"
print(menuUI)
#mainMenu()
return menuUI
def mainMenu():
"""
takes in and displays player input choice
"""
choice = int(input("Enter choice: "))
if choice > 3 or choice < 0 :
print("Invalid number. Please try again.")
return "Invalid number. Please try again."
else:
return choice
def townMenuUI():
"""
Displays UI for town menu
Day 1: You are in a town.
1) View Character
2) View Map
3) Move
4) Rest
5) Save Game
6) Exit Game
"""
townmenuUI = "Day 1: You are in a town.\n1) View Character\n2) View Map\n3) Move\n4) Rest\n5) Save Game\n6) Exit Game"
print(townmenuUI)
return townmenuUI
def townMenu():
"""
takes in and displays player input choice
"""
choice = int(input("Enter choice: "))
if choice > 6 or choice < 0 :
print("Invalid number. Please try again.")
return "Invalid number. Please try again."
else:
return choice
def outdoorMenuUI():
"""
Displays UI for outdoor menu
1) View Character
2) View Map
3) Move
4) Exit Game
"""
outdoorMenuUI = "1) View Character\n2) View Map\n3) Move\n4) Exit Game"
print(outdoorMenuUI)
return outdoorMenuUI
def outdoorMenu():
"""
takes in and displays player input choice
"""
choice = int(input("Enter choice: "))
if choice > 4 or choice < 0 :
print("Invalid number. Please try again.")
return "Invalid number. Please try again."
else:
return choice
"""
"You deal" + damage "to the Rat"
"Ouch! The Rat hit you for" + damage "!"
"You have" + hp + "HP left."
"Encounter! - Rat"
"Damage:" + damage
"Defence:" + defence
"HP:" + hp
"""
def attackMenuUI():
"""
Displays UI for town menu
1) Attack
2) Run
"""
attackMenuUI = "1) Attack\n2) Run"
print(attackMenuUI)
return attackMenuUI
def attackMenu(player):
"""
takes in and displays player input choice
"""
rat = Enemy("Rat", 1, 3, 1, 10)
choice = int(input("Enter choice: "))
if choice > 2 or choice < 0 :
print("Invalid number. Please try again.")
return "Invalid number. Please try again."
else:
if choice == 2:
run(player, rat)
return "You run and hide."
return choice
"""
def main():
choice ='0'
while choice =='0':
print("Welcome to Ratventure!")
print("1) View Character")
print("2) View Map")
print("3) Move")
print("4) Rest")
print("5) Save Game")
print("6) Exit Game")
choice = input ("Enter choice: ")
if choice == "1":
print("Enter choice: 1") #Display stats
print("The Hero")
print(" Damage:" + damage)
print("Defence:" + defence)
print(" HP:" + hp)
elif choice == "2":
print("Enter choice: 2") #Display map
print("+---+---+---+---+---+---+---+---+ \
|H/T| | | | | | | | \
+---+---+---+---+---+---+---+---+ \
| | | | T | | | | | \
+---+---+---+---+---+---+---+---+ \
| | | | | | T | | | \
+---+---+---+---+---+---+---+---+ \
| | T | | | | | | | \
+---+---+---+---+---+---+---+---+ \
| | | | | | | | | \
+---+---+---+---+---+---+---+---+ \
| | | | | | | | | \
+---+---+---+---+---+---+---+---+ \
| | | | | T | | | | \
+---+---+---+---+---+---+---+---+ \
| | | | | | | | K | \
+---+---+---+---+---+---+---+---+") #-> x axis
elif choice == "3": #Move
print("Enter choice: 3")
print("W = up; A = left; S = down; D = right")
elif choice == "4":
print("Enter choice: 4")
self.hp == 20
print("You are fully healed.")
elif choice == "5":
print("Enter choice: 5")
data = {'health':100, 'gold': 1560, 'name': 'mariano'}
print("Game saved.")
elif choice == "6":
print("Enter choice: 6")
sys.exit(0)
else:
print("Please choose a number from 1 to 6.")
def second_menu():
print("This is the second menu")
main()
#load save file
#with open('savefile', 'w') as f:
#pickle.dump(data, f)
#with open('savefile') as f:
#data = pickle.load(f)
"""
|
42595d662e824cbe692fbc043979c3949da91c70 | romenskiy2012/py | /Essentials/vector.py | 192 | 3.71875 | 4 | def combine(array,text):
string = ""
while len(list(array)) > 0:
string += str(array.pop(0))
if len(list(array)) > 0:
string += text
return string |
f20b7b521016022b89d77f5beb10bd18836b256b | talk2mat2/snbank | /bank.py | 4,790 | 3.859375 | 4 |
#customer text file
file= "./customer.txt"
#staff details read from json object file system using json(dictionary) file system of python
def readstaff(files):
import json
with open(files,'r') as staffdetails:
json_data = json.load(staffdetails)
return json_data
staff= readstaff('./staff.txt')
#login user
def login_success():
print('welcome today, \n select an option, select 1, 2 or 3\n (1) Create new bank account\n (2) Check Account Details\n(3) Logout')
option= int(input('selection__ '))
if option == 1:
CreateAcct(file)
if option == 2:
Check_Account_Details(file)
if option ==3:
sesssions.clear_sessions()
print('logged out, bye')
home()# calling home function after log in success
class sesssions():
def create_session():
from datetime import datetime
sessions=open("session.txt",'w')
now = datetime.now()
sessions.write(f'sussion time {now}')
sessions.close()
def check_sessions():
import os
from pathlib import Path
sessions= Path('./session.txt')
if sessions.is_file():
return True
else:
return False
def clear_sessions():
import os
os.remove('session.txt')
#user validaation function
def loginstaff(staff):
authorization = False
print('login--')
while authorization == False:
stafflogin = input('Username: ')
staffpassword = input('Password: ')
for obj in staff:
if obj.get('username')==stafflogin and obj.get('password')==staffpassword:
authorization = True
user=obj['full name']
print(f'success, logged in as {user}')
sesssions.create_session()#create sessions after succesfull login
sesssions.check_sessions() #create user sessions on log in
login_success() # calling home function
if authorization == False:
print('authorization failed try again wrong login details')
#account create function
def CreateAcct(file):
import json
import random
print('welcome to new account creation ssection')
Account_name= input('Account name. ')
Opening_Balance=input('Opening Balance ')
Account_Type= input('Account Type ')
Account_Type= input('Account_email ')
user_data={}
user_data[' Account name']= Account_name
user_data[' Opening Balance']= Opening_Balance
user_data[' Account Type']= Account_Type
user_data['Account Type']= Account_Type
#customer_list.append(user_data)
values="1234567890"
acct=''
acct_no_size=10
while len(acct)<acct_no_size:
acct+=random.choice(values)
acct_no=int(acct)
print(f'hurray!, set up success , new account number for { Account_name } is {acct_no} ')
user_data['account number'] =acct_no
with open(file,'r') as CustomerData:
json_data = json.load(CustomerData)
json_data.append(user_data)
with open(file,'w') as CustomerData:
json.dump(json_data,CustomerData)
login_success() #calling login _success function after creating account success
#json.dump(json_data,CustomerData)
#check account
def Check_Account_Details(file):
import json
Account_number= input('Account number ?. ')
with open(file,'r') as CustomerData:
json_data = json.load(CustomerData)
for customer_details in json_data:
if customer_details.get("account number") == int(Account_number):
print('customer details found')
print(customer_details)
login_success() # calling login success function
if customer_details.get("account number") != int(Account_number):
print(f"customer with account no {Account_number} not found in database")
Check_Account_Details(file)
def home():
if sesssions.check_sessions():
print('user already logged in sesions')
login_success()
else:
print('welcome today, \n select an option, select 1 or 2\n (1) login\n (2) close app')
option= int(input('selection__ '))
if option == 1:
loginstaff(staff)
if option == 2:
print('have a nice day')
pass
else:
print('please selesct a valid option and try again')
home() #looping if the user slect a wrong number
#call the home function which is the entry point(function) of the banking system app
# print(sesssions.check_sessions())
home()
|
d83917e8b2f6639193c940d0d166b8641fa06f9e | 1ggera/programitas_python | /ejercicios_python/lists_and_dicts.py | 1,040 | 3.921875 | 4 | #Una lista puede guardar diccionarios y los diccionarios pueden guardar listas.
#creamos nuestra función principal
def run():
my_list = [1, "Hello", True, 4.5]
my_dict = {"firstname": "Gerard", "lastname": "García"}
super_list = [
{"firstname": "Gerard", "lastname": "García"},
{"firstname": "Alberto", "lastname": "Sputnikandez"},
{"firstname": "Confinamiento", "lastname": "Confinatorio"},
{"firstname": "Nomelacon", "lastname": "Tactoextraterrestre"},
{"firstname": "Nomela ", "lastname": "Concordia"}
]
super_dict = {
"natural_nums": [1, 2, 3, 4, 5],
"integer_nums": [-1, -2, 0, 1, 2],
"floating_nums": [1.1, 4.5, 6.45]
}
#este ciclo recorrera las laves y valores con el método .items()
for key, value in super_dict.items(): #items nos permite recorrer las llaves y valores al mismo tiempo de un diccionario en un ciclo.
print(key, "-", value)
print()
for item in super_list:
print(item["firstname"] , "-", item["lastname"])
if __name__ == '__main__':
run() |
7ec4cc3cff68130c5eb9ded95204bf00a1d720d3 | travisoneill/project-euler | /python/.521.py | 3,548 | 3.53125 | 4 | from generators import primes2
from primesandfactors import prime_factors
def run(limit):
start = [1]
p = 2
for prime in primes2(11):
if prime == 2: continue
def steps(n):
a, b, c = 1, 2, 4
step = 3
while step < n:
a, b, c = b, c, a+b+c
step += 1
return c
def steps2(n):
if n < 0:
return 0
elif n == 0:
return 1
else:
return steps2(n-1) + steps2(n-2) + steps2(n-3)
arr = [-3, 1, 3, 4, 5, 6, 7, 8, 15, 20]
arr = [0,1,2,3,4,5,7,8,9,10]
arr = [-5,-4,3,5,7,8,9,10]
def magic(arr):
lo, hi = 0, len(arr) - 1
while hi - lo > 1:
mid = (hi + lo) // 2
test = mid - arr[mid]
if not test:
break
elif test < 0:
hi = mid
else:
lo = mid
count = 0
search = mid
while not search - arr[search]:
count += 1
search += 1
search = mid - 1
while not search - arr[search]:
count += 1
search -= 1
return count
def m_primes(n):
f = set(prime_factors(n))
m = []
for i in range(1, n):
for p in f:
if not i % p:
break
else:
m.append(i)
# if not set(prime_factors(i)) & f:
return m
def generate(n, limit):
yield n
yield n**2
exponents = [n, n**2]
power = 3
for p in primes2(limit):
if p <= n: continue
if n*p > n**power:
print(n, p, power)
if n**power <= limit:
yield n**power
exponents.append(n**power)
power += 1
for exp in exponents:
if p * exp > limit: break
yield p * exp
def g2(n, limit):
cycle_length = 1
for p in primes2(n-1):
cycle_length *= p
if n == 3: cycle_length = 2
cycle = m_primes(cycle_length)
# print(cycle, cycle_length)
for i in range(n, limit+1, n):
if i % cycle_length in cycle:
yield i
from primesandfactors import prime_factors
from itertools import combinations
from functools import reduce
from generators import primes
product = lambda collection: reduce(lambda x, y: x*y, collection)
c_prod = lambda factors, n: set(map(product, combinations(factors, n)))
def phi(n, limit=None):
idx = n - 1
f = prime_factors(n, 'set')
if limit and len(f) > limit: return n//2
for i in range(len(f)):
multiplier = [-1, 1]
c = c_prod(f, i+1)
for x in c:
idx += (n//x - 1) * multiplier[i%2]
return idx
def g3(n, limit):
yield n
primes = [ p for p in primes2(limit//n) if p >= n ]
product = reduce( lambda x, y: x * y, primes2(n) )
max_exp = 1
while n**max_exp < limit:
max_exp += 1
for exp in range(1, max_exp):
for exp2 in range(1, max_exp):
for p in primes:
x = n**exp * p**exp2
if x > limit: break
yield x
def int_log(b, n):
l = -1
while n:
l += 1
n //= b
return l
il = int_log
def make(n):
p = product(primes2(n-1))
return list(map(lambda x: x*n, m_primes(p)))
def diffs(arr):
return [arr[i+1] - arr[i] for i in range(len(arr)-1)]
def run(n):
prod = 1
for p in primes2(1000):
prod *= p
if prod > n: break
print(p, phi(prod))
def run2(num):
n = 1
for p in primes2(num):
n *= p
ph = phi(n)
print(p, ph, prime_factors(ph))
def subc(sett):
for n in range(2**(len(s))):
pass
|
b4e897435f26761ca83642abe3750738145310a2 | travisoneill/project-euler | /python/080.py | 4,308 | 3.53125 | 4 | from benchmark import benchmark
def square_root(n, precision):
if n < 0: raise 'No sqrt for negative numbers'
if n == 0: return 0
log_10 = -1
m = n
while n > 0:
log_10 += 1
n //= 10
exponent = 2 * (precision - log_10 // 2 ) - 2
return int_sqrt(m * 10**exponent)
def int_sqrt(n):
lo, hi = 1, n
while hi - lo > 1:
mid = (hi + lo) // 2
val = mid * mid
if val == n: return mid
if val > n: hi = mid
if val < n: lo = mid
return lo
def digital_sum(n):
d_sum = 0
while n > 0:
d_sum += n % 10;
n //= 10;
return d_sum
@benchmark()
def run(n, precision):
total = 0
for i in range(n+1):
x = int_sqrt(i)
if x * x == i: continue
total += digital_sum(square_root(i, precision))
print(total)
#TODO take str multiplier from old approch and adapt for module
#
# from stringmath import add_str
# from math import sqrt
# from functools import reduce
# def squared_decimal(string):
# if string >= '0.0001': return mult_str(string, string)
# decimal = string.split('.')[-1]
# trimmed = decimal.lstrip('0')
# leading_zeroes = '0' * (2 * ( len(decimal) - len(trimmed) ))
# trimmed = '0.' + trimmed
# result = mult_str(trimmed, trimmed)
# return '0.' + leading_zeroes + result.split('.')[-1]
#
# def run(n):
# res = 0
# for i in range(1, n+1):
# res += root(i, 100)
# print(res)
# return res
#
# def root(n, decimal_precision):
# if sqrt(n) % 1 == 0: return 0
# square_root = str(sqrt(n))[:-2] #issue if n > 10^12
# decimals = len(square_root.replace('.', ''))
# zeroes = '0' * len(square_root.split('.')[-1])
# digital_sum = reduce( lambda x, y: x + int(y), square_root.replace('.', ''), 0 )
# last = mult_str(square_root, square_root)
# test_val = last
# while decimals < decimal_precision:
# for digit in range(1, 10):
# store = test_val
# ab = '0.' + str(digit)
# a1 = mult_str(ab, '2')
# a2 = mult_str(a1, square_root)
# a = '0.' + add_str(zeroes, a2.split('.')[0]) + a2.split('.')[-1] if zeroes else a2
#
# b = squared_decimal( '0.' + zeroes + str(digit) )
# c = add_str(a, b)
# test_val = add_str(last, c)
# if int(test_val.split('.')[0]) >= n:
# square_root += str(digit-1)
# last = store
# test_val = store
# break
# else:
# square_root += str(digit)
# last = test_val
#
# zeroes += '0'
# decimals += 1
# digital_sum += int(square_root[-1])
# return digital_sum
#
# def mult_str(*args):
# return reduce(multiplier, args)
#
# def multiplier(x, y):
# if len(x) < len(y): x, y = y, x
# negative = '-' if (x[0] == '-') ^ (y[0] == '-') else ''
# carry = 0
# if x[-1] == '.': x += '0'
# if y[-1] == '.': y += '0'
# x_decimal = len(x) - x.index('.') - 1 if '.' in x else 0
# y_decimal = len(y) - y.index('.') - 1 if '.' in y else 0
# result = '0'
# zeroes = ''
# carry = 0
# for dx in reversed(x):
# if dx == '.' or dx == '-': continue
# num = zeroes[:]
# for dy in reversed(y):
# if dy == '.' or dy == '-': continue
# sm = int(dx) * int(dy) + carry
# digit = sm % 10
# num = str(digit) + num
# carry = sm // 10
# if carry > 0: num = str(carry) + num
# carry = 0
# zeroes += '0'
# result = add_str(result, num)
#
# if x_decimal or y_decimal:
# decimal_place = len(result) - x_decimal - y_decimal
# result = negative + result[:decimal_place] + '.' + result[decimal_place:]
# else:
# result = negative + result
#
# return process(result)
#
# def process(string):
# negative = '-' if string[0] == '-' else ''
# string = string[1:] if negative else string
# string = string.lstrip('0')
# if not string: return '0'
# if '.' in string: string = string.rstrip('0')
# if string == '.': return '0.0'
# if string[0] == '.': string = '0' + string
# if string[-1] == '.': string += '0'
# return negative + string
|
25ce186e86fc56201f52b12615caa13f98044d99 | travisoneill/project-euler | /python/007.py | 327 | 3.953125 | 4 | from math import sqrt
def is_prime(n):
if n < 2: return False
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
return False
return True
def nth_prime(n):
count = 2
i = 3
while count < n:
i+=2
if is_prime(i):
count += 1
print(i)
nth_prime(10001)
|
4d5d9b686f9635b85c2bea281be1e197e054b5c2 | travisoneill/project-euler | /python/020.py | 127 | 3.734375 | 4 | from math import factorial
n = factorial(100)
digit_sum = 0
while n > 0:
digit_sum += n % 10
n //= 10
print(digit_sum)
|
7db9acc6ee427d7d4fe61d6d53416e46ebad2a37 | travisoneill/project-euler | /python/037.py | 712 | 3.6875 | 4 | from primesandfactors import is_prime
def run():
primes = {}
def primetest(n):
if n in primes:
return primes[n]
else:
primes[n] = is_prime(n)
return primes[n]
def is_truncatable_prime(n):
power = 1
while n % 10**power != n:
if not primetest(n % 10**power): return False
power += 1
while n > 0:
if not primetest(n): return False
n //= 10
return True
count = 0
result = 0
number = 11
while count < 11:
if is_truncatable_prime(number):
count += 1
result += number
number += 2
print(result)
return result
|
56ed71edf7bbf02583707e2d4139d3a90c07dfe1 | Thamarai-Selvam/Color-it | /app.py | 1,683 | 4 | 4 | import random
import tkinter
colors = ['Red', 'Green', 'Blue', 'Yellow', 'Black', 'White', 'Pink', 'Brown']
points = 0 # points gained
time = 30 # time left to complete
def start(e): # start game method
if time == 30:
timer()
nextColor()
def nextColor(): # array traverse to find next color
global time
global points
if time > 0: # game is going on
e.focus_set()
if e.get().lower() == colors[1].lower():
points += 1
e.delete(0, tkinter.END)
random.shuffle(colors)
label.config(fg = str(colors[1]), text = str(colors[0]))
Ptlabel.config(text= 'POINTS : ' + str(points))
def timer():
global time
if time > 0:
time -= 1
tlabel.config(text = 'Time Left : '+ str(time))
tlabel.after(1000,timer)#run after 1 second
root = tkinter.Tk()
root.title('Color it')
root.geometry('360x240')
instructions = tkinter.Label(root, text = "Type in the colour of the words, and not the word text!",font = ('Helvetica', 12))
instructions.pack()
Ptlabel = tkinter.Label(root, text = "Press enter to start",
font = ('Helvetica', 12))
Ptlabel.pack()
# add a time left label
tlabel = tkinter.Label(root, text = "Time left: " +
str(time), font = ('Helvetica', 12))
tlabel.pack()
# add a label for displaying the colours
label = tkinter.Label(root, font = ('Helvetica', 60))
label.pack()
# add a text entry box for
# typing in colours
e = tkinter.Entry(root)
# run the 'startGame' function
# when the enter key is pressed
root.bind('<Return>', start)
e.pack()
# set focus on the entry box
e.focus_set()
# start the GUI
root.mainloop()
|
9118bb6ac1537fa2ea231501bb177f97748de482 | Yang-J-LIN/KC3F | /run_picar.py | 6,150 | 3.625 | 4 | # This is the main code to run the pi car.
import time
import numpy as np
from cv2 import cv2 as cv
import driver
import image_processing
import camera_capturer
import utils
DEBUG = False
PERIOD = 0 # the period of image caption, processing and sending signal
OFFSET = 371
def cruise_control(bias, k_p=1, k_i=0, k_d=1):
""" Controls the picar on the mode of cruise
"""
return 0
def cruise():
""" Tracks the black line.
Acquires images from front camera and uses it to do pure pursuit.
Uses functions in driver.py to drive the pi car.
There is a three-step process to reach the goal.
Step 1.
Employs CameraCapturer class to acquire images from front camera and
rectify lens distortion.
Step 2.
Chooses the ROI and binarizes the it. Then uses morphology method to
get the target point.
Step 3.
According to target point, applies pure pursuit algorithm and uses
functions in driver.py to drive the car.
Args:
None
Returns:
None
"""
# Initialize CameraCapturer and drive
cap = camera_capturer.CameraCapturer("front")
d = driver.driver()
d.setStatus(motor=0.4, servo=0, mode="speed")
last_time = time.time()
target = OFFSET # -int(cap.width / 5)
# Parameters of PID controller
kp = 1.2
ki = 0
kd = 0.1
# Initialize error to 0 for PID controller
error_p = 0
error_i = 0
error_d = 0
error = 0
servo = 0
last_servo = 0
last_angle = 0
n = 0.2
try:
while True:
this_time = time.time()
if this_time - last_time > PERIOD: # Execute the code below every
# PERIOD time
last_time = this_time
# d.setStatus(motor=0, servo=n, mode="speed")
# n = -n
# continue
# ----------------------------------------------------------- #
# Start your code here #
# Image processing. Outputs a target_point.
frame = cap.get_frame()
start = time.time()
skel, img_bin_rev = image_processing.image_process(frame)
white_rate = \
np.size(img_bin_rev[img_bin_rev == 255]) / img_bin_rev.size
if white_rate > 0.3:
print("stay", white_rate)
d.setStatus(servo=last_servo)
continue
target_point, width, _, img_DEBUG, angle = \
choose_target_point(skel, target)
end = time.time()
if angle == 0:
angle = last_angle
pass
else:
# Update the PID error
error_p = angle # **(9/7)
error_i += error_p
error_d = error_p - error
error = error_p
# PID controller
servo = utils.constrain(- kp*error_p
- ki*error_i
- kd*error_d,
1, -1)
d.setStatus(servo=servo)
last_servo = servo
# print("servo: ", servo, "error_p: ", error_p)
# img_DEBUG[:, target] = 255
# if DEBUG:
# # cv.imshow("frame", frame)
# cv.imshow("img_bin_rev", img_bin_rev)
# cv.imshow("img_DEBUG", img_DEBUG)
# cv.waitKey(300)
# ----------------------------------------------------------- #
else:
# time.sleep(0.01)
pass
except KeyboardInterrupt:
d.setStatus(servo=0, motor=0)
def choose_target_point(skel, target):
""" Selects a target poitn from skeleton for pure pursuit.
Draws a ellipse and applies an and operation to the ellipse with the skel.
Then returns a point that has least distance with the center of the
ellipse.
Args:
skel: skeleton of trajectory.
Returns:
target_point: target point for pure pursuit.
"""
width = skel.shape[1]
height = skel.shape[0]
img = np.zeros((height, width), dtype=np.uint8)
ellipse_a = width // 2
ellipse_b = height // 3
ellipse = cv.ellipse(img,
center=(target, height),
axes=(ellipse_a, ellipse_b),
angle=0,
startAngle=180,
endAngle=360,
color=255,
thickness=1)
img_points = np.bitwise_and(skel, ellipse)
_, contours, _ = cv.findContours(img_points,
mode=cv.RETR_EXTERNAL,
method=cv.CHAIN_APPROX_NONE)
discrete_points = []
img_DEBUG = np.zeros((height, width, 3), dtype=np.uint8)
img_DEBUG[:, :, 0] = skel
img_DEBUG[:, :, 1] = img_points
img_DEBUG[:, :, 2] = ellipse
cv.imwrite("img_DEBUG_2.jpg", img_DEBUG)
# cv.waitKey(200)
for contour in contours:
if contour.size == 2:
discrete_points.append(np.squeeze(contour))
else:
pass
# discrete_points = sorted(discrete_points,
# key=lambda x: (x[0] - width // 2)**2 +
# (x[1] - height) ** 2)
discrete_points = sorted(discrete_points,
key=lambda x: np.abs(x[0] - target))
if len(discrete_points) != 0:
px = discrete_points[0][0] - target
angle = np.arctan2(px, ellipse_a)
# angle = angle[0]
print("angle:", angle)
return discrete_points[0], width, height, img_DEBUG, angle
else:
return [0, 0], width, height, img_DEBUG, 0
# return [target, 0], width, height, img_DEBUG
if __name__ == "__main__":
cruise()
|
8a9b6e0a0e3c93af99710309d448b95617a2f8cc | zombaki/PythonPrac | /LeetSubdomainVisit.py | 1,084 | 3.515625 | 4 | '''class Solution(object):
def subdomainVisits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
d={}
for i in cpdomains:
#print i
li=i.split()
#print li
for b in li[1].split('.'):
#print b
d[b]=d.get(b,0)+int(li[0])
#print d
return ["{} {}".format(value, key) for key, value in d.iteritems()]
a = Solution()
priint a.subdomainVisits(["9001 discuss.leetcode.com"])'''
class Solution(object):
def subdomainVisits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
dic = {}
for item in cpdomains:
cnt, domain = item.split(' ')
subdomain = domain.split('.')
for i in xrange(len(subdomain)):
name = '.'.join(subdomain[i:])
if name not in dic:
dic[name] = int(cnt)
else:
dic[name] += int(cnt)
return ['{} {}'.format(dic[key], key) for key in dic]
|
d568dfb4b19222718d1505aa36fd16b7e80eb551 | zombaki/PythonPrac | /robotPaths.py | 348 | 3.9375 | 4 | def numberOfPaths(m, n):
# If either given row number is first
# or given column number is first
print m,n
if(m == 1 or n == 1):
return 1
#print m,n
# If diagonal movements are allowed
# then the last addition
# is required.
return numberOfPaths(m-1, n) + numberOfPaths(m, n-1)
m=3
n=2
print numberOfPaths(m,n)
|
29d6f7af5cf7bd4970a0db8064981c0309a5a18a | lambdacubed/genetic-algorithm | /plot_functions.py | 1,780 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains functions used for plotting.
"""
import numpy as np # general useful python library
import matplotlib.pyplot as plt # plotting library
# TODO make this a part of people and get rid of plot_functions
def plot_performance(iteration_number, figures_of_merit):
"""
Plot the figures of merit
This plots the num_parents number of best figures of merit
Parameters
----------
iteration_number : int
The number of iterations the algorithm has gone through
figures_of_merit : numpy 1d array
This contains current best figures of merit.
Returns
-------
iteration_number : int
The number of iterations the algorithm has gone through
past_figures_of_merit : numpy 2d array
This contains figures of merit from all of the previous generations.
"""
plt.figure(1) # set the figure to be plotting to
if iteration_number == 0:
plt.ion() # enable interactive mode so we can continuously draw on the graph
plt.show() # show the plot window
plt.title('Figures of merit progression')
plt.xlabel('Iterations')
plt.ylabel('Figures of merit')
iteration_number = iteration_number + 1 # add one to the number of iterations
iteration_vector = np.arange(0, iteration_number+1) # make a vector of [0, 1, 2, ... iteration_number]
plt.figure(1)
for i in range(0, figures_of_merit.shape[0]):
plt.plot(iteration_vector, figures_of_merit[i], '-') # plot the progression of this ith best figure of merit
plt.draw() # draw these things on the graph
plt.pause(.001) # pause the program so the plot can be updated
return iteration_number, figures_of_merit
|
e577cde6b041510ab0bc4db9b398af65afdb0894 | FermiQ/molecular_features | /molreps/methods/props_py.py | 3,108 | 4.0625 | 4 | """Functions using only python.
Note: All functions are supposed to work out of the box without any dependencies, i.e. do not depend on each other.
"""
def element_list_to_value(elem_list, replace_dict):
"""
Translate list of atoms as string to a list of values according to a dictionary.
This is recursive and should also work for nested lists.
Args:
elem_list (list): List of elements like ['H','C','O']
replace_dict (dict): python dictionary of atom label and value e.g. {'H':1,...}
Returns:
list: List of values for each atom.
"""
if isinstance(elem_list, str):
return replace_dict[elem_list]
elif isinstance(elem_list, list):
outlist = []
for i in range(len(elem_list)):
if isinstance(elem_list[i], list):
outlist.append(element_list_to_value(elem_list[i], replace_dict))
elif isinstance(elem_list[i], str):
outlist.append(replace_dict[elem_list[i]])
return outlist
def get_atom_property_dicts(identifier):
"""
Get a Dictionary for properties by identifier.
Args:
identifier (str): Which property to get.
Returns:
dict: Dictionary of Properties.
"""
global_proton_dict = {'H': 1, 'He': 2, 'Li': 3, 'Be': 4, 'b': 5, 'C': 6, 'N': 7, 'O': 8, 'F': 9, 'Ne': 10, 'Na': 11,
'Mg': 12, 'Al': 13, 'Si': 14, 'P': 15, 'S': 16, 'Cl': 17, 'Ar': 18, 'K': 19, 'Ca': 20,
'Sc': 21, 'Ti': 22, 'V': 23, 'Cr': 24, 'Mn': 25, 'Fe': 26, 'Co': 27, 'Ni': 28, 'Cu': 29,
'Zn': 30, 'Ga': 31, 'Ge': 32, 'As': 33, 'Se': 34, 'Br': 35, 'Kr': 36, 'Rb': 37, 'Sr': 38,
'Y': 39, 'Zr': 40, 'Nb': 41, 'Mo': 42, 'Tc': 43, 'Ru': 44, 'Rh': 45, 'Pd': 46, 'Ag': 47,
'Cd': 48, 'In': 49, 'Sn': 50, 'Sb': 51, 'Te': 52, 'I': 53, 'Xe': 54, 'Cs': 55, 'Ba': 56,
'La': 57, 'Ce': 58, 'Pr': 59, 'Nd': 60, 'Pm': 61, 'Sm': 62, 'Eu': 63, 'Gd': 64, 'Tb': 65,
'Dy': 66, 'Ho': 67, 'Er': 68, 'Tm': 69, 'Yb': 70, 'Lu': 71, 'Hf': 72, 'Ta': 73, 'W': 74,
'Re': 75, 'Os': 76, 'Ir': 77, 'Pt': 78, 'Au': 79, 'Hg': 80, 'Tl': 81, 'Pb': 82, 'Bi': 83,
'Po': 84, 'At': 85, 'Rn': 86, 'Fr': 87, 'Ra': 88, 'Ac': 89, 'Th': 90, 'Pa': 91, 'U': 92,
'Np': 93, 'Pu': 94, 'Am': 95, 'Cm': 96, 'Bk': 97, 'Cf': 98, 'Es': 99, 'Fm': 100, 'Md': 101,
'No': 102, 'Lr': 103, 'Rf': 104, 'Db': 105, 'Sg': 106, 'Bh': 107, 'Hs': 108, 'Mt': 109,
'Ds': 110, 'Rg': 111, 'Cn': 112, 'Nh': 113, 'Fl': 114, 'Mc': 115, 'Lv': 116, 'Ts': 117,
'Og': 118, 'Uue': 119}
inverse_global_proton_dict = {value: key for key, value in global_proton_dict.items()}
if identifier == "ToProton":
return global_proton_dict
if identifier == "FromProton":
return inverse_global_proton_dict
|
c1be175fdd677df021128b43da0c2a3fc71c6afb | zakari-gif/Emoticon | /EmoticonsV5_EAD 2/Q6/Q6Emoticon.py | 1,168 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 16 19:47:50 2017
@author: lfoul
"""
import pygame
import math
class Emoticon:
# Constructor
def __init__(self, sensor) :
self.sensor = sensor
# Sets the emoticon parameters
def setEmoticonParameters(self, size) :
self.eyeWidth = 0.1*size
self.eyeHeight = 0.15*size
self.eyeLeftPosition = [-0.15*size, 0.1*size]
self.eyeRightPosition = [0.15*size, 0.1*size]
self.mouthPosition = [0, -0.25*size]
self.mouthMaxHeight = 0.3*size
self.mouthMaxWidth = 0.55*size
self.mouthAngle = math.pi/10
# Computes the position in the screen
def headToArea(self, position):
pass
# Computes the color
def color(self,x):
pass
# Draws head
def head(self, x):
pass
# Draws one eye
def eye(self, position):
pass
# Draws the mouth
def mouth(self, position, x):
pass
# Draws the emoticon
def draw(self):
pass
|
34ca6f24ac93cbae0d56e5e3664071dee70739a2 | zakari-gif/Emoticon | /EmoticonsV5_EAD 2/Q1/Q5Button.py | 1,298 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 16 19:47:50 2017
@author: lfoul
"""
import pygame
from Q3GeneralConfiguration import GeneralConfiguration
class Button:
# Constructor
def __init__(self, sensor) :
self.sensor = sensor
# Gets the sensor position on the screen
def getPosition(self):
return [self.sensor.generalConfiguration.buttonWidth,self.sensor.generalConfiguration.buttonHeight]
# Draws the text
def draw(self):
SIZE = [150,80]
blanc = [255, 255, 255]
rect =[150,70,255,80]
pygame.draw.rect(self.sensor.generalConfiguration.screen, blanc, rect,1)
self.drawLines(['affichage','ok'])
def drawLines(self, lines):
screen = pygame.display.get_surface()
# Creates the font
font = pygame.font.Font(None, 80)
# Creates the text image containing « This is a test » written in white
for i in lines:
textImage = font.render(i, 1, [0,255,255],[0,0,255])
# Pastes the image on the screen. The upper left corner is at the position
screen.blit(textImage,[self.sensor.generalConfiguration.buttonWidth,self.sensor.generalConfiguration.buttonHeight])
|
4f3dc041a0fd1b96c2dd21c4ba2e6afecc34e7fd | Fuerfenf/Basic_things_of_the_SQL | /DB_SQLite/Python_moduls/sqlite3/sqlite_insert_table_db.py | 834 | 3.515625 | 4 | import sqlite3
try:
db_connect = sqlite3.connect('C:\sqlite\database\Egor_test.db')
sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email text NOT NULL UNIQUE,
joining_date datetime,
salary REAL NOT NULL);'''
cursor = db_connect.cursor()
print("Successfully Connected to SQLite")
cursor.execute(sqlite_create_table_query)
db_connect.commit()
print("SQLite table created")
cursor.close()
except sqlite3.Error as error:
print("Error while creating a sqlite table", error)
finally:
if (db_connect):
db_connect.close()
print("sqlite connection is closed")
|
f1b55b29f5091414848893f10f636c509ce57ce7 | WU731642061/LeetCode-Exercise | /python/code_189.py | 1,986 | 4.375 | 4 | #!/usr/bin/env python3
"""
link: https://leetcode-cn.com/problems/rotate-array/
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
"""
def rotate1(nums, k):
"""
第一种思路是利用数组拼接,向右移动N位其实就是将[-n:]位数组拼接到[:-n]数组的前面
需要注意的是k可能会大于数组本身的长度,那么每移动len(nums)位,数组与原数组重合,
所以只需要计算 k % len(nums)后需要移动的结果
"""
length = len(nums)
n = k % length
if n == 0:
return
nums[:] = nums[-n:] + nums[:-n]
def rotate2(nums, k):
"""
第二种思路是通过头部插入的方式,实现向右平移的效果
即向右平移一位就是将数组尾部的数据插入到头部中去
这里有两种实现思路,一种是使用list.insert(index, obj)方法插入头部
另一种是将数组翻转,然后通过list.pop(0)和append()的效果实现平移,最后将数组再次reserve()
关于python中数组方法的时间复杂度,可以参考一下这篇文章:https://blog.csdn.net/u011318721/article/details/79378280
通过上篇文章可以知道,通过insert方法实现平移的思路的时间复杂度为 n * (n + 1) = O(n^2)
通过翻转+pop+insert方法实现平移的思路的时间复杂度为 2n + n * (n + 1) = O(n^2)
"""
length = len(nums)
n = k % length
if n == 0:
return
for i in range(n):
nums.insert(0, nums.pop())
# 因为这两种做法思路相近,只是调用的方法不同,所以写在一个方法中
# length = len(nums)
# n = k % length
# if n == 0:
# return
# # 2n指的是数组需要翻转两次
# nums.reverse()
# for i in range(n):
# nums.append(nums.pop(0))
# nums.reverse()
"""
TODO: 暂时就想到这两种方法,题目说可以有3种以上的解,以后若是有想到,继续补充
"""
|
56b78459da8cd4ca3b2bc16de38822105f02c82c | WU731642061/LeetCode-Exercise | /python/code_234.py | 2,578 | 4.15625 | 4 | #!/usr/bin/env python3
"""
link: https://leetcode-cn.com/problems/palindrome-linked-list/
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
def isPalindrome(head: ListNode) -> bool:
"""
还是先最简单的思路吧,通过list来处理,取出所有的value,然后翻转,就可以检查是否是回文了
但是这里不满足O(1)的空间复杂度
"""
value = []
while head:
value.append(head.val)
head = head.next
return value == value[::-1]
def isPalindrome2(head: ListNode) -> bool:
"""
还是那句话,这样就失去了链表题目考察我们本身的意义了,要用链表打败链表
我们先不考虑进阶的要求,每种思路都去尝试一下,只有在不断优化的过程中,才能体会到算法的美妙
思路:加入我们不考虑时间复杂度,我们该怎么做
1. 拿到链表的长度
2. 从head开始依次比较
3. 每一项比较,我们就去遍历一次链表,0对应len-1,1对应len-2....
4. 返回结果
"""
def getNode(head, n):
node = head
for i in range(n-1):
node = node.next
return node
length = 0
cur = head
while cur:
length += 1
cur = cur.next
cur = head
for i in range(length//2):
# 1,2,3,4,5,4,3,2,1
r = getNode(head, length-i)
if cur.val != r.val:
return False
cur = cur.next
return True
# 结果就是妥妥的超时了,但是不考虑时间情况下的话,这种方法应该是可行的
def isPalindrome3(head: ListNode) -> bool:
"""
这种思路是把链表变成双向链表
先遍历一遍,创建pre属性
然后拿head和last进行一一比较
"""
pre = None
cur = head
last = None
while cur:
cur.pre = pre
pre = cur
cur = cur.next
if cur == None:
last = pre
while True:
if head == last:
break
if head.val != last.val:
return False
else:
head = head.next
last = last.pre
return True
# 我在答案里看到还有一种思路也很有趣,先遍历一遍,获得整个链表的长度,然后翻转其中的一半(length//2),同时取到一半时(length//2+1)的链表节点,同时开始遍历
# 这里我就不写出解法了,如果有缘人看到这,可是尝试着自己写一下
|
bbf989f691633baf5f10f5541798b6bf11deeb87 | WU731642061/LeetCode-Exercise | /python/code_104.py | 1,778 | 4.09375 | 4 | #!/usr/bin/env python3
"""
link: https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回它的最大深度3
思考:
一开始做树的算法题总是蒙蔽的,因为要摆脱常规的逻辑思维,也有一部分原因是,平时很少去用到深度优先、广度优先的算法思想。
这道题的解法有点类似于快排,不过我一开始还是没有想到解法,看来还是不够融会贯通啊,23333
"""
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def maxDepth(root: TreeNode) -> int:
"""
第一种思路就是递归,通过比较左子树和右子树的最大值,来找到二叉树中最长的那条链
唯一的缺陷是,python的默认配置下,最大递归层数是1000,这个会在下一种思路下改进
"""
if not root:
return 0
else:
left = maxDepth(root.left)
right = maxDepth(root.right)
# 加1是因为当前节点确认存在
return max(left, right) + 1
def maxDepth2(root: TreeNode) -> int:
"""
第二种思想思迭代,本质上的思想是和递归一致的,但是可以解决栈溢出的问题
"""
stack = []
if root:
stack.append((1, root))
depth = 0
while stack != []:
current_depth, root = stack.pop()
if root is not None:
depth = max(depth, current_depth)
stack.append((current_depth + 1, root.left))
stack.append((current_depth + 1, root.right))
return depth
|
e6d5a9aab18adc542bb443de968fa140a34a3c8d | emrecanstk/python-ornekler | /sifre-olustur.py | 1,624 | 3.78125 | 4 | # emrecanstk/python-ornekler
# Şifre Oluşturan Program
import random,time
print("Şifre Oluşturucu") # programın isminin ekrana bastırılması
# listelerin tanımlanması
liste,sifre = [],[]
b_harfler = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","R","S","T","U","V","Y","Z"]
k_harfler = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","r","s","t","u","v","y","z"]
rakamlar = [0,1,2,3,4,5,6,7,8,9]
noktalama = [".",",","@","%","&","/","!","?","=","+","-","*"]
sayi = int(input("kaç karakterli: ")) # şifremizin kaç karakterli olacağının alınması
soru = input("\nBüyük harfler olsun mu? (e/h): ")
if soru == "e": liste += b_harfler # evetse listeye eklenilmesi
soru = input("Küçük harfler olsun mu? (e/h): ")
if soru == "e": liste += k_harfler # evetse listeye eklenilmesi
soru = input("Rakamlar olsun mu? (e/h): ")
if soru == "e": liste += rakamlar # evetse listeye eklenilmesi
soru = input("Noktalama işaretleri olsun mu? (e/h): ")
if soru == "e": liste += noktalama # evetse listeye eklenilmesi
for i in range(sayi): # hedef karakter sayısına kadar
sifre.append(random.choice(liste)) # listeden rastgele karakter seçilmesi
for i in sifre: # şifremizdeki karakterleri baştan sona
print(i,end="") # alt satıra geçmeden yazdır
|
2b803b5c53b0fc9cc03049f7b8eb61f39d38125d | thSheen/pythonaz | /Basic/Variables.py | 479 | 4.125 | 4 | greeting = "Hello"
Greeting = "World"
_NAME = "Thiago"
Thiago34 = "What"
t123 = "Wonderful"
print(greeting + ' ' + _NAME)
print(Greeting + ' ' + Thiago34 + ' ' + t123)
a = 12
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
# // to whole numbers, it's important use it to prevent future errors
# Example :
for i in range(1, a//b):
print(i)
# It doesn't work if just use one /
# Wrong :
print(a + b / 3 -4 * 12)
# Right :
print((((a + b)/3)-4)*12) |
e833103aba8776889386a62829fd73c852e1edda | thSheen/pythonaz | /Basic/String.py | 489 | 3.953125 | 4 | parrot = "Hello Everybody"
print(parrot)
print(parrot[0])
# The first le
print(parrot[3])
print(parrot[0:2])
print(parrot[:4])
# Without a first number, it will start from the first letter
print(parrot[6:])
# Without a last number, it will end in the last letter
print(parrot[-1])
print(parrot[0:6:3])
number = "9,234,444,244,039,550,900,857"
print(number[1::4])
# :: Can extract particular strings which you wanna work with
numbers = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10"
print(numbers[0::3])
|
e20a50eb4d2e531139de86a6a43017c5fe9d821f | kelvinlim/lnpireceiver | /read_drivingdata.py | 1,597 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Example code to read in the driving_task data from the REST API server
@author: kolim
https://www.nylas.com/blog/use-python-requests-module-rest-apis/
import request
Also has section on authentication using access tokens
Oauth
https://www.dataquest.io/blog/python-api-tutorial/
"""
import requests
import json
import dateutil.parser
import pandas as pd
urlServer = "https://x0-29.psych.umn.edu/dend/posts"
response = requests.get(urlServer)
print(response.headers)
entries = response.json()
print("There are ", len(entries), " entries")
# pull response
entry = int(input('Enter entry number: '))
req = "http://160.94.0.29:5000/posts/18"
req = urlServer + '/' + str(entry)
response = requests.get(req)
print(response.json()['created_on'])
d = response.json()['data']
# load the json in the data field into a python object
dd = json.loads(response.json()['data'])
# convert ISO 8601 datetime to python datetime
dtstart = dateutil.parser.parse(dd['StartTime'])
dtend = dateutil.parser.parse(dd['EndTime'])
# read the data into a pandas dataframe with headers
mdata = dd["Moves"]
print("length of data list: ", len(mdata))
column_names = mdata.pop(0)
df = pd.DataFrame(mdata, columns=column_names)
print(df)
print("SubjectID: ", dd['SubjectID'])
print("StartTime: ", dtstart)
print("EndTime: ", dtend)
print("Sensitivity: ", dd['Sensitivity'])
print("Number of moves ", len(mdata))
print("Sensitivity: ", dd['Sensitivity'])
print("TaskVersion: ", dd['TaskVersion'])
print("Platform: ", dd['Platform'])
print("Web: ", dd['Web'])
|
a15efdc2554db34cdce12ad5364ab2b55a26d2f3 | Caotick/ADA-ML | /labs-ML/ex04/template/split_data.py | 662 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""Exercise 3.
Split the dataset based on the given ratio.
"""
import numpy as np
def split_data(x, y, ratio, seed=1):
"""
split the dataset based on the split ratio. If ratio is 0.8
you will have 80% of your data set dedicated to training
and the rest dedicated to testing
"""
# set seed
np.random.seed(seed)
random_pick = np.random.default_rng().choice(x.shape[0], int(x.shape[0]*ratio), replace=False)
x_train = x[random_pick]
y_train = y[random_pick]
x_test = np.delete(x, random_pick)
y_test = np.delete(y, random_pick)
return x_train, y_train, x_test, y_test
|
7d947aad5ede437823a02baeedee6c31209c6acc | Benican/fogstream_courses | /Temp/задача1.py | 571 | 3.96875 | 4 | speed = int(input('Введите скорость движения, км/ч. '))
time = int(input('Введите время движения, ч. '))
circle_length = 109
if speed > 0:
number_of_circle = (speed*time)/circle_length
stop_point = round(circle_length * (number_of_circle - int(number_of_circle)))
else:
number_of_circle = (speed*time)/circle_length
stop_point = circle_length - abs(round(circle_length * (number_of_circle - int(number_of_circle))))
print("Вы остановились на" + " " + str(stop_point) + " " + "км.")
|
00780f56a0ce3179679bb1e3950b5bb4ea501469 | sreedhar17/Python_Challenges | /src/main/python/cadbury.py | 645 | 3.609375 | 4 |
def TotalCount(M, N, P, Q):
count=0
for l in range(M, N + 1):
for b in range(P, Q + 1):
count+=CountPerChocolateBar(l, b)
return count
def CountPerChocolateBar(l, b):
count=0
while True:
longer=max(l, b)
shorter=min(l, b)
count+=1
diff=longer - shorter
if diff == 0:
return count
else:
l=min(l, b)
b=diff
if __name__ == "__main__":
numbers=input("Number: ")
M,N,P,Q = int(numbers.split()[0]),int(numbers.split()[1]),int(numbers.split()[2]),int(numbers.split()[3])
tc=TotalCount(M, N, P, Q)
print(tc)
|
073670125f405c6bab1408f80ca0ec785f43be24 | sreedhar17/Python_Challenges | /src/main/python/plusMinusRatio.py | 315 | 3.703125 | 4 |
def plusMinus(arr):
print(arr)
len_arr=len(arr)
print("length::",len_arr)
tot_pos=0
tot_neg=0
tot_zeros=0
print(sum((tot_pos+1,tot_neg+1) for i in range(len(arr)) if arr[i]>0 for j in range(len(arr)) if arr[j]<0 ))
if __name__=="__main__":
arr=[-4,3,-9,0,4,1]
plusMinus(arr) |
1f2896854030a6921beb38d932dac7c0fff4f2b7 | FinleyLi/109-TSH_Python_3.8.3 | /20201103-13(review).py | 4,155 | 3.59375 | 4 | #!/usr/bin/env python
# coding: utf-8
# 日期: 2020. 11. 03
# 課程: 程式語言與設計
# """
# 09/11
# """
# In[2]:
# 四則運算
pv = 10000*(1+0.03)
print(pv/0.03)
# In[4]:
# 記憶體位置
id(pv)
# In[5]:
# 字串相加
str1 = 'Just'
str2 = 'in'
str3 = str1 + str2
print(str3)
# """
# 09/15
# """
# In[7]:
# BMI身體質量指數
# 體重
Wight = 72
# 身高
#Hight = 174.5
print('請輸入身高')
Hight = int(input())
# 計算BMI
x = Hight/100
BMI = Wight/(x*x)
#print(BMI)
type(BMI)
# In[8]:
# 排序
a = [50, 20, 60, 40, 30]
print('a: ', a)
a.sort()
print('排序後的結果 a: ', a)
# """
# 09/26
# 10/09
# """
# In[11]:
# 作業一.1 判斷 3和5的倍數
Num = int(input())# 3, 5最小公倍數
if (Num%15 == 0 ):
print('Num同時為3和5的倍數')
else :
print('Num不是我們要找的數')
# In[13]:
# 作業一.2 輸入兩數,輸出兩數的乘積
Num121 = int(input('輸入數字(1): '))
Num122 = int(input('輸入數字(2): '))
#計算乘積並輸出
Ans12 = Num121*Num122
print('兩數乘積: ', Ans12)
# """
# 10/14
# 10/16
# 不同進位間的轉換
# 迴圈介紹
# """
# """
# 10/23
# """
# In[14]:
# 作業二.1 P.91計算匯率
# 輸入舊匯率
Old_Rate = int(input("請輸入舊匯率 = "))
#Old_Rate = 31.4
# 輸入新匯率
New_Rate = int(input("請輸入新匯率 = "))
# 計算匯率變動幅度並列印
Change = ( (Old_Rate - New_Rate) / New_Rate) * 100
print(Change)
# 判斷匯率變動為升值或貶值
if Change > 0 :
Result = "升值"
else :
Result = "貶值"
print("貨幣升貶值幅度 = % 4.2f%s 表示 %s" % (Change, "%", Result))
# In[16]:
# ver. 10/30
# 視窗輸入數值資料
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 23 09:02:01 2020
@author: user
"""
get_ipython().system('pip install PySimpleGUI')
import PySimpleGUI as sg # Part 1 - The import
# Define the window's contents
layout = [ [sg.Text("What's your name?")], # Part 2 - The Layout
[sg.Input()],
[sg.Button('Ok')] ]
# Create the window
window = sg.Window('Window Title', layout) # Part 3 - Window Defintion
# Display and interact with the Window
event, values = window.read() # Part 4 - Event loop or Window.read call
# Do something with the information gathered
print('Hello', values[0], "! Thanks for trying PySimpleGUI")
# Finish up by removing from the screen
window.close() # Part 5 - Close the Window
# In[17]:
# 作業二.2 網路爬蟲
# 1.全球即時匯率API
"""import requests
import pandas as pd
r=requests.get('https://tw.rter.info/capi.php')"""
# 全球即時匯率API
import requests
import pandas as pd
r=requests.get('https://tw.rter.info/capi.php')
#r
currency=r.json()
#currency
pd = pd.DataFrame(currency)
pd
# In[19]:
# 篩選美金對台幣匯率
pd['USDTWD']
# In[23]:
#抓取台灣銀行牌告匯率
"""import pandas as pd
from datetime import datetime
#source
url="http://rate.bot.com.tw/xrt?Lang=zh-TW"
#讀取網頁
dfs=pd.read_html(url)"""
import pandas as pd
from datetime import datetime
#source
url="http://rate.bot.com.tw/xrt?Lang=zh-TW"
#讀取網頁
dfs = pd.read_html(url)
dfs
# In[25]:
currency = dfs[0]
currency.iloc[:,0:5]
# """
# 追加request商家評論爬蟲
# """
# In[1]:
"""
Python 爬取Google map最新商家資訊評論!- 實作"動態網頁"爬蟲
"""
#引入函式庫
import requests
import json
# 超連結
url = 'https://www.google.com.tw/maps/preview/review/listentitiesreviews?authuser=0&hl=zh-TW&gl=tw&authuser=0&pb=!1m2!1y3765758354820525099!2y10702812502251526020!2m2!1i8!2i10!3e1!4m5!3b1!4b1!5b1!6b1!7b1!5m2!1sZ8efX5C2J4z_0gTnxJOICQ!7e81'
# 發送get請求
text = requests.get(url).text
# 取代掉特殊字元,這個字元是為了資訊安全而設定的喔。
pretext = ')]}\''
text = text.replace(pretext,'')
# 把字串讀取成json
soup = json.loads(text)
# 取出包含留言的List 。
conlist = soup[2]
# 逐筆抓出
for i in conlist:
print("username:"+str(i[0][1]))
print("time:"+str(i[1]))
print("comment:"+str(i[3]))
# In[ ]:
|
77555730fb4447f6f6b5e38b317236727fda094c | dvlupr/Fall2018-PY210A | /students/KyleBarry/session03/mailroom.py | 2,227 | 3.796875 | 4 | #Establish some data to work with in a dictionary
donors = {"Timothy Tander": [100, 200, 300],
"Tara Towers": [200, 400, 600],
"Charlie Day": [700, 100, 2000],
"Sandra Connors": [1800, 2300, 7000],
"Betsy Hammond": [500, 190, 212, 55]}
donors["Timothy Tander"].append(800)
def thank_you(full_name, donation):
print("\n Dear {}, thank you so much for your generous donation of ${}!\n".format(full_name, donation))
def make_report():
total = [round(sum(i)) for i in donors.values()]
num_donations = [len(i) for i in donors.values()]
avg_donations = [round(sum(i)/len(i),2) for i in donors.values()]
zipped = list(zip(list(donors.keys()), total, num_donations, avg_donations))
print("Donor Name | Total Given | Num Donations | Average Donation")
zipped = [list(i) for i in zipped]
for i in zipped:
print(i)
# TypeError: unsupported format string passed to list.__format__]
# I can't seem to figure out why I'm getting this error when the below is
# uncommented
# for i in range(len(zipped)):
# print('{:>20s}{:<12d}{:<10f}{:>12f}'.format(zipped[i][0],zipped[i][1], zipped[i],[2], zipped[i][3]))
def main():
print('Welcome to the mailroom')
answer = ' '
while answer[0].lower() != 'q':
print("Please select one of the following options:")
print("Quit: 'q' \n"
"Thank you: 't' \n"
"Report: 'r' \n")
answer = input(' ')
answer = answer[:1].lower().strip()
if answer == 't':
full_name = input('Please enter a full name (list for donors) ')
if full_name == 'list':
for i in donors.keys():
print(i)
elif full_name in donors.keys():
donation = float(input('How much would you like to donate? '))
donors[full_name].append(donation)
thank_you(full_name, donation)
elif full_name not in donors.keys():
donation = float(input('How much would you like to donate? '))
donors[full_name] = [donation]
thank_you(full_name, donation)
elif answer == 'r':
make_report()
if __name__ == '__main__':
main()
|
a445f67e1b70aaa5538b3e007d26911b3f50da41 | Bertil1/PPVolumeCalculator | /main.py | 315 | 3.828125 | 4 | print('Enter PP length in cm:')
pplength = float(input())
print('Enter PP thickness:')
ppthickness = float(input())
ppvolume = ppthickness/2**2*3.14*pplength
print('your pp is %s cm3'%ppvolume)
if ppvolume > 23:
print('U Hav Beeg PP')
elif ppvolume < 19:
print('U Hav Smol PP')
else:
print('U Hav Normie PP')
|
b777cc4d1682a6a3c1e5a450c282062c4a0514da | jrobind/python-playground | /games/guessing_game.py | 755 | 4.21875 | 4 | # Random number CLI game - to run, input a number to CLI, and a random number between
# zero and the one provided will be generated. The user must guess the correct number.
import random
base_num = raw_input('Please input a number: ')
def get_guess(base_num, repeat):
if (repeat == True):
return raw_input('Wrong! Guess again: ')
else:
return raw_input('Please guess a number between 0 and ' + base_num + '. ')
if (base_num == ''):
print('Please provide a number: ')
else:
random_num = random.randint(0, int(base_num))
guess = int(get_guess(base_num, False))
# use a while loop
while (random_num != guess):
guess = int(get_guess(base_num, True))
print('Well done! You guessed correct.')
|
e88333ce7bd95d7fb73a07247079ae4f5cb12d11 | graciofilipe/differential_equations | /udacity_cs222/final_problems/geo_stat_orb.py | 2,907 | 4.375 | 4 | # PROBLEM 3
#
# A rocket orbits the earth at an altitude of 200 km, not firing its engine. When
# it crosses the negative part of the x-axis for the first time, it turns on its
# engine to increase its speed by the amount given in the variable called boost and
# then releases a satellite. This satellite will ascend to the radius of
# geostationary orbit. Once that altitude is reached, the satellite briefly fires
# its own engine to to enter geostationary orbit. First, find the radius and speed
# of the initial circular orbit. Then make the the rocket fire its engine at the
# proper time. Lastly, enter the value of boost that will send the satellite
# into geostationary orbit.
#
import math
import numpy as np
from scipy.integrate import solve_ivp
# These are used to keep track of the data we want to plot
h_array = []
error_array = []
period = 24. * 3600. # s
earth_mass = 5.97e24 # kg
earth_radius = 6.378e6 # m (at equator)
gravitational_constant = 6.67e-11 # m3 / kg s2
total_time = 9. * 3600. # s
marker_time = 0.25 * 3600. # s
# Task 1: Use Section 2.2 and 2.3 to determine the speed of the inital circular orbit.
initial_radius = earth_radius + 200*1000
initial_speed = np.sqrt(earth_mass*gravitational_constant/initial_radius)
final_radius = 42164e3
boost_time = initial_radius*math.pi/initial_speed
# Task 3: Which is the appropriate value for the boost in velocity? 2.453, 24.53, 245.3 or 2453. m/s?
# Change boost to the correct value.
boost = 245.3 # m / s
ic = [initial_radius, 0, 0, initial_speed]
def x_prime(t, x):
vector_to_earth = -np.array([x[0], x[1]]) # earth located at origin
a = gravitational_constant * earth_mass / np.linalg.norm(vector_to_earth) ** 3 * vector_to_earth
speed_x, speed_y = x[2], x[3]
vec = [speed_x, speed_y, a[0], a[1]]
return vec
def integrate_until(ti, tf, ic, x_prime_fun):
tval = np.linspace(ti, tf, 111)
sol = solve_ivp(x_prime_fun,
t_span=(ti, tf),
t_eval=tval,
y0=ic,
vectorized=False,
rtol=1e-6,
atol=1e-6)
return sol
ic1 = [initial_radius, 0, 0, initial_speed]
sol1 = integrate_until(ti=0, tf=boost_time , ic=ic1, x_prime_fun=x_prime)
ic2 = sol1.y[:, 110]
v = ic2[2], ic2[3]
new_v = v + boost * np.array(v/np.linalg.norm(v))
ic2[2], ic2[3] = new_v[0], new_v[1]
sol2 = integrate_until(ti=boost_time , tf=total_time, ic=ic2, x_prime_fun=x_prime)
import plotly.graph_objs as go
from plotly.offline import plot
data = [go.Scatter(x=[earth_radius*math.cos(i) for i in np.linspace(0, 2*math.pi, 10000)],
y=[earth_radius*math.sin(i) for i in np.linspace(0, 2*math.pi, 10000)],
name='earth'),
go.Scatter(x=sol1.y[0], y=sol1.y[1], name='pre boost'),
go.Scatter(x=sol2.y[0], y=sol2.y[1], name='post boost')]
plot(data)
|
f337411ac670c33d0cc7fc1243cbe62247ae0bd9 | shinta834/purwadhika1 | /jawaban1.py | 321 | 3.765625 | 4 | def kalimat(x):
if len(x)>200:
print('Batas Karakter Maksimal Hanya 200')
elif len(x)==0:
print('Masukkan Sebuah Inputan')
else:
text = '*{}*'
print(text.format(x.upper().replace(' ','')))
x= input('Masukkan Sebuah Kalimat : ')
kalimat(x)
# ini adalah sebuah CONTOH |
deecbd966d71fcdeba94c765506d6ce009741cab | DamianKa/money_for_retirement | /money_for_retirement.py | 505 | 3.953125 | 4 | #how much you need to retire
print ("The How Much You Need to Retire Calculator")
monthly_spend = int(input("How much money in terms of today's money will you need on retirement (per month)? £"))
ir = int(input("What return from investments you can achieve in the long term? %"))
inflation = int(input("What average real inflation should I include in the calculation? %"))
real_ir = ir - inflation
that_much = monthly_spend / (real_ir / (100 * 12))
print ("You need ", that_much, " £ to retire")
|
9b773f07693eab8e686808d640d95e890c12af00 | pradeepkumar1234/pyt1 | /voworcon.py | 223 | 4.0625 | 4 | ch=input("")
if((ch>='a' and ch<='z') or (ch>='A' and ch<='Z')):
if(ch=='a',ch=='e',ch=='i',ch=='o',ch=='u',ch=='A',ch=='E',ch=='I',ch=='O',ch=='U'):
print("Vowel")
else:
print("Constant")
else:
print("invalid")
|
ddc0bf0fdf77f46bf646a5ee2654d391e031647d | rojiani/algorithms-in-python | /dynamic-programming/fibonacci/fib_top_down_c.py | 978 | 4.21875 | 4 | """
Fibonacci dynamic programming - top-down (memoization) approach
Using Python's 'memo' decorator
Other ways to implement memoization in Python: see Mastering Object-Oriented
Python, p. 150 (lru_cache)
"""
def fibonacci(n): # driver
return fib(n, {})
def fib(n, memo= {}):
if n == 0 or n == 1:
return n
try:
return memo[n]
except KeyError:
memo[n] = fib(n-1, memo) + fib(n-2, memo)
return memo[n]
print("Testing")
tests = [(0, 0), (1, 1), (2, 1), (3, 2), (4, 3), (5, 5), (6, 8), (7, 13), \
(8, 21), (9, 34), (10, 55), (25, 75025), (50, 12586269025), \
(100, 354224848179261915075)]
for test in tests:
result = fibonacci(test[0])
if result == test[1]:
print("PASS: %d" % result)
else:
print("FAIL: %d" % result)
import timeit
p=300
print("fibonacci (bottom-up)")
print("%.8f" % (timeit.timeit("fibonacci(p)", setup = "from __main__ import fibonacci, p", number=1)))
|
55b2a9b005f15e7d65f87a5d76667f1a25b2ba60 | rojiani/algorithms-in-python | /dynamic-programming/0_1_knapsack/0_1_knapsack.py | 3,762 | 3.71875 | 4 |
class Item(object):
def __init__(self, name, value, weight):
self.name = name
self.value = value
self.weight = weight
def get_name(self): return self.name
def get_value(self): return self.value
def get_weight(self): return self.weight
def __str__(self):
return '[Item %s: value = %.2f, weight = %.2f]' \
% (self.name, self.value, self.weight)
class KSDecision(object):
def __init__(self, taken, undecided, total_value, rem_capac):
self.taken = taken
self.undecided = undecided
self.total_value = total_value
self.capacity = rem_capac
def get_taken_items(self):
return list(self.taken)
def get_undecided_items(self):
return list(self.undecided)
def get_total_value(self):
return self.total_value
def get_capacity(self):
return self.capacity
def take_item(self):
item = self.undecided[0]
self.taken.append(item)
self.undecided = self.undecided[1:]
self.total_value += item.get_value()
self.capacity -= item.get_weight()
def deciding_completed(self):
return len(self.undecided) == 0
def overloaded(self):
return self.capacity < 0
def filled(self):
return self.capacity == 0
def recursive_01_knapsack(items, max_weight):
ksd = KSDecision(list([]), items, 0, max_weight)
result = decide(ksd)
ks = result.get_taken_items()
# print(ks)
print("Items in knapsack:")
for item in ks:
print(item)
print("Total Value: %.2f" % result.get_total_value())
print("Total Weight: %.2f" % (max_weight - result.get_capacity()))
def decide(ksd):
taken = ksd.get_taken_items()
undecided = ksd.get_undecided_items()
total_value = ksd.get_total_value()
rem_capac = ksd.get_capacity()
if ksd.overloaded() or ksd.filled() or ksd.deciding_completed():
return ksd
else:
skip_ksd = KSDecision(taken, undecided[1:], total_value, rem_capac)
skip = decide(skip_ksd)
take_ksd = ksd
take_ksd.take_item()
take = decide(take_ksd)
if take.overloaded() and skip.overloaded():
return take
elif take.overloaded() and not skip.overloaded():
return skip
elif not take.overloaded() and skip.overloaded():
return take
else:
if take.get_total_value() >= skip.get_total_value():
return take
else:
return skip
def demo_01_knapsack():
items = [Item('a', 6, 3), \
Item('b', 7, 3), \
Item('c', 8, 2), \
Item('d', 9, 5)]
recursive_01_knapsack(items, 5)
# Correct output
items2 = [Item("map", 9, 150), \
Item("compass", 13, 35), \
Item("water", 153, 200), \
Item("sandwich", 50, 160), \
Item("glucose", 15, 60), \
Item("tin", 68, 45), \
Item("banana", 27, 60), \
Item("apple", 39, 40), \
Item("cheese", 23, 30), \
Item("beer", 52, 10), \
Item("suntan cream", 11, 70), \
Item("camera", 32, 30), \
Item("t-shirt", 24, 15), \
Item("trousers", 48, 10),
Item("umbrella", 73, 40), \
Item("waterproof trousers", 42, 70), \
Item("waterproof overclothes", 43, 75), \
Item("note-case", 22, 80), \
Item("sunglasses", 7, 20), \
Item("towel", 18, 12), \
Item("socks", 4, 50), \
Item("book", 30, 10)]
recursive_01_knapsack(items2, 400)
# Incorrect output
demo_01_knapsack() |
cc504fd886f0062c2a11435754683f4ba5e71d21 | gaoalexander/fundamental-data-structures-and-algorithms | /algorithms/merge-sort.py | 1,986 | 3.984375 | 4 | import math
#------------------------------------------------------------
# MERGE SORT (NOT IN PLACE!)
# def merge(lhs, rhs):
# len_lhs = len(lhs)
# len_rhs = len(rhs)
# len_sum = len_lhs + len_rhs
# lhs_new = list(lhs)
# rhs_new = list(rhs)
# lhs_new.append(math.inf)
# rhs_new.append(math.inf)
# merged = [None] * len_sum
# cursor_lhs = 0
# cursor_rhs = 0
# for i in range(len_sum):
# if lhs_new[cursor_lhs] <= rhs_new[cursor_rhs]:
# merged[i] = lhs_new[cursor_lhs]
# cursor_lhs += 1
# elif rhs_new[cursor_rhs] <= lhs_new[cursor_lhs]:
# merged[i] = rhs_new[cursor_rhs]
# cursor_rhs += 1
# # print("len merged:",len(merged))
# return merged
# def mergesort(list):
# if len(list) == 1:
# return list
# if len(list) == 2:
# if list[0] < list[1]:
# return list
# else:
# temp = list[1]
# list[1] = list[0]
# list[0] = temp
# return list
# q = math.floor(len(list)/2)
# lhs = mergesort(list[:q])
# rhs = mergesort(list[q:])
# merge1 = merge(lhs, rhs)
# return merge1
#------------------------------------------------------------
# MERGE SORT (MOSTLY IN PLACE!)
def merge(list1, p, q, r):
len_lhs = q - p + 1
len_rhs = r - q
len_sum = len_lhs + len_rhs
lhs_new = list(list1[p : q+1])
rhs_new = list(list1[q+1:r+1])
lhs_new.append(math.inf)
rhs_new.append(math.inf)
cursor_lhs = 0
cursor_rhs = 0
for i in range(p, r+1):
if lhs_new[cursor_lhs] <= rhs_new[cursor_rhs]:
list1[i] = lhs_new[cursor_lhs]
cursor_lhs += 1
elif rhs_new[cursor_rhs] <= lhs_new[cursor_lhs]:
list1[i] = rhs_new[cursor_rhs]
cursor_rhs += 1
# print("len merged:",len(merged))
def mergesort(list1, p, r):
if p < r:
q = math.floor((p+r)/2)
print(p,q,r)
mergesort(list1, p, q)
mergesort(list1, q+1, r)
merge(list1, p, q, r)
def main():
a = [3,6,5,1,8,6,4,8,7,6,0,3,5,77,53,3,22,4,77,9,-6,8,567,43,2,55,-48,6,7]
mergesort(a, 0, len(a)-1)
print(a)
main()
# a = [1,3,7,8]
# b = [5,7,9,10]
# print(merge(a,b)) |
29fcf40ceb7369d30377d7e67dfaabd121977717 | sent1nu11/mail-merge | /main.py | 584 | 3.59375 | 4 | #TODO: Create a letter using starting_letter.docx
#for each name in invited_names.txt
#Replace the [name] placeholder with the actual name.
#Save the letters in the folder "ReadyToSend".
#Hint1: This method will help you: https://www.w3schools.com/python/ref_file_readlines.asp
#Hint2: This method will also help you: https://www.w3schools.com/python/ref_string_replace.asp
#Hint3: THis method will help you: https://www.w3schools.com/python/ref_string_strip.asp
with open("Input/Names/invited_names.txt") as file:
name_list = []
names = file.readlines()
|
d3e8817579165225de18abb7e43ed4c2a8a33273 | patchiu/math-programmmmm | /D_IN/Simpson's Rule.py | 959 | 4 | 4 | ##Simpson's Rule
def simps(f,a,b,N=50):
'''Approximate the integral of f(x) from a to b by Simpson's rule.
Simpson's rule approximates the integral int_a^b f(x) dx by the sum:
(dx/3) um_{k=1}^{N/2} (f(x_{2i-2} + 4f(x_{2i-1}) + f(x_{2i}))
where x_i = a + i*dx and dx = (b - a)/N.
Parameters
----------
f : function
Vectorized function of a single variable
a , b : numbers
Interval of integration [a,b]
N : (even) integer
Number of subintervals of [a,b]
Returns
-------
float
Approximation of the integral of f(x) from a to b using
Simpson's rule with N subintervals of equal length.
'''
if N % 2 == 1:
raise ValueError("N must be an even integer.")
dx = (b-a)/N
x = np.linspace(a,b,N+1)
y = f(x)
S = dx/3 * np.sum(y[0:-1:2] + 4*y[1::2] + y[2::2])
return S
f=lambda x : 3*x**2
simps(f,0,1,100)
|
0d24f2150c3cd07c0d69a8353f3d01e681c3f1cc | ppdraga/Python.ClientServerApps | /lesson-2/task-5.py | 445 | 3.578125 | 4 | # Реализовать скрипт для преобразования данных в формате csv в формат yaml
import csv
import yaml
from pprint import pprint
with open("lesson-2/data-read.csv", "r") as file:
reader = csv.reader(file)
headers = next(reader)
data = dict(zip(headers, reader))
# print(headers)
pprint(data)
with open("lesson-2/data-from-csv.yaml", "w") as file:
yaml.dump(data, file) |
c0ef9cd59e3fe5840bf90305b6fbcdb35776baca | wudiee/Algorithms | /linked_list.py | 860 | 3.953125 | 4 | class Node:
def __init__(self,data,loc,next = None):
self.data = data
self.loc = loc
self.next = next
def init_list():
global node1
node1 = Node(5,0)
node2 = Node(10,1)
node3 = Node(17,2)
node4 = Node(9,3)
node5 = Node(13,4)
node6 = Node(7,5)
node7 = Node(19,6)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
node5.next = node6
node6.next = node7
def print_list():
global node1
node = node1
while node:
print(node.data,end=" ")
node = node.next
def insert_node(data,loc):
global node1
new_node = Node(data,loc)
node_p = node1
node_t = node1
while node_t.loc != new_node.loc:
node_p = node_t
node_t = node_t.next
new_node.next = node_t
node_p.next = new_node
if __name__ == "__main__":
init_list()
insert_node(33,4)
print_list()
|
28c8eb708788676cdfe917b75ae064399fb65bd0 | uffehellum/dailypy | /daily700/daily740/daily744.py | 6,562 | 3.640625 | 4 | import unittest
# Implement an LFU (Least Frequently Used) cache.
# It should be able to be initialized with a cache size n, and contain the following methods:
#
# set(key, value): sets key to value.
# If there are already n items in the cache and we are adding a new item,
# then it should also remove the least frequently used item.
# If there is a tie, then the least recently used key should be removed.
#
# get(key): gets the value at key.
# If no such key exists, return null.
#
# Each operation should run in O(1) time.
class TestDaily744(unittest.TestCase):
def test_base(self):
c = LeastFrequentlyUsedCache(2)
c.set("a", 1)
c.set("b", 2)
print(c.queue)
self.assertEqual(1, c.get("a"))
print(c.queue)
self.assertEqual(2, c.get("b"))
self.assertIsNone(c.get("c"))
print(c.queue)
c.set("c", 3)
self.assertIsNone(c.get("a"))
self.assertEqual(2, c.get("b"))
self.assertEqual(3, c.get("c"))
print(c.queue)
c.set('d', 4)
self.assertIsNone(c.get("a"))
self.assertEqual(2, c.get("b"))
self.assertIsNone(c.get("c"))
self.assertEqual(4, c.get("d"))
print(c.queue)
class LeastFrequentlyUsedCache:
def __init__(self, maxCount):
self.max_count = maxCount
self.cache = dict()
self.queue = LeastFrequentUseQueue()
def __str__(self):
return 'LFRUC(%s)' % ', '.join((('%s: %s' % (str(k), str(v))) for k, v in self.cache.items()))
def set(self, key, value):
if key in self.cache:
old = self.cache[key]
self.queue.remove(old)
else:
if len(self.cache) == self.max_count:
old = self.queue.remove_first()
del(self.cache[old.key])
new = CacheEntry(key, value)
self.cache[key] = new
self.queue.add(new)
def get(self, key):
if not key in self.cache:
return None
entry = self.cache[key]
self.queue.access(entry)
return entry.value
class CacheEntry:
def __init__(self, key, value):
self.next = None
self.prev = None
self.usagecount = 0
self.key = key
self.value = value
def __str__(self):
return "CacheEntry(%s, %s, usage=%d)" % (self.key, self.value, self.usagecount)
class UsageQueue:
"""double linked list of entries with same usage count, oldest first"""
def __init__(self, usagecount: int):
self.usagecount = usagecount
self.firstentry = None
self.lastentry = None
self.nextqueue = None
self.prevqueue = None
def __str__(self):
s = 'UsageQueue[usagecount: %d' % self.usagecount
c = self.firstentry
while c:
s += ', ' + str(c)
c = c.next
return s + ']'
def add(self, entry: CacheEntry):
if self.firstentry is None:
self.firstentry = entry
self.lastentry = entry
else:
entry.prev = self.lastentry
self.lastentry.next = entry
self.lastentry = entry
def remove(self, entry: CacheEntry):
if entry.prev is None:
self.firstentry = entry.next
if self.firstentry:
self.firstentry.prev = None
else:
entry.prev.next = entry.next
if entry.next:
entry.next.prev = entry.prev
entry.next = None
entry.prev = None
def remove_first(self):
if self.firstentry is None:
raise Exception('There are no entries with %s usages' % self.usagecount)
r = self.firstentry
self.firstentry = r.next
if self.firstentry:
self.firstentry.prev = None
else:
self.lastentry = None
r.next = None
return r
class LeastFrequentUseQueue:
"""double linked list of queues"""
def __init__(self):
self.firstqueue = None
self.lastqueue = None
self.queues = dict()
def __str__(self):
s = 'LeastFrequentUseQueue['
c = self.firstqueue
while c:
s += '\n\t' + str(c)
c = c.nextqueue
return s + '\n]'
def add(self, entry):
"""create a new value that has been added to the cache"""
if entry.usagecount != 0:
raise Exception("New entry does not have usage count zero as expected", entry)
if entry.usagecount in self.queues:
q = self.queues[entry.usagecount]
q.add(entry)
return
q = UsageQueue(entry.usagecount)
q.add(entry)
self.queues[q.usagecount] = q
if self.firstqueue is None:
self.lastqueue = q
self.firstqueue = q
else:
q.nextqueue = self.firstqueue
self.firstqueue.prevqueue = q
self.firstqueue = q
def remove(self, entry: CacheEntry):
"""remove a value that has been removed from the cache"""
q = self.queues[entry.usagecount]
q.remove(entry)
self._remove_queue_if_empty(q)
def _remove_queue_if_empty(self, q: UsageQueue):
if q.firstentry is None:
del self.queues[q.usagecount]
if q.prevqueue is None:
self.firstqueue = q.nextqueue
if q.nextqueue:
q.nextqueue.prevqueue = None
else:
q.prevqueue.nextqueue = q.nextqueue
if q.nextqueue:
q.nextqueue.prevqueue = q.prevqueue
def access(self, entry: CacheEntry):
"""a value has been read so increase access count"""
q = self.queues[entry.usagecount]
q.remove(entry)
entry.usagecount += 1
if entry.usagecount in self.queues:
qnew = self.queues[entry.usagecount]
else:
qnew = UsageQueue(entry.usagecount)
self.queues[qnew.usagecount] = qnew
qnew.nextqueue = q.nextqueue
q.nextqueue = qnew
qnew.prevqueue = q
if qnew.nextqueue:
qnew.nextqueue.prevqueue = qnew
qnew.add(entry)
self._remove_queue_if_empty(q)
def remove_first(self):
"""cache is full, so remove the least frequently used entry and return it"""
if self.firstqueue is None:
return None
q = self.firstqueue
entry = q.remove_first()
self._remove_queue_if_empty(q)
return entry
|
fb6432dc5ea2b79baa5b37c4eb51d758f4b53efb | uffehellum/dailypy | /daily700/daily700/daily707.py | 725 | 3.53125 | 4 | import unittest
def min_range(listeners, towers):
largest = 0
t1 = towers[0]
i = 0
for listener in listeners:
d1 = abs(listener - t1)
if d1 <= largest:
continue
if i + 1 < len(towers):
t2 = towers[i + 1]
d2 = abs(t2 - listener)
if d2 <= d1:
t1 = t2
d1 = d2
i += 1
if d1 > largest:
largest = d1
return largest
class Daily707(unittest.TestCase):
def test_one(self):
self.assertEqual(min_range([2], [0]), 2)
def test_given(self):
self.assertEqual(min_range([1, 5, 11, 20], [4, 8, 15]), 5)
if __name__ == '__main__':
unittest.main()
|
5a01369663f7250eae51cb0cfb46fa227e864f4c | azarrias/udacity-nd256-problems | /src/stock_prices.py | 3,264 | 4.34375 | 4 | """
Stock Prices
Greedy algorithm
You are given access to yesterday's stock prices for a single stock. The data
is in the form of an array with the stock price in 30 minute intervals from
9:30 a.m EST opening to 4:00 p.m EST closing time. With this data, write a
function that returns the maximum profit obtainable. You will need to buy
before you can sell.
For example, suppose you have the following prices:
prices = [3, 4, 7, 8, 6]
Note: This is a shortened array, just for the sake of example—a full set of
prices for the day would have 13 elements (one price for each 30 minute
interval betwen 9:30 and 4:00).
In order to get the maximum profit in this example, you would want to buy at a
price of 3 and sell at a price of 8 to yield a maximum profit of 5. In other
words, you are looking for the greatest possible difference between two numbers
in the array.
The Idea
The given array has the prices of a single stock at 13 different timestamps.
The idea is to pick two timestamps: "buy_at_min" and "sell_at_max" such that
the buy is made before a sell. We will use two pairs of indices while
traversing the array:
- Pair 1 - This pair keeps track of our maximum profit while iterating over
the list. It is done by storing a pair of indices - min_price_index, and
max_price_index.
- Pair 2 - This pair keeps track of the profit between the lowest price
seen so far and the current price while traversing the array. The lowest
price seen so far is maintained with current_min_price_index.
At each step we will make the greedy choice by choosing prices such that our
profit is maximum. We will store the maximum of either of the two profits
mentioned above.
"""
def max_returns(prices):
"""
Calculate maxiumum possible return in O(n) time complexity
Args:
prices(array): array of prices
Returns:
int: The maximum profit possible
"""
if len(prices) < 2:
return 0
min_price_index = 0
max_price_index = 0
current_min_price_index = 0
for i in range(1, len(prices)):
# current minimum price
if prices[i] < prices[current_min_price_index]:
current_min_price_index = i
# current max profit
if prices[i] - prices[current_min_price_index] > prices[max_price_index] - prices[min_price_index]:
max_price_index = i
min_price_index = current_min_price_index
max_profit = prices[max_price_index] - prices[min_price_index]
return max_profit
# Test Cases
def test_function(test_case):
prices = test_case[0]
solution = test_case[1]
output = max_returns(prices)
if output == solution:
print("Pass")
else:
print("Fail")
if __name__ == '__main__':
# Test case 1
prices = [2, 2, 7, 9, 9, 12, 18, 23, 34, 37, 45, 54, 78]
solution = 76
test_case = [prices, solution]
test_function(test_case)
# Test case 2
prices = [54, 18, 37, 9, 11, 48, 23, 1, 7, 34, 2, 45, 67]
solution = 66
test_case = [prices, solution]
test_function(test_case)
# Test case 3
prices = [78, 54, 45, 37, 34, 23, 18, 12, 9, 9, 7, 2, 2]
solution = 0
test_case = [prices, solution]
test_function(test_case)
|
fc72c287a60083ec4a03c9b476cbe4a55a2d68c5 | azarrias/udacity-nd256-problems | /src/coin_change.py | 3,681 | 4.125 | 4 | """
Coin Change
You are given coins of different denominations and a total amount of money.
Write a function to compute the fewest coins needed to make up that amount.
If that amount of money cannot be made up by any combination of the coins,
return -1.
As an example:
Input: coins = [1, 2, 3], amount = 6
Output: 2
Explanation: The output is 2 because we can use 2 coins with value 3. That
is, 6 = 3 + 3. We could also use 3 coins with value 2 (that is, 6 = 2 + 2 +
2), but this would use more coins—and the problem specifies we should use
the smallest number of coins possible.
"""
# recursive solution
# Let's assume F(Amount) is the minimum number of coins needed to make a change from coins [C0, C1, C2...Cn-1]
# Then, we know that F(Amount) = min(F(Amount-C0), F(Amount-C1), F(Amount-C2)...F(Amount-Cn-1)) + 1
def coin_change(coins, amount):
# Use lookup table, to store the fewest coins for a given amount that have
# been already calculated, to be able to use the result without having to
# calculate it again
lookup = {}
def return_change(remaining):
# Base cases
if remaining < 0:
return float("Inf")
if remaining == 0:
return 0
if remaining not in lookup:
lookup[remaining] = min(return_change(remaining - coin) + 1 for coin in coins)
return lookup[remaining]
result = return_change(amount)
if result == float("Inf"):
return -1
return result
# iterative solution
# We initiate F[Amount] to be float('inf') and F[0] = 0
# Let F[Amount] to be the minimum number of coins needed to get change for the Amount.
# F[Amount + coin] = min(F(Amount + coin), F(Amount) + 1) if F[Amount] is reachable.
# F[Amount + coin] = F(Amount + coin) if F[Amount] is not reachable.
def coin_change_iter(coins, amount):
# initialize list with length amount + 1 and prefill with value 'Infinite'
result = [float('Inf')] * (amount + 1)
# when amount is 0, the result will be 0 coins needed for the change
result[0] = 0
i = 0
while i < amount:
if result[i] != float('Inf'):
for coin in coins:
if i <= amount - coin:
result[i+coin] = min(result[i] + 1, result[i + coin])
i += 1
if result[amount] == float('Inf'):
return -1
return result[amount]
def test_function(test_case, fn):
arr = test_case[0]
amount = test_case[1]
solution = test_case[2]
output = fn(arr, amount)
print(output)
if output == solution:
print("Pass")
else:
print("Fail")
if __name__ == '__main__':
print("- Test recursive solution")
# Test case 1
arr = [1,2,5]
amount = 11
solution = 3
test_case = [arr, amount, solution]
test_function(test_case, coin_change)
# Test case 2
arr = [1,4,5,6]
amount = 23
solution = 4
test_case = [arr, amount, solution]
test_function(test_case, coin_change)
# Test case 3
arr = [5,7,8]
amount = 2
solution = -1
test_case = [arr, amount, solution]
test_function(test_case, coin_change)
print("- Test iterative solution")
# Test case 1
arr = [1,2,5]
amount = 11
solution = 3
test_case = [arr, amount, solution]
test_function(test_case, coin_change_iter)
# Test case 2
arr = [1,4,5,6]
amount = 23
solution = 4
test_case = [arr, amount, solution]
test_function(test_case, coin_change_iter)
# Test case 3
arr = [5,7,8]
amount = 2
solution = -1
test_case = [arr, amount, solution]
test_function(test_case, coin_change_iter)
|
5c77c6cf0be7ab2271674c4d70cffb98c18d94f7 | JasonHinds13/CodeJamSolutions | /IEEEXtreme10/Food-Truck/food-truck.py | 1,939 | 3.765625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import time
from math import radians, cos, sin, asin, sqrt
def conv_time(t):
return int((t.split(" ")[1]).replace(":",""))
def conv_date(d):
date = d.split(" ")[0]
return time.strptime(date, "%m/%d/%Y")
def get_nums(lis):
l = []
for d in lis:
l.append(d["PhoneNumber"])
return l
def getbynum(lis, num):
for x in lis:
if x["PhoneNumber"] == num:
return x
inp = raw_input().split(",")
lat1 = radians(float(inp[0]))
long1 = radians(float(inp[1]))
r = 6378.137
rk = float(raw_input()) #radius she wants to reach
direc = {}
c = 0 #counter
res = [] #will store only number
getall = [] #will store all info relating
header = raw_input().split(",")
while(True):
try:
n = raw_input().split(",")
direc[c] = {header[0]: n[0], header[1]: n[1], header[2]: n[2], header[3]: n[3]}
lat2 = radians(float(direc[c]["Latitude"]))
long2 = radians(float(direc[c]["Longitude"]))
d = 2 * r * asin(sqrt (sin((lat2 - lat1)/2)**2 + cos(lat1) * cos(lat2) * sin((long2 - long1)/2)**2))
if d < rk and direc[c]["PhoneNumber"] not in res:
res.append(direc[c]["PhoneNumber"])
getall.append(direc[c])
elif d >= rk and direc[c]["PhoneNumber"] in get_nums(getall):
x = direc[c]["PhoneNumber"]
y = getbynum(getall, x)
#current one
td = conv_date(direc[c]["Date&Time"])
tc = conv_time(direc[c]["Date&Time"])
#one in list
ld = conv_date(y["Date&Time"])
lc = conv_time(y["Date&Time"])
if (tc > lc and td >= ld) or (td > ld):
res = [m for m in res if m != x]
c+=1
except EOFError:
break
res.sort()
print ",".join(res)
|
cab3c1c48f7f2b8eb988d2cd9901d4d832804e6c | carolyn-davis/numpy-pandas-visualization-exercises | /pandas_series_exercises.py | 15,811 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 16 10:51:27 2021
@author: carolyndavis
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# =============================================================================
# EXERCISES PART 1:
# =============================================================================
fruits = ["kiwi", "mango", "strawberry", "pineapple", "gala apple", "honeycrisp apple", "tomato", "watermelon", "honeydew", "kiwi", "kiwi", "kiwi", "mango", "blueberry", "blackberry", "gooseberry", "papaya"]
fruits_series = pd.Series(fruits)
fruits_series
# =============================================================================
# Determine the number of elements in fruits.
# =============================================================================
print(len(fruits_series))
#fruits.size()
#fruits.shape() #returns column of 17 rows
# =============================================================================
# Output only the index from fruits.
# =============================================================================
print(fruits_series.index)
# =============================================================================
# Output only the values from fruits.
# =============================================================================
print(fruits_series.values)
#fruits_series.index.tolist()
#values.tolist()
# =============================================================================
# Confirm the data type of the values in fruits.
# =============================================================================
type(fruits_series.values)
# =============================================================================
# Output only the first five values from fruits. Output the last three values.
# Output two random values from fruits.
# =============================================================================
fruits_series.head(5) #by default returns 5
fruits_series.tail(3)
fruits_series.sample(2)
# =============================================================================
# Run the .describe() on fruits to see what information it returns when called on a
# Series with string values.
# =============================================================================
#depends onn what kind of datatypes are in series
fruits_series.describe()
type(fruits_series.describe())
# =============================================================================
# Run the code necessary to produce only the unique string values from fruits
# =============================================================================
fruits_series.unique() #returns array of just unique values
#fruit_series.nunique.() returns count of unique values
# =============================================================================
# Determine how many times each unique string value occurs in fruits.
# =============================================================================
fruits_series.value_counts()
#fruits.value_counts().head(1)
#fruits.value_counts().idmax() #returns the first occurance works only if no dupes
#fruits.value_counts.nlargest(n=1, keep='all')
# =============================================================================
# Determine the string value that occurs most frequently in fruits.
# =============================================================================
fruits_series.value_counts().tail(11)
# =============================================================================
# EXERCISES PART 2:
# =============================================================================
# =============================================================================
# # Capitalize all the string values in fruits.
# =============================================================================
fruits_series.str.capitalize()
# =============================================================================
# # 1.) Count the letter "a" in all the string values (use string vectorization).
# =============================================================================
fruits_series.str.count('a')
# =============================================================================
# # 2.) Output the number of vowels in each and every string value.
# =============================================================================
def vowel_counter(value, letter):
x = value.count(letter)
return x
vowels = ['a', 'e', 'i', 'o', 'u']
collector = {}
for row in fruits_series:
collector[row] = {}
for letter in vowels:
collector[row][letter] = vowel_counter(row, letter)
# =============================================================================
# # 3.) Write the code to get the longest string value from fruits.
# =============================================================================
def get_max_str(fruit_series):
return max(fruits_series, key=len)
get_max_str(fruits_series) #honeycrisp apple
# =============================================================================
# # 4.) Write the code to get the string values with 5 or more letters in the name.
# =============================================================================
# for i in fruits_series:
# if len(i) >= 5:
# print(i)
max(fruits,key=len)
# =============================================================================
# # 5.) Use the .apply method with a lambda function to find the fruit(s) containing the letter "o" two or more times.
# =============================================================================
fruits_series.str.apply(lambda n: 'o' > 1)
# =============================================================================
# # 6.) Write the code to get only the string values containing the substring "berry".
# =============================================================================
#fruits_series.str.contains('berry')
fruits_series.str.findall('berry')
#Ans: 4 results for berry at indexes: 2,13,14,15
# =============================================================================
# # 7.) Write the code to get only the string values containing the substring "apple".
# =============================================================================
fruits_series.str.findall('apple')
#Ans: 3 results for apple at indexes: 3,4,5
# =============================================================================
# # 8.) Which string value contains the most vowels?
# =============================================================================
def max_char_count(string):
max_char = ''
max_count = 0
for char in set(string):
count = string.count(char)
if count > max_count:
max_count = count
max_char = char
return max_char
# print(max_char_count('apple'))
fruits_series.apply(max_char_count(fruits_series))
# =============================================================================
# EXERCISES PART 3:
# =============================================================================
def split(letters):
return [char for char in letters]
letters = 'hnvidduckkqxwymbimkccexbkmqygkxoyndmcxnwqarhyffsjpsrabtjzsypmzadfavyrnndndvswreauxovncxtwzpwejilzjrmmbbgbyxvjtewqthafnbkqplarokkyydtubbmnexoypulzwfhqvckdpqtpoppzqrmcvhhpwgjwupgzhiofohawytlsiyecuproguy'
split_list = (split(letters))
print(split_list)
letter_series = pd.Series(split_list)
letter_series
type(letter_series)
# =============================================================================
# Which letter occurs the most frequently in the letters Series?
# =============================================================================
import collections
max_freq = letter_series
count =collections.Counter(letter_series)
print(str(max(count, key = count.get)))
#Ans: y
# =============================================================================
# Which letter occurs the Least frequently?
# =============================================================================
min_freq = letter_series
count =collections.Counter(letter_series)
print(str(min(count, key = count.get)))
#Ans: letter 'l'
# =============================================================================
# How many vowels are in the Series?
# =============================================================================
vowels = letter_series.str.count(r'[aeiou]').sum()
#Ans: sum is 34
# =============================================================================
# How many consonants are in the Series?
# =============================================================================
consonants = len(letter_series) - vowels
#ans: 166
# =============================================================================
# Create a Series that has all of the same letters but uppercased.
# =============================================================================
new_letter_series = pd.Series([letter.upper() for letter in letter_series], name= 'Big Letters')
# =============================================================================
#
# Create a bar plot of the frequencies of the 6 most commonly occuring letters.
# =============================================================================
to_plot = letter_series.value_counts()
to_plot = to_plot.head(6)
to_plot.plot.bar()
plt.show()
plt.close()
# =============================================================================
# Use PANDAS to create a Series named numbers from the following list:
# =============================================================================
numbers = pd.Series(['$796,459.41', '$278.60', '$482,571.67', '$4,503,915.98',
'$2,121,418.3', '$1,260,813.3', '$87,231.01', '$1,509,175.45',
'$4,138,548.00', '$2,848,913.80', '$594,715.39', '$4,789,988.17',
'$4,513,644.5', '$3,191,059.97', '$1,758,712.24', '$4,338,283.54',
'$4,738,303.38', '$2,791,759.67', '$769,681.94', '$452,650.23'])
# =============================================================================
# 1.)What is the data type of the numbers Series?
# ============================================================================
for row in numbers:
print(type(row))
#Ans: strings
# =============================================================================
#
# 2.)How many elements are in the number Series?
# =============================================================================
len(numbers)
#Ans: 20
# =============================================================================
# 3.)Perform the necessary manipulations by accessing Series attributes and methods
# to convert the numbers Series to a numeric data type.
# =============================================================================
numbers = [number.replace('$', '') for number in numbers]
numbers = [float(number.replace(',', '')) for number in numbers]
numbers = pd.Series(numbers)
# =============================================================================
# 4.)Run the code to discover the maximum value from the Series.
# =============================================================================
max(numbers)
#Ans: 4789988.17
# =============================================================================
# 5.)Run the code to discover the minimum value from the Series.
# =============================================================================
min(numbers)
#Ans: 278.6
# =============================================================================
# 6.)What is the range of the values in the Series?
# =============================================================================
range_num = max(numbers) - min(numbers)
print(range_num)
#Ans: 4789709.57
# =============================================================================
# 7.)Bin the data into 4 equally sized intervals or bins and output how many values
# fall into each bin.
# =============================================================================
bins = range_num.value_counts(bins=4)
# =============================================================================
# 8.)Plot the binned data in a meaningful way. Be sure to include a title and axis labels.
# =============================================================================
bins.plot()
# =============================================================================
# Use pandas to create a Series named exam_scores from the following list:
# =============================================================================
# =============================================================================
# =============================================================================
exam_scores = pd.Series([60, 86, 75, 62, 93, 71, 60, 83, 95, 78, 65, 72, 69,
81, 96, 80, 85, 92, 82, 78])
# =============================================================================
# 1.)How many elements are in the exam_scores Series?
# =============================================================================
len(exam_scores)
#ans: 20
# =============================================================================
# 2.)Run the code to discover the minimum, the maximum, the mean, and the median scores
# for the exam_scores Series.
# =============================================================================
scores = exam_scores.describe()
medians = pd.Series(exam_scores.median(), name="median")
scores = pd.concat([scores, medians], axis=0)#includes median on the summary describe() gave me
scores = scores.rename(index={0:'median'})
# =============================================================================
# 3.)Plot the Series in a meaningful way and make sure your chart has a title and
# axis labels.
# =============================================================================
import matplotlib.pyplot as plt
exam_scores.plot.bar(edgecolor='black')
plt.title('Exam Scores')
plt.ylabel('Scores')
plt.xlabel('Student ID')
plt.show()
# =============================================================================
# 4.)Write the code necessary to implement a curve for your exam_grades Series and
# save this as curved_grades. Add the necessary points to the highest grade to
# make it 100, and add the same number of points to every other score in the Series
# as well.
# =============================================================================
curve = 100 - exam_scores.max()
curved_grades = pd.Series([i + curve for i in exam_scores])
# =============================================================================
#
# 5.)Use a method to convert each of the numeric values in the curved_grades Series
# into a categorical value of letter grades. For example, 86 should be a 'B' and
# 95 should be an 'A'. Save this as a Series named letter_grades.
# =============================================================================
rubric = {'A': [i for i in range(90, 101)],
'B': [i for i in range(80, 90)],
'C': [i for i in range(70, 80)],
'F': [i for i in range(0, 70)]}
# letter_grades = [key for key, value in rubric.items() if ]
letter_grades = []
for grade in curved_grades:
for key, value in rubric.items():
if grade in value:
letter_grades.append(key)
letter_grades = pd.Series(letter_grades, name='letter')
letter_grades = pd.DataFrame(letter_grades)
# =============================================================================
# 6.)Plot your new categorical letter_grades Series in a meaninful way and include
# a title and axis labels.
# =============================================================================
groups = letter_grades.value_counts().sort_index().plot.bar(edgecolor='black')
plt.title('Student Grades By Letter')
plt.ylabel('Scores')
plt.xlabel('Letter')
plt.show() |
30d42da6fa8c107b6f17ef550ef47ca81ece6233 | swford89/python_code_challenges | /code_challenge_01.py | 1,158 | 4.09375 | 4 | # Coding Nomads - Code Challenge #1: The Sieve of Eratosthenes
# Scott Ford
# April 30th, 2021
def sieve(n):
"""to find all the prime numbers up to a specified maximum"""
sieve_list = []
if n in range(2,65536): # make sure min and max values are >= 2 and < 65,536
for p in range(2,n): # get numbers in the specified range
sieve_list.append(p) # append those numbers to the sieve list
else:
print("Eratosthenes doesn't like this number.")
for num in range(2,n): # get potential multiples of numbers in the range of your list
for p in sieve_list: # get your p values
if num * p in sieve_list: # check if multiple * p is in the list
sieve_list.remove(num * p) # remove the resultant multiple
print(*sieve_list, sep=", ", end="" + "\n")
num_limit = int(input("Eratosthenes would like the number up to which you're looking for primes: "))
sieve(num_limit)
|
e4a241281be2170d39e066a092c8bf0fed1ea3b7 | wangmx116/wdd | /ML-exercise1-4/ex3/ex3.py | 5,563 | 3.984375 | 4 | ## Machine Learning Online Class - Exercise 3 | Part 1: One-vs-all
import scipy.io
import numpy as np
from matplotlib import use
use('TkAgg')
import matplotlib.pyplot as plt
from oneVsAll import oneVsAll
from predictOneVsAll import predictOneVsAll
from displayData import displayData
from predict import predict
np.set_printoptions(threshold=np.inf)
# Instructions
# ------------
#
# This file contains code that helps you get started on the
# linear exercise. You will need to complete the following functions
# in this exericse:
#
# lrCostFunction.m (logistic regression cost function)
# oneVsAll.m
# predictOneVsAll.m
# predict.m
#
# For this exercise, you will not need to change any code in this file,
# or any other files other than those mentioned above.
#
print('Exercise 1: Multi-class Classification')
## Setup the parameters you will use for this part of the exercise
input_layer_size = 400 # 20x20 Input Images of Digits
num_labels = 10 # 10 labels, from 1 to 10
# (note that we have mapped "0" to label 10)
## =========== Part 1: Loading and Visualizing Data =============
# We start the exercise by first loading and visualizing the dataset.
# You will be working with a dataset that contains handwritten digits.
#
# Load Training Data
print('Loading and Visualizing Data ...')
data = scipy.io.loadmat('ex3data1.mat') # training data stored in arrays X, y
X = data['X']
y = data['y']
m, _ = X.shape
print("X shape", X.shape)
print("y shape", y.shape)
# Randomly select 100 data points to display
rand_indices = np.random.permutation(range(m))
sel = X[rand_indices[0:100], :]
displayData(sel)
input("Program paused. Press Enter to continue...")
## ============ Part 2: Vectorize Logistic Regression ============
# In this part of the exercise, you will reuse your logistic regression
# code from the last exercise. You task here is to make sure that your
# regularized logistic regression implementation is vectorized. After
# that, you will implement one-vs-all classification for the handwritten
# digit dataset.
#
print('Training One-vs-All Logistic Regression...')
Lambda = 0.
all_theta = oneVsAll(X, y, num_labels, Lambda)
input("Program paused. Press Enter to continue...")
## ================ Part 3: Predict for One-Vs-All ================
# After ...
pred = predictOneVsAll(all_theta, X)
print('pred.shape', pred.shape)
#print('pred', pred)
n_total, n_correct=0., 0.
for irow in range(X.shape[0]):
n_total+=1
if pred[irow]==y[irow]:
n_correct+=1
print('n_total', n_total, 'n_correct', n_correct)
accuracy=100*n_correct/n_total
#accuracy = np.mean(np.double(pred == np.squeeze(y))) * 100
print('\nTraining Set Accuracy: %f\n' % accuracy)
## ================ Part 4: ================
print('\n')
print('Exercise 2: Neural Networks')
print('\n')
## Setup the parameters you will use for this exercise
input_layer_size = 400 # 20x20 Input Images of Digits
hidden_layer_size = 25 # 25 hidden units
num_labels = 10 # 10 labels, from 1 to 10
# (note that we have mapped "0" to label 10)
## =========== Part 1: Loading and Visualizing Data =============
# We start the exercise by first loading and visualizing the dataset.
# You will be working with a dataset that contains handwritten digits.
#
# Load Training Data
print('Loading and Visualizing Data ...')
data = scipy.io.loadmat('ex3data1.mat')
X = data['X']
y = data['y']
print('X shape', X.shape)
print('y shape', y.shape)
m, _ = X.shape
# Randomly select 100 data points to display
sel = np.random.permutation(range(m))
sel = sel[0:100]
displayData(X[sel,:])
input("Program paused. Press Enter to continue...")
## ================ Part 2: Loading Pameters ================
# In this part of the exercise, we load some pre-initialized
# neural network parameters.
print('Loading Saved Neural Network Parameters ...')
# Load the weights into variables Theta1 and Theta2
data = scipy.io.loadmat('ex3weights.mat')
Theta1 = data['Theta1']
Theta2 = data['Theta2']
print('Theta1 shape', Theta1.shape)
print('Theta2 shape', Theta2.shape)
## ================= Part 3: Implement Predict =================
# After training the neural network, we would like to use it to predict
# the labels. You will now implement the "predict" function to use the
# neural network to predict the labels of the training set. This lets
# you compute the training set accuracy.
pred = predict(Theta1, Theta2, X)
n_total, n_correct=0., 0.
for irow in range(X.shape[0]):
n_total+=1
if pred[irow]==int(y[irow]):
n_correct+=1
print('n_total', n_total, 'n_correct', n_correct)
accuracy=100*n_correct/n_total
print('\nTraining Set Accuracy: %f\n' % accuracy)
#print('Training Set Accuracy: %f\n', np.mean(np.double(pred == np.squeeze(y))) * 100) # np.squeeze(y).shape=(5000,)
input("Program paused. Press Enter to continue...")
# To give you an idea of the network's output, you can also run
# through the examples one at the a time to see what it is predicting.
# Randomly permute examples
rp = np.random.permutation(range(m))
plt.figure()
for i in range(0, 5): #range(m):
# Display
X2 = X[rp[i],:]
print('Displaying 5 Example Images')
X2 = np.matrix(X[rp[i]])
displayData(X2)
pred = predict(Theta1, Theta2, X2.getA())
pred = np.squeeze(pred)
print('Neural Network Prediction: %d (digit %d)\n' % (pred, np.mod(pred, 10)))
input("Program paused. Press Enter to continue...")
plt.close()
|
75c14cfafe64264b72186017643b6c3b3dacb42f | Malak-Abdallah/Intro_to_python | /main.py | 866 | 4.3125 | 4 | # comments are written in this way!
# codes written here are solutions for solving problems from Hacker Rank.
# -------------------------------------------
# Jenan Queen
if __name__ == '__main__':
print("Hello there!! \nThis code to practise some basics in python. \n ")
str = "Hello world"
print(str[2:])
# TASK 1:
# If n is odd, print Weird
# If n is even and in the inclusive range of 2 to 5, print Not Weird
# If n is even and in the inclusive range of 6 to 20, print Weird
# If n is even and greater than 20, print Not Weird
# 1<= n <= 100
print("Enter an integer greater then zero and less or equal 100 ")
n = int(input().strip())
if (n % 2) != 0:
print("Weird")
elif n % 2 == 0:
if n in range(2, 6) or n > 20:
print("Not Weird")
else:
print("Weird")
|
2fbba8408416247b6cbdd3918efbe04a242634d4 | Malak-Abdallah/Intro_to_python | /general.py | 255 | 3.546875 | 4 | from itertools import permutations
if __name__ == '__main__':
word=list(map(str,input().split(" ")))
len = int(word[1])
per=permutations(list(word[0]),len)
arr=sorted(per)
for x in arr:
strr=x[0]+x[1]
print(strr)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.