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 |
|---|---|---|---|---|---|---|
0aca792ff94330e304c5ebfa836d88a53e00b0d5 | jke-zq/my_lintcode | /Sort Colors II.py | 2,813 | 3.546875 | 4 | class Solution:
"""
@param colors: A list of integer
@param k: An integer
@return: nothing
"""
def sortColors2(self, colors, k):
# write your code here
# def helper(start, end, kstart, kend, colors):
# if kstart >= kend or start >= end:
# return
# kmid = kstart + (kend - kstart) / 2
# left, pivot, right = start, start, end
# while left <= right:
# if colors[left] < kmid:
# colors[pivot], colors[left] = colors[left], colors[pivot]
# pivot += 1
# left += 1
# elif colors[left] == kmid:
# left += 1
# else:
# colors[left], colors[right] = colors[right], colors[left]
# right -= 1
# ##[pivot, left - 1] are all the kmid value
# helper(start, pivot - 1, kstart, kmid - 1, colors)
# helper(left, end, kmid + 1, kend, colors)
# if not colors:
# return None
# length = len(colors)
# helper(0, length - 1, 1, k, colors)
length = len(colors)
for i in range(length):
if colors[i] > 0:
while colors[colors[i] - 1] > 0 and colors[i] != i + 1 and colors[i] != colors[colors[i] - 1]:
colors[colors[i] - 1], colors[i] = -1, colors[colors[i] - 1]
if colors[i] == i + 1:
colors[i] = -1
elif colors[i] == colors[colors[i] - 1]:
colors[colors[i] - 1] = -2
colors[i] = 0
else:
colors[colors[i] - 1] -= 1
colors[i] = 0
index = length - 1
while k > 0:
pos = colors[k - 1] + index + 1
while index >= pos:
colors[index] = k
index -= 1
k -= 1
class Solution:
"""
@param colors: A list of integer
@param k: An integer
@return: nothing
"""
def sortColors2(self, colors, k):
# write your code here
length = len(colors)
for i in range(length):
tmp = colors[i]
if tmp > 0:
colors[i] = 0
while tmp > 0 and colors[tmp - 1] > 0:
next_one = colors[tmp - 1]
colors[tmp - 1] = -1
tmp = next_one
if tmp <= 0:
continue
if colors[tmp - 1] <= 0:
colors[tmp - 1] -= 1
# print(colors)
priovt = length - 1
for i in range(length - 1, -1, -1):
while colors[priovt] >= 0:
priovt -= 1
colors[priovt] += 1
colors[i] = priovt + 1
|
e7deb4de032c109bfc552e93888ce0e74da6147d | jke-zq/my_lintcode | /Tweaked Identical Binary Tree.py | 779 | 4 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param a, b, the root of binary trees.
@return true if they are tweaked identical, or false.
"""
def isTweakedIdentical(self, a, b):
# Write your code here
def helper(nodea, nodeb):
if not nodea and not nodeb:
return True
if nodea and nodeb and nodea.val == nodeb.val:
return (helper(nodea.left, nodeb.right) and helper(nodea.right, nodeb.left)) or (helper(nodea.left, nodeb.left) and helper(nodea.right, nodeb.right))
else:
return False
return helper(a, b) |
10a51c8544b7dd713b7d107a59c56ca1342a7f3d | jke-zq/my_lintcode | /Insertion Sort List.py | 1,263 | 3.953125 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list.
@return: The head of linked list.
"""
def insertionSortList(self, head):
# write your code here
def insert(dummy, node):
cur = dummy
while cur.next:
if cur.next.val < node.val:
cur = cur.next
else:
tmp = cur.next
cur.next = node
node.next = tmp
return dummy
cur.next = node
# node.next = None
return dummy
def judge(root):
cur = root
while cur.next:
if cur.val < cur.next.val:
cur = cur.next
else:
return False
return True
if judge(head):
return head
dummy = ListNode(0)
cur = head
while cur:
tmp = cur
cur = cur.next
tmp.next = None
insert(dummy, tmp)
return dummy.next |
6bf431880aa9181b7b4db9bec2b98c633be6977b | jke-zq/my_lintcode | /Ugly Number II.py | 687 | 3.5625 | 4 | import heapq
class Solution:
"""
@param {int} n an integer.
@return {int} the nth prime number as description.
"""
def nthUglyNumber(self, n):
# write your code here
ans = [1]
factors = [2, 3, 5]
times = [0] * len(factors)
values = []
for i in range(len(factors)):
heapq.heappush(values, (factors[i], i))
while len(ans) < n:
v, index = heapq.heappop(values)
times[index] += 1
if v != ans[-1]:
ans.append(v)
heapq.heappush(values, (factors[index] * ans[times[index]], index))
return ans[-1]
|
a26f915fbc8f1239d40f56c382a64079798a848b | jke-zq/my_lintcode | /Number of Airplanes in the Sky.py | 727 | 3.734375 | 4 | """
Definition of Interval.
class Interval(object):
def __init__(self, start, end):
self.start = start
self.end = end
"""
class Solution:
# @param airplanes, a list of Interval
# @return an integer
def countOfAirplanes(self, airplanes):
# write your code here
airs = []
for interval in airplanes:
s, e = interval.start, interval.end
airs.append((s, 1))
airs.append((e, 0))
airs.sort()
count = 0
ret = 0
for time, fly in airs:
if fly == 1:
count += 1
ret = max(ret, count)
else:
count -= 1
return ret |
986002310e86fe8863f0bf202682e0bb1a45a2d0 | jke-zq/my_lintcode | /Nuts & Bolts Problem.py | 2,019 | 4.03125 | 4 | # class Comparator:
# def cmp(self, a, b)
# You can use Compare.cmp(a, b) to compare nuts "a" and bolts "b",
# if "a" is bigger than "b", it will return 1, else if they are equal,
# it will return 0, else if "a" is smaller than "b", it will return -1.
# When "a" is not a nut or "b" is not a bolt, it will return 2, which is not valid.
import random
class Solution:
# @param nuts: a list of integers
# @param bolts: a list of integers
# @param compare: a instance of Comparator
# @return: nothing
def sortNutsAndBolts(self, nuts, bolts, compare):
# write your code here
def helper(left, right, nuts, bolts, compare):
if left >= right:
return
boltIndex = random.randint(left, right)
target = nuts[boltIndex]
l, pivot, r = left, left, right
while l <= r:
if compare.cmp(target, bolts[l]) == 1:
bolts[l], bolts[r] = bolts[r], bolts[l]
r -= 1
elif compare.cmp(target, bolts[l]) == 0:
l += 1
else:
bolts[l], bolts[pivot] = bolts[pivot], bolts[l]
pivot += 1
l += 1
target = bolts[pivot]
l, pivot, r = left, left, right
while l <= r:
if compare.cmp(nuts[l], target) == -1:
nuts[l], nuts[r] = nuts[r], nuts[l]
r -= 1
elif compare.cmp(nuts[l], target) == 0:
l += 1
else:
nuts[l], nuts[pivot] = nuts[pivot], nuts[l]
pivot += 1
l += 1
helper(left, pivot - 1, nuts, bolts, compare)
helper(pivot + 1, right, nuts, bolts, compare)
if not nuts:
return
length = len(nuts)
helper(0, length - 1, nuts, bolts, compare)
|
db2243fb1c78847358a9e6602fe3e714b987b2b4 | jke-zq/my_lintcode | /Sqrt(x).py | 664 | 4.0625 | 4 | class Solution:
"""
@param x: An integer
@return: The sqrt of x
"""
def sqrt(self, x):
# write your code here
left, right = 0, x
while left + 1 < right:
mid = left + (right - left) / 2
if mid * mid <= x:
left = mid
else:
right = mid
#error: we should not check the left because there is no exception for the left.(0 is belong to the left * left <= x)
# if left * left <= x:
# return left
if right * right <= x:
return right
else:
return left
|
ae96a2e0c735c36a8e9556bb5458c83169151728 | jke-zq/my_lintcode | /Search in Rotated Sorted Array II.py | 2,059 | 3.625 | 4 | class Solution:
"""
@param A : an integer ratated sorted array and duplicates are allowed
@param target : an integer to be searched
@return : a boolean
"""
def search(self, A, target):
# write your code here
if not A:
return False
left, right = 0, len(A) - 1
while left + 1 < right:
while left + 1 < right and A[left] == A[right]:
left += 1
mid = left + (right - left) / 2
if A[mid] == target:
return True
# if target >= A[left]:
# if A[left] <= A[mid] < target:
# left = mid
# else:
# right = mid
# else:
# if A[right] >= A[mid] > target:
# right = mid
# else:
# left = mid
if A[mid] >= A[left]:
if A[mid] > target >= A[left]:
right = mid
else:
left = mid
else:
if A[right] >= target > A[mid]:
left = mid
else:
right = mid
if target in (A[right], A[left]):
return True
else:
return False
# solution II
def search(self, A, target):
# write your code here
if A is None or len(A) == 0:
return False
start, end = 0, len(A) - 1
while start + 1 < end:
mid = (start + end) // 2
if A[mid] == target:
return True
if A[mid] == A[end]:
end -= 1
continue
if A[mid] < A[end]:
if A[mid] < target <= A[end]:
start = mid
else:
end = mid
else:
if A[mid] > target >= A[start]:
end = mid
else:
start = mid
return target in (A[start], A[end])
|
610166915f6cf184fba95786259e143c548217fa | jke-zq/my_lintcode | /Rehashing.py | 1,204 | 3.796875 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param hashTable: A list of The first node of linked list
@return: A list of The first node of linked list which have twice size
"""
def rehashing(self, hashTable):
# write your code here
def add(node, newTable, hashFunc):
if node:
index = hashFunc(node.val)
if newTable[index]:
root = newTable[index]
while root.next:
root = root.next
root.next = ListNode(node.val)
else:
root = ListNode(node.val)
newTable[index] = root
length = len(hashTable) * 2
newTable = [None] * length
hashFunc = lambda x: x % length
for i in range(length / 2):
if hashTable[i]:
root = hashTable[i]
while root:
add(root, newTable, hashFunc)
root = root.next
return newTable
|
eeab506beb08c5689d60f046aa721edaa0a295a0 | jke-zq/my_lintcode | /Binary Tree Preorder Traversal.py | 1,575 | 3.828125 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: Preorder in ArrayList which contains node values.
"""
def preorderTraversal(self, root):
# write your code here
# def doTrav(node, ret):
# if not node:
# return
# else:
# ret.append(node.val)
# doTrav(node.left, ret)
# doTrav(node.right, ret)
# ret = []
# doTrav(root, ret)
# return ret
# if not root:
# return []
# ret = []
# node = root
# stack = []
# while node:
# stack.append(node)
# ret.append(node.val)
# node = node.left
# while stack:
# node = stack.pop()
# # ret.append(node.val)
# if node.right:
# node = node.right
# while node:
# stack.append(node)
# ret.append(node.val)
# node = node.left
# return ret
if not root:
return []
stack = [root]
ret = []
while stack:
cur = stack.pop()
ret.append(cur.val)
if cur.right:
stack.append(cur.right)
if cur.left:
stack.append(cur.left)
return ret
|
5d0260047d4f389d9d78c518c11e2ee83085db9e | jke-zq/my_lintcode | /Construct Binary Tree from Inorder and Postorder Traversal.py | 1,022 | 3.96875 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param inorder : A list of integers that inorder traversal of a tree
@param postorder : A list of integers that postorder traversal of a tree
@return : Root of a tree
"""
def buildTree(self, inorder, postorder):
# write your code here
def helper(instart, inend, inorder, poststart, postend, postorder):
if poststart > postend:
return None
node = TreeNode(postorder[postend])
index = inorder.index(node.val)
node.left = helper(instart, index - 1, inorder, poststart, poststart + index - instart - 1, postorder)
node.right = helper(index + 1, inend, inorder, poststart + index - instart, postend - 1, postorder)
return node
return helper(0, len(inorder) - 1, inorder, 0, len(postorder) - 1, postorder) |
ad310e83dc738c9318e78c685549c3735f52723a | ddxygq/PyCode | /Python基础语法/算法/SortAlgo.py | 2,268 | 3.9375 | 4 | # -*- coding:utf-8 -*-
# 冒泡排序
def bubbleSort(arr):
for i in range(len(arr) - 1):
for j in range(i+1, len(arr)):
if arr[i] > arr[j]:
arr[i],arr[j] = arr[j],arr[i]
# 选择排序
def selectSort(arr):
for i in range(len(arr) - 1):
# 使用变量存储最小元素的index
minIndex = i
for j in range(i+1, len(arr)):
if arr[minIndex] > arr[j]:
minIndex = j
arr[i],arr[minIndex] = arr[minIndex],arr[i]
# 插入排序
def insertSort(arr):
for i in range(1,len(arr)):
temp = arr[i]
j = i - 1
while j >= 0 and temp < arr[j]:
arr[j + 1] = arr[j]
j = j - 1
arr[j + 1] = temp
# 快速排序
def quickSort(arr, begin, end):
if begin < end:
key = arr[begin]
i = begin
j = end
while i < j:
while i < j and arr[j] > key:
j = j - 1
if i < j:
arr[i] = arr[j]
i = i + 1
while i < j and arr[i] < key:
i = i + 1
if i < j:
arr[j] = arr[i]
j = j - 1
arr[i] = key
quickSort(arr, begin, i - 1)
quickSort(arr, i + 1, end)
# 堆排序
def heap_sort(arr):
length = len(arr)
# 循环 n - 1次
for i in range(length - 1):
print('第%s次构建堆' % (i),arr)
# 建堆
build_heap(arr, length - 1 - i)
# 交换堆顶和"最后"一个元素
arr[0],arr[length - 1 - i] = arr[length - 1 - i], arr[0]
print('交换后',arr)
# 构建堆
def build_heap(arr, last):
# 长度为last的堆,最后一个非叶子节点下标索引是(last - 1) / 2
last_node = int((last - 1)/2)
# range(4,-1,-1) 表示 [4,3,2,1,0]
for i in list(range(last_node, -1, -1)):
k = i
# 左节点下标
left = 2*i + 1
# left < last表命有右子节点,left存储的是左右节点中较大数的下标索引
if left < last and arr[left] < arr[left + 1]:
left = left + 1
# 子节点比父节点大,交换
if arr[i] < arr[left]:
# 交换位置,把大数放在上面,小数放在子节点
arr[i],arr[left] = arr[left],arr[i]
if __name__ == '__main__':
data = [2,56,7,10,69,5,23,34,12,24,4]
# bubbleSort(data)
# selectSort(data)
# insertSort(data)
# quickSort(data, 0, len(data) - 1)
heap_sort(data)
print(data) |
652fe49d11f5fb18e15cbad5085f680d3aed13a0 | ddxygq/PyCode | /Python基础语法/面向对象/senior_object.py | 579 | 3.875 | 4 | # 面向对象高级
class Teacher(object):
# 限制该类能动态添加的属性
__slots__ = ('name', 'age')
pass
def set_name(self, name):
self.name = name
def set_age(self, age):
self.age = age
if __name__ == '__main__':
teacher = Teacher()
# 给实例绑定方法
from types import MethodType
teacher.set_name = MethodType(set_name, teacher)
teacher.set_name('keguang')
print(teacher.name)
# 给类绑定方法
Teacher.set_age = set_age
teacher2 = Teacher()
teacher2.set_age(24)
print(teacher2.age)
|
a21e2a40f49e48372fbeb400a24219b7ae657fb1 | DrydenHenriques/50-coding-interview-questions | /bit/33_Bit-Int-Modulus.py | 476 | 3.578125 | 4 | #!/usr/bin/python
# coding=utf-8
'''
__author__ = 'sunp'
__date__ = '2019/1/27'
Given a list of bytes a, each representing one byte of a larger integer (ie. {0x12, 0x34, 0x56, 0x78} represents the integer 0x12345678), and an integer b, find a % b.
mod({0x03, 0xED}, 10) = 5
'''
def mod(bits, num):
res = 0
for bit in bits:
res = (res << 8) | (bit & 0xff)
res %= num
return res
if __name__ == '__main__':
assert mod([0x03, 0xED], 10) == 5
|
5749bc33bc6565336b29598ef3ec651190a7346f | DrydenHenriques/50-coding-interview-questions | /recursion/24_Balanced-Binary-Tree.py | 704 | 4.09375 | 4 | #!/usr/bin/python
# coding=utf-8
'''
__author__ = 'sunp'
__date__ = '2019/2/17'
Given a binary tree, write a function to determine whether the tree is balanced.
- all branches are same height(±1).
- all subtrees are balanced.
'''
class TreeNode(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_balanced(root):
return _balanced_height(root) > -1
def _balanced_height(root):
if not root:
return 0
h1 = _balanced_height(root.left)
h2 = _balanced_height(root.right)
if h1 == -1 or h2 == -1:
return -1
if abs(h1-h2) > 1:
return -1
return max(h1, h2) + 1
|
0685929c6aefd5016521602eded7981f46d9e19f | DrydenHenriques/50-coding-interview-questions | /stack/28_Sort-Stacks.py | 772 | 3.96875 | 4 | #!/usr/bin/python
# coding=utf-8
'''
__author__ = 'sunp'
__date__ = '2019/1/26'
Given a stack, sort the elements in the stack using one additional stack.
'''
def sort1(stack):
# two additional stacks
buf1, buf2 = [], []
while stack:
top = stack.pop()
while buf1 and buf1[-1] > top:
buf2.append(buf1.pop())
buf1.append(top)
while buf2:
buf1.append(buf2.pop())
return buf1
def sort2(stack):
# one additional stack
buf = []
while stack:
top = stack.pop()
while buf and buf[-1] > top:
stack.append(buf.pop())
buf.append(top)
return buf
if __name__ == '__main__':
for sort in [sort1, sort2]:
assert sort([1, 3, 2, 4]) == [1, 2, 3, 4]
|
8fa7b4b95e0fd65016df733a187f1794bab79367 | DrydenHenriques/50-coding-interview-questions | /array/06_Zero-Matrix.py | 1,154 | 3.890625 | 4 | #!/usr/bin/python
# coding=utf-8
'''
__author__ = 'sunp'
__date__ = '2019/1/24'
Given a boolean matrix, update it so that if any cell is true, all the cells in that row and column are true.
[true, false, false] [true, true, true ]
[false, false, false] -> [true, false, false]
[false, false, false] [true, false, false]
'''
def zero_matrix(matrix):
if not matrix or not matrix[0]:
return
m, n = len(matrix), len(matrix[0])
points = []
for i in range(m):
for j in range(n):
if matrix[i][j]:
points.append((i, j))
for i, j in points:
for x in range(m):
matrix[x][j] = True
for y in range(n):
matrix[i][y] = True
if __name__ == '__main__':
matrix1 = [[True, False, False], [False, False, False], [False, False, False]]
zero_matrix(matrix1)
assert matrix1 == [[True, True, True], [True, False, False], [True, False, False]]
matrix2 = [[True, False, True], [False, False, False], [False, False, False]]
zero_matrix(matrix2)
assert matrix2 == [[True, True, True], [True, False, True], [True, False, True]]
|
86e16a7c1ea92437fcbaceec30dae0f4558ddf56 | DrydenHenriques/50-coding-interview-questions | /bit/34_Swap-Variables.py | 506 | 4.09375 | 4 | #!/usr/bin/python
# coding=utf-8
'''
__author__ = 'sunp'
__date__ = '2019/1/27'
Given two integers, write a function that swaps them without using any temporary variables.
'''
def swap1(num1, num2):
num1 = num1 ^ num2
num2 = num1 ^ num2
num1 = num1 ^ num2
return num1, num2
def swap2(num1, num2):
num1 = num1 + num2
num2 = num1 - num2
num1 = num1 - num2
return num1, num2
if __name__ == '__main__':
for swap in [swap1, swap2]:
assert swap(1, 2) == (2, 1)
|
df88a89721806474b5792478f2209806defbd69c | DrydenHenriques/50-coding-interview-questions | /array/07_Square-Submatrix.py | 1,721 | 3.609375 | 4 | #!/usr/bin/python
# coding=utf-8
'''
__author__ = 'sunp'
__date__ = '2019/1/24'
Given a 2D array of 1s and 0s, find the largest square subarray of all 1s.
subarray([1, 1, 1, 0]
[1, 1, 1, 1]
[1, 1, 0, 0]) = 2
'''
def subarray1(matrix):
# brute
if not matrix or not matrix[0]:
return 0
m, n = len(matrix), len(matrix[0])
res = 0
for i in range(m):
for j in range(n):
res = max(res, _extend(matrix, i, j, m, n))
return res
def _extend(matrix, i, j, m, n):
length = 0
while length < min(m-i, n-j):
flag = True
for x in range(i, i+1+length):
if not matrix[x][j+length]:
flag = False
break
for y in range(j, j+1+length):
if not matrix[i+length][y]:
flag = False
break
if flag:
length += 1
else:
break
return length
def subarray2(matrix):
# bottom-up dp: extend up and left
if not matrix or not matrix[0]:
return 0
m, n = len(matrix), len(matrix[0])
res = 0
dp = [[0 for _ in range(n)] for _ in range(m)]
for i in range(m):
for j in range(n):
if not i or not j:
dp[i][j] = 1 if matrix[i][j] else 0
elif matrix[i][j]:
dp[i][j] = min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) + 1
res = max(res, dp[i][j])
return res
if __name__ == '__main__':
matrix1 = [[1, 1, 1, 0], [1, 1, 1, 1], [1, 1, 0, 0]]
matrix2 = [[1, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 0]]
for subarray in [subarray1, subarray2]:
assert subarray(matrix1) == 2
assert subarray(matrix2) == 3
|
261769794d54cf67e348842dd778fb8fda97abe2 | tau49/Lommeregner | /Lommeregner.py | 1,067 | 4.0625 | 4 | import Divider
import Gange
import Plus
import Minus
while(True):
print("[1] Divider")
print("[2] Gange")
print("[3] Plus")
print("[4] Minus")
Choice = input("Please choose an option")
if Choice == "1":
number1 = int(input("Choose the first number"))
number2 = int(input("Choose the second number"))
result = Divider.divider(number1, number2)
break
elif Choice == "2":
number1 = int(input("Choose the first number"))
number2 = int(input("Choose the second number"))
result = Gange.gange(number1, number2)
break
elif Choice == "3":
number1 = int(input("Choose the first number"))
number2 = int(input("Choose the second number"))
result = Plus.plus(number1, number2)
break
elif Choice == "4":
number1 = int(input("Choose the first number"))
number2 = int(input("Choose the second number"))
result = Minus.minus(number1, number2)
break
else:
print("Please enter a correct number")
print(result) |
7fb3399b4a0a07395ce5be57e062dca4b4fdaf90 | MakDon/toy_calculator | /toy_calculator_python/test.py | 2,511 | 3.875 | 4 | import unittest
from calculator import Calculator
calculator = Calculator()
class TestCalculator(unittest.TestCase):
def test_calculate0(self):
question = "1+2+3+5+7"
self.assertEqual(calculator.calculate(question), eval(question))
def test_calculate01(self):
question = "11.5+12.5+3+5+7"
self.assertEqual(calculator.calculate(question), eval(question))
def test_calculate1(self):
question = "1 + 2 + 3"
self.assertEqual(calculator.calculate(question), eval(question))
def test_calculate2(self):
question = "1+ 2+ 3"
self.assertEqual(calculator.calculate(question), eval(question))
def test_calculate3(self):
question = "1*2+3"
self.assertEqual(calculator.calculate(question), eval(question))
def test_calculate4(self):
question = "1+2*3"
self.assertEqual(calculator.calculate(question), eval(question))
def test_calculate5(self):
question = "1-2+3"
self.assertEqual(calculator.calculate(question), eval(question))
def test_calculate6(self):
question = "1+2/3"
self.assertEqual(calculator.calculate(question), eval(question))
def test_calculate7(self):
question = "1.1+2.3*(3.0+5)+4"
self.assertEqual(calculator.calculate(question), eval(question))
def test_calculate8(self):
question = "1+2*(3.235+5)+4"
self.assertEqual(calculator.calculate(question), eval(question))
def test_calculate9(self):
question = "1+2*(3+5.78)+4"
self.assertEqual(calculator.calculate(question), eval(question))
def test_calculate10(self):
question = "1+2*(3+5+4"
try:
calculator.calculate(question)
except ValueError as e:
self.assertEqual(e.args[0], "Error Grammar")
def test_calculate11(self):
question = "1+2(3+5)+4"
try:
calculator.calculate(question)
except ValueError as e:
self.assertEqual(e.args[0], "Error Grammar")
def test_calculate12(self):
question = "1+2*(3+5)+"
try:
calculator.calculate(question)
except ValueError as e:
self.assertEqual(e.args[0], "Error Grammar")
def test_calculate13(self):
question = "1.+2*(3+5)+"
try:
calculator.calculate(question)
except ValueError as e:
self.assertEqual(e.args[0], "Unknown Token")
if __name__=='__main__':
unittest.main() |
b2ca6afbd9940a891d59ed0164ce7cb3d13921a0 | sebastianrmirz/collaborative-filterting | /collab.py | 731 | 3.53125 | 4 | import math
def pearsons(r, i, j, num_items):
""" Computes pearsons similarity coefficient
parameters
r -- vector of ratings, where r[i][k] represents the rating user i gave to item k
i -- user i
j -- user j
num_items -- number of items
"""
avg_r_i = sum(r[i])/len(r[i])
avg_r_j = sum(r[j])/len(r[j])
i_ratings = [(r[i][k] - avg_r_i) for k in range(num_items)]
j_ratings = [(r[j][k] - avg_r_j)for k in range(num_items)]
sim = sum(a * b for a,b in zip(i_ratings, j_ratings))
i_sqrd = (a*a for a in i_ratings)
j_sqrd = (b*b for b in j_ratings)
var = math.sqrt(sum(i_sqrd)) * math.sqrt(sum(j_sqrd))
return sim / var
|
36987ff25b32b7f90e4fdcddbb0e8067acdbd4ec | saubhagyav/100_Days_Code_Challenge | /DAYS/Day61/Collatz_Sequence.py | 315 | 4.34375 | 4 | def Collatz_Sequence(num):
Result = [num]
while num != 1:
if num % 2 == 0:
num = num/2
else:
num = 3*num+1
Result.append(num)
return Result
if __name__ == "__main__":
num = int(input("Enter a Number: "))
print(Collatz_Sequence(num)) |
a9edafde6f0d863850db43754b465bae1fb20537 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day28/Remove_Tuple_of_length_k.py | 233 | 3.96875 | 4 | def Remove_Tuple(Test_list, K):
return [elements for elements in Test_list if len(elements) != K]
Test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
K = int(input("Enter K: "))
print(Remove_Tuple(Test_list, K))
|
36f35dd3437b55bd7f7ca44373cf578309d23a01 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day29/Leap_Year.py | 325 | 3.9375 | 4 | import calendar
def Leap_Year(Test_input):
count = 0
Result = []
while count < 15:
if calendar.isleap(Test_input):
Result.append(Test_input)
count += 1
Test_input += 1
return Result
Test_input = int(input("Enter Year: "))
print(Leap_Year(Test_input))
|
e3302797c8258c01afea690eca6bd70cba19fc4d | saubhagyav/100_Days_Code_Challenge | /DAYS/Day48/String_start_with_substring.py | 357 | 3.828125 | 4 | import re
def String_start_with_Substring(Test_string, Test_sample):
Result = "^"+Test_sample
if re.search(Result, Test_string):
return "True"
else:
return "False"
Test_string = "100 Days of Code Challenge makes your basic clear"
Test_sample = "100"
print(String_start_with_Substring(Test_string, Test_sample))
|
461493440fce1408696e7acc596556c6622232c5 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day22/Size_of_Largest_Subset_in_Anagram.py | 385 | 3.984375 | 4 | from collections import Counter
def Max_Anagram(Test_string):
for i in range(0, len(Test_string.split(" "))):
Test_string[i] = ''.join(sorted(Test_string[i]))
Dict_Frequency = Counter(Test_string)
return max(Dict_Frequency.values())
if __name__ == "__main__":
Test_string = 'ant magenta magnate tan gnamate'
print(Max_Anagram(Test_string))
|
b36a4f25c517fde8bd57a573ec089b41f1bf6839 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day1/Number_is_Fibonacci_or_not.py | 443 | 3.765625 | 4 | import math
def check_Perfect_Square(m):
semifinal = int(math.sqrt(m))
if pow(semifinal, 2) == m:
return True
return False
def fibo(n):
t1 = 5*n*n+4
t2 = 5*n*n-4
if check_Perfect_Square(t1) or check_Perfect_Square(t2):
return True
else:
return False
a = int(input("Enter a Number: "))
if fibo(a):
print("Yup! It's a Fibinacci Number")
else:
print("It's not a Fibonacci Number")
|
7d05b911c7a34e6f39829c6ed7a7befa7f472829 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day9/Product_of_All_Elements_in_Matrix.py | 354 | 3.546875 | 4 | def Final_Product(Check_list):
Prod = 1
for ele in Check_list:
Prod *= ele
return Prod
def Product_Matrix(Test_list):
Semi_Result = Final_Product(
[element for ele in Test_list for element in ele])
return Semi_Result
Test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
print(Product_Matrix(Test_list))
|
5491efb3841bc753f8de6fff6b0f5233c132a805 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day22/Remove_Duplicates_in_Dictionary.py | 364 | 4.21875 | 4 | def Remove_Duplicates(Test_string):
Test_list = []
for elements in Test_string.split(" "):
if ((Test_string.count(elements) > 1 or Test_string.count(elements) == 1) and elements not in Test_list):
Test_list.append(elements)
return Test_list
Test_string = input("Enter a String: ")
print(*(Remove_Duplicates(Test_string))) |
d2a637895e2db739ff8fa2a691a6fcd0ff3da411 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day69/Triangular_Number.py | 461 | 3.828125 | 4 | def divisor(num):
Result = []
for i in range(1, int(num)):
if num % i == 0:
Result.append(i)
return Result
def triangular_number(num):
count = True
natural = 1
while count:
ctr = (natural*(natural+1))/2
if len(divisor(ctr)) >= num:
return int(ctr)
natural += 1
if __name__ == "__main__":
num = int(input("Enter n: "))
print(triangular_number(num))
|
da3594bcfad1473e9cb47e5ee182638695d023d3 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day45/Starts_End_with_same_Character.py | 298 | 3.625 | 4 | import re
def Starts_End(Pattern, Test_string):
if re.search(Pattern, Test_string):
print("Valid...")
else:
print("Invalid...")
if __name__ == "__main__":
Pattern = r'^[a-z]$|^([a-z]).*\1$'
Test_string = "abba"
Starts_End(Pattern, Test_string)
|
dc9da0a4798e250e060a08117a204a9bed31c13f | saubhagyav/100_Days_Code_Challenge | /DAYS/Day48/String_Starting_with_Vowel.py | 311 | 3.796875 | 4 | import re
def Vowel_String(Test_string):
pattern = "^[aeiouAEIOU][a-zA-Z0-9]*"
if re.search(pattern, Test_string):
print("Accepted")
else:
print("Discarded")
Test_string1 = "code"
Test_string2 = "expression20"
Vowel_String(Test_string1)
Vowel_String(Test_string2)
|
6233668a16cfacdc34604fd06b72c9310ce10326 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day29/Rabbits_Chicken_Heads_and_Legs.py | 334 | 3.671875 | 4 | def solve(heads, legs):
error_msg = "No solution"
chicken_count = 0
rabbit_count = 0
if legs % 2 != 0:
print("No Solution")
else:
rabbit_count = (legs-2*heads)/2
chicken_count = (4*heads-legs)/2
print(int(chicken_count))
print(int(rabbit_count))
solve(35, 94) |
8d88ed7cb958f7e8a9ad0efb1611afdc6142188c | saubhagyav/100_Days_Code_Challenge | /DAYS/Day21/Binary_Representation_of_Two_Numbers_is_Anagram_or_not.py | 562 | 3.96875 | 4 | from collections import Counter
def Check_Binary_Representation(Num_1, Num_2):
Bin_1 = bin(Num_1)[2:]
Bin_2 = bin(Num_2)[2:]
Zeroes = abs(len(Bin_1)-len(Bin_2))
if len(Bin_2) > len(Bin_1):
Bin_1 = Zeroes*'0'+Bin_1
else:
Bin_2 = Zeroes*'0'+Bin_2
Dict_1 = Counter(Bin_1)
Dict_2 = Counter(Bin_2)
if Dict_1 == Dict_2:
return "True"
else:
return "False"
Num_1 = int(input("1st Number: "))
Num_2 = int(input("2nd Number: "))
print(Check_Binary_Representation(Num_1, Num_2))
|
4bd416b64aebef2483ac3d4faeecfc319e80a651 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day27/Size_of_Tuple.py | 384 | 3.640625 | 4 | import sys
Tuple_1 = ("A", 1, "B", 2, "C", 3)
Tuple_2 = ("Geek1", "Satyam", "hey you yeah you", "Tushar", "Geek3", "Aditya")
Tuple_3 = ((1, "Lion"), (2, "Tiger"), (3, "Fox"), (4, "Wolf"))
print(f"Size of Tuple_1: {str(sys.getsizeof(Tuple_1))} bytes")
print(f"Size of Tuple_2: {str(sys.getsizeof(Tuple_2))} bytes")
print(f"Size of Tuple_3: {str(sys.getsizeof(Tuple_3))} bytes")
|
d6e99faeff373c8ab030181c665115375da3ef2d | saubhagyav/100_Days_Code_Challenge | /DAYS/Day22/Counting_the_Frequency.py | 319 | 4.0625 | 4 | def Counting_the_frequency(Test_list):
Test_dict = {}
for items in Test_list:
Test_dict[items] = Test_list.count(items)
for key, value in Test_dict.items():
print(f"{key} : {value}")
Test_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
Counting_the_frequency(Test_list) |
4f5300f78579e7a9f6025cf18cc39a61c0d629a9 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day28/Occurrences_of_Characters.py | 344 | 3.828125 | 4 | def encode(Test_string):
count = 1
Result = ""
for i in range(len(Test_string)):
if (i+1) < len(Test_string) and (Test_string[i] == Test_string[i+1]):
count += 1
else:
Result += str(count)+Test_string[i]
count = 1
return Result
print(encode("ABBBBCCCCCCCCAB"))
|
7de91698b3caac78d74d5c09c8e338c414db5d51 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day18/Sorting_Dictionary_Using_Itemgetter.py | 509 | 3.625 | 4 | from operator import itemgetter
def Sort_list_Name_and_Age(Test_list):
Test_list.sort(key=itemgetter("Age", "Name"))
return Test_list
def Sort_list_Age(Test_list):
Test_list.sort(key=itemgetter('Age'))
return Test_list
Test_list = [{"Name": "Tushar", "Age": 20},
{"Name": "Aditya", "Age": 19},
{"Name": "Satyam", "Age": 21}]
print(f"Age Sorting: {Sort_list_Age(Test_list)}")
print(f"Name and Age Sorting: {Sort_list_Name_and_Age(Test_list)}")
|
5f8a8d0431696f22ca84bc4a73cf97b39a091507 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day32/Sort_tuple_by_Maximum_Values.py | 209 | 3.625 | 4 | def Sort_Tuple(Test_list):
Test_list.sort(key=lambda Sub: max(Sub), reverse=True)
return Test_list
Test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]
print(Sort_Tuple(Test_list))
|
f78a0db46b8f87c58f5b99517121ec59a6eb4c96 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day27/Join_Tuples_if_Similar_initial_elements.py | 323 | 3.75 | 4 | from collections import defaultdict
def Join_Tuples(Test_list):
Result = defaultdict(list)
for key, value in Test_list:
Result[key].append(value)
return [(key, *value) for key, value in Result.items()]
Test_list = [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
print(Join_Tuples(Test_list))
|
65fe822aaedb3fb8aa89d11c919e7db3ba321474 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day6/Maximum_of_Each_key_in_List.py | 486 | 3.765625 | 4 | def Maximum_Key(Test_list):
Result = {}
for dictionary in Test_list:
for key, value in dictionary.items():
if key in Result:
Result[key] = max(Result[key], value)
else:
Result[key] = value
return Result
Test_list = [{"Days": 8, "Code": 1, "Challenge": 9},
{"Days": 2, "Code": 9, "Challenge": 1},
{"Days": 5, "Code": 10, "Challenge": 7}]
print(Maximum_Key(Test_list))
|
f2f47ab9d8e116d43c619e88b3db0807b4d658f9 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day10/String_Palindrome.py | 203 | 4.1875 | 4 | def Palindrome(Test_String):
if Test_String == Test_String[::-1]:
return True
else:
return False
Test_String = input("Enter a String: ")
print(Palindrome(Test_String))
|
816b1917aa477d70f2ce4c30323d811ae7896bde | saubhagyav/100_Days_Code_Challenge | /DAYS/Day18/Remove_Keys_from_Dictionary.py | 387 | 4.1875 | 4 | def Remove_Keys(Test_dict, Remove_Value):
return {key: value for key, value in Test_dict.items() if key != Remove_Value}
N_value = int(input("Enter n: "))
Test_dict = {}
for i in range(N_value):
key = input("Key: ")
Value = int(input("Value: "))
Test_dict[key] = Value
Remove_Value = input("Which Key to Delete: ")
print(Remove_Keys(Test_dict, Remove_Value)) |
c2ccff1ef8bb8cd4089a941333a125e934139ff1 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day18/Extract_Unique_Dictionary_Values.py | 325 | 3.515625 | 4 | def Extract_Dictionary_Values(Test_dict):
return [sorted({numbers for ele in Test_dict.values() for numbers in ele})]
Test_dict = {'Challenges': [5, 6, 7, 8],
'are': [10, 11, 7, 5],
'best': [6, 12, 10, 8],
'for': [1, 2, 5]}
print(*(Extract_Dictionary_Values(Test_dict)))
|
52d46272af760df140aa8e4ba0bdaf87e587ed94 | fjsaca2001/proyectosPersonales | /python/funciones.py | 269 | 3.859375 | 4 | def insertar():
lista = []
b = True
while b:
dato = input("Ingrese un dato para agregar a la lista: ")
cond = input("Desea ingresar otro valor y/n: ")
lista.append(dato)
b = True if cond == "y" else print(lista)
insertar()
|
de68e76d6f9ec522b48bd55f48e1c42f2dcd0356 | phully/PythonHomeWork | /day05/Calculator/calculator.py | 4,381 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
该计算器思路:
1、递归寻找表达式中只含有 数字和运算符的表达式,并计算结果
2、由于整数计算会忽略小数,所有的数字都认为是浮点型操作,以此来保留小数
使用技术:
1、正则表达式
2、递归
请计算表达式: 1 - 2 * ( (60-30 +(-40.0/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )
"""
import re
def jj_ys(new_str):
'''加减运算函数'''
new_str = new_str.replace('--','+')
new_str = new_str.replace('+-', '-')
new_str = new_str.replace('-+', '-')
new_str = new_str.replace('++', '+')
print("新的运算公式:", new_str)
jj_neirong = re.split('\-|\+', new_str)
fuhao = re.findall('\-|\+', new_str)
jj_result = 0
for index, i in enumerate(jj_neirong):
if index == 0 and i is not '':
jj_result = float(i)
elif i is '':
jj_result = 0
elif fuhao[index - 1] is "-":
jj_result -= float(i)
elif fuhao[index - 1] is "+":
jj_result += float(i)
else:
print("错误!")
print("加减运算结果:", jj_result)
return jj_result
def chengchu(cc_ys):
'''乘除运算函数'''
print("乘除运算内容:", cc_ys)
cc_neirong = re.split('\*|\/', cc_ys)
cc_fuhao = re.findall('\*|\/', cc_ys)
cc_result = 1
for index, i in enumerate(cc_neirong):
if index == 0 and i is not '':
cc_result = float(i)
elif i is '':
cc_result = 0
elif cc_fuhao[index - 1] is "/":
cc_result /= float(i)
elif cc_fuhao[index - 1] is "*":
cc_result *= float(i)
else:
print("错误!")
return cc_result
def nei_kuohao_handle(nei_kuohao):
'''括号内运算函数'''
cc = re.findall("[^-+]+", nei_kuohao) # 找出不是“+”和“-”的字符串
jj = re.findall("(?<!\*|\/)([-+]+)",nei_kuohao) # 找出连接乘除运算的加减符号
print("处理前乘除运算内容:",cc)
cc1 = []
cc2 = []
cc3 = []
for index, i in enumerate(cc):
i = i.strip()
if i.endswith("*") or i.endswith("/"):
cc1.append(i+('-'+cc[index+1]))
cc2.append(index+1)
else:
cc1.append(i)
for index1 in cc2:
cc3.append(cc1[index1])
for item in cc3:
cc1.remove(item)
print("处理后乘除运算内容:", cc1)
print("加减符号:", jj)
new_l = []
for index, cc_ys in enumerate(cc1):
cc_ys_jg = str(chengchu(cc_ys))
print("乘除运算结果:", cc_ys_jg)
try:
if nei_kuohao.startswith("-"):
new_l.append(jj[index] + cc_ys_jg)
elif len(jj) > 1 :
new_l.append(cc_ys_jg + jj[index])
else:
new_l.append(cc_ys_jg + jj[index])
except:
new_l.append(cc_ys_jg)
print("乘除运算处理后内容:", new_l)
new_str = ""
for i1 in new_l:
new_str += i1
jj_jieguo = jj_ys(new_str)
return jj_jieguo
def zhu(gongshi):
print("处理前公式内容:", gongshi)
gongshi = gongshi.replace(" ", "")
gongshi = gongshi.replace("(", "(")
gongshi = gongshi.replace(")", ")")
if re.search("\([^()]+\)", gongshi):
nei_kuohao = re.search("\([^()]+\)", gongshi) # 找到公式最里层括号
nei_kuohao_neirong = nei_kuohao.group().strip("()") # 去除括号只保留括号里内容
print("最里层括号内容:", nei_kuohao_neirong)
nei_kuohao_jieguo=nei_kuohao_handle(nei_kuohao_neirong) # 括号内容处理
gongshi = re.sub("\([^()]+\)", str(nei_kuohao_jieguo), gongshi, 1) # 用处理结果替代括号内容
print("最里层括号运算结果:", nei_kuohao_jieguo)
print("替换后公式:", gongshi)
return zhu(gongshi) # 递归直到找不到括号为止
else:
nei_kuohao_jieguo=nei_kuohao_handle(gongshi)
print("最后结果:",nei_kuohao_jieguo)
if __name__ == "__main__":
gongshi = "-1 - 2 *((-60+30+(-40/5)*(-9-2*-5/30-7/3*99/4*2998+10/-568/14))-(-4*-3)/(16-3*2))+3"
a = zhu(gongshi)
# 1 - 2 * ( (60-30 +(-40.0/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )
|
9866933ef4f88513e71df0a966ccb7af00eb1e4e | Gkish/Fundamentals-of-data-science | /Assignment 3.py | 8,913 | 3.828125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Assignment 3
#
# Welcome to Assignment 3. This will be even more fun. Now we will calculate statistical measures.
#
# ## You only have to pass 4 out of 7 functions
#
# Just make sure you hit the play button on each cell from top to down. There are seven functions you have to implement. Please also make sure than on each change on a function you hit the play button again on the corresponding cell to make it available to the rest of this notebook.
# This notebook is designed to run in a IBM Watson Studio default runtime (NOT the Watson Studio Apache Spark Runtime as the default runtime with 1 vCPU is free of charge). Therefore, we install Apache Spark in local mode for test purposes only. Please don't use it in production.
#
# In case you are facing issues, please read the following two documents first:
#
# https://github.com/IBM/skillsnetwork/wiki/Environment-Setup
#
# https://github.com/IBM/skillsnetwork/wiki/FAQ
#
# Then, please feel free to ask:
#
# https://coursera.org/learn/machine-learning-big-data-apache-spark/discussions/all
#
# Please make sure to follow the guidelines before asking a question:
#
# https://github.com/IBM/skillsnetwork/wiki/FAQ#im-feeling-lost-and-confused-please-help-me
#
#
# If running outside Watson Studio, this should work as well. In case you are running in an Apache Spark context outside Watson Studio, please remove the Apache Spark setup in the first notebook cells.
# In[2]:
from IPython.display import Markdown, display
def printmd(string):
display(Markdown('# <span style="color:red">'+string+'</span>'))
if ('sc' in locals() or 'sc' in globals()):
printmd('<<<<<!!!!! It seems that you are running in a IBM Watson Studio Apache Spark Notebook. Please run it in an IBM Watson Studio Default Runtime (without Apache Spark) !!!!!>>>>>')
# In[3]:
get_ipython().system('pip install pyspark==2.4.5')
# In[4]:
try:
from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession
except ImportError as e:
printmd('<<<<<!!!!! Please restart your kernel after installing Apache Spark !!!!!>>>>>')
# In[5]:
sc = SparkContext.getOrCreate(SparkConf().setMaster("local[*]"))
spark = SparkSession .builder .getOrCreate()
# All functions can be implemented using DataFrames, ApacheSparkSQL or RDDs. We are only interested in the result. You are given the reference to the data frame in the "df" parameter and in case you want to use SQL just use the "spark" parameter which is a reference to the global SparkSession object. Finally if you want to use RDDs just use "df.rdd" for obtaining a reference to the underlying RDD object. But we discurage using RDD at this point in time.
#
# Let's start with the first function. Please calculate the minimal temperature for the test data set you have created. We've provided a little skeleton for you in case you want to use SQL. Everything can be implemented using SQL only if you like.
# In[6]:
def minTemperature(df,spark):
minRow=df.agg({"temperature": "min"}).collect()[0]
mintemp = minRow["min(temperature)"]
return spark.sql("SELECT (temperature) as mintemp from washing").first().mintemp
# Please now do the same for the mean of the temperature
# In[7]:
def meanTemperature(df,spark):
avgRow=df.agg({"temperature": "avg"}).collect()[0]
avgtemp = avgRow["avg(temperature)"]
return spark.sql("SELECT (temperature) as meantemp from washing").first().meantemp
# Please now do the same for the maximum of the temperature
# In[8]:
def maxTemperature(df,spark):
maxRow=df.agg({"temperature": "max"}).collect()[0]
maxtemp = maxRow["max(temperature)"]
return spark.sql("SELECT (temperature) as maxtemp from washing").first().maxtemp
# Please now do the same for the standard deviation of the temperature
# In[9]:
def sdTemperature(df,spark):
temprddrow = df.select('temperature').rdd #in row(temp=x) format
temprdd = temprddrow.map(lambda x : x["temperature"]) #only numbers
temp = temprdd.filter(lambda x: x is not None).filter(lambda x: x != "") #remove None params
n = float(temp.count())
sum=temp.sum()
mean =sum/n
from math import sqrt
sd=sqrt(temp.map(lambda x : pow(x-mean,2)).sum()/n)
return spark.sql("SELECT (temperature) as sdtemp from washing").first().sdtemp
# Please now do the same for the skew of the temperature. Since the SQL statement for this is a bit more complicated we've provided a skeleton for you. You have to insert custom code at four positions in order to make the function work. Alternatively you can also remove everything and implement if on your own. Note that we are making use of two previously defined functions, so please make sure they are correct. Also note that we are making use of python's string formatting capabilitis where the results of the two function calls to "meanTemperature" and "sdTemperature" are inserted at the "%s" symbols in the SQL string.
# In[10]:
def skewTemperature(df,spark):
temprddrow = df.select('temperature').rdd #in row(temp=x) format
temprdd = temprddrow.map(lambda x : x["temperature"]) #only numbers
temp = temprdd.filter(lambda x: x is not None).filter(lambda x: x != "") #remove None params
n = float(temp.count())
sum=temp.sum()
mean =sum/n
from math import sqrt
sd=sqrt(temp.map(lambda x : pow(x-mean,2)).sum()/n)
skew=n*(temp.map(lambda x:pow(x-mean,3)/pow(sd,3)).sum())/(float(n-1)*float(n-2))
return spark.sql
# Kurtosis is the 4th statistical moment, so if you are smart you can make use of the code for skew which is the 3rd statistical moment. Actually only two things are different.
# In[11]:
def kurtosisTemperature(df,spark):
temprddrow = df.select('temperature').rdd
temprdd = temprddrow.map(lambda x : x["temperature"])
temp = temprdd.filter(lambda x: x is not None).filter(lambda x: x != "")
n = float(temp.count())
sum=temp.sum()
mean =sum/n
from math import sqrt
sd=sqrt(temp.map(lambda x : pow(x-mean,2)).sum()/n)
kurtosis=temp.map(lambda x:pow(x-mean,4)).sum()/(pow(sd,4)*(n))
# Just a hint. This can be solved easily using SQL as well, but as shown in the lecture also using RDDs.
# In[12]:
def correlationTemperatureHardness(df,spark):
return spark.sql("SELECT (temperature,hardness) as temperaturehardness from washing").first().temperaturehardness
# Now it is time to grab a PARQUET file and create a dataframe out of it. Using SparkSQL you can handle it like a database.
# In[13]:
get_ipython().system('wget https://github.com/IBM/coursera/blob/master/coursera_ds/washing.parquet?raw=true')
get_ipython().system('mv washing.parquet?raw=true washing.parquet')
# In[14]:
df = spark.read.parquet('washing.parquet')
df.createOrReplaceTempView('washing')
df.show()
# Now let's test the functions you've implemented
# In[15]:
min_temperature = 0
mean_temperature = 0
max_temperature = 0
sd_temperature = 0
skew_temperature = 0
kurtosis_temperature = 0
correlation_temperature = 0
# In[16]:
min_temperature = minTemperature(df,spark)
print(min_temperature)
# In[17]:
mean_temperature = meanTemperature(df,spark)
print(mean_temperature)
# In[18]:
max_temperature = maxTemperature(df,spark)
print(max_temperature)
# In[19]:
sd_temperature = sdTemperature(df,spark)
print(sd_temperature)
# In[20]:
skew_temperature = skewTemperature(df,spark)
print(skew_temperature)
# In[21]:
kurtosis_temperature = kurtosisTemperature(df,spark)
print(kurtosis_temperature)
# In[22]:
correlation_temperature = correlationTemperatureHardness(df,spark)
print(correlation_temperature)
# Congratulations, you are done, please submit this notebook to the grader.
# We have to install a little library in order to submit to coursera first.
#
# Then, please provide your email address and obtain a submission token on the grader’s submission page in coursera, then execute the subsequent cells
#
# ### Note: We've changed the grader in this assignment and will do so for the others soon since it gives less errors
# This means you can directly submit your solutions from this notebook
# In[23]:
get_ipython().system('rm -f rklib.py')
get_ipython().system('wget https://raw.githubusercontent.com/IBM/coursera/master/rklib.py')
# In[24]:
from rklib import submitAll
import json
key = "Suy4biHNEeimFQ479R3GjA"
email = "kishorenocs@gmail.com"
token = "xB9omYAfMgiQ7aAR"
# In[32]:
parts_data = {}
parts_data["FWMEL"] = json.dumps(min_temperature)
parts_data["3n3TK"] = json.dumps(mean_temperature)
parts_data["KD3By"] = json.dumps(max_temperature)
parts_data["06Zie"] = json.dumps(sd_temperature)
parts_data["Qc8bI"] = json.dumps(skew_temperature)
parts_data["LoqQi"] = json.dumps(kurtosis_temperature)
parts_data["ehNGV"] = json.dumps(correlation_temperature)
submitAll(email, token, key, parts_data)
# In[ ]:
# In[ ]:
|
114547be0035b90ea6f8e47883f3d1e62a7e9906 | victonpp/Algoritmos-ADS20171 | /ALGORITMOS/Faça um Programa que leia 20 números inteiros e armazene-os num vetor. Armazene os números pares no vetor PAR e os números IMPARES no vetor impar. Imprima os três vetores.py | 242 | 3.671875 | 4 | numero=[]
par=[]
impar=[]
for i in range (4):
digito=int(input("Digite um número: "))
numero.append(digito)
if (digito%2)==0:
par.append(digito)
else:
impar.append(digito)
print(numero)
print(par)
print(impar) |
9869989a61b358b5372aa0205063cffc47c27842 | victonpp/Algoritmos-ADS20171 | /ALGORITMOS/DESAFIOFaça um algoritmo que leia um número inteiro calcule o seu número de Fibonacci.py | 278 | 3.9375 | 4 | nfinal = 0
while (nfinal <= 0):
nfinal = int(input('Você quer que a série de Fibonacci vá até qual número '))
if (nfinal <= 0):
print('O número deve ser positivo!')
f1 = 1
print (f1)
f2 = 1
for i in range(1, nfinal):
print(f2)
f3 = f1 + f2
f1 = f2
f2 = f3
|
08ff60fcb166b3f5158a437e70015b7929ce61a3 | victonpp/Algoritmos-ADS20171 | /ALGORITMOS/sistema deve perguntar quantos cigarros a pessoa fuma por dia e por quantos anos ela já fuma.py | 154 | 3.71875 | 4 | C=int(input("Quantos cigarros você fuma por dia?"))
D=int(input("Faz quantos anos que você fuma?"))
print("Dias perdidos: %2.0f" %((C*10*365*D)/1440))
|
718d4999826a00c394434ca15ac7a28d8061f0ae | victonpp/Algoritmos-ADS20171 | /ALGORITMOS/O sistema deve informar a o consumo médio (kml).py | 229 | 3.8125 | 4 | k1=int(input("Digite os km no momento em que o tanque é cheio: "))
k2=int(input("Digite os km percorridos: "))
g=int(input("Digite a quantidade necessária para completar o tanque: "))
m=(k2-k1)/g
print("Média de:",m, "km/l ")
|
adfb29dc678d620373b3902a661c9c9148f2c799 | japablaza/DevOps | /Python/101/game02.py | 513 | 3.671875 | 4 | #/usr/bin/python
# Este es el juego de los datos
from random import randint as ri
computador = ri(1,6)
usuario = int(input('Dame un numero entre el 1 y el 6:\n'))
print(f'El computador saco: {computador}')
if computador == usuario:
print('\n**********')
print('Hay un empate')
print('**********')
elif computador > usuario:
print('\n**********')
print('El computador gano')
print('**********')
else:
print('\n**********')
print('El usuario gano')
print('**********') |
d0558531a0a1e78eceda6f22bb2eca1f4588691a | vergi1iu5/CodeForce-Solutions | /Young_Physicist.py | 1,095 | 3.5625 | 4 | ################################################
#algorith:
#
#open input file
#read first line and asses:
# if interger <= 0
# print yes, end program
#
#for i in range(first line - 1)
# read next line
# divide into xi, yi, and zi (function)
# if i is 0
# if x + xi or y + yi or z + zi is not 0
# break
# else
# add xi, yi, and zi to each
#else
# return no
##################################################
def main(inFileStr):
inFile = open(inFileStr, "r")
numVec = inFile.readline()
if numVec == 0:
return "YES"
else:
return addVectors(int(numVec), inFile)
def addVectors(numVec, inFileObj):
x, y, z = 0, 0, 0
for i in range(numVec - 1, -1, -1):
xi, yi, zi = divideInputs(inFileObj)
if i == 0:
if ((x + xi != 0) or (y + yi != 0) or (z + zi != 0)):
return "NO"
else:
x = x + xi
y = y + yi
z = z + zi
else:
return "YES"
def divideInputs(inFileObj):
nextVect = inFileObj.readline().split(" ")
return int(nextVect[0]), int(nextVect[1]), int(nextVect[2])
if __name__ == '__main__':
fileStr = input("Enter file name: ")
print(main(fileStr))
|
2c3195375addf50e0de113f0d5a131c6da7ec6fc | offscript/python_practice | /company_manager/company.py | 592 | 3.515625 | 4 | import employee
class Company():
def __init__(self, revenue, employees):
self.revenue = revenue
def generate_wages(revenue):
executive_wages = revenue * .01
manager_wages = revenue .001
human_resources_wages = revenue * .0005
sales_associate_wages = revenue * .0003
'''
def generate_employees(employees):
def generate_executive():
tom = employee.Executive(100000, "male", "black", 65, 20)
def generate_managers():
def generate human_resources():
def generate_sales_associates():
'''
tom = employee.Executive(100000, "male", "black", 65, 20)
print(tom.wage) |
59542f43766de71953f8dd4d9af74dbe89096558 | cormacdoyle/BattleShips | /PycharmProjects/Computer science/new.py | 44,378 | 3.984375 | 4 | import pygame, random
print("The user is given a start screen, from here they choose to start, go to high score screen, or quit.")
print("When the user chooses start they will be presented with the game board.")
print("If the user looks in the top right they will see a ‘status’ bar this bar provides basic instructions to the user. ")
print("If the user looks in the bottom left corner they will see a plus and a minus sign and two bars that say sideways and up. ")
print("When creating their ships the user will select their direction (up or sideways) and their ship size (controlled using + and -) their ship can be either 1 blocks, 2 blocks or 3 blocks.")
print("Once the user has placed 5 ships of their choosing they may begin to fire at the enemy ships, this consists of clicking squares on the right side of the screen.")
print("If an enemy ship is hit the block will turn green, if your shot is a miss the shot will turn red. ")
print("When the takes their shot the computer will automatically take theirs instantaneously, this means no wait times!")
print("The user has 15 shots to get as high a score as possible in order to beat the computer. ")
print("If the user does beat the computer they will move on to level 2 which is very similar to level 1 except that the user can now only place 3 ships.")
print("If the user wins level 2 they will be given the option to proceed back to the home screen.")
print("Once at the home screen menu they can select ‘highscore’ to view their top scores.")
# Colours
light_green = (34, 177, 76)
dark_green = (68, 119, 60)
black = (0, 0, 0)
shiptestcolour = (0, 50, 255)
shipfinalcolour = (0, 200, 255)
white = (255, 255, 255)
red = (255, 0, 0)
gold = (255, 215, 0)
# Font
pygame.font.init()
myfont = pygame.font.SysFont('arial bold', 36)
mybigfont = pygame.font.SysFont('arial bold', 50)
intro_title_font = pygame.font.SysFont('arial bold', 140)
big_title_font = pygame.font.SysFont('arial bold', 80)
highscore_list = []
# Intro Screen click logic
def mouse_selction(x, y):
if (x > 100 and x < 500) and (y > 200 and y < 400):
level_one(True)
return False
if (x > 700 and x < 1100) and (y > 200 and y < 400):
highscore()
if (x > 525 and x < 675) and (y > 450 and y < 550):
quit()
# Loads intro screen
def intro_screen(state):
# Sets display window
intro_display = pygame.display.set_mode([1200, 600])
# Makes mouse visible
pygame.mouse.set_visible(True)
while state:
# Background
pygame.draw.rect(intro_display, light_green, (0, 0, 1200, 600))
# Tiles
pygame.draw.rect(intro_display, dark_green, (100, 200, 400, 200))
pygame.draw.rect(intro_display, dark_green, (700, 200, 400, 200))
pygame.draw.rect(intro_display, dark_green, (525, 450, 150, 100))
# Text
txt_start = big_title_font.render("START", True, black)
txt_highscore = big_title_font.render("HIGHSCORE", True, black)
txt_quit = big_title_font.render("QUIT", True, black)
txt_battleships = intro_title_font.render("Battleships_1.0", True, dark_green)
# Blit
intro_display.blit(txt_start, (200, 275))
intro_display.blit(txt_highscore, (730, 275))
intro_display.blit(txt_quit, (530, 475))
intro_display.blit(txt_battleships, (250, 50))
# UI
for event in pygame.event.get():
# Quit button
if event.type == pygame.QUIT:
quit()
# If there is a mouse click
if event.type == pygame.MOUSEBUTTONDOWN:
# Unpack two variables from pygame.mouse function x and y position of mouse
x, y = pygame.mouse.get_pos()
# Activate click logic
state = mouse_selction(x, y)
# Updates screen
pygame.display.update()
# Function controls logic for computer to choose tiles to click
def computer_move():
x_length = 0
y_length = 0
x = random.randint(0, 9)
y = random.randint(0, 9)
y_or_x = random.randint(0, 1)
if y_or_x:
x_length = random.randint(0, 3)
else:
y_length = random.randint(0, 3)
return x, y, x_length, y_length
# Function controls tip on screen at each moment during game
def tutorial(state):
if state == 0:
return "Place your ships!"
if state == 1:
return "Choose where to bomb!"
if state == 2:
return "Player's turn"
if state == 3:
return "Miss, try again!"
if state == 4:
return "Already a ship placed here"
if state == 5:
return "Player's turn!"
if state == 6:
return "Player's turn"
if state == -5:
return "Player's turn!"
# Loads all paramteres for level one
def highscore():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: # when Exit button in the top right is pressed the window will close
quit()
break
pygame.font.init()
myfont = pygame.font.SysFont('arial bold', 36)
mybigfont = pygame.font.SysFont('arial bold', 40)
highscore_display = pygame.display.set_mode([800, 600])
highscore_display.fill(red)
keys = pygame.key.get_pressed()
highscorefont = mybigfont.render("Highscores:", True, black)
highscore_display.blit(highscorefont, (300, 50))
copy_of_highscore_list = highscore_list[:]
if len(highscore_list) > 0:
if len(highscore_list) == 1:
highscore1 = myfont.render("1) " + str(max(highscore_list)), True, white)
highscore_display.blit(highscore1, (50, 100))
elif len(highscore_list) == 2:
bestscore1 = max(copy_of_highscore_list)
copy_of_highscore_list.remove(bestscore1)
bestscore2 = max(copy_of_highscore_list)
highscore1 = mybigfont.render("1) " + str(bestscore1), True, white)
highscore_display.blit(highscore1, (50, 100))
highscore2 = mybigfont.render("2) " + str(bestscore2) , True, white)
highscore_display.blit(highscore2, (50, 150))
elif len(highscore_list) >= 3:
bestscore1 = max(copy_of_highscore_list)
copy_of_highscore_list.remove(bestscore1)
bestscore2 = max(copy_of_highscore_list)
copy_of_highscore_list.remove(bestscore2)
bestscore3 = max(copy_of_highscore_list)
highscore1 = mybigfont.render("1) " + str(bestscore1), True, white)
highscore_display.blit(highscore1, (50, 100))
highscore2 = mybigfont.render("2) " + str(bestscore2) , True, white)
highscore_display.blit(highscore2, (50, 150))
highscore3 = mybigfont.render("3) " + str(bestscore3), True, white)
highscore_display.blit(highscore3, (50, 200))
else:
highscore3 = myfont.render("Oops no scores stored yet.", True, white)
highscore_display.blit(highscore3, (50,100))
pressspacetointro = myfont.render("Press Space to return to Home Page", True, black)
highscore_display.blit(pressspacetointro, (50, 500))
if keys[pygame.K_SPACE]:
intro_screen(True)
pygame.display.update()
def youlost():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: # when Exit button in the top right is pressed the window will close
quit()
break
pygame.font.init()
myfont = pygame.font.SysFont('arial bold', 36)
mybigfont = pygame.font.SysFont('arial bold', 40)
youlost_display = pygame.display.set_mode([800, 600])
youlost_display.fill(red)
keys = pygame.key.get_pressed()
losefont = mybigfont.render("You Lost", True, black)
youlost_display.blit(losefont, (100, 300))
pressqtoquit = myfont.render("Press Q to quit", True, white)
youlost_display.blit(pressqtoquit, (100, 400))
pressspacetointro = myfont.render("Press SPACE to return to home page", True, white)
youlost_display.blit(pressspacetointro, (100, 450))
if keys[pygame.K_q]:
quit()
break
if keys[pygame.K_SPACE]:
intro_screen(True)
pygame.display.update()
def tie_game():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: # when Exit button in the top right is pressed the window will close
quit()
break
pygame.font.init()
myfont = pygame.font.SysFont('arial bold', 36)
mybigfont = pygame.font.SysFont('arial bold', 40)
youtied_display = pygame.display.set_mode([800, 600])
youtied_display.fill(white)
keys = pygame.key.get_pressed()
losefont = mybigfont.render("You Tied.", True, black)
youtied_display.blit(losefont, (100, 100))
pressspacetolevel2 = myfont.render("Press SPACE to retry Level 1", True, black)
youtied_display.blit(pressspacetolevel2, (100, 200))
pressqtoquit = myfont.render("Press Q to Quit", True, black)
youtied_display.blit(pressqtoquit, (100, 250))
if keys[pygame.K_SPACE]:
level_one(True)
if keys[pygame.K_q]:
quit()
break
pygame.display.update()
def tie_game_2():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: # when Exit button in the top right is pressed the window will close
quit()
break
pygame.font.init()
myfont = pygame.font.SysFont('arial bold', 36)
mybigfont = pygame.font.SysFont('arial bold', 40)
youtied_display = pygame.display.set_mode([800, 600])
youtied_display.fill(white)
keys = pygame.key.get_pressed()
losefont = mybigfont.render("You Tied.", True, black)
youtied_display.blit(losefont, (100, 100))
pressspacetolevel2 = myfont.render("Press SPACE to retry Level 2", True, black)
youtied_display.blit(pressspacetolevel2, (100, 200))
pressqtoquit = myfont.render("Press Q to Quit", True, black)
youtied_display.blit(pressqtoquit, (100, 250))
if keys[pygame.K_SPACE]:
level_two(True)
if keys[pygame.K_q]:
quit()
break
pygame.display.update()
def win_level_two():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: # when Exit button in the top right is pressed the window will close
quit()
break
pygame.font.init()
myfont = pygame.font.SysFont('arial bold', 36)
mybigfont = pygame.font.SysFont('arial bold', 40)
youwin2_display = pygame.display.set_mode([800, 600])
youwin2_display.fill(gold)
keys = pygame.key.get_pressed()
win2font = mybigfont.render("Thanks for playing!", True, black)
youwin2_display.blit(win2font, (100, 100))
pressqtoquit = myfont.render("Press Q to go to QUIT!", True, black)
youwin2_display.blit(pressqtoquit, (100, 200))
level1_to_level2 = myfont.render("Press SPACE to return to the Home Screen", True, black)
youwin2_display.blit(level1_to_level2, (100, 250))
if keys[pygame.K_SPACE]:
intro_screen(True)
break
if keys[pygame.K_q]:
quit()
break
pygame.display.update()
def win_level_one():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: # when Exit button in the top right is pressed the window will close
quit()
break
pygame.font.init()
myfont = pygame.font.SysFont('arial bold', 36)
mybigfont = pygame.font.SysFont('arial bold', 40)
youwin_display = pygame.display.set_mode([800, 600])
youwin_display.fill(gold)
keys = pygame.key.get_pressed()
winfont = mybigfont.render("You Won!", True, black)
youwin_display.blit(winfont, (100, 100))
pressspacetolevel2 = myfont.render("Press SPACE to go to level 2!", True, black)
youwin_display.blit(pressspacetolevel2, (100, 200))
level1_to_level2 = myfont.render("Level 2 has fewer ships, good luck!", True, black)
youwin_display.blit(level1_to_level2, (100, 250))
pressqtoquit = myfont.render("Press Q to Quit", True, black)
youwin_display.blit(pressqtoquit, (100, 300))
if keys[pygame.K_SPACE]:
level_two(True)
break
if keys[pygame.K_q]:
quit()
break
pygame.display.update()
def level_two(state):
clock = pygame.time.Clock()
pygame.font.init()
myfont = pygame.font.SysFont('arial bold', 25)
mybigfont = pygame.font.SysFont('arial bold', 40)
# Starts tip at tip #1
tut_count = 0
# Allows game inputs to be locked, True is unlocked, False is locked
game_lock = True
# Sets display parameters
display = pygame.display.set_mode([1280, 720])
pygame.display.set_caption("Battleships") # name this screen "Battleships"
# Mouse is visible
pygame.mouse.set_visible(True)
# Level 1 allows you to use 5 ships
ships_left = 3
# Unpacks x and y position of mouse to variables l and k
l, k = pygame.mouse.get_pos()
# Set ship size to 1 block
ship_size_x = 1
ship_size_y = 1
# x_or_y is a variable that controls the orientation of the ship , 0 is sideways 1 is up
x_or_y = 0
# Sets coords of first grid for x axis
grid_coords = [100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, -50]
# Sets coords of second grid for x axis
computer_grid_coords = [740, 790, 840, 890, 940, 990, 1040, 1090, 1140, 1190]
# Sets inital state to an off screen position
x_boat_coords = [11, 11, 11, 11, 11, 11]
y_boat_coords = [11, 11, 11, 11, 11, 11]
# Sets initial to a length of one
x_boat_length = [1, 1, 1, 1, 1, 1]
y_boat_length = [1, 1, 1, 1, 1, 1]
# Intializes score
ai_score = 0
user_score = 0
# intializes Shot counter
shots_left = 15
# User grid is a 10x10 multi dimensional array which uses integers to denote the status of each block in the grid
user_grid = [
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]
]
computer_grid = [
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]
[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]
]
]
while True:
# Iterated through user grid
for i in range(10):
for x in range(10):
# The integer 1 denotes a ship position
if user_grid[i][x] == 1:
pygame.draw.rect(display, black, (grid_coords[i], grid_coords[x], 50, 50))
# The integer 2 denotes a missed shot
if user_grid[i][x] == 2:
pygame.draw.rect(display, red, (grid_coords[i], grid_coords[x], 50, 50))
# The integer 3 denotes a hit ship
if user_grid[i][x] == 3:
pygame.draw.rect(display, (0, 255, 0), (grid_coords[i], grid_coords[x], 50, 50))
for i in range(10):
for x in range(10):
# The integer 2 will denote a missed shot
if computer_grid[i][x] == 2:
pygame.draw.rect(display, red, (computer_grid_coords[i], grid_coords[x], 50, 50))
# The integer 3 will denote a hit ship
if computer_grid[i][x] == 3:
pygame.draw.rect(display, (0, 255, 0), (computer_grid_coords[i], grid_coords[x], 50, 50))
pygame.display.update()
# Ship size is a single integer and thus must be multiplied by 50 to fit to the 50 x 50 block size
ship_x = 50 * ship_size_x
ship_y = 50 * ship_size_y
for event in pygame.event.get():
if event.type == pygame.MOUSEMOTION:
# Cast the position of the mouse to variables l and k
l, k = pygame.mouse.get_pos()
if event.type == pygame.MOUSEBUTTONDOWN:
# If the mouse is clicked on the increase ship size tile
if (l > 20 and l < 85) and (k > 650 and k < 700):
# Checks upper and lower bounds of size of ship
if (ship_size_x > 0 and ship_size_x < 4) and (ship_size_y > 0 and ship_size_y < 3):
# Applies increase in ship size to correct axis based on x_or_y variable
if x_or_y == 1:
ship_size_y = ship_size_y + 1
if x_or_y == 0:
ship_size_x = ship_size_x + 1
# Handles the clicking of the decrease size button
if (l > 110 and l < 175) and (k > 650 and k < 700):
# Check upper and lower bounds
if (ship_size_x > 0 and ship_size_x < 4) and (ship_size_y > 0 and ship_size_y < 3):
# Applies decrease to correct axis
if x_or_y == 1:
ship_size_y = ship_size_y - 1
if x_or_y == 0:
ship_size_x = ship_size_x - 1
# Changes the orientation of the ship
if (l > 290 and l < 385) and (k > 650 and k < 700):
x_or_y = 1
ship_size_x = 1
# Chnages the orientation of the ship
if (l > 420 and l < 515) and (k > 650 and k < 700):
x_or_y = 0
ship_size_y = 1
# Gamelock breakc point
if game_lock:
if ships_left != 0:
# If a ship is placed in the first grid
if (l > 100 and l < 600) and (k > 100 and k < 600):
l = (l * 50) // 50
k = (k * 50) // 50
# x spot reduces the position of the click to an index for the coordinate system that is grid
x_spot = int(round((l - 124) / 50))
x_boat_coords[5 - ships_left] = x_spot
# include boat length information when placing ship
x_boat_length[5 - ships_left] = ship_size_x - 1
y_spot = int(round(k - 124) / 50)
y_boat_coords[5 - ships_left] = y_spot
y_boat_length[5 - ships_left] = ship_size_y - 1
# The case in which a ship is placed above a ship already present
if user_grid[x_spot][y_spot] == 1:
tut_count = 4
ships_left = ships_left + 1
# Assign value of 1 in grid system to signnify a ship present
user_grid[x_spot][y_spot] = 1
# Adjusts if ship is larger than 1 unit so that etire ship is saved
if ship_size_x > 1:
for i in x_boat_length:
user_grid[x_spot + i][y_spot] = 1
if ship_size_y > 1:
for i in y_boat_length:
user_grid[x_spot][y_spot + i] = 1
# Reduces number of ships left
ships_left = ships_left - 1
# Accounts for what to do when all ships are used
if ships_left == 0:
ship_size_x == 1
ship_size_y == 1
# Change tip
tut_count = 1
# Computer will place 5 ships at random using random computer_move() function
for i in range(5):
x, y, xl, yl = computer_move()
computer_grid[x][y] = 1
for i in range(xl):
# Accounts for ship size which extends the bounds of the grid
if (x + i) > 9:
computer_grid[x][y] = 1
else:
computer_grid[x + i][y] = 1
for i in range(yl):
if (y + i) > 9:
computer_grid[x][y]
else:
computer_grid[x][y + i] = 1
tut_count = -5
# Another game_lock breakpoint
if game_lock:
# Manages button clicks in second grid
if (l > 740 and l < 1250) and (k > 100 and k < 600):
# Reduces position of click to an index
x_spot = int(round((l - 774) / 50))
y_spot = int(round(k - 124) / 50)
# Hit logic, if cell point = 1 then a ship is present
if computer_grid[x_spot][y_spot] == 1:
user_score = user_score + 1
tut_count = 2
computer_grid[x_spot][y_spot] = 3
else:
# if no ship present show miss
computer_grid[x_spot][y_spot] = 2
tut_count = 3
# Reduces shop counter
shots_left = shots_left - 1
# Change tip
tut_count = 5
# Unpacks random nits from computer logic
x, y, xl, yl = computer_move()
tut_count * -1
# Accoutns for computer hit logic
if user_grid[x][y] == 1:
# Change tip
tut_count = 6
# Increase ai score
ai_score = ai_score + 1
# Changes block to hit block
user_grid[x][y] = 3
else:
# If no hit change to a miss
user_grid[x][y] = 2
# Locks ths game when user runs out of shots
if shots_left == 0:
user_score_constant = user_score
highscore_list.append(user_score_constant)
game_lock = False
if user_score == ai_score:
tie_game_2()
break
elif user_score > ai_score:
win_level_two()
break
elif user_score < ai_score:
display.fill(red)
pygame.display.update()
youlost()
break
# If user clicks quit game will end
if event.type == pygame.QUIT:
quit()
# Sets y bound
y_text = 630
# Draw Buttons and tiles
pygame.draw.rect(display, shipfinalcolour, (0, 0, 640, 720))
pygame.draw.rect(display, (0, 0, 128), (640, 0, 640, 720))
pygame.draw.rect(display, black, (20, 650, 65, 50))
pygame.draw.rect(display, shipfinalcolour, (22, 652, 60, 45))
pygame.draw.rect(display, black, (110, 650, 65, 50))
pygame.draw.rect(display, shipfinalcolour, (112, 653, 60, 45))
pygame.draw.rect(display, black, (290, 650, 95, 50))
pygame.draw.rect(display, shipfinalcolour, (292, 652, 90, 45))
pygame.draw.rect(display, black, (420, 650, 95, 50))
pygame.draw.rect(display, shipfinalcolour, (422, 652, 90, 45))
pygame.font.init()
# Initializes font values
# Creates text files to be used
text1 = myfont.render("Change Ship Size", True, (255, 255, 255))
display.blit(text1, (25, y_text))
text2 = mybigfont.render("+", True, (255, 255, 255))
display.blit(text2, (45, y_text + 30))
text3 = mybigfont.render("-", True, (255, 255, 255))
display.blit(text3, (140, y_text + 30))
text4 = myfont.render("Ship Orientation", True, (255, 255, 255))
display.blit(text4, (350, y_text))
text5 = myfont.render("Up", True, (255, 255, 255))
display.blit(text5, (325, y_text + 38))
text6 = myfont.render("User Score: " + (str(user_score)), True, (255, 255, 255))
display.blit(text6, (800, 650))
text7 = myfont.render("Computer Score: " + str(ai_score), True, (255, 255, 255))
display.blit(text7, (1000, 650))
text8 = myfont.render("Sideways", True, (255, 255, 255))
display.blit(text8, (430, y_text + 38))
text9 = mybigfont.render("Ships Left: " + (str(ships_left)), True, (255, 255, 255))
display.blit(text9, (50, 25))
text10 = myfont.render("Status: " + tutorial(tut_count), True, (255, 255, 255))
display.blit(text10, (800, 25))
text11 = mybigfont.render("Shots left: " + (str(shots_left)), True, (255, 255, 255))
display.blit(text11, (250, 25))
# Draw grid
for i in range(0, 11):
coordinate_change_blk_2 = i * 50 + 740
coordinate_change = i * 50 + 100
pygame.draw.line(display, [0, 0, 0], (coordinate_change, 100), (coordinate_change, 600), 4)
pygame.draw.line(display, [0, 0, 0], (100, coordinate_change), (600, coordinate_change), 4)
pygame.draw.line(display, [0, 0, 0], (coordinate_change_blk_2, 100), (coordinate_change_blk_2, 600), 4)
pygame.draw.line(display, [0, 0, 0], (740, coordinate_change), (1240, coordinate_change), 4)
# Draw grid characters
for i in range(0, 10):
x_coord_change_blk_2 = i * 50 + 760
x_coord_change = i * 50 + 120
y_coord_change = i * 50 + 110
Letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
pygame.font.init()
myfont = pygame.font.SysFont('arial bold', 36)
text = myfont.render(Letters[i], True, (255, 255, 255))
numbers = myfont.render(numbers[i], True, (255, 255, 255))
display.blit(text, (x_coord_change, 65))
display.blit(numbers, (65, y_coord_change))
display.blit(text, (x_coord_change_blk_2, 65))
display.blit(numbers, (700, y_coord_change))
# Draw block on grid as mouse moves
if (l > 100 and l < 600) and (k > 100 and k < 600):
pygame.draw.rect(display, black, (l - 25, k - 25, ship_x, ship_y))
pygame.display.update()
clock.tick(100)
def level_one(state):
clock = pygame.time.Clock()
pygame.font.init()
myfont = pygame.font.SysFont('arial bold', 25)
mybigfont = pygame.font.SysFont('arial bold', 40)
# Starts tip at tip #1
tut_count = 0
# Allows game inputs to be locked, True is unlocked, False is locked
game_lock = True
# Sets display parameters
display = pygame.display.set_mode([1280, 720])
pygame.display.set_caption("Battleships") # name this screen "Battleships"
# Mouse is visible
pygame.mouse.set_visible(True)
# Level 1 allows you to use 5 ships
ships_left = 5
# Unpacks x and y position of mouse to variables l and k
l, k = pygame.mouse.get_pos()
# Set ship size to 1 block
ship_size_x = 1
ship_size_y = 1
# x_or_y is a variable that controls the orientation of the ship , 0 is sideways 1 is up
x_or_y = 0
# Sets coords of first grid for x axis
grid_coords = [100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, -50]
# Sets coords of second grid for x axis
computer_grid_coords = [740, 790, 840, 890, 940, 990, 1040, 1090, 1140, 1190]
# Sets inital state to an off screen position
x_boat_coords = [11, 11, 11, 11, 11, 11]
y_boat_coords = [11, 11, 11, 11, 11, 11]
# Sets initial to a length of one
x_boat_length = [1, 1, 1, 1, 1, 1]
y_boat_length = [1, 1, 1, 1, 1, 1]
# Intializes score
ai_score = 0
user_score = 0
# intializes Shot counter
shots_left = 15
# User grid is a 10x10 multi dimensional array which uses integers to denote the status of each block in the grid
user_grid = [
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]
]
computer_grid = [
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]
[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]
]
]
while True:
# Iterated through user grid
for i in range(10):
for x in range(10):
# The integer 1 denotes a ship position
if user_grid[i][x] == 1:
pygame.draw.rect(display, black, (grid_coords[i], grid_coords[x], 50, 50))
# The integer 2 denotes a missed shot
if user_grid[i][x] == 2:
pygame.draw.rect(display, red, (grid_coords[i], grid_coords[x], 50, 50))
# The integer 3 denotes a hit ship
if user_grid[i][x] == 3:
pygame.draw.rect(display, (0, 255, 0), (grid_coords[i], grid_coords[x], 50, 50))
for i in range(10):
for x in range(10):
# The integer 2 will denote a missed shot
if computer_grid[i][x] == 2:
pygame.draw.rect(display, red, (computer_grid_coords[i], grid_coords[x], 50, 50))
# The integer 3 will denote a hit ship
if computer_grid[i][x] == 3:
pygame.draw.rect(display, (0, 255, 0), (computer_grid_coords[i], grid_coords[x], 50, 50))
pygame.display.update()
# Ship size is a single integer and thus must be multiplied by 50 to fit to the 50 x 50 block size
ship_x = 50 * ship_size_x
ship_y = 50 * ship_size_y
for event in pygame.event.get():
if event.type == pygame.MOUSEMOTION:
# Cast the position of the mouse to variables l and k
l, k = pygame.mouse.get_pos()
pygame.display.update()
if event.type == pygame.MOUSEBUTTONDOWN:
# If the mouse is clicked on the increase ship size tile
if (l > 20 and l < 85) and (k > 650 and k < 700):
# Checks upper and lower bounds of size of ship
if (ship_size_x > 0 and ship_size_x < 4) and (ship_size_y > 0 and ship_size_y < 4):
# Applies increase in ship size to correct axis based on x_or_y variable
if x_or_y == 1:
ship_size_y = ship_size_y + 1
if x_or_y == 0:
ship_size_x = ship_size_x + 1
# Handles the clicking of the decrease size button
if (l > 110 and l < 175) and (k > 650 and k < 700):
# Check upper and lower bounds
if (ship_size_x > 0 and ship_size_x < 4) and (ship_size_y > 0 and ship_size_y < 4):
# Applies decrease to correct axis
if x_or_y == 1:
ship_size_y = ship_size_y - 1
if x_or_y == 0:
ship_size_x = ship_size_x - 1
# Changes the orientation of the ship
if (l > 290 and l < 385) and (k > 650 and k < 700):
x_or_y = 1
ship_size_x = 1
# Chnages the orientation of the ship
if (l > 420 and l < 515) and (k > 650 and k < 700):
x_or_y = 0
ship_size_y = 1
# Gamelock breakc point
if game_lock:
# If a ship is placed in the first grid
if ships_left != 0:
if (l > 100 and l < 600) and (k > 100 and k < 600):
# x spot reduces the position of the click to an index for the coordinate system that is grid
x_spot = int(round((l - 124) / 50))
x_boat_coords[5 - ships_left] = x_spot
# include boat length information when placing ship
x_boat_length[5 - ships_left] = ship_size_x - 1
y_spot = int(round(k - 124) / 50)
y_boat_coords[5 - ships_left] = y_spot
y_boat_length[5 - ships_left] = ship_size_y - 1
# The case in which a ship is placed above a ship already present
if user_grid[x_spot][y_spot] == 1:
tut_count = 4
ships_left = ships_left + 1
# Assign value of 1 in grid system to signnify a ship present
user_grid[x_spot][y_spot] = 1
# Adjusts if ship is larger than 1 unit so that etire ship is saved
if ship_size_x > 1:
for i in x_boat_length:
user_grid[x_spot + i][y_spot] = 1
if ship_size_y > 1:
for i in y_boat_length:
user_grid[x_spot][y_spot + i] = 1
# Reduces number of ships left
ships_left = ships_left - 1
# Accounts for what to do when all ships are used
if ships_left == 0:
ship_size_x == 1
ship_size_y == 1
# Change tip
tut_count = 1
# Computer will place 5 ships at random using random computer_move() function
for i in range(5):
x, y, xl, yl = computer_move()
computer_grid[x][y] = 1
for i in range(xl):
# Accounts for ship size which extends the bounds of the grid
if (x + i) > 9:
computer_grid[x][y] = 1
else:
computer_grid[x + i][y] = 1
for i in range(yl):
if (y + i) > 9:
computer_grid[x][y]
else:
computer_grid[x][y + i] = 1
tut_count = -5
# Another game_lock breakpoint
if game_lock:
# Manages button clicks in second grid
if (l > 740 and l < 1250) and (k > 100 and k < 600):
# Reduces position of click to an index
x_spot = int(round((l - 774) / 50))
y_spot = int(round(k - 124) / 50)
# Hit logic, if cell point = 1 then a ship is present
if computer_grid[x_spot][y_spot] == 1:
user_score = user_score + 1
tut_count = 2
computer_grid[x_spot][y_spot] = 3
else:
# if no ship present show miss
computer_grid[x_spot][y_spot] = 2
tut_count = 3
# Reduces shop counter
shots_left = shots_left - 1
# Change tip
tut_count = 5
# Unpacks random nits from computer logic
x, y, xl, yl = computer_move()
tut_count * -1
# Accoutns for computer hit logic
if user_grid[x][y] == 1:
# Change tip
tut_count = 6
# Increase ai score
ai_score = ai_score + 1
# Changes block to hit block
user_grid[x][y] = 3
else:
# If no hit change to a miss
user_grid[x][y] = 2
# Locks ths game when user runs out of shots
if shots_left == 0:
user_score_constant = user_score
highscore_list.append(user_score_constant)
game_lock = False
if user_score == ai_score:
tie_game()
break
elif user_score > ai_score:
win_level_one()
break
elif user_score < ai_score:
youlost()
break
# If user clicks quit game will end
if event.type == pygame.QUIT:
quit()
# Sets y bound
y_text = 630
# Draw Buttons and tiles
pygame.draw.rect(display, shipfinalcolour, (0, 0, 640, 720))
pygame.draw.rect(display, (0, 0, 128), (640, 0, 640, 720))
pygame.draw.rect(display, black, (20, 650, 65, 50))
pygame.draw.rect(display, shipfinalcolour, (22, 652, 60, 45))
pygame.draw.rect(display, black, (110, 650, 65, 50))
pygame.draw.rect(display, shipfinalcolour, (112, 653, 60, 45))
pygame.draw.rect(display, black, (290, 650, 95, 50))
pygame.draw.rect(display, shipfinalcolour, (292, 652, 90, 45))
pygame.draw.rect(display, black, (420, 650, 95, 50))
pygame.draw.rect(display, shipfinalcolour, (422, 652, 90, 45))
pygame.font.init()
# Initializes font values
# Creates text files to be used
text1 = myfont.render("Change Ship Size", True, (255, 255, 255))
display.blit(text1, (25, y_text))
text2 = mybigfont.render("+", True, (255, 255, 255))
display.blit(text2, (45, y_text + 30))
text3 = mybigfont.render("-", True, (255, 255, 255))
display.blit(text3, (140, y_text + 30))
text4 = myfont.render("Ship Orientation", True, (255, 255, 255))
display.blit(text4, (350, y_text))
text5 = myfont.render("Up", True, (255, 255, 255))
display.blit(text5, (325, y_text + 38))
text6 = myfont.render("User Score: " + (str(user_score)), True, (255, 255, 255))
display.blit(text6, (800, 650))
text7 = myfont.render("Computer Score: " + str(ai_score), True, (255, 255, 255))
display.blit(text7, (1000, 650))
text8 = myfont.render("Sideways", True, (255, 255, 255))
display.blit(text8, (430, y_text + 38))
text9 = mybigfont.render("Ships Left: " + (str(ships_left)), True, (255, 255, 255))
display.blit(text9, (50, 25))
text10 = myfont.render("Status: " + tutorial(tut_count), True, (255, 255, 255))
display.blit(text10, (800, 25))
text11 = mybigfont.render("Shots left: " + (str(shots_left)), True, (255,255,255))
display.blit(text11, (250, 25))
# Draw grid
for i in range(0, 11):
coordinate_change_blk_2 = i * 50 + 740
coordinate_change = i * 50 + 100
pygame.draw.line(display, [0, 0, 0], (coordinate_change, 100), (coordinate_change, 600), 4)
pygame.draw.line(display, [0, 0, 0], (100, coordinate_change), (600, coordinate_change), 4)
pygame.draw.line(display, [0, 0, 0], (coordinate_change_blk_2, 100), (coordinate_change_blk_2, 600), 4)
pygame.draw.line(display, [0, 0, 0], (740, coordinate_change), (1240, coordinate_change), 4)
# Draw grid characters
for i in range(0, 10):
x_coord_change_blk_2 = i * 50 + 760
x_coord_change = i * 50 + 120
y_coord_change = i * 50 + 110
Letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
pygame.font.init()
myfont = pygame.font.SysFont('arial bold', 36)
text = myfont.render(Letters[i], True, (255, 255, 255))
numbers = myfont.render(numbers[i], True, (255, 255, 255))
display.blit(text, (x_coord_change, 65))
display.blit(numbers, (65, y_coord_change))
display.blit(text, (x_coord_change_blk_2, 65))
display.blit(numbers, (700, y_coord_change))
# Draw block on grid as mouse moves
if (l > 100 and l < 600) and (k > 100 and k < 600):
pygame.draw.rect(display, black, (l - 25, k - 25, ship_x, ship_y))
pygame.display.update()
clock.tick(100)
# Run
intro_screen(True) |
21439a41943032771b39965644296b90d59effe5 | arun-siv/tutor_pyclass | /tableExtend1.py | 1,704 | 3.5625 | 4 | #what if the Parent class initialized some value. How to deal with it for child classes
import sys
def print_tables(objects, colnames, formatter):
#emits some table header
formatter.headings(colnames)
for obj in objects:
rowdata = [str(getattr(obj, colname)) for colname in colnames]
formatter.row(rowdata)
class TableFormatter(object):
# design specs
def __init__(self, outfile=None):
if outfile == None:
self.outfile = sys.stdout
self.outfile = outfile
def headings(self, headers):
raise NotImplementedError
def row(self, rowdata):
raise NotImplementedError
class TextTableFormatter(TableFormatter):
def __init__(self,outfile=None, width=10):
super().__init__(outfile)
self.width = width
def headings(self, headers):
for header in headers:
print('{:>{}s}'.format(header, self.width), end=' ', file=self.outfile)
print()
def row(self, rowdata):
for item in rowdata:
print('{:>{}s}'.format(item,self.width), end=' ', file=self.outfile)
print()
class CSVTableFormatter(TableFormatter):
def headings(self, headers):
print(",".join(headers), file=self.outfile)
def row(self, rowdata):
print(",".join(rowdata), file=self.outfile)
class HTMLTableFormatter(TableFormatter):
def headings(self, headers):
print('<tr>', end='')
for h in headers:
print('<th>{}</th>'.format(h), end = ' ')
print('</tr>')
def row(self, rowdata):
print('<tr>', end='')
for d in rowdata:
print('<td>{}</td>'.format(d), end = ' ')
print('</tr>') |
a95dcf4d629f3f43bdd94778206f1474a42ee02c | jackchauvin/Python | /Vector/test-vec.py | 765 | 3.671875 | 4 | from Vector import Vector
#Test for __init__
vec=Vector(1.356,2.434)
#Test for __str__
print("vec:",vec)
#Test for __repr__
print('vec.__repr__():',vec.__repr__())
vec2=Vector(3.65576,1.4785)
#Test for __add__
vec3 = vec + vec2
print(vec,'+',vec2,'=',vec3)
#Tests for __sub__
vec3 = vec - vec2
print(vec,'-',vec2,'=',vec3)
#Test for __mul__
vec4 = vec * 3
print(vec,'* 3 =',vec4)
#Test for __rmul__
vec4 = 3 * vec
print('3 *',vec,'=',vec4)
#Tests for __eq__
print('vec==vec3:',vec==vec3)
print('vec==vec:',vec==vec)
#Test for magnitude
print('Magnitude of vec:', vec.magnitude())
#Test for unit
print('Unit vector of vec:', vec.unit())
#Test for unit vector of zero
zero=Vector()
print('Unit vector of <0,0>:',zero.unit()) |
075cae912cdbce6709803c00b4e289070ecd6a89 | aamp19/Poisson-Regression | /Poisson Regression.py | 5,383 | 3.640625 | 4 | import numpy as np
import util
import pandas as pd
import matplotlib.pyplot as plt
def main(lr, train_path, eval_path, save_path):
"""Problem: Poisson regression with gradient ascent.
Args:
lr: Learning rate for gradient ascent.
train_path: Path to CSV file containing dataset for training.
eval_path: Path to CSV file containing dataset for evaluation.
save_path: Path to save predictions.
"""
# Load training set
x_train, y_train = util.load_dataset(train_path, add_intercept=True)
# *** START CODE HERE ***
# Fit a Poisson Regression model
# Run on the validation set, and use np.savetxt to save outputs to save_path
# *** END CODE HERE ***
valid_data = pd.read_csv(eval_path)
valid_x = np.array(valid_data[["x_1","x_2","x_3","x_4"]].values)
valid_y = np.array(valid_data[["y"]].values)
train = pd.read_csv(train_path)
train_x = np.array(train[["x_1","x_2","x_3","x_4"]].values)
train_y = np.array(train[["y"]].values)
poisson_model = PoissonRegression(step_size=lr)
poisson_model.fit(train_x, train_y)
y = poisson_model.predict(valid_x)
plt.figure()
print('valid_y', valid_y.shape)
print('y ',y.shape)
plt.scatter(valid_y, y, alpha=0.4, c='red', label='Ground Truth vs Predicted')
plt.xlabel('Ground Truth')
plt.ylabel('Predictions')
plt.legend()
plt.savefig('poisson_valid.png')
class PoissonRegression:
"""Poisson Regression.
Example usage:
> clf = PoissonRegression(step_size=lr)
> clf.fit(x_train, y_train)
> clf.predict(x_eval)
"""
def __init__(self, step_size=1e-5, max_iter=10000000, eps=1e-5,
theta_0=np.array([0.00001,0.0001,0.00001,0.0001]), verbose=True):
"""
Args:
step_size: Step size for iterative solvers only.
max_iter: Maximum number of iterations for the solver.
eps: Threshold for determining convergence.
theta_0: Initial guess for theta. If None, use the zero vector.
verbose: Print loss values during training.
"""
self.theta = theta_0
#self.theta = self.theta.reshape(len(self.theta),1)
self.step_size = step_size
self.max_iter = max_iter
self.eps = eps
self.verbose = verbose
def fit(self, x, y):
"""Run gradient ascent to maximize likelihood for Poisson regression.
Args:
x: Training example inputs. Shape (n_examples, dim).
y: Training example labels. Shape (n_examples,).
"""
# *** START CODE HERE ***
#print('theta shape',self.theta.shape)
m, n = x.shape
if self.theta is None:
self.theta = np.zeros(n, dtype=np.float32)
for i in range(m):
# self.theta += self.theta + self.step_size * (np.exp(x[i].dot(np.transpose(self.theta))) - y[i]).dot(x[i])
# self.theta += self.step_size*(np.dot(np.exp(np.dot(self.theta.transpose(), x[i].reshape(len(x[i]),1))) - y[i], x[i].reshape(1,len(x[i])))).transpose()
# self.theta += self.theta + self.step_size * (np.exp(x.dot(np.transpose(self.theta)) - y)).dot(x)
#theta = self.theta.reshape(len(self.theta),1)
exponent = self.step_size*(np.exp(np.dot(self.theta.reshape(1,len(self.theta)),x[i].reshape(len(x[i]),1)))) - y[i]
# print("exponent ",exponent.shape)
# print('x ',x[i].reshape(len(x[i]),1).shape)
dot = exponent*x[i].reshape(len(x[i]),1)
# print('dot ',dot.shape)
# print('x',x[i].shape)
# print('y',y[i].shape)
# print('theta',self.theta.shape)
#self.theta = self.theta.reshape(len(self.theta),1) + dot
self.theta += (self.step_size * (np.exp(np.dot(self.theta,x[i])) - y[i]) * x[i])*-1
#print('theta size',self.theta.shape)
# self.theta += 10**-5(np.exp((np.dot(self.theta.reshape(1,len(self.theta)),x[i].reshape(len(x[i]),1)))) - y[i])*x[i].reshape(len(x[i]),1)
# *** END CODE HERE ***
def predict(self, x):
"""Make a prediction given inputs x.
Args:
x: Inputs of shape (n_examples, dim).
Returns:
Floating-point prediction for each input, shape (n_examples,).
"""
# *** START CODE HERE ***
#print("x", x.shape)
#print(self.theta.shape)
#print('theta ',self.theta.shape)
# print('x shape', x.shape)
#y_hat = np.exp(np.dot(self.theta.transpose(), x.reshape(4,len(x))))
#print('self.theta', self.theta.shape)
#print('x ',x.shape)
y_hat = np.exp(np.dot(self.theta.transpose(),x.transpose()))
#yhat = np.exp(np.dot(self.theta.reshape(1,len(self.theta)), x.transpose()))
return y_hat
#print('y_hat',y_hat.shape)
# yhat = np.exp(np.dot(self.theta.transpose().reshape(len(self.theta),1),x.transpose()))
#return yhat
# *** END CODE HERE ***
if __name__ == '__main__':
main(lr=1e-5,
train_path='train.csv',
eval_path='valid.csv',
save_path='poisson_pred.png')
|
b895438fc8c05bb23d27ea21433387cb5b955a64 | at-vo/HackWestern7 | /tests/test.py | 2,557 | 3.53125 | 4 | from nltk.corpus import wordnet as wn
import string
import numpy
import matplotlib.pyplot as plt
### Synonym checker using nltk package
# def check_synonym(word, sent):
# word_synonyms = []
# for synset in wn.synsets(word):
# for lemma in synset.lemma_names():
# if lemma in sent and lemma != word:
# word_synonyms.append(lemma)
# return word_synonyms
# sent = input("what do you want to say")
# said = sent.split(" ")
# word_synonyms = check_synonym(word, sent)
goodDays = 0
badDays = 0
neutralDays = 0
goodWords = 0
badWords = 0
neutralWords = 0
# extract info from keywords.txt
# make and fill dictionary
kfile = open("tests/keywords.txt", "r", encoding="utf‐8")
dictk = {}
words = kfile.readlines()
for i in range(len(words)):
line = words[i]
# print(line)
line = line.split(",")
keyword = line[0]
sentimentvalue = int(line[1])
dictk [keyword] = sentimentvalue
num = 0
### REMOVE commented line for demo static string
# phrase = input("what do you want to say?")
phrase = "I’m afraid to work, but I’m also afraid to refuse unsafe work. I want to help, but I don’t want to get sick or die either. If all the health professionals get sick, who will care for the patients?"
line = phrase.split(" ")
# Calculate happiness score
happinessScore = 0
score = 0
noofkeywords = 0
for i in range(len(line)):
line[i] = line[i].lower()
if line[i] in dictk:
score += dictk[line[i]]
noofkeywords += 1
word = dictk[line[i]]
if word > 6:
goodWords += 1
elif happinessScore < 4:
badWords += 1
else:
neutralWords += 1
if noofkeywords > 0 and score > 0:
happinessScore = score/noofkeywords
# print(dictk)
print(happinessScore)
# print(score)
if happinessScore > 6:
print("today was a good day :)")
goodDays+=1
elif happinessScore < 4:
print("today was a bad day :(")
badDays+=1
else:
print("today was ok :| ")
neutralDays+=1
print("num good words:", goodWords)
print("num bad words:", badWords)
print("num neutral words:", neutralWords)
labels = 'Good', 'Bad', 'Neutral'
sizes = [goodWords, badWords, neutralWords]
explode = (0, 0.1, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
plt.show()
# print ("WORD:", word)
# print ("SENTENCE:", sent)
# print ("SYNONYMS FOR '" + word.upper() + "' FOUND IN THE SENTENCE: " + ", ".join(word_synonyms)) |
59796135369dd236a8a209931f937640ae117926 | TriCot-Game-Studio/bullets | /bullets/enemy.py | 1,361 | 3.515625 | 4 | from .actor import Actor
class Enemy(Actor):
def __init__(self, pos, radius, color, max_health, pcb1, pcb2, pcb3, img=None):
super().__init__(pos=pos, radius=radius, color=color, img=img)
self.health = max_health
self.max_health = max_health
self.phase = 0
self.damage = 0
self.pcb1 = pcb1
self.pcb2 = pcb2
self.pcb3 = pcb3
# pcbs are health thresholds for phase change
@property
def is_alive(self):
return self.health > 0
def update(self, damage):
# so what i was thinking here is that damage
# done to the boss is incremented per interval,
# and then reset every time the boss is updated -
# this way, everytime boss is updated,
# damage done between updates is incremented to
# the health and phase, and then the damage is reset
# to zero for the new interval after having been
# incremented in the update for the previous interval
self.health -= damage
self.damage = 0
if self.pcb1 < self.health <= self.max_health:
self.phase = 0
elif self.pcb2 < self.health <= self.pcb1:
self.phase = 1
elif self.pcb3 < self.health <= self.pcb2:
self.phase = 2
elif 0 < self.health <= self.pcb3:
self.phase = 3
|
a6bc5c5f70191259ccbf727497a4c8f0c7dd8b18 | malay190/quiz_assignments | /Hangman/hangman_game.py | 3,409 | 3.953125 | 4 | import random
#library for hangman
movi = ["baghi","ddlj","raazi","parmanu","newton"]
actor = ["hritik","varun","sidharth","arjun"]
profession = ["student","teacher","enterpreneur","farmer","pilote"]
fastfood = ["choumin","springroll","sandwich","noodles","burger"]
list_of_list = [movi,actor,profession,fastfood]
#some functions for hangman
def shuffel_and_choose(list1):
random.shuffle(list1)
return list1[0]
def find_random_list_name(w):
if w == movi:
list_name = "movie"
elif w == actor:
list_name = "actor"
elif w == profession:
list_name = "profession"
else:
list_name = "fast food"
return list_name
def replace(search_word):
under_score_subtracted = 0
for i in range(len(random_word)):
if random_word[i] == search_word:
under_score_list[i] = search_word
under_score_subtracted += 1
return under_score_subtracted
#some prepration and global variables :)
random_list = shuffel_and_choose(list_of_list)
random_list_name = find_random_list_name(random_list)
random_word = list(shuffel_and_choose(random_list))
under_score_list = []
for x in random_word:
under_score_list.append("_")
under_score_number = len(random_word)
user_try=0
#welcome screen
print("*"*40)
print("*"*40)
print("*"*16,"HANGMAN","*"*16)
print("*"*40)
print("*"*40)
# some default first lines
user_name=input("enter your name :")
d=input("select difficulty by entering choice number(int type) :\n1.>easy\n2.>hard\n")
if d.isdigit():
difficulty=int(d)
else:
print("you have entered wrong choice ")
exit(1)
#application code
print("guess the name of %s"%(random_list_name))
if difficulty==2:
#hard level
print(" ".join(under_score_list))
while under_score_number>0:
word = input("guess the letter\t")
number_of_places = replace(word.lower())
under_score_number = under_score_number - number_of_places
print(" ".join(under_score_list))
user_try += 1
if user_try > 10:
print("sorry %s" % (user_name))
print("better luck next time")
print("%s name was " % (random_list_name), end="")
print(" ".join(random_word))
break
if under_score_number == 0:
print("congratulations %s"%(user_name))
print("hurrey ..,you win...,in %d try.." % (user_try))
elif difficulty == 1:
#easy level
index_list = []
for i in range(len(random_word)):
index_list.append(i)
index_no=shuffel_and_choose(index_list)
word=random_word[index_no]
number_of_places = replace(word.lower())
under_score_number = under_score_number - number_of_places
print(" ".join(under_score_list))
while under_score_number>0:
word = input("guess the letter\t")
number_of_places = replace(word.lower())
under_score_number = under_score_number - number_of_places
print(" ".join(under_score_list))
user_try += 1
if user_try > 15:
print("sorry %s" % (user_name))
print("better luck next time")
print("%s name was "%(random_list_name),end="")
print(" ".join(random_word))
break
if under_score_number==0:
print("congratulations %s" % (user_name))
print("hurrey.. ,you win...,in %d try.."%(user_try))
else:
print("enter correct choice ")
|
ab24f06d7a40626bf37222236b0ad610637171bb | yuttana76/python_study | /py_dictionary.py | 563 | 4.125 | 4 | phonebook = {
'John':999,
'Jack':888,
'Jill':777
}
print(phonebook)
#Interating
for name,tel in phonebook.items():
print('%s has phone number is %s' %(name,tel))
#Delete item
print('Delete item')
del phonebook['Jill']
print(phonebook)
#Update and Add item
print('Update and Add item')
phonebook.update({'AAA':222})
phonebook.update({'Jack':555})
print(phonebook)
if "Jack" in phonebook:
print('Hi Jack your phone number is %s' %(phonebook['Jack']) )
if "Jill-x" in phonebook:
print('Jill-x here.')
else:
print('Jill-x not here.')
|
df5550b64ecc4b55d5fa441990258debad0f1414 | nzh1992/pydesign | /create_mode/factory_method/creator.py | 969 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# !/usr/bin/env python3
"""
@Author : ziheng.ni
@Time : 2021/2/7 16:57
@Contact : nzh199266@163.com
@Desc :
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from create_mode.factory_method.product import Product, Truck, Ship
class Creator(ABC):
"""
构造器抽象类。
factory_method方法用于所有子类提供实例化后的对象。
some_operation方法用于在获取子类对象后做一些操作,比如日志等信息。
"""
@abstractmethod
def factory_method(self):
pass
def some_operation(self) -> str:
product = self.factory_method()
result = f"Creator: {product.operation()}"
return result
class TruckCreator(Creator):
"""
卡车构造器
"""
def factory_method(self) -> Product:
return Truck()
class ShipCreator(Creator):
"""
船构造器
"""
def factory_method(self):
return Ship()
|
7ec071d5462baac29552f523f3793b8d1ab96a3c | alexei-alexov/compilation | /lab3.py | 1,880 | 3.796875 | 4 |
SUPPORTED = set('/*-+')
OPERATORS = {
'/': lambda a, b: a / b,
'*': lambda a, b: a * b,
'-': lambda a, b: a - b,
'+': lambda a, b: a + b,
}
class Node(object):
"""Tree node"""
def __init__(self, data):
self.l = None
self.r = None
self.data = data
def insert(self, node):
if self.l is None:
self.l = node
elif self.r is None:
self.r = node
else:
lw = self.l.get_weight()
rw = self.r.get_weight()
if lw < rw:
self.l.insert(node)
else:
self.r.insert(node)
def get_weight(self):
w = 1
if self.l: w += self.l.get_weight()
if self.r: w += self.r.get_weight()
return w
def __str__(self, depth=0):
ret = ""
if self.r != None:
ret += self.r.__str__(depth + 1)
ret += "\n" + (" "*depth) + str(self.data)
if self.l != None:
ret += self.l.__str__(depth + 1)
return ret
def result(self):
if self.data in SUPPORTED:
return OPERATORS[self.data](self.l.result(), self.r.result())
else:
return self.data
if __name__ == "__main__":
root = Node(input("Enter root element operator (%s):" % (", ".join(SUPPORTED), )))
current = root
allowed = False
while True:
current = Node("*?*")
root.insert(current)
print(root)
data = input('Enter node.\n? - to skip.\n! - to stop.\nsupported operators: +, -, *, /\n?: ')
if data == "!" or (not allowed and data == "?"):
break
if data in SUPPORTED:
current
continue
data = int(data)
current.data = data
allowed = True
print("Tree:\n%s\nResult: %s" % (root, root.result(), ))
|
86c20902e76e3869adb32bf478fddd39f156c6aa | Ekozmaster/python-experiments | /lil_math.py | 1,491 | 3.671875 | 4 | import math
class Vector3:
x = y = z = 0.0
def __init__(self, x=0.0, y=0.0, z=0.0):
self.x = x
self.y = y
self.z = z
# Algebra Operators
def __add__(self, other):
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vector3(self.x - other.x, self.y - other.y, self.z - other.z)
def __mul__(self, other):
return Vector3(self.x * other.x, self.y * other.y, self.z * other.z)
def __mul__(self, other=1.0):
return Vector3(self.x * other, self.y * other, self.z * other)
def __truediv__(self, other):
return Vector3(self.x / other.x, self.y / other.y, self.z / other.z)
def __neg__(self):
return Vector3(-self.x, -self.y, -self.z)
def __str__(self):
return "({0}, {1}, {2})".format(self.x, self.y, self.z)
def normalize(self):
mag = self.magnitude()
self.x /= mag
self.y /= mag
self.z /= mag
def normalized(self):
v = Vector3(self.x, self.y, self.z)
v.normalize()
return v
def magnitude(self):
return math.sqrt(self.sqr_magnitude())
def sqr_magnitude(self):
return self.x * self.x + self.y * self.y + self.z * self.z
def dot(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
def test():
a = Vector3(1,1,0)
b = Vector3(0.7071, 0.7071, 0)
print(a.normalized())
print(a)
|
37ef42e9a772c3eabb06e9e6a7f62eb7dcc383e1 | britannica/euler-club | /Week31/euler31_smccullars.py | 1,000 | 3.5625 | 4 | desired_total = 200
denominations = (1,2,5,10,20,50,100,200)
def resolve(solutions):
additions = set()
deletions = set()
for solution in solutions:
current_total = sum(solution)
if current_total < desired_total:
deletions.add(solution)
for coin in denominations:
# performance optimization: this ensures that
# our solution tuples are always in ascending
# order...which guarantees uniqueness
if coin >= solution[-1]:
if current_total + coin <= desired_total:
additions.add(solution + (coin,))
if additions or deletions:
solutions.difference_update(deletions)
solutions.update(additions)
return resolve(solutions)
else:
return solutions
# convert the tuple of denominations into a set of one-element tuples
one_coin_solutions = {(c,) for c in denominations}
print(len(resolve(one_coin_solutions)))
|
73d106223ed6a7d1b8435d731bf0ac076927484e | britannica/euler-club | /Week33/euler33_smccullars.py | 2,818 | 4.125 | 4 | class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def __eq__(self, other):
return self.numerator == other.numerator and self.denominator == other.denominator
def __str__(self):
return '{}/{}'.format(self.numerator, self.denominator)
def simplify(self):
# check for a common prime factor -- since we are only interested in two digit numbers,
# we can stop checking when x * n > 99 (where x and n is prime). if x == 2 (aka the
# smallest prime), n cannot be more than 47.
for p in (2,3,5,7,11,13,17,19,23,29,31,37,41,43,47):
if self.numerator % p == 0 and self.denominator % p == 0:
simpler_fraction = Fraction(int(self.numerator/p), int(self.denominator/p))
return simpler_fraction.simplify()
return self
# bad simplification means "transform the fraction's numerator and denominator into strings,
# find a shared digit, remove the shared digit from those strings, and then use those strings
# to make a new fraction"
def bad_simplify(self):
for x in str(self.numerator):
for y in str(self.denominator):
if x == y and x != '0':
digit_cancelled_numerator = int(str(self.numerator).replace(x, '', 1))
digit_cancelled_denominator = int(str(self.denominator).replace(x, '', 1))
return Fraction(digit_cancelled_numerator, digit_cancelled_denominator)
return None
curious_fractions = []
# we want all two digit numerators
for numerator in range(10, 100):
# we want a two digit denominator, but it must be larger than the numerator for the
# fraction to be less than 1
for denominator in range(numerator+1, 100):
raw_fraction = Fraction(numerator, denominator)
mangled_fraction = raw_fraction.bad_simplify()
# prevent divide by zero errors
if mangled_fraction and mangled_fraction.denominator != 0:
if raw_fraction.simplify() == mangled_fraction.simplify():
curious_fractions.append(raw_fraction)
numerator_product = 1
denominator_product = 1
for fraction in curious_fractions:
numerator_product *= fraction.numerator
denominator_product *= fraction.denominator
solution_fraction = Fraction(numerator_product, denominator_product)
print(solution_fraction.simplify().denominator)
# --------------------------------------
# TLDR
# --------------------------------------
# raw --> mangled --> simplified
# 16/64 --> 1/4 --> 1/4
# 19/95 --> 1/5 --> 1/5
# 26/65 --> 2/5 --> 2/5
# 49/98 --> 4/8 --> 1/2
#---------------------------------------
# (1*1*2*1)/(2*5*5*4) == 2/200 --> 1/100
|
0d5b66817cd3395f69eb8ac4b5522becd7a7d867 | britannica/euler-club | /Week6/euler6_smccullars.py | 226 | 3.78125 | 4 | sum_of_squares = 0
sum_to_be_squared = 0
for i in range(1, 101):
sum_of_squares += i ** 2
sum_to_be_squared += i
difference = (sum_to_be_squared ** 2) - sum_of_squares
print("sum square difference is: ", difference)
|
bb94b387948467639dcca67d43407db437c9ab1d | britannica/euler-club | /Week16/euler16_mwieche.py | 244 | 3.5625 | 4 | from functools import reduce
def sum_digits(n):
i = [int(d) for d in str(n)]
result = reduce(lambda x, y: x+y, i)
return result
if __name__ == '__main__':
num = 2**1000
answer = sum_digits(num)
print(answer) # 1366
|
22cda89eae84abdda5716d9f74a8e20d238e95f5 | britannica/euler-club | /Week14/euler14_mwiechec.py | 1,587 | 3.765625 | 4 | import time
import functools
def memoize(func):
"""Wrapper function to cache function results"""
memo = {}
@functools.wraps(func)
def wrapper(key):
if key in memo:
return memo[key]
else:
memo[key] = func(key)
return memo[key]
return wrapper
def timer(func):
"""Wrapper function to time function call"""
@functools.wraps(func)
def wrapper_timer(*args, **kwargs):
start_time = time.perf_counter()
value = func(*args, **kwargs)
end_time = time.perf_counter()
run_time = end_time - start_time
print(f"Finished {func.__name__!r} in {run_time:.4f} secs")
return value
return wrapper_timer
def collatz_func(x):
"""Collatz function"""
if x % 2 == 0:
y = x//2
else:
y = (x*3)+1
return y
# @functools.lru_cache(maxsize=None)
@memoize
def collatz_sequence_length(x):
"""Calculates the length of a Collatz Sequence"""
y = collatz_func(x)
if y == 1:
return 2
else:
sequence_length = collatz_sequence_length(y)
sequence_length += 1
return sequence_length
@timer
def get_longest_sequence(limit):
"""Finds the longest Collatz Sequence upto a given limit, returns the seed value and length"""
solution = (0, 1)
for num in range(1, limit):
length = collatz_sequence_length(num)
if solution[1] < length:
solution = (num, length)
return solution
if __name__ == '__main__':
answer = get_longest_sequence(1000000)
print(answer)
|
3ab90e3010619636be2f1bb71b35001846d6b635 | britannica/euler-club | /Week37/euler37_smccullars.py | 1,107 | 3.75 | 4 | ####### begin sieve generation of primes #######
MAX_PRIME = 1000000
# initialize sieve
sieve = [None] * MAX_PRIME
# zero and one are not primes
sieve[0] = False
sieve[1] = False
# populate the sieve
for x in range(2,MAX_PRIME):
if sieve[x] is None:
sieve[x] = True
for y in range(x*2, MAX_PRIME, x):
sieve[y] = False
# turn the sieve into an ordered (ascending) list of primes for convenience
primes = set(n for n,is_prime in enumerate(sieve) if is_prime)
####### end sieve generation of primes #######
def truncate(d, reverse=False):
return int(str(d)[:-1]) if reverse else int(str(d)[1:])
def is_truncatable(p, reverse=False):
if p not in primes:
return False
if len(str(p)) == 1:
return True
return is_truncatable(truncate(p, reverse=reverse), reverse=reverse)
truncatable_primes = []
for prime in sorted(list(primes)):
if prime > 7 and is_truncatable(prime) and is_truncatable(prime, reverse=True):
truncatable_primes.append(prime)
if len(truncatable_primes) == 11:
break
print(sum(truncatable_primes))
|
8d1104d588f6fed18dad78923939984efcd18ea9 | britannica/euler-club | /Week2/euler2-mwiechec.py | 316 | 3.5625 | 4 | import time
def fibsumeven(x):
res1 = 1
res2 = 1
evens = 0
sum = 0
while sum < 4000000:
sum = res1 + res2
res1, res2 = res2, sum
if (sum % 2 == 0):
evens += sum
return evens
start = time.time()
print (fibsumeven(35))
end = time.time()
print(end - start)
|
fb9eff4ed31a3a1cb47286a3639461233966d189 | scudan/TestPython | /com/liaoxuefeng/OO/classAndInstance1.py | 624 | 3.875 | 4 | class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s: %s' %(self.__name, self.__score))
def get_name(self):
return self.__name;
def get_score(self):
return self.__score;
def set_name(self, name):
self.__name = name;
def set_score(self, score):
self.__score = score;
bart = Student('Test01',89)
bart.print_score()
# 私有属性,不能直接访问
bart.set_name('sundan1')
print(bart.get_name())
bart.__name = 'sundan'
bart.print_score()
print(bart.get_name())
|
01273d79f5a771eeb48a3b357afdddb7e1d2a2c5 | scudan/TestPython | /com/python/sundan/controlor.py | 107 | 3.84375 | 4 | a = 10;
b = 10;
if a > b :
print("a > b")
elif (a == b):
print ("a = b")
else:
print ("a < b") |
b12f7071fdcb5ccd38cff72b70c7aaf189ac75b1 | scudan/TestPython | /com/python/sundan/basic/yieldTest.py | 194 | 4 | 4 | #生成器:结果生成一个序列,而不仅仅是一个值
def countdown(n):
print("Count down!");
while n > 0:
yield (n)
n -= 1;
for i in countdown(10):
print(i);
|
1e85e424aca7ac12163b3385ae89891a57c3ef09 | scudan/TestPython | /com/liaoxuefeng/highFeture/Iteration.py | 743 | 3.765625 | 4 | from collections import Iterable
d= {'a':1,'b':2,'c':3,'d':4}
for key in d:
print(key, d.get(key))
for k,v in d.items():
print("key:"+k,v);
for ch in 'ABCD':
print(ch)
print(isinstance('abc',Iterable))
print(isinstance([1,2,3],Iterable))
for i, va in enumerate(['A','b','d']):
print(i, va)
print("-"*10)
for x, y in [(2,4),(3,9),(4,16)] :
print(x,y)
minMax = [34,44,-22,47,45,23]
minMax1 = []
minMax2 = [7,7]
minMax3 =[7,1]
minn=0 ;
maxn= 0
num = 0
for num in minMax3:
indexx = minMax3.index(num)
temp = num
print(temp)
if indexx == 0 :
minn = num;
maxn = num
else:
if minn> num:
minn = num
if maxn < num:
maxn =num
print(minn, maxn) |
d386360920ee5b5e08654d3e2c781148839fbdc9 | scudan/TestPython | /com/refrencePython/function/FunctionT1.py | 468 | 4.375 | 4 | #可变参数函数
def concat(*args , sep ='/'):
return sep.join(args);
result = concat("earth","mars","venus");
print(result);
result1 = concat("earth","mars","venus",sep =".");
print(result1);
# 参数分拆
# *args 分拆 元祖
# **args 分拆 字典
list1 = list(range(3,6))
print(list1);
args = [3,6]
list2 = list(range(*args))
print(list2);
def make_inc(n):
return lambda x: x+n;
f= make_inc(42);
re = f(2);
print(re);
print(make_inc.__doc__)
|
c7cc071afaa110c71ea0bb98d5ce7307a5f84b08 | scudan/TestPython | /com/refrencePython/exception/test.py | 281 | 3.875 | 4 | while True:
try:
x = int(input(("please enter a num:")))
break
# 有异常,且匹配则走异常分支,完了继续转到try.
# 如果未匹配到,则直接退出
except ValueError:
print("Oops! That was no valud num. try again...") |
2cd0932519e63d2cd2d93c78150f371d58838f56 | scudan/TestPython | /com/python/sundan/third/referenceAndcopy.py | 352 | 3.984375 | 4 | import copy
a = [1,2,3,4]
b = a # b引用a
print(b is a )
b [2] = 10 # a 也改变
print(a)
d = [1,2,[3,4]]
c = list(d) # 浅复制
print(c is d )
c.append(100)
print(d)
c[2][0] = -1000 # c 和 d 共享浅复制的内容,当c改变,d对应改变
print(d)
e = [1,2,[3,4]]
f = copy.deepcopy(e)
f[2][0] = -1000
print("e:") # e 不会有变化
print(e)
|
889a98204abf5681a27085284c75c120ab1acff9 | scudan/TestPython | /com/refrencePython/APITest/Tdecimal/Tdecimal1.py | 293 | 3.703125 | 4 | from decimal import *
#十进制
print(round(Decimal('0.70')*Decimal('1.05'),2))
#二进制
print(round(.70*1.05,2))
print(Decimal('1.00') % Decimal('.10'))
print(1.00 % 0.10)
print("-----",sum([Decimal(0.1)]*10))
print(sum([Decimal(0.1)]*10) == Decimal('1.0'))
print(sum([0.1]*10) == 1.0) |
c2676d58846f6d041a3fcbf4a95fad9fa30753fa | HemangShimpi/To-Do-App | /Source Code/Main.py | 1,487 | 3.828125 | 4 | '''
File Name: Main.py
Author: Hemang Shimpi
Date Created: 12/19/20
Date last modified: 12/25/20
Language: Python
Gui: Tkinter
'''
# importing all the necessary tkinter gui modules here
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
# importing class here
from LoginPage import LoginPage
# main method
def main():
# creating tkinter window here and modifying its elements such as title, window size, etc
window = Tk()
window.resizable(0,0)
window.title("To-Do Application")
window.geometry("530x400+400+150")
# using PhotoImage to set a background image as a label for the window
bg_img = PhotoImage(file="C:\\bg_img.png")
bg_lbl = Label(window, image=bg_img)
# places the image directly in the center
bg_lbl.place(x=0, y=0, relheight=1, relwidth=1)
# creating thanks method here to thank the user for using the app by using tkinter messagebox
def thanks():
messagebox.showinfo("Goodbye! ", "Thanks for using my app!")
# destroys (closes) the window
window.destroy()
# using protocol method to run thanks method after user closes the window
window.protocol("WM_DELETE_WINDOW", thanks)
# passing window in the LoginPage class parameters to have it contain all elements that the class has
LoginPage(window)
# mainloop to run and end the window
window.mainloop()
# if test
if __name__ == "__main__":
main()
# end of program
|
3b691f146cf9a241b242506b38be69a919aa5443 | lurium-ruri/python_automate | /chapter9/renameDates.py | 726 | 3.515625 | 4 | #! python3
# renameDates.py - 米国式日付を欧州式に書き換える
import shutil
import os
import re
def main():
date_pattern = re.compile(r"""~(.*?)
((0|1)?\d)-
((0|1|2|3)?\d)-
(.*?)$
""", re.VERBOSE)
for amer_filename in os.listdir('.'):
mo = date_pattern.search(amer_filename)
if mo == None:
continue
before_part = mo.group(1)
month_part = mo.group(2)
day_part = mo.group(4)
year_part = mo.group(6)
after_part = mo.group(8)
euro_filename = f'{before_part}{day_part}-{month_part}-{year_part}{after_part}'
print(f'Renaming {amer_filename} to {euro_filename}')
if __name__ == '__main__':
main()
|
f5b84d9f58c607b5c21dbc564ea13efbc9eabaee | lurium-ruri/python_automate | /chapter9/backupToZip.py | 1,016 | 4.03125 | 4 | #! python3
# backupToZip.py フォルダ全体を連番付きZIPファイルにコピーする
import os
import zipfile
from pathlib import Path
def backup_to_zip(folder):
folder = Path(folder).absolute
number = 1
while True:
zip_filename = Path(f'{folder}_{str(number)}.zip')
if not Path(zip_filename).exists:
break
number = number + 1
print(f'Creating{zip_filename}...')
backup_zip = zipfile.ZipFile(zip_filename, 'w')
# FIXME
for foldername, subfolders, filenames in os.walk(folder):
print(f'Adding files in {foldername}...')
backup_zip.write(foldername)
for filename in filenames:
new_base = Path(f'{folder}_')
if filename.startswith(new_base) and filename.endswith('.zip'):
continue
backup_zip.write(Path(foldername).joinpath(filename))
backup_zip.close
print('Done.')
def main():
backup_to_zip('C:\\delicious')
if __name__ == '__main__':
main()
|
1b7784bc087a5a12ea6e4bca861f623ba2277b2d | youirong/PracticePython | /src/chapter1.py | 703 | 3.8125 | 4 | '''
Created on 2015年4月11日
@author: Rong
'''
# movies = ["a", "b", "c"]
# print (movies[1])
#
# movies.insert(1, 1)
# movies.insert(3, 2)
# movies.append(3)
# for movie in movies:
# print(movie)
#
# a = 0
# print (isinstance(movies, list))
# print (isinstance(a, list))
movies = ["a", "b", ["c", ["d", "e"]]]
# print (movies)
#
# for each in movies:
# print(each)
for eachitem in movies:
if isinstance(eachitem, list) == False:
print(eachitem)
else:
for a in eachitem:
if isinstance(a, list) ==False:
print (a)
else:
for b in a:
print (b)
|
ece97500c6445bd645e0f0d84c2f2dab9a4ddbca | PeterCassell92/Slither-pygame | /slither.py | 6,962 | 3.59375 | 4 | import pygame
import random
pygame.init()
white= (255,255,255)
black= (0,0,0)
red = (255,0,0)
green = (0,155,0)
display_width = 800
display_height = 600
block_size =20
appleThickness = 30
img = pygame.image.load('Snakehead.png')
appleimg= pygame.image.load('Apple.png')
FPS = 10
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Slither')
pygame.display.update()
pygame.display.set_icon(img)
clock = pygame.time.Clock()
smallfont= pygame.font.SysFont(None, 25)
medfont= pygame.font.SysFont(None, 50)
largefont= pygame.font.SysFont(None, 80)
def gameIntro():
intro = True
while intro:
gameDisplay.fill(white)
message_to_screen("Welcome to Slither", green, -100, "large")
message_to_screen("The objective of the game is to eat red apples", black, -30)
message_to_screen("The more apples you eat, the longer you become", black, 10)
message_to_screen("You will lose if you collide with yourself or the edges", black, 50)
message_to_screen("Press C to Continue or Q to Quit", black, 150, "medium")
for event in pygame.event.get():
if event.type == pygame.KEYDOWN :
if event.key == pygame.K_q:
pygame.quit()
quit()
elif event.key == pygame.K_c:
intro = False
if event.type == pygame.QUIT :
pygame.quit
quit()
pygame.display.update()
clock.tick(5)
def pause():
paused = True
message_to_screen("Paused", black, -100, "large")
message_to_screen("Press C to continue or Q to quit ", black, -30)
pygame.display.update()
while paused:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN :
if event.key == pygame.K_q:
pygame.quit()
quit()
elif event.key == pygame.K_c:
paused = False
if event.type == pygame.QUIT :
pygame.quit
quit()
#gameDisplay.fill(white)
clock.tick(5)
def score(score):
text = smallfont.render("Score: " + str(score), True, black)
gameDisplay.blit(text, (0,0))
def apple(applex, appley):
gameDisplay.blit(appleimg, (applex, appley))
def randAppleGen():
randapple_y = round(random.randrange(0,display_height - appleThickness))
randapple_x = round(random.randrange(0,display_width - appleThickness))
return randapple_x, randapple_y
def snake(snakeList, block_size):
if direction == 'right':
head= pygame.transform.rotate(img, 270)
if direction == 'left':
head= pygame.transform.rotate(img, 90)
if direction == 'up':
head= pygame.transform.rotate(img, 0)
if direction == 'down':
head= pygame.transform.rotate(img, 180)
gameDisplay.blit(head, (snakeList[-1][0], snakeList[-1][1]))
for XnY in snakeList[:-1] :
pygame.draw.rect(gameDisplay,green,[XnY[0],XnY[1],block_size,block_size])
def text_Objects(text, color, size):
if size == "small":
textSurface = smallfont.render(text, True, color)
elif size == "medium":
textSurface = medfont.render(text, True, color)
elif size == "large":
textSurface = largefont.render(text, True, color)
return textSurface, textSurface.get_rect()
def message_to_screen(msg, color,y_displace =0, size = "small"):
#screen_text = font.render(msg, True, color)
#gameDisplay.blit(screen_text, [display_width/4, display_height/2])
textSurf, textRect = text_Objects(msg, color, size)
textRect.center = (display_width/2), (display_height/2) + y_displace
gameDisplay.blit(textSurf,textRect)
def gameLoop():
global direction
global mode
direction = 'right'
gameExit= False
gameOver= False
snakeList = []
snakeLength = 1
growthperapple =1
snakeSpeed = block_size
lead_x = display_width/2
lead_y = display_height/2
lead_xchange= snakeSpeed
lead_ychange= 0
randapple_x, randapple_y = randAppleGen()
#print randapple_x
#print randapple_y
while not gameExit:
if gameOver == True:
message_to_screen("Game Over", red, -100, "large")
message_to_screen(" Press C to continue or Q to quit", black, 50, "medium")
pygame.display.update()
while gameOver == True:
#gameDisplay.fill(white)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN :
if event.key == pygame.K_q:
gameOver = False
gameExit = True
elif event.key == pygame.K_c:
gameLoop()
if event.type == pygame.QUIT :
gameOver = False
gameExit = True
for event in pygame.event.get():
#print event
if event.type == pygame.QUIT :
gameExit = True
if event.type == pygame.KEYDOWN :
if event.key == pygame.K_RIGHT:
lead_xchange = snakeSpeed
lead_ychange = 0
direction= 'right'
if event.key == pygame.K_LEFT:
lead_xchange = -snakeSpeed
lead_ychange = 0
direction= 'left'
if event.key == pygame.K_DOWN:
lead_ychange = snakeSpeed
lead_xchange = 0
direction= 'down'
if event.key == pygame.K_UP:
lead_ychange = -snakeSpeed
lead_xchange = 0
direction= 'up'
if event.key == pygame.K_ESCAPE:
pause()
if lead_x >= display_width or lead_x < 0 or lead_y >= display_height or lead_y < 0:
gameOver = True
lead_x += lead_xchange
lead_y += lead_ychange
# if lead_x == randapple_x and lead_y == randapple_y:
# randapple_x = round(random.randrange(0,display_width - block_size)/10.0)*10.0
# randapple_y = round(randomrandrange(0, display_height - block_size)/10.0)*10.0
# snakeLength += growthperapple
#if lead_x >= randapple_x and lead_x < randapple_x + appleThickness:
# if lead_y >= randapple_y and lead_y < randapple_y + appleThickness or lead_y + block_size > randapple_y and lead_y + block_size < randapple_y + appleThickness:
# randapple_y = round(random.randrange(0,(display_height - appleThickness)/block_size))*10
# randapple_x = round(random.randrange(0,(display_width - appleThickness)/block_size))*10
#print randapple_x
#print randapple_y
# snakeLength += growthperapple
if lead_x >= randapple_x and lead_x < randapple_x +appleThickness or lead_x + block_size > randapple_x and lead_x + block_size < randapple_x + appleThickness:
#print "X crossover"
if lead_y >= randapple_y and lead_y <randapple_y +appleThickness or lead_y + block_size > randapple_y and lead_y + block_size < randapple_y + appleThickness:
randapple_x, randapple_y = randAppleGen()
snakeLength += growthperapple
#print lead_x
#print lead_y
#print "X & Y crossover"
gameDisplay.fill(white)
#pygame.draw.rect(gameDisplay, red, [randapple_x, randapple_y,appleThickness,appleThickness])
snakeHead = []
snakeHead.append(lead_x)
snakeHead.append(lead_y)
snakeList.append(snakeHead)
if len(snakeList) >(snakeLength):
del snakeList[0]
for eachSegment in snakeList[:-1]:
if eachSegment == snakeHead :
gameOver = True
apple(randapple_x,randapple_y)
snake(snakeList, block_size)
score((snakeLength-1)*10)
#gameDisplay.fill(red, rect = [100,100,40,40]) example of fill to draw square/ rect
pygame.display.update()
clock.tick(FPS)
gameIntro()
gameLoop()
pygame.quit
quit() |
471899721408786f171a4d48c329c4b56e775bcf | saintlyzero/Interview-Coding-Problems | /CheekySolutions/MigratoryBirds.py | 473 | 3.796875 | 4 | """
Problem Link: https://www.hackerrank.com/challenges/migratory-birds
Time Complexity : O(N)
Space Complexity: O(M) ; M : Distinct Numbers
"""
def migratoryBirds(arr):
count = [0]*6
for i in arr:
count[i] += 1
return count.index(max(count))
# index() considers index of first occurence of the element
if __name__ == "__main__":
arr = [1,4,4,4,5,5,5,3]
max_bird = migratoryBirds(arr)
print("res: ",max_bird) # 4
|
bb1a8090d3fc97546339037bbc0e9b06ff43b438 | 3point14guy/Interactive-Python | /strings/count_e.py | 1,153 | 4.34375 | 4 | # Assign to a variable in your program a triple-quoted string that contains your favorite paragraph of text - perhaps a poem, a speech, instructions to bake a cake, some inspirational verses, etc.
#
# Write a function that counts the number of alphabetic characters (a through z, or A through Z) in your text and then keeps track of how many are the letter ‘e’. Your function should print an analysis of the text like this:
#
# Your text contains 243 alphabetic characters, of which 109 (44.8%) are 'e'.
import string # has sets of characters to use with 'in' and 'not in'
letters = string.ascii_lowercase + string.ascii_uppercase
strng = """The stump thunk the skunk stunk and the skunk thunk the stump stunk."""
def count(p):
#count characters, "e", and calc % "e"
counter = 0
e = 0
for char in p:
if char in letters:
counter = counter + 1
if char == "e" or char == "E":
e = e + 1
perc = e / counter * 100
return counter, e, perc
#returns a set
ans = count(strng)
print("Your text contains {} alphabetic characters, of which {} ({:.2}%) are 'e'.".format(ans[0], ans[1], ans[2]))
|
f4f2cb69d567572b77f784f50d6c7c06633898a6 | 3point14guy/Interactive-Python | /turtles/preso/sierpinski_recursive_colored.py | 1,442 | 3.515625 | 4 | import turtle
import time
def draw_triangle(points,color,t):
t.fillcolor(color)
t.up()
t.goto(points[0][0],points[0][1])
t.down()
t.begin_fill()
t.goto(points[1][0],points[1][1])
t.goto(points[2][0],points[2][1])
t.goto(points[0][0],points[0][1])
t.end_fill()
def get_mid(p1, p2):
return ( (p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2)
def sierpinski(points, iters, t):
colormap = ['blue','red','green','white','yellow',
'violet','orange']
time.sleep(2)
draw_triangle(points, colormap[iters], t)
# base case
if iters > 0:
# recursive call
# iters - 1 changes state getting closer to base case
sierpinski([points[0],
get_mid(points[0], points[1]),
get_mid(points[0], points[2])],
iters - 1, t)
sierpinski([points[1],
get_mid(points[0], points[1]),
get_mid(points[1], points[2])],
iters - 1, t)
sierpinski([points[2],
get_mid(points[2], points[1]),
get_mid(points[0], points[2])],
iters - 1, t)
def main():
t = turtle.Turtle()
t.speed(1)
wn = turtle.Screen()
turtle.tracer(False)
start_points = [[-200,-100], [0,200], [200,-100]]
sierpinski(start_points, 5, t)
turtle.update()
wn.exitonclick()
main()
|
11992691b92d6d74aa41fe6797f70f810ea3bfb9 | 3point14guy/Interactive-Python | /tkinter/hello_world_tkinter.py | 1,249 | 4.15625 | 4 | import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkinter import simpledialog
window = tk.Tk()
# my_label = ttk.Label(window, text="Hello World!")
# my_label.grid(row=1, column=1)
# messagebox.showinfo("Information", "Information Message")
# messagebox.showerror("Error", "My error message")
# messagebox.showwarning("WARNING!", "Warning message")
# answer = messagebox.askokcancel("QUESTION", "DO YOU WANT TO OPEN A FILE?")
# answer = messagebox.askretrycancel("Question", "Do you want to try again?")
# answer = messagebox.askyesno("Question", "Do you like Python?")
# answer = messagebox.askyesnocancel("Hey You!", "Continue playing?")
answer = simpledialog.askstring("input", "WHat is your first name?", parent=window)
if answer is not None:
print("Hello ", answer)
else:
print("hello annonymous user")
answer = simpledialog.askinteger("input", "What is your age", parent=window, minvalue=0, maxvalue=100)
if answer is not None:
my_label = ttk.Label(window, text="Wow, I am {} too!".format(answer))
my_label.grid(row=10, column=20)
else:
my_label = ttk.Label(window, text="Most people who feel old won't enter their age either.")
my_label.grid(row=10, column=20)
window.mainloop()
|
28ee083d251af397d591971df533d3a22f696ce0 | 3point14guy/Interactive-Python | /alice.py | 1,772 | 3.671875 | 4 | # -*- coding: utf-8 -*-
import string
book = open("alice_in_wonderland.txt", "r")
# dict = {}
#
# for lines in book:
# words = lines.split()
# for word in words:
# word = list(word.lower())
# for letter in word:
# if letter in string.punctuation:
# word = word.replace(letter, " ")
# word = "".join(word)
# # print(word)
# if word in dict:
# dict[word] += 1
# else:
# dict[word] = 1
#
# keyz = sorted(dict.keys())
# # for key in keyz:
# # print key, dict[key]
#
# valuez = dict.values()
# max = max(valuez)
# print max
#
# print(dict['alice'])
count = {}
longest_word = ""
for line in book:
for word in line.split():
# remove punctuation
word = word.replace('_', '').replace('"', '').replace(',', '').replace('.', '')
word = word.replace('-', '').replace('?', '').replace('!', '').replace("'", "")
word = word.replace('(', '').replace(')', '').replace(':', '').replace('[', '')
word = word.replace(']', '').replace(';', '')
# ignore case
word = word.lower()
# print(word)
# ignore numbers
if word.isalpha():
if word in count:
count[word] = count[word] + 1
else:
count[word] = 1
if len(word) > len(longest_word):
longest_word = word
keys = count.keys()
keys.sort()
# save the word count analysis to a file
out = open('alice_words.txt', 'w')
for word in keys:
out.write(word + " " + str(count[word]))
out.write('\n')
print("The word 'alice' appears " + str(count['alice']) + " times in the book.")
print("The longest word is", longest_word, "and has", len(longest_word), "letters.")
|
3390cf0821cb88815d9dbf7ad72bcde2ab971932 | 3point14guy/Interactive-Python | /turtles/fractals/fractal_tree.py | 2,260 | 3.796875 | 4 | # import turtle
#
# def tree(branchLen,t, i):
#
# if branchLen > 5:
# t.forward(branchLen)
# t.right(20)
# tree(branchLen-15,t, i)
# t.left(40)
# tree(branchLen-15,t, i)
# t.right(20)
# t.backward(branchLen)
#
#
# def main():
# t = turtle.Turtle()
# myWin = turtle.Screen()
# t.left(90)
# t.up()
# t.backward(100)
# t.down()
# t.color("brown")
# t.speed(5)
# tree(75,t, 0)
# myWin.exitonclick()
#
# main()
import turtle
import random
def branch_width(branchLen, t):
if branchLen > 60:
t.width(6)
elif branchLen > 45:
t.width(4)
elif branchLen > 30:
t.width(3)
elif branchLen > 15:
t.width(2)
def draw_leaves(branchLen, t, color, degrees):
t.fillcolor("green")
t.color("green")
# print(t.heading(), "before")
for i in range(int(360/degrees)):
if branchLen <= 20:
radius = random.randrange(15, 25)
t.left(degrees)
t.begin_fill()
t.circle(radius)
t.end_fill()
# draw_leaves(branchLen, t, color, degrees)
# print(t.heading())
t.color("brown")
def direction():
coin_flip = random.choice([1, 2])
if coin_flip == 1:
return 1
else:
return -1
def tree(branchLen, t):
shorten = random.randrange(10, 20)
angle = random.randrange(15, 40)
if branchLen < 15:
t.color("green")
if branchLen > 5:
dir = direction()
t.forward(branchLen)
t.right(angle * dir)
branch_width(branchLen, t)
tree(branchLen - shorten,t)
t.left((angle * (2 + random.randrange(1, 3)/15)) * dir)
draw_leaves(branchLen, t, "green", 60)
branch_width(branchLen, t)
tree(branchLen - shorten,t)
draw_leaves(branchLen, t, "green", 90)
t.right(angle * dir)
t.backward(branchLen)
def go():
t.reset()
t.left(90)
t.up()
t.backward(100)
t.down()
t.color("brown")
t.speed(0)
t.width(8)
tree(random.randrange(65, 95, 5), t)
turtle.tracer(False)
turtle.hideturtle()
t = turtle.Turtle()
wn = turtle.Screen()
wn.onkey(go, "Up")
wn.listen()
turtle.update()
turtle.mainloop()
|
fe393e270b76b8816201dc34faa287205f5e5825 | george-git-dev/CursoemVideo | /PYTHON/ex007.py | 153 | 3.5 | 4 |
# Média aritimética
n1 = float(input("Primeira nota: "))
n2 = float(input("Segunda nota: "))
conta = (n1 + n2)/2
print("Média {}".format(conta))
|
4c561fa0bc9be90dce570c79417005b2502e5b95 | george-git-dev/CursoemVideo | /PYTHON/ex074.py | 239 | 3.515625 | 4 | from random import randint
n = (randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10))
print(f"Eu sorteei os valores {n}")
print(f"O maior valor sorteado foi {max(n)}")
print(f"O menor valor sorteado foi {min(n)}") |
e7954829da25b91dc96ae66347e5ea50a47402c2 | george-git-dev/CursoemVideo | /PYTHON/ex049.py | 129 | 3.703125 | 4 | tabuada = int(input("Tabuada do numero: "))
for c in range(1, 11):
print("{} X {} = {}".format(tabuada, c, tabuada*(c)))
|
ed68079ef6d98818c687a28667436620442e7196 | mh453Uol/PythonLearning | /learning/lamda_functions.py | 181 | 3.921875 | 4 | double = lambda x: x * 2
triple = lambda x: x * 3
square_root = lambda x: x * x
print(double(10) == 20)
print(double(5) == 10)
print(triple(10) == 30)
print(square_root(10) == 100) |
9987ad5ff9385a13234a4ee808b7236384495d80 | mh453Uol/PythonLearning | /learning/student_manager.py | 1,631 | 3.765625 | 4 | students = []
def titlecase(element: str) -> str:
to_return = []
words = element.split(" ")
for word in words:
titlecased = word[0].upper() + word[1:].lower()
to_return.append(titlecased)
return " ".join(to_return)
def add_student(name:str, student_id:int = -1):
student = {
"name":titlecase(name),
"student_id":titlecase(student_id)
}
students.append(student)
# reading console
def add_student_ui():
student_name = input("Enter a student name:")
student_id = input("Enter a student id:");
add_student(student_name,student_id)
print(students)
def what_to_add_student() -> bool:
user_input = input("Press E to EXIT or C to CONTINUE")
if user_input == "E" or user_input == "e":
return False
return True
file_access_modes = [
{"appending","a"},
{"writing","w"},
{"writing_binary","wb"},
{"reading","r"},
{"reading_binary","rb"},
]
def save_file(path,access_mode,text):
try:
file = open(path,access_mode)
file.write(text)
file.close()
except Exception:
print("Count not save file")
def read_file(path,access_mode):
try:
file = open(path,access_mode)
for line in file.readlines():
print(line)
file.close()
except Exception:
print("Could not read file")
while True:
print("\t Current Students:")
read_file("student.txt","r");
print("----------------------------------")
add_student_ui()
if not what_to_add_student():
save_file("student.txt","a",str(students) + "\n")
break
|
3142444064cdc70471f4878bc431a51b6a8bb22c | mh453Uol/PythonLearning | /pythonbo-course/pyStudentManager/functions.py | 1,465 | 3.984375 | 4 | students = [
{"name":"majid hussain khattak","id":1},
{"name":"majid","id":2},
{"name":"h","id":3},
{"name":"MAJID HUSSAIN KHATTAK","id":4}
]
countIndex = 0 # this variable is in the main scope
def get_student_titlecase(students):
titledcased = []
for student in students:
print(student)
return titledcased
def titlecase(name):
titled = ""
names = name.split(' ')
length = len(names)
for n in range(length):
titled += names[n][0].upper() + names[n][1:].lower()
if n < length - 1:
titled += " "
return titled
def add_student(name,id = 1):
# countIndex = countIndex + 1 # this would create a
# variable in the function scope this is because
# python thinks we are assigning a variable
# since to assign all you do it write variable name
if id == 1:
# To tell python we mean global we do
global countIndex
countIndex = countIndex + 1
students.append({"name": name, "id": countIndex})
else:
students.append({"name": name, "id": id})
def my_print(*args):
for arg in args:
print(arg)
def kwargs_key_word(**kwargs):
print(kwargs["name"])
print(kwargs["id"])
add_student("majid",12)
add_student("majid")
add_student("majid")
add_student("majid")
#print(get_student_titlecase(students))
#my_print("majid","is","not","so","good","at","python")
#kwargs_key_word(name = "majid", id = "10", not_printed = "foo")
|
1aa991d0a31100b8fddb5eb00fdabc146f221d14 | smile0304/py_asyncio | /chapter01/type_object_class.py | 361 | 3.765625 | 4 | a=1
b="abc"
print(type(1))
print(type(int))
#type->int->1
print(type(b))
print(type(str))
#type->str->abc
class Student:
pass
print(type(Student))
a=[1,2]
print(type(a))
print(type(list))
print(Student.__bases__)
class My_Student(Student):
pass
print(My_Student.__bases__)
print(type(object))
print(type(int.__bases__))
print(type(tuple.__bases__)) |
3c600900972e76cf65fc068e2612e12dd976e720 | smile0304/py_asyncio | /chapter04/abc_test.py | 1,223 | 3.5625 | 4 | class Company(object):
def __init__(self,employee_list):
self.employee = employee_list
def __len__(self):
return len(self.employee)
com = Company(["TT1","TT2","TT3"])
#我们在某些情况下,判定某些对象的类型
#from collections.abc import Sized
from collections.abc import *
#print(hasattr(com,"__len__"))
print(isinstance(com,Sized))
#print(len(com))
#强制某些子类必须实现的某些方法
#实现一个框架,集成cache(redis,memachary,cache)
#需要设计一个抽象积累,指定子类必须实现某些方法
#如何去模拟一个抽象基类
import abc
# class CachBase():
#
# def get(self,key):
# raise NotImplementedError
#
# def set(self,key,value):
# raise NotImplementedError
#
# class RedisCache(CachBase):
#
# def set(self,key,value):
# print("set")
#
# redis_cache = RedisCache()
# redis_cache.set("key","value")
import abc
class CacheBase(metaclass=abc.ABCMeta):
@abc.abstractmethod
def get(self,key):
pass
@abc.abstractmethod
def set(self,key,value):
pass
class RedisCache(CacheBase):
pass
# def set(self,key,value):
# print("set")
redis_cache = RedisCache()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.