text
stringlengths 37
1.41M
|
---|
# coding:utf-8
# 2019-2-1
"""
导致引用计数+1的情况
对象被创建,例如a=23
对象被引用,例如b=a
对象被作为参数,传入到一个函数中,例如func(a)
对象作为一个元素,存储在容器中,例如list1=[a,a]
导致引用计数-1的情况
对象的别名被显式销毁,例如del a
对象的别名被赋予新的对象,例如a=24
一个对象离开它的作用域,例如f函数执行完毕时,func函数中的局部变量(全局变量不会)
对象所在的容器被销毁,或从容器中删除对象
"""
import gc
class A(object):
pass
class B(object):
pass
def foo():
collected = gc.collect()
print("start gc.collect(): ", collected)
a = A()
b = B()
a.b = b
b.a = a
del a
del b
collected = gc.collect()
print("end gc.collect(): ", collected)
grbage = gc.garbage()
print("gc.garbage(): ", garbage)
if __name__ == '__main__':
gc.set_debug(gc.DEBUG_LEAK) #设置gc模块的日志
foo() |
'''
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
'''
# 2018-6-16
# Reverse Integer
import sys
# 利用字符串转换
class Solution1(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
strs = str(x)
res = ""
pre = ""
for i in strs:
if i == "0":
continue
elif i == "-":
pre = i
else:
res = i + res
res = pre+res
r = int(res)
if r > 2**31 or r < -2**31:
return 0
return r
# 利用余数
class Solution2(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
negative = False
if x < 0:
negative = True
if negative:
x = -x
r = 0
while x > 0 :
r = r * 10 + x % 10
x /= 10
if negative:
r = -r
if r > 2**31 or r < -2**31:
return 0
return r
# test
x = -3320
test = Solution1()
re = test.reverse(x)
print(re) |
# coding=utf-8
import sys
"""
1. We have an integer array where all the elements appear twice while only 1 elements appears once. Please find the 1 elements. [直接说出步骤,然后换成下面这道题]
2. We have an integer array where all the elements appear twice while only 2 elements appears once. Please find the 2 elements.
数组中只有两个数字只出现了一次,其余数字重复了两次,找出这两个数字
使用异或操作--最简单
面试官说不要使用异或操作,我想出来使用快排,然后面试官说对的,但细节有点问题
说了细节之后开始写代码
"""
# 代码有bug,没有完成
# 2019/8/27 17:03 完成
def findUnique(nums):
ret = []
left, right = 0, len(nums) - 1
while True:
boundary = quickHelper(nums, left, right)
print("[debug] boundary: {}".format(boundary))
retL = handle(nums, left, boundary+1)
retR = handle(nums, boundary+1, right+1)
print("[debug] retL: {}, retR: {}".format(retL, retR))
# 1. left ret not equals 0
if retL != 0:
if retR != 0:
ret.append(retL)
ret.append(retR)
break
else:
right = boundary
# 2. right
else: # left ret equals 0
left = boundary
return ret
def handle(nums, left, right):
ret = 0
for n in nums[left:right]:
ret = ret ^ n
return ret
def quickHelper(nums, left, right):
mid = left + (left - right) >> 1
nums[mid], nums[right] = nums[right], nums[mid]
boundary = left
for i in range(left, right):
if nums[i] <= nums[right]:
nums[i], nums[boundary] = nums[boundary], nums[i]
boundary += 1
nums[boundary], nums[right] = nums[right], nums[boundary] # exchange
return boundary
def test():
nums = [1,2,5,4,4,2,3,1]
ret = findUnique(nums)
print(ret)
if __name__ == '__main__':
test() |
# 2018-8-16
# 算法导论 P245
"""
压缩原理:统计词频
编码分为:
a. 定长编码
非满二叉树
b. 变长编码
满二叉树,比定长编码节约25%空间
"""
class TreeNode(object):
"""Define a tree"""
def __init__(self, x=None):
self.freq = x
self.left = None
self.right = None
class minQueue(object):
"""
最小优先列队,先进先出。
有待改进。
"""
def __init__(self,n=[]):
self.queue = []
def popMin(self):
"""
弹出最小项
"""
# print(self.queue)
r = self.queue[-1]
self.queue.pop()
return r
def insert(self, x):
self.queue.append(x)
self.queue = sorted(self.queue,key=lambda n : n.freq,reverse=True)
def huffman(f):
"""
f 为词频字典
"""
lens = len(f)
nums = [f[i] for i in f] # 构造一个数组存储词频以方便操作,最后映射关键字
nums = sorted(nums,reverse=True)
print("词频: ", nums)
# 将每个节点插入最小列队中
Q = minQueue()
for i in nums:
Q.insert(TreeNode(i))
# 每次抽取最小的两个节点合并成一个节点,然后将合并后的节点插入列队中供下次使用
for i in range(len(nums)-1):
z = TreeNode()
z.left = Q.popMin()
z.right = Q.popMin()
if z.right == None:
Q.insert(z.left)
break
z.freq = z.left.freq + z.right.freq
Q.insert(z)
tree = Q.popMin()
# 遍历树得到编码
r = traversal(tree,nums)
# 映射还原
huff = {}
for i in f:
huff[i] = r[nums.index(f[i])]
return huff
def traversal(tree,nums):
"""
返回每个叶子的编码,返回数组的索引跟nums一一对应
"""
stack = [] # 存储每个节点
code = {} # 存储每个节点的编码
cur = tree # cur 为当前处理项
code[tree] = [] # 根节点编码为空
pre = tree
res = [0] * len(nums)
while cur != None or len(stack) != 0:
while cur != None:
# print(code,"-----", cur, cur.freq,"---------",pre, pre.freq)
stack.append(cur)
dummy = cur
# if cur not in code:
# code[cur] = code[pre].copy()
# code[cur].append(0)
cur = cur.left
if cur not in code:
code[cur] = code[dummy].copy()
code[cur].append(0)
pre = dummy
cur = stack.pop()
# 遇到叶子的时候生成编码
if cur.right == None:
# print("result=======>", code[cur], cur.freq)
res[nums.index(cur.freq)] = code[cur]
pre = cur
cur = cur.right
if cur not in code:
code[cur] = code[pre].copy()
code[cur].append(1)
# 将数组中的数字转换成字符并连接成字符串
c = 0
for i in res:
tmp = ""
for j in i:
tmp += str(j)
res[c] = tmp
c += 1
return res
if __name__ == "__main__":
f = {'a':45,'b': 13, 'c':12, 'd':16, 'e':9, 'f':5}
res = huffman(f)
print(res)
"""
输出结果:
词频: [45, 16, 13, 12, 9, 5]
{'a': '0', 'b': '101', 'c': '100', 'd': '111', 'e': '1101', 'f': '1100'}
[Finished in 0.2s]
"""
|
# 2018-8-5 ~ 2018-8-6
# Bucket Sort
# Reference
# Introduction to Algorithms [P112]
# Data Structures and Algorithm Analysis in C [P189]
# https://www.cnblogs.com/shihuc/p/6344406.html
class BucketSort(object):
"""
1. Define the data mapping function f(x) according to the data type
2. Plan the data separately into the bucket
3. Sort the bucket based on sequence number
4. Sort the data in each bucket (fast row or other sorting algorithm)
5. Map the sorted data to the original input array as output
"""
def __init__(self, A, m = 33):
self.A = A # Integer Arrary
self.lens = len(A)
self.m = m
self.bucket = {}
def sort(self):
self.putIntoBucket()
nums = self.sortBucket()
# print(nums)
return self.merge(nums)
def putIntoBucket(self):
for n in self.A:
m = self.getBuck(n)
if m in self.bucket:
self.bucket[m].append(n)
else:
self.bucket[m] = [n]
def getBuck(self, n):
try:
n = int(n) % self.m
except:
sums = 0
for i in n:
sums += ord(i)
n = ord(sums) % self.m
return n
def sortBucket(self):
num = [] # store the bucket number
for i in self.bucket:
num.append(i)
func = QuickSort(num)
nums = func.quickSort()
for n in nums:
f = QuickSort(self.bucket[n])
nu = f.quickSort()
self.bucket[n] = nu
return nums
def merge(self, nums):
res = self.bucket[nums[0]]
i = 1
while i < len(nums):
tmp = []
cur = self.bucket[nums[i]]
while len(res) > 0 and len(cur) > 0:
if res[0] <= cur[0]:
tmp.append( res.pop(0) )
else:
tmp.append( cur.pop(0) )
tmp += res
tmp += cur
res = tmp
i += 1
return res
class QuickSort(object):
"""
Quick Sort
"""
def __init__(self, A):
self.A = A
self.lens = len(A)
def swap(self, a, b):
tmp = self.A[a]
self.A[a] = self.A[b]
self.A[b] = tmp
def findPivot(self, left, right):
mid = (left + right) / 2
self.swap(mid, right)
boundary = left
for index in range(left, right):
if self.A[index] < self.A[right]:
self.swap(boundary, index)
boundary += 1
self.swap(boundary, right)
return boundary
def quickSort(self):
self.quicksortHelper(0, self.lens - 1)
return self.A
def quicksortHelper(self, left, right):
if left < right:
pivot = self.findPivot(left, right)
self.quicksortHelper(left, pivot - 1)
self.quicksortHelper(pivot + 1, right)
lists = [5,2,8,4,3,7,6,9,1,10,13,21,34,132]
test = BucketSort(lists)
re = test.sort()
print(re) |
'''
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
'''
# 2018-11-6
# 279. Perfect Squares
# https://leetcode.com/problems/perfect-squares/
# Time Limit Exceeded/ 112
class Solution:
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
if n < 2:
return n
nums = []
for i in range(1, n):
if i * i <= n:
nums.append(i**2)
else:
break
# print(nums)
res = []
self.dp(nums, n, [], 0, res)
# print(res)
return min(res)
def dp(self, nums, n, tmp, index, res):
total = sum(tmp)
# print(res)
if total == n:
len_tmp = len(tmp)
res.append(len_tmp)
else:
for i in range(index, len(nums)):
if sum(tmp) + nums[i] > n:
break
tmp.append(nums[i])
self.dp(nums, n, tmp, i, res)
tmp.pop()
# https://leetcode.com/problems/perfect-squares/discuss/71475/Short-Python-solution-using-BFS
class Solution2:
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
if n < 2:
return n
nums = []
for i in range(1, n):
if i * i <= n:
nums.append(i**2)
else:
break
check = [n]
ret = 0
while check:
ret += 1
tmp = set()
for x in check:
for y in nums:
if x == y:
return ret
if x < y:
break
tmp.add(x - y)
check = tmp
return ret
n = 112
test = Solution2()
res = test.numSquares(n)
print(res) |
'''
There are n different online courses numbered from 1 to n. Each course has some duration(course length) t and closed on dth day. A course should be taken continuously for t days and must be finished before or on the dth day. You will start at the 1st day.
Given n online courses represented by pairs (t,d), your task is to find the maximal number of courses that can be taken.
Example:
Input: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]
Output: 3
Explanation:
There're totally 4 courses, but you can take 3 courses at most:
First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.
Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day.
Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day.
The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.
Note:
The integer 1 <= d, t, n <= 10,000.
You can't take two courses simultaneously.
'''
# 2018-9-2
# 630. Course Schedule III
# TLE
class Solution:
def scheduleCourse(self, courses):
"""
:type courses: List[List[int]]
:rtype: int
"""
courses.sort(key = lambda x: x[1])
sumTime = 0
maxQueue = []
for course in courses:
t = course[0]
d = course[1]
maxQueue.append(t)
sumTime += t
if sumTime > d:
curMax = max(maxQueue)
maxIndex = maxQueue.index(curMax)
maxQueue.pop(maxIndex)
sumTime -= curMax
return len(maxQueue)
test = Solution()
courses = [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]
res = test.scheduleCourse(courses)
print(res) |
"""
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Example 2:
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,9]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
"""
# 2018-6-21
# Insert Intervals
# Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution:
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
i = 0
index = 0
flag = 0
res,first,second,tmp = [],[],[],[]
while i < len(intervals):
# print("newInterval:",i,newInterval.start,newInterval.end)
if newInterval.end < intervals[i].start or newInterval.start > intervals[i].end:
res.append(intervals[i])
i += 1
continue
first.append(intervals[i].start)
first.append(intervals[i].end)
second.append(newInterval.start)
second.append(newInterval.end)
for f in first:
tmp.append(f)
for s in second:
tmp.append(s)
tmp.sort()
if tmp[1] == tmp[2]:
newInterval = Interval(tmp[0],tmp[-1])
tmp,first,second = [],[],[]
if flag == 0:
index = i
flag = 1
elif tmp[0:2] != first:
newInterval = Interval(tmp[0],tmp[-1])
tmp,first,second = [],[],[]
if flag == 0:
flag = 1
index = i
i += 1
# return res
# print(index,newInterval,res)
if len(intervals) == len(res):
res.append(newInterval)
return sorted(res, key=lambda i: i.start)
else:
res.insert(index,newInterval)
return sorted(res, key=lambda i: i.start)
nums = [[1,2],[3,5],[6,7],[8,10],[12,16]]
newInterval = [4,9]
newInterval = Interval(newInterval[0],newInterval[1])
intervals = []
for i in nums:
add = Interval(i[0],i[1])
intervals.append(add)
test = Solution()
res = test.insert(intervals,newInterval)
for r in res:
print(r.start,r.end) |
# 2018-9-2
# Binary Indexed Tree
# https://www.hackerearth.com/zh/practice/notes/binary-indexed-tree-made-easy-2/
# 推荐看: https://www.cnblogs.com/whensean/p/6851018.html
# 网页底部有数据结构总览表: https://en.wikipedia.org/wiki/Fenwick_tree
# 来源于LeetCode
# 307. Range Sum Query - Mutable
# Binary Indexed Tree
# 关键在于 k -= (k & -k) 和 k += (k & -k), 前者用于update后者用于sum
class NumArray:
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.nums = nums
self.lens = len(nums)
# 初始化存储sum的数组
self.BIT = [0] * (self.lens + 1)
# map(update, range(self.lens), nums)
for i in range(self.lens):
k = i + 1
while k <= self.lens:
self.BIT[k] += nums[i]
k += (k & -k)
def update(self, i, val):
"""
update 操作一直都是遍历左侧
:type i: int
:type val: int
:rtype: void
"""
diff = val - self.nums[i]
self.nums[i] = val
i += 1
while i <= self.lens:
self.BIT[i] += diff
i += (i & -i)
# print(self.BIT)
def sumRange(self, i, j):
"""
sum: 遍历右侧
上一层已经把左侧的值加上去了,而左侧的索引又是小于右侧,所以是合理的
:type i: int
:type j: int
:rtype: int
"""
res = 0
j += 1
while j > 0:
res += self.BIT[j]
j -= (j & -j)
while i > 0:
res -= self.BIT[i]
i -= (i & -i)
return res
# Your NumArray object will be instantiated and called as such:
nums = [1, 3, 5]
obj = NumArray(nums)
obj.update(1, 2)
obj.update(1, 44)
obj.update(2, 44)
r1 = obj.sumRange(0, 2)
print(r1,obj.nums) |
# coding:utf-8
# 2019-2-4
"""建造模式:将产品的内部表象和产品的生成过程分割开来,从而使一个建造过程生成具有不同的内部表象的产品对象。建造模式使得产品内部表象可以独立的变化,客户不必知道产品内部组成的细节。建造模式可以强制实行一种分步骤进行的建造过程
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
角色:
抽象建造者(Builder)
具体建造者(Concrete Builder)
指挥者(Director)
产品(Product)
建造者模式与抽象工厂模式相似,也用来创建复杂对象。主要区别是建造者模式着重一步步构造一个复杂对象,而抽象工厂模式着重于多个系列的产品对象。
适用场景:
当创建复杂对象(对象由多个部分组构成, 且对象的创建要经过多个不同的步骤, 这些步骤也许还要遵从特定的顺序)
优点:
隐藏了一个产品的内部结构和装配过程
将构造代码与表示代码分开
可以对构造过程进行更精细的控制
---------------------
作者:孤傲的天狼
来源:CSDN
原文:https://blog.csdn.net/weixin_42040854/article/details/80612620
版权声明:本文为博主原创文章,转载请附上博文链接!"""
class computer(object):
"""计算机类"""
def __init__(self, serial_number):
self.serial_number = serial_number
self.gpu = None
self.cpu = None
def __str__(self):
return "cpu : {self.gpu}\ngpu : {self.cpu}".format(self=self)
class computerBuilder(object):
"""建造者"""
def __init__(self, serial_number):
self.computer = computer(serial_number)
def gpu_config(self, gpu):
self.computer.gpu = gpu
def cpu_config(self, cpu):
self.computer.cpu = cpu
class HardwareEngineer(object):
"""指挥者
参数入口在指挥者函数上
返回值也是由指挥者返回"""
def __init__(self, builder=None):
self.builder = builder
def construct(self, serial_number, gpu, cpu):
self.builder = computerBuilder(serial_number)
self.builder.gpu_config(gpu)
self.builder.cpu_config(cpu)
@property
def computer(self):
return self.builder.computer
def main():
serial_number = 'aaa'
engineer = HardwareEngineer()
engineer.construct(serial_number=serial_number, gpu='Inter Core 7', cpu='8BG')
computer = engineer.computer
print(computer)
if __name__ == '__main__':
main() |
'''
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
'''
# 2018-6-19
# Longest valid Parenthese
# 暴力破解(超出时间限制)
class Solution1:
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0:
return 0
dicts = {")":"(","(":"#"}
r = []
res = []
index = []
res.append(0)
k = 0
i = 0
while i < len(s):
if dicts[s[i]] in r:
k += 2
r.pop()
index.pop()
else:
index.append(i)
r.append(s[i])
res.append(k)
i += 1
res.pop(0)
index.append(i-1)
print(r,k,maxs,res,index)
if len(index) == 1:
return res[-1]
n = 0
node = []
node.append(res[index[0]]-res[0])
while n < len(index)-1:
node.append(res[index[n+1]]-res[index[n]])
n += 1
print(node)
return max(node)
class Solution2:
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
stack = [0]
longest = 0
for c in s:
if c == "(":
stack.append(0)
else:
if len(stack) > 1:
val = stack.pop()
stack[-1] += val + 2
longest = max(longest, stack[-1])
else: # 可以不需要else判断
stack = [0]
# print(c,longest,stack)
return longest
# s = ")()((()()(())"
# s = ""
s = "())))((())(())()(("
test = Solution2()
res = test.longestValidParentheses(s)
print(res)
|
# coding:utf-8
"""给定一个字符串A,一个字符串B,求B在A中出现的次数"""
import sys
def solver(a, b):
ret = 0
lenB = len(b)
lenA = len(a)
if lenA < lenB:
return ret
for i in range(0, lenA - lenB + 1):
cur = a[i:i+lenB]
if cur == b:
ret += 1
return ret
def test():
a, b = "zyzyzyz", "zyz"
ret = solver(a, b)
print(ret)
def inputs():
a = sys.stdin.readline().strip()
b = sys.stdin.readline().strip()
ret = solver(a, b)
print(ret)
if __name__ == '__main__':
inputs() |
from tkinter import *
from tweet import *
def search():
tweet_list.delete(0,'end')
index = 0
count = input_count.get()
username = input_name.get()
tweets = get_result(username,count).most_common()
for tweet in tweets:
index+=1
tweet_list.insert(index, str(tweet[0])+":"+str(tweet[1]))
root = Tk()
root.title("Twitter Search")
root.geometry("300x400")
root.resizable(False,False)
lbl_id = Label(root, text="트위터 아이디")
lbl_id.pack()
input_name = Entry(root)
input_name.insert(0,"아이디")
input_name.pack()
input_count = Entry(root)
input_count.insert(0,"개수")
input_count.pack()
btn = Button(root, text="검색" , command=search)
btn.pack()
lbl_list = Label(root, text="결과")
lbl_list.pack()
tweet_list = Listbox()
tweet_list.config(width=30)
tweet_list.pack()
root.mainloop() |
#
# @lc app=leetcode.cn id=88 lang=python3
#
# [88] 合并两个有序数组
#
# @lc code=start
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
# 在判断m和n时,需要判别m与n的关键性
# nums2的关键点>nums1,理由为它是添加的核心,无它则该操作无意义
if n == 0:
pass
elif m == 0:
nums1[:n]=nums2[:n]
else:
# 与普通数组合并不同的是,此次是添加至数组1上
# 需要确定原数组的数字是否遍历完毕,故添加k做原数组计数用
i, j, k = 0, 0, 0
while k < m and j < n:
if nums1[i] < nums2[j]:
i += 1
k += 1
continue
# 添加=的原因是保持判等空间闭合
if nums2[j] <= nums1[i]:
nums1.insert(i, nums2[j])
nums1.pop()
j += 1
i += 1
continue
if j < n:
nums1[m + j:] = nums2[j:]
# @lc code=end
|
#
# @lc app=leetcode.cn id=107 lang=python3
#
# [107] 二叉树的层序遍历 II
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
if root == None:
return []
result, iqueue = [], []
iqueue.append(root)
while len(iqueue) > 0:
temp, l = [], len(iqueue)
for i in range(0, l):
cur = iqueue[0]
iqueue = iqueue[1:]
temp.append(cur.val)
if cur.left != None:
iqueue.append(cur.left)
if cur.right != None:
iqueue.append(cur.right)
result.insert(0, temp)
return result
# @lc code=end
|
def goroad(road: list, curp: list, direc: int):
left, right = curp[0], curp[1]
if direc == 2:
while right >= 0:
if road[left][right] == '#':
break
right -= 1
return [left, right + 1]
elif direc == 3:
while right < len(road[0]):
if road[left][right] == '#':
break
right += 1
return [left, right - 1]
elif direc == 0:
while left >= 0:
if road[left][right] == '#':
break
left -= 1
return [left + 1, right]
elif direc == 1:
while left < len(road):
if road[left][right] == '#':
break
left += 1
return [left - 1, right]
def finddirec( direction: list, direc: str):
for i in range(len(direction)):
if direc == direction[i]:
return i
return -1
inputlist = list(map(int, input().split(' ')))
n, m, k = inputlist[0], inputlist[1], inputlist[2]
road, mark = [], []
for _ in range(n):
temp = input()
road.append(temp)
for _ in range(k):
temp = input()
mark.append(temp)
direction = ["NORTH", "SOUTH", "WEST", "EAST"]
curposition = [0, 0]
for i in range(n):
for j in range(m):
if road[i][j] == '@':
curposition = [i, j]
break
while len(mark) != 0:
if mark[0] in direction:
direc = finddirec(direction, mark[0])
curposition = goroad(road, curposition, direc)
mark = mark[1:]
print(curposition[0] + 1, curposition[1] + 1)
|
from sys import exit
def ip_valid(ip):
'''This functions tests if IPv4 address is valid. If yes, it returns IPv4 address.
Function will accepts IP address from classess A, B and C except:
- 127.0.0.0/8 - uses for loopback addresses
- 169.254.0.0/16 - used for link-local addresses'''
ip_octets = ip.split(".")
if len(ip_octets) == 4 and 1 <= int(ip_octets[0]) <= 223 and int(ip_octets[0]) != 127 and (int(ip_octets[0]) != 169 or int(ip_octets[1]) != 254) \
and 0 <= int(ip_octets[1]) <= 255 and 0 <= int(ip_octets[2]) <= 255 and 0 <= int(ip_octets[3]) <= 255:
return ip
def subnet_mask_valid(subnet_mask):
'''This function tests if subnet mask is valid. If yes, it returns subnet mask.
Valid subnet masks are in range /8 - /32.'''
subnet_octets = subnet_mask.split(".")
valid_masks = (255, 254, 252, 248, 240, 224, 192, 128, 0)
if len(subnet_octets) == 4 and int(subnet_octets[0]) == 255 and int(subnet_octets[1]) in valid_masks and int(subnet_octets[2]) in valid_masks \
and int(subnet_octets[3]) in valid_masks and int(subnet_octets[0]) >= int(subnet_octets[1]) >= int(subnet_octets[2]) \
and int(subnet_octets[2]) >= int(subnet_octets[3]):
if int(subnet_octets[0]) != 255 and int(subnet_octets[1]) ==0 and int(subnet_octets[2]) == 0 and int(subnet_octets[3]) == 0:
return subnet_mask
elif int(subnet_octets[0]) == 255:
if int(subnet_octets[1]) != 255 and int(subnet_octets[2]) == 0 and int(subnet_octets[3]) == 0:
return subnet_mask
elif int(subnet_octets[1]) == 255:
if int(subnet_octets[2]) != 255 and int(subnet_octets[3]) == 0:
return subnet_mask
elif int(subnet_octets[2]) == 255:
return subnet_mask
def ip_binary(ip):
'''This fuction returns IP address in binary format.'''
ip_octets = ip.split(".")
ip_addr_binary = [(8 - len(bin(int(octet)).lstrip("0b"))) * "0" + bin(int(octet)).lstrip("0b") for octet in ip_octets]
ip_addr_binary = "".join(ip_addr_binary)
return ip_addr_binary
def subnet_mask_binary(subnet_mask):
'''This function returns subnet mask in binary format'''
subnet_octets = subnet_mask.split(".")
subnet_binary = [(8 - len(bin(int(octet)).lstrip("0b"))) * "0" + bin(int(octet)).lstrip("0b") for octet in subnet_octets]
subnet_binary = "".join(subnet_binary)
return subnet_binary
def network_address(ip, subnet_mask):
'''This function returns network address for given IP address if subnet mask is not /31 or /32'''
count_ones = subnet_mask_binary(subnet_mask).count("1")
count_zeros = 32 - count_ones
if count_zeros > 2:
network_addr_bin = ip_binary(ip)[:count_ones] + count_zeros * "0"
network_addr_bin = [network_addr_bin[i:i+8] for i in range(0, 32, 8)]
network_addr = [str(int(octet, 2)) for octet in network_addr_bin]
network_addr = ".".join(network_addr)
return network_addr
def broadcast_address(ip, subnet_mask):
'''This function returns broadcast adress for given IP address if subnet mask is not /31 or /32.'''
count_ones = subnet_mask_binary(subnet_mask).count("1")
count_zeros = 32 - count_ones
if count_zeros > 2:
broadcast_addr_bin = ip_binary(ip)[:count_ones] + count_zeros * "1"
broadcast_addr_bin = [broadcast_addr_bin[i:i+8] for i in range(0, 32, 8)]
broadcast_addr = [str(int(octet, 2)) for octet in broadcast_addr_bin]
broadcast_addr = ".".join(broadcast_addr)
return broadcast_addr
def first_ip_address(ip, subnet_mask):
'''This function returns first IP address in the subnet if subnet mask is not /31 or /32.'''
count_ones = subnet_mask_binary(subnet_mask).count("1")
count_zeros = 32 - count_ones
if count_zeros > 2:
first_addr_bin = ip_binary(ip)[:count_ones] + (count_zeros - 1) * "0" + "1"
first_addr_bin = [first_addr_bin[i:i+8] for i in range(0, 32, 8)]
first_addr = [str(int(octet, 2)) for octet in first_addr_bin]
first_addr = ".".join(first_addr)
return first_addr
def last_ip_address(ip, subnet_mask):
'''This function returns last IP address in the subnet if subnet mask is not /31 or /32.'''
count_ones = subnet_mask_binary(subnet_mask).count("1")
count_zeros = 32 - count_ones
if count_zeros > 2:
last_addr_bin = ip_binary(ip)[:count_ones] + (count_zeros - 1) * "1" + "0"
last_addr_bin = [last_addr_bin[i:i+8] for i in range(0, 32, 8)]
last_addr = [str(int(octet, 2)) for octet in last_addr_bin]
last_addr = ".".join(last_addr)
return last_addr
def wildcard_mask(subnet_mask):
'''This function returns wildcard mask for a given subnet mask.'''
subnet_octets = subnet_mask.split(".")
wildcard_mask = [str(255 - int(octet)) for octet in subnet_octets]
wildcard_mask = ".".join(wildcard_mask)
return wildcard_mask
def cidr_notation(subnet_mask):
'''This function returns subnet mask in CIDR notation.'''
count_ones = subnet_mask_binary(subnet_mask).count("1")
count_zeros = 32 - count_ones
cidr = "/" + str(count_ones)
return cidr
def usable_hosts_per_subnet(subnet_mask):
'''This function returns number of usable hosts per subnet if if subnet mask is not /31 or /32.'''
count_ones = subnet_mask_binary(subnet_mask).count("1")
count_zeros = 32 - count_ones
if count_zeros > 2:
hosts_per_subnet = (2 ** count_zeros - 2)
return hosts_per_subnet
def main():
while True:
try:
ip_input = input("Enter an IP address: ")
if ip_valid(ip_input):
ip = ip_input
break
else:
print("IP address is invalid.")
except ValueError:
print("IP address is invalid.")
except KeyboardInterrupt:
print("\nGoodbye.")
exit()
while True:
try:
subnet_input = input("Enter a subnet mask: ")
if subnet_mask_valid(subnet_input):
subnet_mask = subnet_input
break
else:
print("Subnet mask is invalid.")
except ValueError:
print("Subnet mask is invalid.")
except KeyboardInterrupt:
print("\nGoodbye.")
exit()
print("-" * 50)
print(f"IP address: {ip}")
print(f"Subnet mask: {subnet_mask} {cidr_notation(subnet_mask)}")
print(f"Network address: {network_address(ip, subnet_mask)}")
print(f"Broadcast address: {broadcast_address(ip, subnet_mask)}")
print(f"First IP in the subnet: {first_ip_address(ip, subnet_mask)}")
print(f"Last IP in the subnet: {last_ip_address(ip, subnet_mask)}")
print(f"Usable hosts per subnet: {usable_hosts_per_subnet(subnet_mask)}")
print(f"Wildcard mask: {wildcard_mask(subnet_mask)}")
if __name__ == "__main__":
main()
|
def bubble_sort(seq):
for i in range(len(seq)):
for j in range(i, len(seq)):
if seq[j] < seq[i]:
tmp = seq[j]
seq[j] = seq[i]
seq[i] = tmp
def selection_sort(seq):
for i in range(len(seq)):
position = i
for j in range(i, len(seq)):
if seq[position] > seq[j]:
position = j
if position != i:
tmp = seq[position]
seq[position] = seq[i]
seq[i] = tmp
def insertion_sort(seq):
if len(seq) > 1:
for i in range(1, len(seq)):
while i > 0 and seq[i] < seq[i - 1]:
tmp = seq[i]
seq[i] = seq[i - 1]
seq[i - 1] = tmp
i = i - 1
# -*- coding: utf-8 -*-
if __name__ == "__main__":
print("--------bubble_sort-------------")
seq = [21, 3, 33, 41, 7, 6, 8, 9, 11]
bubble_sort(seq)
print(seq)
print("--------selection_sort-------------")
seq = [88, 44, 33, 5, 15, 6, 8, 9, 11]
selection_sort(seq)
print(seq)
print("--------insertion_sort-------------")
seq = [777, 44, 33, 54, 17, 26, 1111, 100, 11]
insertion_sort(seq)
print(seq)
|
def factorial(n):
if n==1:
return 1
else:
return n * factorial(n-1)
print(factorial(10))
def sum(n):
if n ==1:
return 1
else:
return n +sum(n-1)
def tail_sum(n,accumulator=0):
if n==0:
return accumulator
else:
return tail_sum(n-1, accumulator+n)
print(tail_sum(20)) |
passerby_speech='Hello'
if passerby_speech == 'Hello':
print("Hello how are you ????")
elif passerby_speech=='hi':
print("Hi How are you????")
else:
print("Hey")
"""
Ternary operator demo
"""
me = "Hi" if passerby_speech =='Hi' or passerby_speech=='Hello' else "Hey"
print(me)
a=3
a =7 if 3**3 >9 else 14
print(a) |
print("Today I had {0} cup of {1}".format(3,'Coffee'))
print("prices: {x},{y},{z}".format(x=20,y=40,z=80))
print("The {vehicle} had {0} crashes in {1} months".format(5,6,vehicle='car')) |
class Person:
def __init__(self, pid, x, y, rescue_time):
self.id = pid
self.x = x
self.y = y
self.rescue_time = rescue_time
self.hospital_idx = None
self.hospital_x = None
self.hospital_y = None
def assign_hospital(self, hospital_id, x, y):
self.hospital_id = hospital_id
self.hospital_x = x
self.hospital_y = y
def time_from_hospital(self):
return abs(self.x - self.hospital_x) + abs(self.y - self.hospital_y)
def get_time_from(self, px, py):
return abs(self.x - px) + abs(self.y - py)
def __str__(self):
return "Person: {0} ({1}, {2}) {3}s {4}s\n".format(self.id, self.x, self.y, self.rescue_time, self.time_from_hospital())
def __repr__(self):
return "Person: {0} ({1}, {2}) {3}s {4}s\n".format(self.id, self.x, self.y, self.rescue_time, self.time_from_hospital()) |
"""Solutions to Data Manipulation section of 100 DS questions set."""
import numpy as np
def num_to_color(arr):
"""Return array replacing 0's with 'red' and 1's are replaced with 'blue'.
Converts 0's to the string 'red' and 1's to the string 'blue'.
Parameters
----------
arr: numpy array
An array of 0's and 1's.
Returns
-------
arr: numpy array
An array of the strings 'red' and 'blue'.
"""
color_arr = np.array(['red', 'blue'])
return color_arr[arr]
def compute_part_mean(x, b):
"""Return the mean of x where b == 0 and the mean of x where b == 1.
x and b must have equal lengths.
Parameters
----------
x: numpy array
Array of generic numeric data.
b: numpy array
Array of 0's and 1's.
Return
------
b_0_mean: float
Mean of X at the indices where b == 0.
b_1_mean: float
Mean of X at the indeices where b == 1.
"""
return x[b == 0].mean(), x[b == 1].mean()
def find_smallest_angle(x, M):
"""Return the row in M that has the smallest angle with x.
The number of columns in M must equal the length of x.
Parameters
----------
x: numpy array
A vector.
M: numpy array
2 dimensional matrix.
Returns
-------
row_i: int
The index of the row from M that has the smallest angle with x.
row: numpy array
The row from M that has the smallest angle with x.
"""
distances = M.dot(x) / (np.linalg.norm(x) * np.linalg.norm(M, axis=1))
row_i = distances.argmax()
return row_i, M[row_i]
def offset_diagonals(n):
"""Return matrix with ones on the diagonals above and below main diagonal.
Matrix is a square matrix of shape (n, n).
Parameters
----------
n: int
The dimensions of the returned matrix.
Returns
-------
final_matrix: numpy array, shape = (n, n)
Square matrix with ones on diagonals above and below main diagonal.
"""
final_matrix = np.zeros((n, n))
diag_indices1 = np.arange(0, n-1)
diag_indices2 = np.arange(1, n)
final_matrix[(diag_indices1, diag_indices2)] = 1
final_matrix[(diag_indices2, diag_indices1)] = 1
return final_matrix
def cols_with_neg_value(M):
"""Return matrix made of the cols of M where at least one value is <0.
Parameters
----------
M: numpy array
Returns
-------
numpy array
Matrix containing only cols of M where at least one value is negative.
"""
return M[:, np.min(M, axis=0) < 0]
def swap_rows(M, i, j):
"""Swap the row i with row j in M.
Modifies M in-place!
Parameters
----------
M: numpy array
A matrix of data.
i: int
Index of first row
j: int
Index of second row
Returns
-------
None
"""
M[[i, j]] = M[[j, i]]
|
#Local Search
import sys as sys
import random as rd
def testSolution(sol):
for k in range(len(sol)-1):
for i in range(k+1,len(sol)):
if(sol[k] == sol[i]+(i-k) or sol[k] == sol[i]-(i-k)):
return False
return True
def iterations(sol,n):
for j in range(n):
if(testSolution(sol)):
return j,sol
else:
rd.shuffle(sol)
return "No solution found in " + str(n) +" iterations"
it = int(sys.argv[2])
st = list(range(int(sys.argv[1])))
print iterations(st,it)
|
from turtle import Turtle
import random
class Food(Turtle):
def __init__(self):
super().__init__("circle")
self.penup()
self.shapesize(0.5, 0.5)
self.color("red")
self.speed("fastest")
x = random.randint(-14, 14) * 20
y = random.randint(-13, 14) * 20
self.goto(x=x, y=y)
def refresh(self):
x = random.randint(-14, 14) * 20
y = random.randint(-14, 14) * 20
self.goto(x=x, y=y) |
#goes through list num by num to find the given num
def linearSearch(numlist, numSought):
index = -1
i = 0
found = False
while i < len(numlist) and found == False:
if numlist[i] == numSought:
index = i
found = True
i = i + 1
return index
#test list
numlist = [1,2,3,4,5,6,7,8,9,10,12,14,15,16,25,26,467]
#main program
print(linearSearch(numlist, 16))
|
def insertion_sort(arr):
for i in range(1, len(arr)):
cur_num = arr[i]
j = i - 1
while j >= 0 and cur_num < arr[j]:
arr[j+1] = arr[j]
j = j - 1
arr[j+1] = cur_num
return arr
if __name__ == '__main__':
A = [20, 15, 2, 3, 25, 30, 14, 26, 5, 10, 18, 1]
s = insertion_sort(A)
print(s)
|
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def insert_at_beginning(self, data):
node = Node(data, self.head)
self.head = node
def insert_at_end(self, data):
if self.head is None:
self.head = Node(data, None)
return
itr = self.head
while itr.next:
itr = itr.next
itr.next = Node(data, None)
def insert_values(self, data_list):
self.head = None
for data in data_list:
self.insert_at_end(data)
def get_length(self):
count = 0
itr = self.head
while itr:
count += 1
itr = itr.next
return count
def remove_at(self, index):
if index < 0 or index >= self.get_length():
raise Exception("Invalid index")
if index == 0:
self.head = self.head.next
return
count = 0
itr = self.head
while itr:
if count == index-1:
itr.next = itr.next.next
break
itr = itr.next
count += 1
def insert_at(self, index, data):
if index < 0 or index >= self.get_length():
raise Exception("Invalid Index")
if index == 0:
self.insert_at_beginning(data)
return
count = 0
itr = self.head
while itr:
if count == index-1:
node = Node(data, itr.next)
itr.next = node
break
itr = itr.next
count += 1
def print(self):
if self.head is None:
print("Linked list is empty")
return
itr = self.head
listr = ''
while itr:
listr += str(itr.data) + " "
itr = itr.next
print(listr)
if __name__ == '__main__':
ll = LinkedList()
ll.insert_values(['A', 'B', 'C', 'D', 'E'])
ll.insert_at_end('F')
ll.insert_at_beginning('a')
ll.print() # a A B C D E F
ll.remove_at(2)
ll.print() # a A C D E F
ll.insert_at(3, 'Z')
ll.print() # a A C Z D E F
ll.insert_at(3, 'X')
ll.print() # a A C X Z D E F
print("Length of linked list: ", ll.get_length())
# Length of linked list: 8
|
# Dynamic Programming Python implementation of Matrix Chain Multiplication
# See the Cormen book for details of the following algorithm
import sys
# Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
def MatrixChainOrder(p, n):
# For simplicity of the program, one extra row and one extra column are
# allocated in m[][]. 0th row and 0th column of m[][] are not used
m = [[0 for x in range(n)] for x in range(n)]
s = [[0 for x in range(n)] for x in range(n)]
# m[i,j] = Minimum number of scalar multiplications needed to compute
# the matrix A[i]A[i+1]...A[j] = A[i..j] where dimention of A[i] is
# p[i-1] x p[i]
# cost is zero when multiplying one matrix.
for i in range(1, n):
m[i][i] = 0
# L is chain length.
for L in range(2, n):
for i in range(1, n-L+1):
j = i+L-1
m[i][j] = sys.maxint
for k in range(i, j):
# q = cost/scalar multiplications
q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j]
if q < m[i][j]:
m[i][j] = q
s[i][j] = k
return (m, s)
# Driver program to test above function
arr = [5, 10, 3 ,12, 5, 50, 6]
size = len(arr)
m, s = MatrixChainOrder(arr, size);
print m
print s
def PrintOptimalParens(s, i, j):
if i==j:
print "A"+str(i)
else:
print "(";
PrintOptimalParens(s, i, s[i][j]);
PrintOptimalParens(s, s[i][j] + 1, j);
print ")";
PrintOptimalParens(s, 1, 6);
# This Code is contributed by Bhavya Jain
|
from my_util.graph_util import *
__author__ = 'He Li'
"""
Can modify depth first search to add parenthesis theorem
"""
def depth_first_search(graph):
# 0 stands for white
# 1 stands for gray
# 2 stands for black
color = [0] * len(graph)
pi = [None] * len(graph)
d = [0] * len(graph)
f = [0] * len(graph)
time = 0
vertices = fetch_vertices(graph)
for vertex in vertices:
if color[vertex] == 0:
time = depth_visit(graph, vertex, color, pi, d, f, time)
return color, pi, d, f
def depth_visit(graph, u, color, pi, d, f, time):
color[u] = 1
time += 1
d[u] = time
u_adj = fetch_adjacent(graph, u)
for adj in u_adj:
if color[adj] == 0:
pi[adj] = u
time = depth_visit(graph, adj, color, pi, d, f, time)
time += 1
f[u] = time
color[u] = 2
return time
# gg = [
# [0, 1, 1, 0, 0, 0],
# [0, 0, 1, 0, 0, 0],
# [0, 0, 0, 1, 0, 0],
# [0, 1, 0, 0, 0, 0],
# [0, 0, 0, 1, 0, 1],
# [0, 0, 0, 0, 0, 1]
# ]
# print depth_first_search(gg)
|
__author__ = 'He Li'
def fib_dp(n):
c = [0 for i in range(n+1)]
c[0] = 0
c[1] = c[2] = 1
for i in range(3, n+1):
c[i] = c[i-1] = c[i-2]
return c[n]
def fib_memoize(n):
c = [0 for i in range(n+1)]
c[0] = 0
c[1] = c[2] = 1
for i in range(3, n+1):
c[i] = -1
x = fib_look(n, c)
print c
return x
def fib_look(n, c):
if n == 1 or n == 2:
return 1
if n == 0:
return 0
if c[n] == -1:
if c[n-1] == -1:
fib_look(n-1, c)
if c[n-2] == -1:
fib_look(n-2, c)
c[n] = c[n-1] + c[n-2]
return c[n]
print fib_memoize(10)
|
import os
import platform
from operator import attrgetter
def clear():
os.system("clear" if platform.system() == "Darwin" else "cls")
class Book():
def __init__(self):
self.ID = -1
self.name = ""
self.author = ""
self.price = -1.0
def setID(self, val):
self.ID = val
def setName(self, text):
self.name = text
def setAuthor(self, text):
self.author = text
def setPrice(self, val):
self.price = val
#sorted with object, using key
def __repr__(self):
return repr((self.price, self.name, self.ID, self.author))
class BookList():
def __init__(self):
self.List = []
def printAll(self):
for book in self.List:
print(book.ID, book.name, book.author, "$", book.price)
def findBookName(self, text):
flg = False
for book in self.List:
if text in book.name:
if flg == False:#first time print the name
print("查詢結果:")
print(book.name, book.author, "$", book.price)
flg = True
if flg == False:
print("查無此書名")
def printByIncreasePrice(self):
beSorted = sorted(self.List, key=attrgetter("price"))
for book in beSorted:
print(book.name, book.author, book.price)
def printByDecreasePrice(self):
beSorted = sorted(self.List, key=attrgetter("price"), reverse=True)
for book in beSorted:
print(book.name, book.author, book.price)
class Calculator():
def __init__(self, bookList):
self.bookList = bookList
while True:
clear()
print("輸入 0 列出所有書籍。\n輸入 1 進入查詢功能,可以用關鍵字查詢書籍。\n輸入 2 可以將所有書籍依照價格升冪排序。\n輸入 3 則是依價格降冪排序。\n輸入 4 進入結帳區,可以輸入要購買書籍的ID(例如:1,2,3)。")
print("\n請輸入欲執行的功能編號:")
state = input()
try:
state = int(state)
except:
print("請輸入數字")
continue
if state == 0:
self.exec0()
elif state == 1:
self.exec1()
elif state == 2:
self.exec2()
elif state == 3:
self.exec3()
elif state == 4:
self.exec4()
else:
continue
print("\n是否結束程式?(Y/N)")
s = input()
if len(s) == 1:
if s[0] == "Y" or s[0] == "y":
break
elif s[0] =="N" or s[0] == "n":
continue
#else:
#暫時想不到好的處理方法QQ
#else:
#暫時想不到好的處理方法QQ
def exec0(self):
clear()
self.bookList.printAll()
def exec1(self):
clear()
print("請輸入關鍵字查詢書名:")
s = input()
print("\n")
self.bookList.findBookName(s)
def exec2(self):
clear()
print("\n按價格由低至高:")
self.bookList.printByIncreasePrice()
def exec3(self):
clear()
print("\n按價格由高至低:")
self.bookList.printByDecreasePrice()
def exec4(self):
total = 0.0
bookCount = []
for i in range(0, len(self.bookList.List)):
bookCount.append(0)
clear()
self.bookList.printAll()
print("\n請輸入要購買書的ID(例如:1, 2, 3)或是輸入-1結束購買")
val = input()
while True:
try:
val = int(val)
except ValueError:
clear()
self.bookList.printAll()
print("\n輸入錯誤")
print("\n請輸入要購買書的ID(例如:1, 2, 3)或是輸入-1結束購買")
val = input()
continue
if val == -1:
break
elif val>0 and val <= len(self.bookList.List):
val -= 1 #adjust to fit array
print("已加入購物車: "+self.bookList.List[val].name )
total += self.bookList.List[val].price
bookCount[val] += 1 #id為val的book 數量+1
print("\n目前總金額為$"+str(total))
#continue
clear()
self.bookList.printAll()
print("\n已加入購物車: "+self.bookList.List[val].name+" x "+str(bookCount[val]))
print("目前總金額為$"+str(total))
print("\n請輸入要購買書的ID(例如:1, 2, 3)或是輸入-1結束購買")
val = input()
else:
clear()
self.bookList.printAll()
print("\n輸入錯誤")
print("\n請輸入要購買書的ID(例如:1, 2, 3)或是輸入-1結束購買")
val = input()
clear()
print("您的購買清單:")
for i in range(0, len(bookCount)):
if bookCount[i] != 0:
print(self.bookList.List[i].name, "$"+str(self.bookList.List[i].price)+" x", bookCount[i])
print("\n您的帳單金額總共為$" + str(total) + "元")
print("謝謝您的惠顧")
def LoadFile(bookList, filePath):
if os.path.exists(filePath):
f = open(filePath, "r")
for s in f:
s = s.strip()
if len(s) > 0:
s = s.split(",")
book = Book()
book.setID(int(s[0]))
book.setName(s[1])
book.setAuthor(s[2])
book.setPrice(float(s[3]))
bookList.List.append(book)
else:
print("No Input File!")
if __name__=='__main__':
bookList = BookList()
LoadFile(bookList, "./01-input.txt")
Calculator(bookList)
|
# How to determine if triangle exists.
a,b,c= input('Enter three sides of a triangle: ').split(',')
a=float(a)
b=float(b)
c=float(c)
if (b+c > a) and (a+c > b) and (b+a > c):
print('The triangle exists.')
else:
print("The triangle doesnot exists.")
|
# Number of digits in an Integers.
count = 0
num = int(input('Enter any number: '))
while num > 0:
num = num // 10
count += 1
print('Number of digits:', count) |
# How to create multiplication table using for loop?
x = int(input('Which number multiplication table do you want? '))
for y in range(1,11):
print(x, 'x', y, '=', x * y)
|
# How to create a multiplication table using while loop.
x = int(input('Which number multiplication table do you want? '))
y = 0
while y <= 10:
print(x, 'x', y, '=', x*y)
y = y+1 |
# How to check if a point belongs to a circle?
import math
try:
x, y = [float(s) for s in input('Enter points: ').split(',')]
h, k = [float(s) for s in input('Enter centre point: ').split(',')]
r = float(input('Enter radius of circle: '))
check = math.sqrt((x - h) ** 2 + (y - k) ** 2)
if r == check:
print('The point lies at circumference of a circle.')
elif r > check:
print('The point lies inside circle.')
elif r < check:
print('The point lies outside circle')
except:
print('Input valid data only.(separate points with comma)')
|
# How to check for file extension.
exe = ['gif', 'png', 'jpeg', 'jpg', 'txt', 'py']
file_exe = input('Enter you filename: ').split('.')
if len(file_exe) >= 2:
extension = file_exe[-1]
if extension in exe:
print('File extension exists')
else:
print('File extension does not exist')
else:
print('File has no extension')
|
# How to reverse number?
word = input('Enter any word:')
rev = word[::-1]
print(rev)
|
# This is a comment. Python will ignore these lines (starting with #) when running
import math as ma
# To use a math function, write "ma." in front of it. Example: ma.sin(3.146)
# These functions will ask you for your number ranges, and assign them to 'x1' and 'x2'
x1 = raw_input('smallest number to check: ')
x2 = raw_input('largest number to check: ')
# This line will print your two numbers out
print x1, x2
""" Text enclosed in triple quotes is also a comment.
This code should find and output all prime numbers between (and including) the numbers entered initially.
If no prime numbers are found in that range, it should print a statement to the user.
Now we end the comment with triple quotes."""
# The rest is up to you'
x1=eval(x1)
x2=eval(x2)
p="is prime"
for A in range(x1,x2):
p="is prime"
if A < 2:
print false
if A > 2:
for i in range(2,A-1):
if A % i == 0:
print(A,"not prime")
p="not prime"
break
if p=="is prime":
print(A,"is prime")
|
import numpy as np
class Knapsack01Problem:
"""This class encapsulates the Knapsack 0-1 Problem from RosettaCode.org
"""
def __init__(self):
# initialize instance variables:
self.items = []
self.maxCapacity = 0
# initialize the data:
self.__initData()
def __len__(self):
"""
:return: the total number of items defined in the problem
"""
return len(self.items)
def __initData(self):
"""initializes the RosettaCode.org knapsack 0-1 problem data
"""
self.items = [
("map", 9, 150),
("compass", 13, 35),
("water", 153, 200),
("sandwich", 50, 160),
("glucose", 15, 60),
("tin", 68, 45),
("banana", 27, 60),
("apple", 39, 40),
("cheese", 23, 30),
("beer", 52, 10),
("suntan cream", 11, 70),
("camera", 32, 30),
("t-shirt", 24, 15),
("trousers", 48, 10),
("umbrella", 73, 40),
("waterproof trousers", 42, 70),
("waterproof overclothes", 43, 75),
("note-case", 22, 80),
("sunglasses", 7, 20),
("towel", 18, 12),
("socks", 4, 50),
("book", 30, 10)
]
self.maxCapacity = 400
def getValue(self, zeroOneList):
"""
Calculates the value of the selected items in the list, while ignoring items that will cause the accumulating weight to exceed the maximum weight
:param zeroOneList: a list of 0/1 values corresponding to the list of the problem's items. '1' means that item was selected.
:return: the calculated value
"""
totalWeight = totalValue = 0
for i in range(len(zeroOneList)):
item, weight, value = self.items[i]
if totalWeight + weight <= self.maxCapacity:
totalWeight += zeroOneList[i] * weight
totalValue += zeroOneList[i] * value
return totalValue
def printItems(self, zeroOneList):
"""
Prints the selected items in the list, while ignoring items that will cause the accumulating weight to exceed the maximum weight
:param zeroOneList: a list of 0/1 values corresponding to the list of the problem's items. '1' means that item was selected.
"""
totalWeight = totalValue = 0
for i in range(len(zeroOneList)):
item, weight, value = self.items[i]
if totalWeight + weight <= self.maxCapacity:
if zeroOneList[i] > 0:
totalWeight += weight
totalValue += value
print("- Adding {}: weight = {}, value = {}, accumulated weight = {}, accumulated value = {}".format(item, weight, value, totalWeight, totalValue))
print("- Total weight = {}, Total value = {}".format(totalWeight, totalValue))
# testing the class:
def main():
# create a problem instance:
knapsack = Knapsack01Problem()
# creaete a random solution and evaluate it:
randomSolution = np.random.randint(2, size=len(knapsack))
print("Random Solution = ")
print(randomSolution)
knapsack.printItems(randomSolution)
if __name__ == "__main__":
main() |
'''Ciphers file'''
import random
import crypto_utils
class Cipher():
'''Cipher class'''
def __init__(self):
'''Constructor'''
self.alphabet = [chr(i) for i in range(32, 127)]
self.alphabet_size = len(self.alphabet)
self.clear_text = ""
self.code = ""
def encode(self, clear_text, key):
'''Dummy method'''
def decode(self, code, key):
'''Dummy method'''
def verify(self, clear_text, encode_key, decode_key):
'''Verify cipher'''
encoded = self.encode(clear_text, encode_key)
decoded = self.decode(encoded, decode_key)
return encoded == decoded
class Caesar(Cipher):
'''Caesar cipher'''
def encode(self, clear_text, key):
'''Encoding'''
self.code = ""
for letter in clear_text:
self.code += self.alphabet[(self.alphabet.index(letter) + key) %
self.alphabet_size]
return self.code
def decode(self, code, key):
'''Decode'''
self.code = ""
return self.encode(code, key)
def generate_keys(self):
'''Generating keys for Caesar'''
key1 = random.randint(0, self.alphabet_size - 1)
key2 = self.alphabet_size - key1
return key1, key2
def get_possible_keys(self):
'''Returning possible keys for this Cipher'''
return [i for i in range(0, self.alphabet_size)]
class Multiplication(Cipher):
'''Caesar cipher'''
def generate_keys(self):
'''Generating keys for Multiplication'''
key1 = random.randint(1, self.alphabet_size)
key2 = crypto_utils.modular_inverse(key1, self.alphabet_size)
while not key2:
key1 = random.randint(1, self.alphabet_size - 1)
key2 = crypto_utils.modular_inverse(key1, self.alphabet_size)
return key1, key2
def get_possible_keys(self):
'''Returning possible keys for this Cipher'''
key_list = []
for i in range(self.alphabet_size):
possible_key = crypto_utils.modular_inverse(i, self.alphabet_size)
if possible_key:
key_list.append(possible_key)
return key_list
def encode(self, clear_text, key):
'''Encoding'''
self.code = ""
for letter in clear_text:
self.code += self.alphabet[(self.alphabet.index(letter)
* key) % self.alphabet_size]
return self.code
def decode(self, code, key):
'''Decoding'''
self.code = ""
return self.encode(code, key)
class Affine(Cipher):
'''Affine cipher'''
caesar = Caesar()
mult = Multiplication()
def generate_keys(self):
'''Generating keys for Affine'''
caesar_keys = self.caesar.generate_keys()
mult_keys = self.mult.generate_keys()
return caesar_keys + mult_keys
def get_possible_keys(self):
'''Possible keys'''
possible_keys = []
caesar_keys = self.caesar.get_possible_keys()
mult_keys = self.mult.get_possible_keys()
for caesar_key in caesar_keys:
for mult_key in mult_keys:
possible_keys.append((mult_key, caesar_key))
return possible_keys
def encode(self, clear_text, key):
'''Encoding'''
self.code = ""
self.code = self.mult.encode(clear_text, key[0])
self.code = self.caesar.encode(self.code, key[1])
return self.code
def decode(self, code, key):
'''Decode'''
self.code = ""
self.code = self.caesar.decode(code, key[1])
self.code = self.mult.decode(self.code, key[0])
return self.code
class Unbreakable(Cipher):
'''Class Unbreakable'''
def generate_keys(self):
'''Generating keys for Caesar'''
word_key = "kiev"
word_key_decrypt = self.generate_decryption_key(word_key)
return word_key, word_key_decrypt
def generate_decryption_key(self, key):
'''Generating a decryption key based on the original key'''
decrypting_key = ""
for letter in enumerate(key):
letter_index = self.alphabet.index(letter[1])
letter_number = self.alphabet_size - (letter_index % self.alphabet_size)
decrypting_key += self.alphabet[letter_number % self.alphabet_size]
return decrypting_key
def get_possible_keys(self):
'''Returns the english dictionary as decryption keys!'''
with open("english_words.txt") as file:
content = file.readlines()
content = [x.strip() for x in content]
possible_keys = []
for word in content:
possible_keys.append(self.generate_decryption_key(word))
return possible_keys
def encode(self, clear_text, key):
'''Encoding'''
self.code = ""
for letter in enumerate(clear_text):
key_number = self.alphabet.index(key[letter[0] % len(key)])
self.code += self.alphabet[(self.alphabet.index(letter[1]) +
key_number) % self.alphabet_size]
return self.code
def decode(self, code, key):
'''Decode'''
self.code = ""
return self.encode(code, key)
class RSA(Cipher):
'''RSA class'''
def generate_keys(self):
'''Generating two keys'''
rsa_p = crypto_utils.generate_random_prime(8)
rsa_q = crypto_utils.generate_random_prime(8)
while rsa_p == rsa_q:
rsa_p = crypto_utils.generate_random_prime(8)
rsa_q = crypto_utils.generate_random_prime(8)
rsa_n = rsa_p * rsa_q
phi = (rsa_p - 1) * (rsa_q - 1)
rsa_e = random.randint(3, phi - 1)
rsa_d = crypto_utils.modular_inverse(rsa_e, phi)
while not rsa_d:
rsa_e = random.randint(3, phi - 1)
rsa_d = crypto_utils.modular_inverse(rsa_e, phi)
return rsa_n, rsa_d, rsa_e
def encode(self, clear_text, key):
'''Encoding'''
integer_list = crypto_utils.blocks_from_text(clear_text, 2)
encrypted_list = [pow(i, key[1], key[0]) for i in integer_list]
return encrypted_list
def decode(self, code, key):
'''Decode'''
decrypted_list = [pow(number, key[1], key[0]) for number in code]
message = crypto_utils.text_from_blocks(decrypted_list, 8)
return message
|
from cs50 import get_int
def main():
"""
Print out a pyramid with '#' for the height chosen by the user
"""
# Store int from user in a variable
height = get_valid_int("Height: ")
# Loop over the number of rows
for row in range(1, height + 1):
# Calculate and store the number of blanks and hashes at 'row'
blanks = " " * (height - row)
pyramid = "#" * row
# Format row with f-string
print(f"{blanks}{pyramid} {pyramid}")
# Propmt user for a valid integer
def get_valid_int(prompt):
while True:
n = get_int(prompt)
# Repeat until user inputs an int between 1-8, inclusive
if n > 0 and n < 9:
break
return n
main()
|
print("Code start")
# task 1: replace name
print("Hello, my name is", "kasturi")
print("and I'm learning Python.")
# task 2: calculate math expression
c=2894//274
print(c)
print(c**4)
#Let's use recently acquired knowledge to solve the next task.
#Task
#In the first print replace "name" with your name.
#Calculate the whole part of division 2894 by 274 and raise the result to the 4 power.
#Comment lines representing start and end of code. |
# Module for reading CSV files
import os
import csv
#locate file to read
csvpath = os.path.join('election_data.csv')
#Variable
TotalVotes = 0
KhanVotes = 0
CorreyVotes = 0
LiVotes = 0
OtooleyVotes = 0
#open the csv
with open(csvpath, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
#Read the header row first
header = next(csvreader)
#loop through data
for row in csvreader:
#Count the total number of voters by unique voter ID and keep
TotalVotes +=1
#Count and store number of votes for each of the 4 candidtaes ***INDENT
if row[2] == "Khan":
KhanVotes +=1
elif row[2] == "Correy":
CorreyVotes +=1
elif row[2] == "Li":
LiVotes +=1
elif row[2] == "O'Tooley":
OtooleyVotes +=1
#Create a list for the candidates and votes to store
Candidates = ["Khan", "Correy", "Li","O'Tooley"]
Votes = [KhanVotes, CorreyVotes,LiVotes,OtooleyVotes]
#Put Candidates and Votes list together to create a dictonary - ZIP
dictCandidateVote = dict(zip(Candidates,Votes))
key = max(dictCandidateVote, key=dictCandidateVote.get)
# Print a the summary of the analysis
KhanPercent = (KhanVotes/TotalVotes) *100
CorreyPercent = (CorreyVotes/TotalVotes) * 100
LiPercent = (LiVotes/TotalVotes)* 100
OtooleyPercent = (OtooleyVotes/TotalVotes) * 100
# Print the summary table
print(f"Election Results")
print(f"----------------------------")
print(f"Total Votes: {TotalVotes}")
print(f"----------------------------")
print(f"Khan: {KhanPercent:.3f}% ({KhanVotes})")
print(f"Correy: {CorreyPercent:.3f}% ({CorreyVotes})")
print(f"Li: {LiPercent:.3f}% ({LiVotes})")
print(f"O'Tooley: {OtooleyPercent:.3f}% ({OtooleyVotes})")
print(f"----------------------------")
print(f"Winner: {key}")
print(f"----------------------------")
# create new txt file
file = open("ElectionResults.txt","w")
# Write methods to print to Elections_Results_Summary
file.write(f"Election Results")
file.write("\n")
file.write(f"----------------------------")
file.write("\n")
file.write(f"Total Votes: {TotalVotes}")
file.write("\n")
file.write(f"----------------------------")
file.write("\n")
file.write(f"Khan: {KhanPercent:.3f}% ({KhanVotes})")
file.write("\n")
file.write(f"Correy: {CorreyPercent:.3f}% ({CorreyVotes})")
file.write("\n")
file.write(f"Li: {LiPercent:.3f}% ({LiVotes})")
file.write("\n")
file.write(f"O'Tooley: {OtooleyPercent:.3f}% ({OtooleyVotes})")
file.write("\n")
file.write(f"----------------------------")
file.write("\n")
file.write(f"Winner: {key}")
file.write("\n")
file.write(f"----------------------------")
#close file
file.close() |
import csv
import os
import math
import operator
'''
External Reference used
https://machinelearningmastery.com/tutorial-to-implement-k-nearest-neighbors-in-python-from-scratch/
https://realpython.com/welcome/
'''
#Loading Training data sets from inputdata.txt file
def loadDataSet():
dataPoints = []
fileh = open(os.getcwd() + "//code//inputdata.txt",'r')
try:
csv_reader = csv.reader(fileh,delimiter=',')
for row in csv_reader:
tempList = []
tempList.append(float(row[0])) # Height
tempList.append(float(row[1])) # Weight
tempList.append(float(row[2])) # Age
tempList.append(row[3]) # Class Label
dataPoints.append(tempList)
except:
pass
fileh.close()
return dataPoints
#Loading Test data sets from sampledata.txt file
def loadInputData():
sampleData = []
fileSecondh = open(os.getcwd() + "//code//sampledata.txt")
try:
csv_reader = csv.reader(fileSecondh,delimiter=',')
for row in csv_reader:
tempList = []
tempList.append(float(row[0])) # Height
tempList.append(float(row[1])) # Weight
tempList.append(float(row[2])) # Age
#tempList.append(row[3]) # Class Label
sampleData.append(tempList)
except:
pass
fileSecondh.close()
return sampleData
#Main fucntion contains main entry for the programme
def mainFunc():
inputDataList = loadDataSet()
sampleDataList = loadInputData()
kValues = [1,3,5]
count = 0
for i in range(0,len(sampleDataList)):
count+=1
#find distance of each input point with available training set for each feature
resultLabel = []
#neighbours = []
for j in range(len(kValues)):
#get neighbours
neighbours = getNeighbour(kValues[j],sampleDataList[i],inputDataList)
resultLabel.append(neighbours)
print sampleDataList[i]
formatter = "For k = %r , class is %r"
for k in range(0,len(resultLabel)):
print formatter % (kValues[k],resultLabel[k])
print " "
#calculate euclidean distance between testdata and each dataPoints of training Data
def getEuclideanDistance(testData,trainingData,length):
distance = 0
for x in range(length):
distance+= (testData[x] - trainingData[x])**2
return math.sqrt(distance)
#Result label for the maximum occurrring class type based on value for k
def getNeighbour(k,testInstance,trainingList):
distances = []
length = len(testInstance) - 1
tempList = []
for x in range(len(trainingList)):
trainList = trainingList[x]
sqrTerm = 0
for j in range(len(testInstance)):
sqrTerm += ((testInstance[j] - trainList[j])**2)
squareRootTerm = math.sqrt(sqrTerm)
tempList.append(squareRootTerm)
distances.append(squareRootTerm)
newList = []
newList = sorted(range(len(distances)),key = lambda k: distances[k])
neighbours = []
trainInListIndex = 0
trainInListIndex
for i in range(k):
trainInListIndex = newList[i]
label = trainingList[trainInListIndex][3]
neighbours.append(label)
return min([sublist[-1] for sublist in neighbours])
#calling main function
mainFunc()
|
def fac(n):
if n > 1:
return fac(n-1) * n
else:
return 1
print(fac(3))
def fac2(n):
def loop(n, ans):
if n > 1:
return loop(n-1, ans*n)
else:
return ans
return loop(n, 1)
print(fac2(4))
def fac3(n):
ans = 1
while n > 1:
n, ans = n-1, ans*n
return ans
print(fac3(3)) |
import pygame
from player import Player
# Setup pygame
pygame.init()
# Create color constants
WHITE = (255, 255, 255)
BLACK = (255, 255, 255)
# Setup the display window
display_width = 800
display_height = 600
game_display = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Sprite Game :)')
game_display.fill(WHITE)
pygame.display.update()
# Setup the clock
FPS = 60
clock = pygame.time.Clock()
# Create a player
pirate = Player(game_display)
# Control variable
still_playing = True
# Game loop
while still_playing:
# Clear the pygame events queue
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
still_playing = False
# Move the pirate if they press down an arrow key
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
pirate.go_left()
elif event.key == pygame.K_RIGHT:
pirate.go_right()
# Stop moving the pirate if they let go of an arrow key
if event.type == pygame.KEYUP:
# Stop moving the
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
pirate.stop_moving()
# Display the characters
game_display.fill(WHITE)
pirate.draw()
pygame.display.update()
clock.tick(60)
|
#!/bin/python3
""" Extra Long Factorials:
You are given an integer N. Print the factorial of this number
Inputs:
- line 1:: a single integer N
Output:
- the factorial of integer N
"""
import math
# nothing special, python does this automagically
n = int(input().strip())
print(math.factorial(n)) |
#!/bin/python3
""" Staircase:
Given a required height N, draw a staircase with '#' symbols that goes
from left to right, and is N steps high
Input:
- line 1:: You are given an integer N - the staircase height
Output:
print a staircase of height N
"""
# Input Line 1 (N)
n = int(input().strip())
# Loop through n times and create steps
for i in range(n):
steps = '#'*(i+1)
spaces = ' '*(n - 1 - i)
print(spaces + steps) |
""" Simple Array Sum:
You are given an array of integers of size N. Can you find the sum of the
elements in the array?
Input:
- Line 1:: an integer N
- line 2:: an N space-separated list of integers representing the array
elements
Output:
A single value equal to the sum of the elements in the array
"""
#!/bin/python
N = int(input())
# Input Line 2, an N number space delimited array
arr = map(int, raw_input().strip().split(' '))
arr_sum = 0
for i in arr:
arr_sum += i
print(arr_sum) |
# Created by Alex Hurtado
import sqlite3
import click
import os
import datetime
class Planner(object):
"""Defines a Planner class"""
def __init__(self, db_name='planner.db'):
self.db_name = db_name
self.connected = None
self.PATH = os.path.dirname(os.path.realpath(__file__))
self.db = self.PATH + "\\"+ self.db_name
def make_db(self):
"""Makes a database, if it doesn't exist already"""
self.open_connection()
self.cur.execute('''CREATE TABLE events
(date text, events_name text)''')
self.conn.commit()
def open_connection(self):
"""Opens a database connection."""
if not self.connected:
self.conn = sqlite3.connect(self.db)
self.connected = True
self.cur = self.conn.cursor()
def close_connection(self):
"""Closes the database connection."""
if self.check_connection():
self.cur.close()
self.conn.close()
self.connected = False
def check_connection(self):
"""Checks to see if a connection is open"""
if self.connected:
return True
else:
return False
def create_event(self, date, event):
"""Creates an event inside of a database"""
if not self.connected:
self.open_connection()
self.cur.execute('INSERT INTO events (date, events_name) VALUES (?, ?)', (date, event))
self.conn.commit()
def read_all(self):
"""Reads the whole database and prints it out"""
click.echo("Collecting data from database....")
try:
self.info = self.cur.execute('''SELECT * FROM events''').fetchall()
click.echo("Here are the events that you have set: ")
for i in self.info:
click.echo(i)
except sqlite3.OperationalError:
click.echo("Table events does not exist. First use planner init to initialise the database.")
def checkout(self, event, allow_list):
"""User controlled option to remove event from database."""
if not self.connected:
self.open_connection()
self.cur.execute('DELETE FROM events WHERE events_name=(?)', (event,))
self.conn.commit()
if allow_list:
self.read_all()
def read_all_proto(self):
"""Lists out events in order of importance"""
pass
def get_dates(self): # Experimental, not tested yet...
"""Fetches all the dates present in the database"""
self.info = self.cur.execute('''SELECT * FROM events''')
self.date_list = []
for i in self.info:
self.date_list.append(i[0])
return self.date_list
|
# -*- coding: UTF-8 -*-
"""Resume Analysis Module."""
import os
import string
# Counter is used later in the program
from collections import Counter
# Paths
resume_path = os.path.join(".", "Resources", 'resume.md')
# Skills to match
REQUIRED_SKILLS = {"excel", "python", "mysql", "statistics"}
DESIRED_SKILLS = {"r", "git", "html", "css", "leaflet"}
# function to load a file
def load_file(filepath):
"""Helper function to read a file and return the data."""
with open(filepath, "r") as resume_file_handler:
return resume_file_handler.read().lower().split()
# Grab the text for a Resume
word_list = load_file(resume_path)
# Create a set of unique words from the resume
resume = set()
# Remove trailing punctuation from words
for token in word_list:
resume.add(token.split(',')[0].split('.')[0])
# Remove Punctuation that were read as whole words
punctuation = set(string.punctuation)
resume = resume - punctuation
print(f"\n{resume}")
# Calculate the Required Skills Match using Set Intersection
print("\nREQUIRED SKILLS")
print("=============")
print(resume & REQUIRED_SKILLS)
# Calculate the Desired Skills Match using Set Intersection
print("\nDESIRED SKILLS")
print("=============")
print(resume & DESIRED_SKILLS)
# Resume Word Count
# ==========================
# Initialize a dictionary with default values equal to zero
word_count = {}.fromkeys(word_list, 0)
# Loop through the word list and count each word.
for word in word_list:
word_count[word] += 1
print(f"\n{word_count}")
# Using collections.Counter
word_counter = Counter(word_list)
print(f"\n{word_counter}")
# Comparing both word count solutions
print(f"\n{word_count == word_counter}")
# Top 10 Words
# ==========================
# Initialize list for words in resume
word_raw = []
# Remove trailing punctuation and add to list
for word in word_list:
word_raw.append(word.split(",")[0].split(".")[0])
# Convert punctuation set into a list
punctuation = list(punctuation)
# Remove punctuations
for entry in punctuation:
for row in word_raw:
if entry == row:
word_raw.remove(row)
# Create list with stop words
stop_words = ["and", "with", "using", "##", "working", "in", "to"]
# Remove stop words
for entry in stop_words:
for row in word_raw:
if entry == row:
word_raw.remove(row)
# Initialize dictionary that will be used to count the number of times a word appears in resume
word_counter = dict.fromkeys (word_raw, 0)
for word in word_raw:
word_counter[word] += 1
# Sort words by count and print the top 10 words
sorted_words = sorted(word_counter, key = word_counter.get, reverse = True)
print("\nTop 10 Words")
print("=============")
for word in sorted_words[:10]:
print(f"Word: {word:20} Count: {word_counter[word]}") |
import collections
def read_trigrams(filename):
file = open(filename, "r")
words = dict()
for line in file:
items = line.split()
words[items[0].strip()] = int(items[1].strip())
vocab = collections.Counter(words)
return vocab
def write_trigrams(trigrams,filename):
with open(filename,"w") as f:
for key,value in trigrams.most_common():
f.write("{} {}\n".format(key,value))
|
x,y=input().split()
x=int(x)
y=int(y)
magazine=input()
note=input()
note_list=list(note.split())
magazine_list=list(magazine.split())
mag={}
#Converting magazine_list to the Dictionary for account of words present in the list.
for i in magazine_list:
if(i in mag):
mag[i]=mag[i]+1
else:
mag[i]=1
#Checking Words in the magazine_list and also updating the quantity of words once used.
for i in note_list:
if(i in mag and mag[i]>0):
decision=True
mag[i]=mag[i]-1
else:
decision=False
break
if(decision==True):
print("Yes")
else:
print("No")
|
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
total_length = len(s)
visited = [[False for x in range(total_length)] for y in range(total_length + 1)]
for length in range(total_length, 0, -1):
for start_index in range(0, total_length - length + 1):
if self.search(s, length, start_index, visited):
return s[start_index:start_index + length]
return s[0]
def search(self, s, length, start_index, visited):
if visited[length][start_index]:
return False
visited[length][start_index] = True
if length <= 1:
return True
else:
if s[start_index] == s[start_index + length - 1]:
return self.search(s, length - 2, start_index + 1, visited)
else:
return False
|
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def get_repeated_set(num_list):
repeated_set = set()
prev = num_list[0]
for curr in num_list[1:]:
if curr == prev:
repeated_set.add(curr)
prev = curr
return repeated_set
def is_unique_triplet(triplet, triplets_dict):
n_1, n_2, n_3 = triplet[0], triplet[1], triplet[2]
return triplets_dict.get(n_1, {}).get(n_2, {}).get(n_3) is None \
and triplets_dict.get(n_1, {}).get(n_3, {}).get(n_2) is None \
and triplets_dict.get(n_2, {}).get(n_1, {}).get(n_3) is None \
and triplets_dict.get(n_2, {}).get(n_3, {}).get(n_1) is None \
and triplets_dict.get(n_3, {}).get(n_1, {}).get(n_2) is None \
and triplets_dict.get(n_3, {}).get(n_2, {}).get(n_1) is None
def add_to_triplets_dict(triplet, triplets_dict):
n_1, n_2, n_3 = triplet[0], triplet[1], triplet[2]
if triplets_dict.get(n_1) is None:
triplets_dict[n_1] = {n_2: {n_3: True}}
elif triplets_dict[n_1].get(n_2) is None:
triplets_dict[n_1][n_2] = {n_3: True}
else:
triplets_dict[n_1][n_2][n_3] = True
def search(unique_nums, counter_nums, triplets, counter_num_sign, triplets_dict):
if len(counter_nums) < 2:
# Less then 2 counter nums, impossible to form 3 numbers
return
repeated_counter_nums = get_repeated_set(counter_nums)
counter_nums_set = set(counter_nums)
counter_nums = list(counter_nums_set)
for num in unique_nums:
for counter_num in counter_nums:
if abs(num) >= abs(counter_num):
other_counter_num = (abs(num) - abs(counter_num)) * counter_num_sign
if (other_counter_num == counter_num and counter_num in repeated_counter_nums) \
or (not other_counter_num == counter_num and other_counter_num in counter_nums_set):
triplet = (num, counter_num, other_counter_num)
if is_unique_triplet(triplet, triplets_dict):
triplets.append(triplet)
add_to_triplets_dict(triplet, triplets_dict)
positives = []
negatives = []
zeros = []
for n in nums:
if n > 0:
positives.append(n)
elif n < 0:
negatives.append(n)
else:
zeros.append(n)
positives = sorted(positives, reverse=True)
negatives = sorted(negatives)
if len(zeros) > 0:
positives.append(0)
negatives.append(0)
trs = [] # Triplets
td = {} # Triplet dicts
# Put 3 zeros first
if len(zeros) >= 3:
trs.append((0, 0, 0))
# 1 positive, 2 negative
search(list(set(positives)), negatives, trs, -1, td)
# 1 negative, 2 positives
search(list(set(negatives)), positives, trs, 1, td)
return trs
print(Solution().threeSum([-4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6]))
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
# Get index of nodes
nodes = []
curr = head
while curr is not None:
nodes.append(curr)
curr = curr.next
length = len(nodes)
if n == length:
# Remove first node
head = head.next
elif n == 0:
# Remove last node
nodes[length - 2].next = None
else:
# Remove some nodes in between
target = nodes[length - n]
prev = nodes[length - n - 1]
prev.next = target.next
return head
def convert_to_linked_list(a):
head = None
prev = None
for i in range(len(a)):
if prev == None:
head = ListNode(a[i])
prev = head
else:
curr = ListNode(a[i])
prev.next = curr
prev = curr
return head
def convert_to_list(head):
a = []
while head is not None:
a.append(head.val)
head = head.next
return a
head = Solution().removeNthFromEnd(convert_to_linked_list([1, 2, 3, 4, 5]), 5)
print(convert_to_list(head))
|
#Program for creating new Buttons
import pygame
pygame.init()
BLACK = (0, 0, 0)
GREY=(50,50,50)
WHITE = (255, 255, 255)
BLUE=(127,255,212)
WIDTH = 14
HEIGHT = 14
MARGIN = 1
r=int(input('Enter no. of rows: '))
c=int(input('Enter no. of cols: '))
name=input('Enter B_Name: ')
temp=WIDTH+MARGIN
WINDOW_SIZE = [temp*c, temp*r]
winlogo=pygame.image.load(".\winlogo.png")
screen = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption("NewButton")
pygame.display.set_icon(winlogo)
clock = pygame.time.Clock()
m=[]
for n_rows in range(r):
row_temp=[]
for n_col in range(c):
row_temp.append(0)
m.append(row_temp)
def display():
screen.fill(GREY)
for row in range(r):
for column in range(c):
color = BLACK
if m[row][column] == 1:
color = WHITE
pygame.draw.rect(screen,color,[(MARGIN + WIDTH)*(column)+MARGIN,(MARGIN + HEIGHT)*(row)+MARGIN,WIDTH,HEIGHT])
clock.tick(60)
pygame.display.flip()
def m_coordinate():
return pygame.mouse.get_pos()[0] // (WIDTH + MARGIN), pygame.mouse.get_pos()[1] // (HEIGHT + MARGIN)
#Reading the design from the user
running=True
while running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
quit()
elif event.type == pygame.KEYDOWN:
if event.key== pygame.K_RETURN:
running=False
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button==1:
column,row=m_coordinate()
if row<r:
m[row][column] = 1
display()
#Saving the design in a text file
f=open('design\\'+name+'.txt','w')
lines=[]
for i in m:
line=''
for j in i:
if j==0:
line=line+'.'
if j==1:
line=line+'*'
lines.append(line+'\n')
f.writelines(lines)
f.close()
|
"""
Python script to perform the hungarian method of solving the assignment problem
While making this, certain python features were avoided in some instances to ensure
people using other languages may read the code
"""
def get_subjects():
""" Gets the list of subjects that should be taught from the user """
number_of_subjects = int(input("Enter the number of subjects to be taught"))
subjects = []
for i in range(number_of_subjects):
subject_name = ""
while subject_name == "":
subject_name = input("Enter the subject's name")
number_of_instances = -1
while number_of_instances < 0:
try:
number_of_instances = int(input("Enter the number of instances the subject is to have"))
except Exception:
print("Please enter a valid number")
number_of_instances = -1
subjects.append([subject_name, number_of_instances])
return subjects
def get_teachers():
""" Gets a list of teachers to teach the subjects """
number_of_teachers = int(input("Enter the number of teachers available"))
teachers = []
for i in range(number_of_teachers):
teacher_name = ""
while teacher_name == "":
teacher_name = input("Enter the teacher's name")
number_of_classes = -1
while number_of_classes < 0:
try:
number_of_classes = int(input("Enter the number of classes the person is to teach"))
except Exception:
print("Please enter a valid value")
number_of_classes = -1
teachers.append([teacher_name, number_of_classes])
return teachers
def get_teacher_ratings(teachers, subjects):
ratings = []
for teacher in teachers:
teacher_ratings = []
for subject in subjects:
rating = -1
while rating < 0 or rating > 5:
try:
rating = int(input("Enter the rating of " + teacher + " in " + subject + " on a scale of 1 (Best) to 5 (Worst)"))
except Exception:
print("Please enter a valid value")
teacher_ratings.append(rating)
ratings.append(teacher_ratings)
return ratings
def teachers_available(teachers):
for teacher in teachers:
if teacher[1] > 0:
return True
return False
def subjects_unassigned(subjects):
for subject in subjects:
if subject[1] > 0:
return True
return False
def get_column(matrix, column_number):
column = []
for row in matrix:
column.append(row[column_number])
return column
def reduce_matrix(matrix):
for i, row in enumerate(matrix):
minimum = min(row)
matrix[i] = [value - minimum for value in row]
for i, value in enumerate(matrix):
column = get_column(matrix, i)
minimum = min(column)
for j in range(len(column)):
matrix[j][i] -= minimum
return matrix
def row_scan(matrix, eliminated_columns):
row_scan_result = []
for i, row in enumerate(matrix):
if row.count(0) == 1 and i not in eliminated_columns and row.index(0) not in row_scan_result:
row_scan_result.append(row.index(0))
else:
row_scan_result.append(-1)
return row_scan_result
def row_scan_remaining_rows(matrix, eliminated_columns, eliminated_rows):
row_scan_result = eliminated_rows.copy()
for i, row in enumerate(matrix):
if row_scan_result[i] == -1 and i not in eliminated_columns:
zero_locations = []
for j, value in enumerate(row):
if value == 0:
if j not in row_scan_result and j not in eliminated_rows:
zero_locations.append(j)
if len(zero_locations) > 1:
break
if len(zero_locations) == 1:
row_scan_result[i] = zero_locations[0]
else:
row_scan_result[i] = -1
else:
row_scan_result[i] = -1
return row_scan_result
def column_scan(matrix, eliminated_rows):
column_scan_results = []
for i, row in enumerate(matrix):
if eliminated_rows[i] == -1:
column = get_column(matrix, i)
if column.count(0) == 1 and column.index(0) not in column_scan_results:
column_scan_results.append(column.index(0))
else:
column_scan_results.append(-1)
else:
column_scan_results.append(-1)
return column_scan_results
def column_scan_remaining_columns(matrix, eliminated_rows, eliminated_columns):
column_scan_results = eliminated_columns.copy()
for i, row in enumerate(matrix):
if eliminated_columns[i] == -1 and i not in eliminated_rows:
if i not in eliminated_rows:
column = get_column(matrix, i)
zero_positions = []
for j, value in enumerate(column):
if j not in column_scan_results and j not in eliminated_columns:
if value == 0:
zero_positions.append(j)
if len(zero_positions) > 1:
break
if len(zero_positions) == 1:
column_scan_results[i] = zero_positions[0]
else:
column_scan_results[i] = -1
else:
column_scan_results[i] = -1
else:
column_scan_results[i] = -1
return column_scan_results
def get_minimum_lines(matrix, row_selection):
selected_rows = []
for i, selection in enumerate(row_selection):
if selection == -1:
selected_rows.append(i)
selected_columns = []
for row in selected_rows:
for i, value in enumerate(matrix[row]):
if value == 0 and i not in selected_columns:
selected_columns.append(i)
if i in row_selection:
selected_rows.append(row_selection.index(i))
unselected_rows = []
for i in range(len(matrix)):
if i not in selected_rows:
unselected_rows.append(i)
return [unselected_rows, selected_columns]
def sublists_empty(parent_list):
for sub_list in parent_list:
if len(sub_list) > 0:
return False
return True
FINAL_ASSIGNMENTS = []
def main():
subjects = get_subjects()
teachers = get_teachers()
teacher_names = []
for teacher in teachers:
teacher_names.append(teacher[0])
subject_names = []
for subject in subjects:
subject_names.append(subject[0])
ratings = get_teacher_ratings(teacher_names, subject_names)
assignments = []
while teachers_available(teachers) and subjects_unassigned(subjects):
teachers_in_use = []
subjects_in_use = []
for row, teacher in enumerate(teachers):
if teacher[1] > 0:
teachers_in_use.append(row)
teachers[row][1] -= 1
for row, subject in enumerate(subjects):
if subject[1] > 0:
subjects_in_use.append(row)
subjects[row][1] -= 1
extra_zeros = len(teachers_in_use) - len(subjects_in_use)
matrix = []
for teacher_index in teachers_in_use:
teacher_ratings = []
for subject_index in subjects_in_use:
teacher_ratings.append(ratings[teacher_index][subject_index])
if extra_zeros > 0:
teacher_ratings.extend([0] * extra_zeros)
matrix.append(teacher_ratings)
if extra_zeros < 0:
extra_zeros = extra_zeros * -1
for x in range(extra_zeros):
matrix.append([0] * len(subjects_in_use))
assignments = [-1] * len(matrix)
optimal_solution_found = False
while not optimal_solution_found:
matrix = reduce_matrix(matrix)
row_scan_result = row_scan(matrix, [])
column_scan_result = column_scan(matrix, row_scan_result)
if row_scan_result.count(-1) + column_scan_result.count(-1) != len(matrix):
scan_updated = True
while scan_updated:
scan_updated = False
extra_row_scan = row_scan_remaining_rows(matrix, column_scan_result, row_scan_result)
for row, row in enumerate(extra_row_scan):
if row != -1:
scan_updated = True
row_scan_result[row] = row
extra_column_scan = column_scan_remaining_columns(matrix, row_scan_result, column_scan_result)
for row, column in enumerate(extra_column_scan):
if column != -1:
scan_updated = True
column_scan_result[row] = column
if row_scan_result.count(-1) + column_scan_result.count(-1) != len(matrix):
row_assignment = row_scan_result.copy()
for row, value in enumerate(column_scan_result):
if value != -1:
row_assignment[value] = row
minimum_lines = get_minimum_lines(matrix, row_assignment)
if len(minimum_lines[0]) + len(minimum_lines[1]) != len(matrix):
safe_rows = []
safe_columns = []
for row in range(len(matrix)):
if row not in minimum_lines[0]:
safe_rows.append(row)
if row not in minimum_lines[1]:
safe_columns.append(row)
minimum = matrix[safe_rows[0]][safe_columns[0]]
for row in safe_rows:
for j in safe_columns:
if matrix[row][j] < minimum:
minimum = matrix[row][j]
for row in range(len(matrix)):
for j in range(len(matrix)):
if row in minimum_lines[0] and j in minimum_lines[1]:
matrix[row][j] += minimum
if row not in minimum_lines[0] and j not in minimum_lines[1]:
matrix[row][j] -= minimum
else:
optimal_solution_found = True
if row_scan_result.count(-1) + column_scan_result.count(-1) == len(matrix):
optimal_solution_found = True
zero_locations = []
available_columns_to_assign = []
for row, row in enumerate(matrix):
zero_positions = []
for j, value in enumerate(row):
if value == 0:
zero_positions.append(j)
if j not in available_columns_to_assign and j not in assignments:
available_columns_to_assign.append(j)
zero_locations.append(zero_positions)
while not sublists_empty(zero_locations):
column_count = []
for column in available_columns_to_assign:
count = 0
for locations in zero_locations:
if column in locations:
count += 1
column_count.append(count)
least_index = column_count.index(min(column_count))
column_to_assign = available_columns_to_assign[least_index]
row_found = False
row = 0
while not row_found and row < len(matrix):
if column_to_assign in zero_locations[row]:
row_found = True
else:
row += 1
if row_found:
assignments[row] = column_to_assign
available_columns_to_assign.remove(column_to_assign)
zero_locations[row] = []
for i, assignment in enumerate(assignments):
if len(teachers_in_use) > i:
if len(subjects_in_use) > assignment:
FINAL_ASSIGNMENTS.append([teachers[teachers_in_use[i]][0], subjects[subjects_in_use[assignment]][0]])
else:
# print("FAILED " + teachers[i][0])
teachers[teachers_in_use[i]][1] += 1
else:
# print("FAILED " + subjects[assignment][0])
subjects[subjects_in_use[assignment]][1] += 1
for assignment in FINAL_ASSIGNMENTS:
print(assignment)
if __name__ == '__main__':
main()
|
import numpy
import pandas
x=pandas.read_csv("car_price.csv",header=0,usecols=[1,3,4,5,6,7,8,9,10,12],converters={i: str for i in range(13)})
#print(x)
####_____________________________________________________DATA_PREPROCESSING
####_________________________MAX_POWER
temp=[]
zeros=0
for each in x['max_power']:
if type(each)==str:
number=each.split()
if len(number)>1:
temp.append(float(number[0]))
else:
temp.append(0)
zeros+=1
else:
temp.append(0)
zeros=1
avg=numpy.sum(temp)/(len(temp)-zeros)
maxx=numpy.max(temp)
minn=numpy.min(temp)
for i in range(len(temp)):
if temp[i]==0:
temp[i]=(avg-minn)/(maxx-minn)
else:
temp[i]=(temp[i]-minn)/(maxx-minn)
x['max_power']=temp
####___________________________mileage
temp=[]
zeros=0
for each in x['mileage']:
if type(each)==str:
number=each.split()
if len(number)>1:
temp.append(float(number[0]))
else:
temp.append(0)
zeros+=1
else:
temp.append(0)
zeros=1
avg=numpy.sum(temp)/(len(temp)-zeros)
maxx=numpy.max(temp)
minn=numpy.min(temp)
for i in range(len(temp)):
if temp[i]==0:
temp[i]=(avg-minn)/(maxx-minn)
else:
temp[i]=(temp[i]-minn)/(maxx-minn)
x['mileage']=temp
####________________________engine
temp=[]
zeros=0
for each in x['engine']:
if type(each)==str:
number=each.split()
if len(number)>1:
temp.append(float(number[0]))
else:
temp.append(0)
zeros+=1
else:
temp.append(0)
zeros=1
avg=numpy.sum(temp)/(len(temp)-zeros)
maxx=numpy.max(temp)
minn=numpy.min(temp)
for i in range(len(temp)):
if temp[i]==0:
temp[i]=(avg-minn)/(maxx-minn)
else:
temp[i]=(temp[i]-minn)/(maxx-minn)
x['engine']=temp
####________________________YEAR
temp=[]
zeros=0
for each in x['year']:
if len(str(each))!=0:
temp.append(float(each))
else:
temp.append(0)
zeros=1
avg=numpy.sum(temp)/(len(temp)-zeros)
maxx=numpy.max(temp)
minn=numpy.min(temp)
for i in range(len(temp)):
if temp[i]==0:
temp[i]=(avg-minn)/(maxx-minn)
else:
temp[i]=(temp[i]-minn)/(maxx-minn)
x['year']=temp
###_________________________km_driven
temp=[]
zeros=0
for each in x['km_driven']:
if len(str(each))!=0:
temp.append(float(each))
else:
temp.append(0)
zeros=1
avg=numpy.sum(temp)/(len(temp)-zeros)
maxx=numpy.max(temp)
minn=numpy.min(temp)
for i in range(len(temp)):
if temp[i]==0:
temp[i]=(avg-minn)/(maxx-minn)
else:
temp[i]=(temp[i]-minn)/(maxx-minn)
x['km_driven']=temp
##_________________________seats
temp=[]
zeros=0
for each in x['seats']:
if len(str(each))!=0:
temp.append(float(each))
else:
temp.append(0)
zeros=1
avg=numpy.sum(temp)/(len(temp)-zeros)
maxx=numpy.max(temp)
minn=numpy.min(temp)
for i in range(len(temp)):
if temp[i]==0:
temp[i]=(avg-minn)/(maxx-minn)
else:
temp[i]=(temp[i]-minn)/(maxx-minn)
x['seats']=temp
#x
####_____________________________________________fuel
types=numpy.unique(x['fuel'])
keys=numpy.linspace(0,1,len(types))
print(types)
print(keys)
temp=[]
for each in x['fuel']:
for i,every in enumerate(types):
if every == each:
temp.append(keys[i])
x['fuel']=temp
####_____________________________________________seller_type
types=numpy.unique(x['seller_type'])
print(types)
keys=numpy.linspace(0,1,len(types))
print(keys)
temp=[]
for each in x['seller_type']:
for i,every in enumerate(types):
if every == each:
temp.append(keys[i])
x['seller_type']=temp
####_____________________________________________transmission
types=numpy.unique(x['transmission'])
print(types)
keys=numpy.linspace(0,1,len(types))
print(keys)
temp=[]
for each in x['transmission']:
for i,every in enumerate(types):
if every == each:
temp.append(keys[i])
x['transmission']=temp
###________________________________________________owner
types=numpy.unique(x['owner'])
print(types)
keys=numpy.linspace(0,1,len(types))
print(keys)
temp=[]
for each in x['owner']:
for i,every in enumerate(types):
if every == each:
temp.append(keys[i])
x['owner']=temp
###__________________________________________________END
###_______________________________________________SLPITTING_SAMPLES_AND_ADDING_BIAS_WEIGHTS
l=len(x)
print(l)
x=x.to_numpy()
x = numpy.hstack([numpy.ones((l, 1)),x])
print(numpy.shape(x))
print(x)
y=pandas.read_csv("car_price.csv",usecols=[2])
y=y.to_numpy()
maxx=numpy.max(y)
minn=numpy.min(y)
y=(y-minn)/(maxx-minn)
samples=len(y)
print(numpy.shape(y))
y_train=y[0:samples-128]
y_test=y[samples-128:]
x_train=x[0:samples-128]
x_test=x[samples-128:]
#print(numpy.shape(x_test))
###_______________________________________________________END
###________________________________________________LINEAR_REGRESSION
def loss(x,y,w):
l = len(y)
h = x.dot(w)
error = (h-y)**2
return numpy.sum(error)/(2*l)
def gradient_descent(x,y,w):
m = len(y)
for i in range(10000):
h = x.dot(w)
#print(numpy.shape(h))
error = ((h-y).transpose()).dot(x)
#print(numpy.shape(error))
w -= 0.00001*(1/m)*(error.transpose())
print("Loss : ",loss(x,y,w))
return w
weights= numpy.zeros([x_train.shape[1],1])
print(numpy.shape(weights))
weights= gradient_descent(x_train,y_train,weights)
###______________________________________________________END
###___________________________________________________PREDICT
print("Prediction Loss: "loss(x_test,y_test,weights))
|
# implementation of card game - Memory
import simplegui
import random
state = 0
numbers = []
first_pos = 0
second_pos = 0
#exposed = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
#exposed = ["false","false","false","false","false","false","false","false","false","false","false","false","false","false","false","false"]
exposed = [False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False]
paired = [False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False]
# helper function to initialize globals
def new_game():
global numbers
numbers = range(8) * 2
#random.shuffle(numbers)
print "Len of numbers", len(numbers), numbers
# define event handlers
def mouseclick(pos):
# add game state logic here
global numbers, state, exposed, first_pos, second_pos, paired
#if (exposed[(pos[0]//50)] == False):
if state == 0:
first_pos = (pos[0]//50)
exposed[first_pos] = True
if paired[first_pos] != True:
state = 1
#print "exposed = ", exposed[(pos[0]//50)] = "true"
elif state == 1:
second_pos = (pos[0]//50)
exposed[second_pos] = True
if paired[second_pos] != True:
state = 2
else:
state = 1
#if (numbers[first_pos] != numbers[second_pos]) and not paired[first_pos] and not paired[second_pos]:
if (numbers[first_pos] != numbers[second_pos]):
if (not paired[first_pos]):
print "close"
exposed[first_pos] = False
exposed[second_pos] = False
else:
print "this"
paired[first_pos] = True
paired[second_pos] = True
print "paired[first_pos] = ", paired[first_pos]
print "paired[0] = ", paired[0]
#if numbers[first_pos] == "true"
first_pos = (pos[0]//50)
exposed[first_pos] = True
print "state = ", state, "first_pos = ", first_pos, "second_pos = ", second_pos, "paired first = ", paired[first_pos]
#print "POS = ", pos
#print pos[0] // 50
#print "Exposed = ", exposed[n]
# cards are logically 50x100 pixels in size
def draw(c):
global state, numbers, exposed
#c.draw_line((0,0),(800,0),2,"white")
#c.draw_line((0,0),(0,100),2,"white")
#c.draw_line((0,100),(800,100),2,"white")
#c.draw_line((0,100),(800,100),2,"white")
for x in range(16):
c.draw_polygon([(x * 50, 0), (x * 50, 100), ((x + 1) * 50, 100), ((x + 1) * 50, 0)], 1, 'White', 'Green')
#print [(x * 50, 0), (x * 50, 100), ((x + 1) * 50, 100), ((x + 1) * 50, 0)]
#c.draw_text(str(state) + " card exposed", [30, 62], 24, "White")
#c.draw_text('1', [40 / 2, 60], 30, 'Red')
x = 0
for n in numbers:
if exposed[x] == True:
#c.draw_text(str(n), [x * 50 / 2, 50], 30, 'Red')
c.draw_text(str(n), [(x * 50) + 5, 80], 80, 'Red')
x += 1
# create frame and add a button and labels
frame = simplegui.create_frame("Memory", 800, 100)
frame.add_button("Restart", new_game)
label = frame.add_label("Turns = 0")
# register event handlers
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)
# get things rolling
new_game()
frame.start()
# Always remember to review the grading rubric |
numb1 = input("Enter a number : ")
numb2 = input("Enter another a number : ")
result = float(numb1) + float(numb2)
print(result)
|
def uniques_only(arr):
return list(set(arr))
# sets are unordered - arr should be return in same order but dupes removed
def uniques_only(arr):
items = []
for i, item in enumerate(arr):
if item not in arr[:i]:
items.append(item)
return items
# Here we're slicing the sequence that comes into our function to get all items before our current one (the i-th one). This allows us to check whether an item appeared before our current item.
# only works on sequences though
def uniques_only(arr):
items = []
for item in arr:
if item not in items:
items.append(item)
return items
# works but slow for large lists
def uniques_only(arr):
seen = set()
items = []
for item in iterable:
if item not in seen:
items.append(item)
seen.add(item)
return items
# Sets rely on hashes for lookups so containment checks won't slow down as our hash grows in size. Notice we're building up both a list and a set but we're checking only the set for containment and returning only the list. We still need to make a list in addition to our set because sets are unordered by nature and we want the order of first appearance of each item to be maintained.
def uniques_only(arr):
return dict.fromkeys(arr).keys()
# This is a somewhat clever and hacky solution. It's short, but it's not very clear. It also only works on Python 3.6+. I prefer the set solution from a readability standpoint, but the dict.fromkeys solution is likely faster.
# Bonus #1
# Let's try tackling the first bonus.
def uniques_only(iterable):
seen = set()
for item in iterable:
if item not in seen:
yield item
seen.add(item)
# We're using a generator function here. Generator functions are unlike regular functions. They return a generator object which will return items every time a yield statement is hit in our generator function.
# We can't turn this generator function into a generator expression because we need to add items to our set as we iterate, which isn't possible with a generator expression.
# Bonus #2
# Let's talk about the second bonus now.
# If we want our function to work with non-hashable types, we'll need to use something besides a set or a dictionary to store seen values. We could use a list, like we did before:
def uniques_only(iterable):
seen = []
for item in iterable:
if item not in seen:
yield item
seen.append(item)
# This works, but it will be slower. Answering the question "item not in seen" when using a list requires iterating all the way through the list looking for a match. A set can answer the same question without iterating at all.
# Bonus #3
# If we want to tackle the third bonus problem and make our code continue to work efficiently for hashable types, we could check each item to see if it's hashable:
from collections.abc import Hashable
def uniques_only(iterable):
seen_hashable = set()
seen_unhashable = []
for item in iterable:
if isinstance(item, Hashable):
if item not in seen_hashable:
yield item
seen_hashable.add(item)
else:
if item not in seen_unhashable:
yield item
seen_unhashable.append(item)
# The collections.abc.Hashable type uses duck typing when doing an isinstance check, so asking isinstance(item, Hashable) will always give us the correct answer for each object in Python.
# Another way we could check for hashability is to simply try to add each item to the set and if it fails, add it to the list instead:
def uniques_only(iterable):
seen_hashable = set()
seen_unhashable = []
for item in iterable:
try:
if item not in seen_hashable:
yield item
seen_hashable.add(item)
except TypeError:
if item not in seen_unhashable:
yield item
seen_unhashable.append(item)
# This is practicing "it's easier to practice forgiveness than permission", which is a common programming practice in the Python world. The exception handling involved does make the non-hashable case a bit slower though, so that if statement might be better overall depending on what we're optimizing for.
|
def containsCloseNums(nums, k):
'''
are there duplicate numbers k indices apart?
'''
if len(nums) <= 1:
return False
ht = {}
for key, value in enumerate(nums):
if value in ht and key - ht[value] <= k:
return True
ht[value] = key
return False
|
# Singly-linked lists are already defined with this interface:
# class ListNode(object):
# def __init__(self, x):
# self.value = x
# self.next = None
#
'''
Approach:
1. Edge case: n == 0, just return the list.
2. Establish nodes for head, last, and previous (one before start).
3. Edge case: If n is the length of the list, return the list.
4. Iterate through the list until we find the last, updating head, last, and previous.
5. Clean up by setting the next node for end and previous.
'''
def rearrangeLastN(l, n):
if n == 0:
return l
head = l # this is what we return
last = l # this will be connected to l, the original linked list, before the return
prev = 1 # this tracks the node right before the start of the new list
count = 1
while count < n:
last = last.next
count += 1
if last.next == None:
return l
while last.next is not None:
if last.next is not None:
last = last.next
prev = head
head = head.next
last.next = l
prev.next = None
return head |
number_of_runs = 0
total_time = 0
while True:
one_run = input("Enter 10 km run time, or 'q' to exit: ")
if one_run == 'q':
break
else:
number_of_runs += 1
total_time += float(one_run)
average_time = total_time / number_of_runs
print(f"Average of {average_time}, over {number_of_runs} runs")
# In a real-world Python application, if you’re taking input from the user and calling float (docs.python.org/3/library/functions.html#float), you should probably wrap it within try (docs.python.org/3/reference/compound_stmts.html#the-try-statement), in case the user gives us an illegal value:
# try:
# n = float(input("Enter a number: "))
# print(f"n = {n}")
# except ValueError as e:
# print("Hey! That's not a valid number!") |
def areFollowingPatterns(strings, patterns):
'''
if the string follows the pattern then true
if the string doesn't follow the pattern false
verify string an pattern are same lenghth = base case
set dict
loop through string for words
loop through pattern for assigned pattern
compare return true or false
'''
if len(strings) != len(patterns):
return False
ht = {}
for i in range(len(strings)):
if patterns[i] not in ht:
if strings[i] not in ht.values():
ht[patterns[i]] = strings[i]
else:
return False
elif ht[patterns[i]] != strings[i]:
return False
return True
|
# for checking palindrome
s =input("enter the word:")
z=s[::-1]
if s ==z:
print("word is a palindrome")
else:
print{"word is not palindrome"} |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import graphSearch
import popularity
import nltk
def getPersonality(text):
names = []
personalitiesFile = open ("../entityExtraction/personalities.txt", 'rb')
personalitiesList = {}
for line in personalitiesFile:
personalitiesList = eval(line)
for p , value in personalitiesList["listPersonalities"].iteritems(): #value is not relevant
if p in text:
names.append(p)
return names
def printPeopleGraph(dictNames):
related = []
for p in dictNames.keys():
related.append(p)
related.append(" : ")
related.append(str(dictNames[p]))
related.append(" ; ")
result = "".join(related)
return result
def relatedPersonalities(names):
relatePersonalities = {}
if len(names) == 0:
return
else:
for name in names:
relatePersonalities[name] = graphSearch.graphSearch(name)
#print relatePersonalities
return relatePersonalities
def personPopularity(names):
result = {}
if len(names) == 0:
return
else:
for name in names:
result[name] = popularity.personalityPopularity(name)
return result
def printPersonality(text):
related = {}
popularity = {}
names = []
names = getPersonality(text)
related = relatedPersonalities(names)
popularity = personPopularity(names)
for i in range(0,len(names)):
print '-------------------------'
print 'Personality: ' + names[i]
if popularity[names[i]][0] != 0 or popularity[names[i]][1] != 0 or popularity[names[i]][2] != 0 or popularity[names[i]][3]:
print 'Popularity: ' + str(popularity[names[i]][3])
print 'Appears in: ' + str(popularity[names[i]][0]) + ' News'
print 'PositiveScore: ' + str(popularity[names[i]][1])
print 'NegativeScore: ' + str(popularity[names[i]][2])
if len (related[names[i]]) != 0 :
print 'People Graph: ' + printPeopleGraph(related[names[i]])
print '-------------------------'
print '\n'
#printPersonality("ola eu sou o Miguel Relvas e o Carlos Zorrinho")
#print relatedPersonalities(getPersonality("ola eu sou o Miguel Relvas e o Carlos Zorrinho"))
|
import random
class Card:
#Card class has instance attributes: suit, rank and value
#value ranges from 0-9 since the game is baccarat
def __init__(self, suit, rank):
#suit converter
if suit == 1:
self.suit = "Spades"
if suit == 2:
self.suit = "Clubs"
if suit == 3:
self.suit = "Diamonds"
if suit == 4:
self.suit = "Hearts"
#rank and value converter
if rank == 10:
self.rank = rank
if rank == 11:
self.rank = "J"
if rank == 12:
self.rank = "Q"
if rank == 13:
self.rank = "K"
if rank >= 10:
self.value = 0
else:
self.value = rank
self.rank = rank
if rank == 1:
self.rank = "A"
def getcard(self):
return self
class Deck:
#initializes the deck and the cards for the deck and stores them in the list
def __init__(self):
self.DeckArr = []
for x in range(1, 5):
for y in range(1, 14):
self.DeckArr.append(Card(x, y))
#calling to shuffle after initialization of deck
self.shuffle()
#randomly shuffles cards in deck
def shuffle(self):
#trying to make random library more random with a seed
random.seed(None, 2)
for x in range(0,200):
j = random.randint(0, self.getsize() - 1)
k = random.randint(0, self.getsize() - 1)
#swapping cards in deck places
temp = self.DeckArr[k]
self.DeckArr[k] = self.DeckArr[j]
self.DeckArr[j] = temp
#returns a card from the deck class to give to the dealer or the player's receive function
def getcard(self):
returnvalue = self.DeckArr.pop() #store the popped value to return to the player or dealer
return returnvalue
#returns the current size of the deck
def getsize(self):
return len(self.DeckArr)
class Player:
wins = 0
losses = 0
ties = 0
def __init__(self):
self.cardsHeld = []
self.currentScore = 0
#to get a card
def receive(self, deck): #receives pulled card from the deck's getcard function
self.cardsHeld.append(deck.getcard())
def getScore(self):
self.currentScore = 0
for card in self.cardsHeld:
self.currentScore += card.value
if self.currentScore > 9:
self.currentScore = self.currentScore%10
return self.currentScore
def getHand(self): #plays
for x in self.cardsHeld:
print(x.rank, " of ", x.suit)
#regarding wins losses and conditions, use only for player
@staticmethod
def win():
print("\nThe player wins!")
Player.wins += 1
@staticmethod
def lose():
print("\nThe dealer wins!")
Player.losses += 1
@staticmethod
def tie():
print("\nIt's a tie!")
Player.ties += 1
#report wins and losses
@staticmethod
def stats():
print("\nPlayer's stats:")
print("---------------")
print("Wins:", Player.wins, "\nLosses:", Player.losses, "\nDraws:", Player.ties)
class Dealer:
def __init__(self):
self.cardsHeld = []
self.currentScore = 0
def receive(self, deck):
self.cardsHeld.append(deck.getcard())
def getHand(self):
for x in self.cardsHeld:
print(x.rank, " of ", x.suit)
def getScore(self):
self.currentScore = 0
for x in self.cardsHeld:
self.currentScore += x.value
if self.currentScore > 9:
self.currentScore = self.currentScore%10
return self.currentScore
|
# 적절한 형식으로 공연장 정보를 출력
def print_all_buildings(db):
print("--------------------------------------------------------------------------------")
print_form = '%-10s%-34s%-14s%-14s%-s\n'
column = print_form % ('id', 'name', 'location', 'capacity', 'assigned')
print(column + "--------------------------------------------------------------------------------")
buildings = db.select("select * from building")
table_info = ''
for i in buildings:
building_id = i['ID']
name = i['name']
location = i['location']
capacity = i['capacity']
assigned_query = f'select count(performance_id) from assignment where assignment.building_id = {building_id}'
assigned = db.select(assigned_query)[0]['count(performance_id)']
table_info += print_form %(building_id, name, location, capacity, assigned)
print(table_info + "--------------------------------------------------------------------------------\n")
# 적절한 형식으로 공연 정보를 출력
def print_all_performances(db):
print("--------------------------------------------------------------------------------")
print_form = '%-10s%-34s%-14s%-14s%-s\n'
column = print_form % ('id', 'name', 'type', 'price', 'booked')
print(column + "--------------------------------------------------------------------------------")
performances = db.select("select * from performance")
table_info = ''
for i in performances:
performance_id = i['ID']
name = i['name']
genre_type = i['type']
price = i['price']
booked_query = f'select count(audience_id) from reservation where reservation.performance_id = {performance_id}'
booked = db.select(booked_query)[0]['count(audience_id)']
table_info += print_form %(performance_id, name, genre_type, price, booked)
print(table_info + "--------------------------------------------------------------------------------\n")
# 적절한 형식으로 관객 정보를 출력
def print_all_audiences(db):
print("--------------------------------------------------------------------------------")
print_form = '%-10s%-40s%-15s%-20s\n'
column = print_form % ('id', 'name', 'gender', 'age')
print(column + "--------------------------------------------------------------------------------")
audiences = db.select("select * from audience")
table_info = ''
for i in audiences:
audience_id = i['ID']
name = i['name']
gender = i['gender']
age = i['age']
table_info += print_form %(audience_id, name, gender, age)
print(table_info + "--------------------------------------------------------------------------------\n")
# 새로운 공연장을 추가
def insert_a_new_building(db):
name = input("Building name: ")[:200]
location = input("Building location: ")[:200]
capacity = int(input("Building capacity: "))
if capacity>0:
query = f'insert into building (name, location, capacity) values ("{name}", "{location}", {capacity});'
db.insert_delete(query)
print('A building is successfully inserted\n')
else:
print('Capacity should be more than 0\n')
# 공연장을 공연장 id를 가지고 삭제
def remove_a_building(db):
building_id = int(input("Building ID: "))
select_query = f'select * from building where id = {building_id}'
if db.select(select_query) == []:
print(f"Building {building_id} doesn't exist\n")
else:
query = f'delete from building where id = {building_id};'
db.insert_delete(query)
print("A building is successfully removed\n")
# 새로운 공연을 추가
def insert_a_new_performance(db):
name = input("Performance name: ")[:200]
genre_type = input("Performance type: ")[:200]
price = int(input("Performance price: "))
if price>=0:
query = f'insert into performance (name, type, price) values ("{name}", "{genre_type}", {price});'
db.insert_delete(query)
print('A performance is successfully inserted\n')
else:
print('Price should be 0 or more\n')
# 공연을 공연 id를 가지고 삭제
def remove_a_performance(db):
performance_id = int(input("Performance ID: "))
select_query = f'select * from performance where id = {performance_id}'
if db.select(select_query) == []:
print(f"Performance {performance_id} doesn't exist\n")
else:
query = f'delete from performance where id = {performance_id};'
db.insert_delete(query)
print("A performance is successfully removed\n")
# 새로운 관객을 추가
def insert_a_new_audience(db):
name = input("Audience name: ")[:200]
gender = input("Audience gender: ")[:200]
if not (gender=='F' or gender=='M'):
print("Gender should be 'M' or 'F'\n")
return
age = int(input("Audience age: "))
if age<=0:
print("Age should be more than 0\n")
else:
query = f'insert into audience (name, gender, age) values ("{name}", "{gender}", {age});'
db.insert_delete(query)
print('An audience is successfully inserted\n')
# 관객을 관객 id를 가지고 삭제
def remove_an_audience(db):
audience_id = int(input("Audience ID: "))
select_query = f'select * from audience where id = {audience_id}'
if db.select(select_query) == []:
print(f"Audience {audience_id} doesn't exist\n")
else:
query = f'delete from audience where id = {audience_id};'
db.insert_delete(query)
print("An audience is successfully removed\n")
# 공연장에 공연을 배정
def assign_a_performance_to_a_building(db):
building_id = int(input("Building ID: "))
# building이 있는지 확인
building_exist = f'select * from building where ID = {building_id}'
if db.select(building_exist) == []:
print(f"Building {building_id} doesn't exist\n")
return
performance_id = int(input("Performance ID: "))
performance_exist = f'select * from performance where ID = {performance_id}'
# performance가 있는지 확인
if db.select(performance_exist) == []:
print(f"Performance {performance_id} doesn't exist\n")
return
assigned = f'select * from assignment where performance_id = {performance_id}'
# performance가 이미 배정되었는지 확인
if db.select(assigned) == []:
query = f'insert into assignment (building_id, performance_id) values ("{building_id}", "{performance_id}");'
db.insert_delete(query)
print("Successfully assign a performance\n")
else:
print(f"Performance {performance_id} is already assigned\n")
# 관객이 공연을 예약
def book_a_performance(db):
performance_id = int(input("Performance ID: "))
# 공연이 존재하는지 확인
if db.select(f'select * from performance where ID = {performance_id}') == []:
print(f"Performance {performance_id} doesn't exist\n")
return
# 공연이 공연장에 배정되어 있지 않으면 실패
if db.select(f'select * from assignment where performance_id = {performance_id}') == []:
print(f"Performance {performance_id} isn't assigned\n")
return
audience_id = int(input("Audience ID: "))
# 관객이 존재하는지 확인
if db.select(f'select * from audience where ID = {audience_id}') == []:
print(f"Audience {audience_id} doesn't exist\n")
return
seat_number = input("Seat number: ").split(",")
#print(seat_number)
int_seat = []
for i in seat_number:
i = i.replace(" ","")
int_seat.append(int(i))
#print(int_seat)
capacity_query = f'''select capacity from building, assignment
where assignment.performance_id = {performance_id}
and building.ID = assignment.building_id'''
capacity = db.select(capacity_query)
# 좌석 번호 하나라도 범위를 벗어나면 실패
for i in int_seat:
if capacity[0]['capacity'] < i:
print("Seat number out of range\n")
return
# 좌석 번호 하나라도 예매되어 있으면 실패
for i in int_seat:
if db.select(f'select * from reservation where performance_id = {performance_id} and seat_number = {i}') != []:
print("The seat is already taken\n")
return
for i in int_seat:
query = f'insert into reservation (performance_id, audience_id, seat_number) values ("{performance_id}", "{audience_id}", "{i}");'
db.insert_delete(query)
# price 계산
price_query = f''' select price from performance
where ID = {performance_id}'''
price = db.select(price_query)[0]['price']
age_query = f''' select age from audience
where ID = {audience_id}'''
age = db.select(age_query)[0]['age']
if age <= 7:
price = 0
elif age >= 8 and age <=12:
price = rounding(price*(0.5)*len(int_seat))
elif age >= 13 and age <= 18:
price = rounding(price*(0.8)*len(int_seat))
else:
price = price*len(int_seat)
price = format(price, ',')
print(f"Successfully book a performance\nTotal ticket price is {price}\n")
# 반올림 함수 구현
def rounding(n):
if n - int(n) >= 0.5:
return int(n)+1
return int(n)
# 공연장에 배정된 공연을 출력
def print_all_performances_which_assigned_at_a_building(db):
building_id = int(input("Building ID: "))
if db.select(f'select * from building where ID = {building_id}') == []:
print(f"Building {building_id} doesn't exist\n")
else:
print("--------------------------------------------------------------------------------")
print_form = '%-10s%-34s%-14s%-14s%-s\n'
column = print_form % ('id', 'name', 'type', 'price', 'booked')
print(column + "--------------------------------------------------------------------------------")
performance_sql = f'''
select * from performance, assignment
where assignment.building_id = {building_id} and
performance.id = assignment.performance_id;
'''
performances = db.select(performance_sql)
table_info = ''
for i in performances:
performance_id = i['ID']
name = i['name']
genre_type = i['type']
price = i['price']
table_info += print_form %(performance_id, name, genre_type, price, '0')
print(table_info + "--------------------------------------------------------------------------------\n")
# 공연을 예매한 관객을 출력
def print_all_audiences_who_booked_for_a_performance(db):
#print("13")
performance_id = int(input("Performance ID: "))
if db.select(f'select * from performance where ID = {performance_id}') == []:
print(f"Performance {performance_id} doesn't exist\n")
return
query = f'''
select distinct ID, name, gender, age from reservation, audience
where reservation.performance_id = {performance_id} and
reservation.audience_id = audience.ID
'''
print("--------------------------------------------------------------------------------")
print_form = '%-10s%-40s%-15s%-20s\n'
column = print_form % ('id', 'name', 'gender', 'age')
print(column + "--------------------------------------------------------------------------------")
audiences = db.select(query)
table_info = ''
for i in audiences:
audience_id = i['ID']
name = i['name']
gender = i['gender']
age = i['age']
table_info += print_form %(audience_id, name, gender, age)
print(table_info + "--------------------------------------------------------------------------------\n")
# 좌석 예매 현황을 확인
def print_ticket_booking_status_of_a_performance(db):
#print("14")
performance_id = int(input("Performance ID: "))
if db.select(f'select * from performance where ID = {performance_id}') == []:
print(f"Performance {performance_id} doesn't exist\n")
return
elif db.select(f'select * from assignment where performance_id = {performance_id}') == []:
print(f"Performance {performance_id} isn't assigned\n")
return
capacity_query = f'''select capacity from building, assignment
where assignment.performance_id = {performance_id}
and building.ID = assignment.building_id'''
capacity = db.select(capacity_query)[0]['capacity']
print("--------------------------------------------------------------------------------")
print_form = '%-50s%-50s\n'
column = print_form % ('seat_number', 'audience_id')
print(column + "--------------------------------------------------------------------------------")
#seats = db.select(query)
table_info = ''
for i in range(1, capacity + 1):
seat_number = i
#audience_id = i['audience_id']
audience_query = f''' select audience_id from reservation
where performance_id = {performance_id} and seat_number = {seat_number}'''
audience_id = db.select(audience_query)
#print(audience_id)
if audience_id == []:
table_info += print_form %(seat_number, '')
else:
table_info += print_form %(seat_number, audience_id[0]['audience_id'])
print(table_info + "--------------------------------------------------------------------------------\n")
# database를 reset
def reset_database(db):
#print("16")
while True:
delete = input("Delete? (y/n) ")
if delete == 'y':
db.reset()
break
elif delete == 'n':
break
print("") |
'''
cs5001
fall 2018
final project (othello)
'''
import turtle
import collections
import random
# CONSTANTS
SQUARE = 50
PAD = SQUARE/2
TILE_SIZE = 20
BOARD_SIZE = 8
BLACK = "black"
WHITE = "white"
PLAYER = collections.deque([BLACK, WHITE])
SPACES = []
COORDINATES = []
FONT = ("Arial", 14, "normal")
black_legal_moves = []
white_legal_moves = []
# INIT MAIN TURTLE AND SCREEN
t = turtle.Turtle()
t.up()
t.speed(0)
t.hideturtle()
wn = turtle.Screen()
# INIT TURTLE TILE ANNOUNCER
tile_announcer = turtle.Turtle()
tile_announcer.up()
tile_announcer.speed(0)
tile_announcer.hideturtle()
tile_announcer.color(BLACK)
# INIT TURTLE TURN ANNOUNCER
turn_announcer = turtle.Turtle()
turn_announcer.up()
turn_announcer.speed(0)
turn_announcer.hideturtle()
turn_announcer.color(BLACK)
#### PURPOSE
# This function starts the game by calling functions to draw the board,
# create a nested listed of spaces, created a nested list of space
# coordinates, draw the starting tiles, and draw static text, which is
# used to display messages to the user
#### SIGNATURE
# init_game :: Void => Void
#### EXAMPLES
# n/a
def init_game():
draw_board()
create_spaces()
create_coordinates()
draw_starting_tiles()
draw_static_text()
#### PURPOSE
# This function determines the corner value of the board based on the
# size of the board (BOARD_SIZE) and each space (SQUARE). Valid board
# sizes are powers of 2 >= 4. Note: BOARD_SIZE and SQUARE are constants
# defined above.
#### SIGNATURE
# signature :: Void => Int
#### EXAMPLES
# If BOARD_SIZE = 4 and SQUARE = 50, corner() => 100
# If BOARD_SIZE = 8 and SQUARE = 50, corner()=> 200
def corner():
return SQUARE * (BOARD_SIZE/2)
#### PURPOSE
# This function opens a window and draws the Othello game board.
#### SIGNATURE
# draw_board() :: Void => Void
#### EXAMPLES
# n/a
def draw_board():
# Create the screen & canvas for the board
wn.setup(BOARD_SIZE * SQUARE * 3, BOARD_SIZE * SQUARE * 1.5)
wn.screensize(BOARD_SIZE * SQUARE, BOARD_SIZE * SQUARE)
wn.bgcolor(WHITE)
# Line color is black, fill color is green
t.color(BLACK, "forest green")
# Move the turtle to the lower left corner
t.setposition(-corner(), -corner())
# Draw the green background
t.begin_fill()
for i in range(4):
t.down()
t.forward(SQUARE * BOARD_SIZE)
t.left(90)
t.end_fill()
# Draw the horizontal lines
for i in range(BOARD_SIZE + 1):
t.setposition(-corner(), SQUARE * i + -corner())
draw_lines()
# Draw the vertical lines
t.left(90)
for i in range(BOARD_SIZE + 1):
t.setposition(SQUARE * i + -corner(), -corner())
draw_lines()
# Uncomment to toggle draw row & column indicies for 8x8 board
# x = -175
# y = 215
# for i in range(BOARD_SIZE):
# t.setposition(x,y)
# t.write(i, font=("Arial", 14, "normal"))
# x += SQUARE
# x = -225
# y = 165
# for i in range(BOARD_SIZE):
# t.setposition(x,y)
# t.write(i, font=("Arial", 14, "normal"))
# y -= SQUARE
#### PURPOSE
# This function is called by draw_board() and draws lines that divide
# the game board into a BOARD_SIZE x BOARD_SIZE grid.
#### SIGNATURE
# draw_lines() :: Void => Void
#### EXAMPLES
# n/a
def draw_lines():
t.down()
t.forward(SQUARE * BOARD_SIZE)
t.up()
#### PURPOSE
# This function replaces SPACES (a constant) with a nested list of spaces,
# which is used as a virtual representation of the game board spaces.
# Each space is initialized as empty by appending None to each space.
# The number of lists = BOARD_SIZE and the number of lists within each
# list = BOARD_SIZE.
#### SIGNATURE
# create_spaces() :: Void => Void
#### EXAMPLES
# If BOARD_SIZE = 8, create_spaces() => Void, SPACES is updated to be:
# [
# [None, None, None, None, None, None, None, None],
# [None, None, None, None, None, None, None, None],
# [None, None, None, None, None, None, None, None],
# [None, None, None, None, None, None, None, None],
# [None, None, None, None, None, None, None, None],
# [None, None, None, None, None, None, None, None],
# [None, None, None, None, None, None, None, None],
# [None, None, None, None, None, None, None, None]
# ]
def create_spaces():
for row in range(BOARD_SIZE):
temp = []
for column in range(BOARD_SIZE):
temp.append(None)
SPACES.append(temp)
#### PURPOSE
# This function is creates a nested list that is the same same as the
# nested list created by create_spaces(). The list stores the
# cooresponding x- and y-coordinates for tiles to be drawn on each space.
# This function doesn't return anything. Rather, it updates the
# COORDINATES list (constant).
#### SIGNATURE
# create_coordinates() :: Void => Void
#### EXAMPLES
# If BOARD_SIZE = 8, create_coordinates() => Void, COORDINATES is updated:
# [
# [(-175.0, 155.0), (-125.0, 155.0), (-75.0, 155.0), (-25.0, 155.0), (25.0, 155.0), (75.0, 155.0), (125.0, 155.0), (175.0, 155.0)],
# [(-175.0, 105.0), (-125.0, 105.0), (-75.0, 105.0), (-25.0, 105.0), (25.0, 105.0), (75.0, 105.0), (125.0, 105.0), (175.0, 105.0)],
# [(-175.0, 55.0), (-125.0, 55.0), (-75.0, 55.0), (-25.0, 55.0), (25.0, 55.0), (75.0, 55.0), (125.0, 55.0), (175.0, 55.0)],
# [(-175.0, 5.0), (-125.0, 5.0), (-75.0, 5.0), (-25.0, 5.0), (25.0, 5.0), (75.0, 5.0), (125.0, 5.0), (175.0, 5.0)],
# [(-175.0, -45.0), (-125.0, -45.0), (-75.0, -45.0), (-25.0, -45.0), (25.0, -45.0), (75.0, -45.0), (125.0, -45.0), (175.0, -45.0)],
# [(-175.0, -95.0), (-125.0, -95.0), (-75.0, -95.0), (-25.0, -95.0), (25.0, -95.0), (75.0, -95.0), (125.0, -95.0), (175.0, -95.0)],
# [(-175.0, -145.0), (-125.0, -145.0), (-75.0, -145.0), (-25.0, -145.0), (25.0, -145.0), (75.0, -145.0), (125.0,-145.0), (175.0, -145.0)],
# [(-175.0, -195.0), (-125.0, -195.0), (-75.0, -195.0), (-25.0, -195.0), (25.0, -195.0), (75.0, -195.0), (125.0, -195.0), (175.0, -195.0)]]
def create_coordinates():
y = corner() - SQUARE*0.9
for row in range(BOARD_SIZE):
temp = []
x = -corner() + SQUARE/2
for column in range(BOARD_SIZE):
temp.append((x,y))
x += SQUARE
COORDINATES.append(temp)
y -= SQUARE
#### PURPOSE
# This function draws the starting tiles.
#### SIGNATURE
# draw_starting_tiles :: Void => Void
#### EXAMPLES
# n/a
def draw_starting_tiles():
PLAYER.rotate(1)
for row in range(BOARD_SIZE):
if row == (BOARD_SIZE/2)-1 or row == (BOARD_SIZE/2):
for column in range(BOARD_SIZE):
if column == (BOARD_SIZE/2)-1 or column == (BOARD_SIZE/2):
tile_x_coord, tile_y_coord = COORDINATES[row][column]
draw_tile(tile_x_coord, tile_y_coord)
PLAYER.rotate(1)
PLAYER.rotate(1)
PLAYER.rotate(1)
#### PURPOSE
# This function draws static text on the game window, used to display
# messages to the user.
#### SIGNATURE
# draw_static_text :: Void => Void
#### EXAMPLES
# n/a
def draw_static_text():
# position static text (turn, black tiles, white tiles) next to board
x = corner() + PAD
y = corner() - SQUARE
t.color(BLACK)
text = ["Turn:", "Black tiles:", "White tiles:"]
for i in range(3):
t.setpos(x,y)
t.write(text[i], font=FONT)
y -= PAD
#### PURPOSE
# This function draws a tile based on the x- and y-coordinate of the
# selected move made by either the human or ai player.
#### SIGNATURE
# draw_tile :: (Float, Float) => Void
#### EXAMPLES
# n/a
def draw_tile(x, y):
row = get_row_index(y)
column = get_column_index(x)
tile_x_coord, tile_y_coord = COORDINATES[row][column]
t.setheading(0)
t.setpos(tile_x_coord,tile_y_coord)
t.color(PLAYER[0])
t.begin_fill()
t.down()
t.circle(TILE_SIZE)
t.end_fill()
t.up()
# update SPACES matrix
update_spaces(row, column)
#### PURPOSE
# This function updates the SPACES list after tiles are drawn.
#### SIGNATURE
# update_spaces :: Void => Void
#### EXAMPLES
# n/a
def update_spaces(row, column):
SPACES[row][column] = PLAYER[0]
#### PURPOSE
# This function verifies that the user click is within the boundaries
# of the board.
#### SIGNATURE
# click_in_bounds :: (Float, Float) => Bool
#### EXAMPLES
# click_in_bounds(-500,-500) => False
# click_in_bounds(0,0) => True
# click_in_bounds(-154,176) => True
# click_in_bounds(201,201) => False
def click_in_bounds(x, y):
bound = SQUARE * BOARD_SIZE/2
return -bound <= x <= bound and -bound <= y <= bound
#### PURPOSE
# This function converts the y-coordinate of the user click into a
# corresponding row index that can be used to access elements in the
# SPACES and COORDINATES nested lists.
#### SIGNATURE
# get_row_index :: (Float) => Int
#### EXAMPLES
# get_row_index(190) => 0
# get_row_index(-199) => 7
# get_row_index(20) => 3
def get_row_index(y):
row_index = int((-y + SQUARE*(BOARD_SIZE/2)) // SQUARE)
return row_index
#### PURPOSE
# This function converts the x-coordinate of the user click into a
# corresponding column index that can be used to access elements in the
# SPACES and COORDINATES nested lists.
#### SIGNATURE
# get_column_index :: (Float) => Int
#### EXAMPLES
# get_column_index(155) == 7
# get_column_index(-80) == 2
# get_column_index(-176) == 0
def get_column_index(x):
column_index = int((x + SQUARE*(BOARD_SIZE/2)) // SQUARE)
return column_index
#### PURPOSE
# This function draws dynamic text on the game window, used to display
# messages to the user. After each move, this text is cleared and updated.
# For example, this is used to update the number of black and white tiles
# on the board before/after every turn.
#### SIGNATURE
# draw_dynamic_text :: Void => Void
#### EXAMPLES
# n/a
def update_dynamic_text():
# clear tile counts from previous turn
tile_announcer.clear()
# clear turn indicator from previous turn
turn_announcer.clear()
# align dynamic text with static text
x = corner() + PAD*5
y = corner() - SQUARE
# write, in order: current player, # black tiles, # white tiles
text = [PLAYER[0], count_black_tiles(), count_white_tiles()]
for i in range(3):
if i == 0:
turn_announcer.setpos(x,y)
turn_announcer.write(text[i], font=FONT)
else:
tile_announcer.setpos(x,y)
tile_announcer.write(text[i], font=FONT)
y -= PAD
#### PURPOSE
# This function switches the player by rotating the PLAYER deque,
# calls the functions to update dynamic text and update lists of legal
# moves, and starts the human move or ai move accordingly.
#### SIGNATURE
# switch_player :: Void => Void
#### EXAMPLES
# n/a
def switch_player():
PLAYER.rotate(1)
update_dynamic_text()
update_legal_moves()
if PLAYER[0] == BLACK:
start_user_move()
else:
# disable user click event capture
wn.onscreenclick(None)
start_ai_move()
#### PURPOSE
# This function starts the human player turn. If there are legal moves,
# available, it will activate the onscreenclick method to capture
# the user move selection. If no legal moves remain for the human player
# but legal moves remain for the ai player, it will call the
# switch_player() function. If no legal moves are left for either player,
# it will trigger the report_winner() function.
#### SIGNATURE
# start_user_move :: Void => Void
#### EXAMPLES
# n/a
def start_user_move():
if black_legal_moves_remain():
wn.onscreenclick(execute_user_move)
elif white_legal_moves_remain():
switch_player()
else:
report_winner()
#### PURPOSE
# This function executes the human player move. It gets the x- and y-
# coordinates from the start_user_move() function, converts those
# coordinates to row/column values, verifies the click is in bounds,
# validates the legality of the selected move, and, if valid, draws/flips
# tiles. If a move is invalid, the function will simply wait until
# a valid move is selected.
#### SIGNATURE
# execute_user_move :: (Float, Float) => Void
#### EXAMPLES
# n/a
def execute_user_move(x, y):
row = get_row_index(y)
column = get_column_index(x)
if click_in_bounds(x, y):
if validate_move(row, column):
tile_x_coord, tile_y_coord = COORDINATES[row][column]
draw_tile(tile_x_coord, tile_y_coord)
north_flip_tiles(row, column)
NE_flip_tiles(row, column)
east_flip_tiles(row, column)
SE_flip_tiles(row, column)
south_flip_tiles(row, column)
SW_flip_tiles(row, column)
west_flip_tiles(row, column)
NW_flip_tiles(row, column)
switch_player()
#### PURPOSE
# This function starts the ai player turn. If there are legal moves,
# available, it will choose the move that flips tiles in as many
# directions as possible. If there are no legal moves for the ai player
# but there are for the human player, it will call the switch_user()
# function. If no legal moves are left for either player, it will trigger
# the report_winner() function.
#### SIGNATURE
# start_ai_move :: Void => Void
#### EXAMPLES
# n/a
def start_ai_move():
if white_legal_moves_remain():
freq = collections.Counter(white_legal_moves).most_common()
most_freq = [i for i in freq if (i[1] == freq[0][1])]
choice = random.choice(most_freq)[0]
row = choice[0]
column = choice[1]
execute_ai_move(row, column)
elif black_legal_moves_remain():
switch_player()
else:
report_winner()
#### PURPOSE
# This function executes the ai move. Since the ai player will never
# attempt an invalid move, it simply proceeds to drawing/flipping tiles
# as relevant.
#### SIGNATURE
# execute_ai_move :: (Int, Int) => Void
#### EXAMPLES
# n/a
def execute_ai_move(row, column):
tile_x_coord, tile_y_coord = COORDINATES[row][column]
draw_tile(tile_x_coord, tile_y_coord)
north_flip_tiles(row, column)
NE_flip_tiles(row, column)
east_flip_tiles(row, column)
SE_flip_tiles(row, column)
south_flip_tiles(row, column)
SW_flip_tiles(row, column)
west_flip_tiles(row, column)
NW_flip_tiles(row, column)
switch_player()
#### PURPOSE
# This function updates but does not return a list of legal moves available
# to the human player (black_legal_moves) and a separate list of legal
# moves available to the ai player (white legal moves).
#### SIGNATURE
# update_legal_moves :: Void => Void
#### EXAMPLES
# n/a
def update_legal_moves():
black_legal_moves.clear()
white_legal_moves.clear()
for i in range(2):
if PLAYER[0] == BLACK:
for row in range(BOARD_SIZE):
for column in range(BOARD_SIZE):
if validate_move(row, column):
black_legal_moves.append((row, column))
if PLAYER[0] == WHITE:
for row in range(BOARD_SIZE):
for column in range(BOARD_SIZE):
if space_empty(row, column):
if north_legal_move(row, column):
white_legal_moves.append((row, column))
if NE_legal_move(row, column):
white_legal_moves.append((row, column))
if east_legal_move(row, column):
white_legal_moves.append((row, column))
if SE_legal_move(row, column):
white_legal_moves.append((row, column))
if south_legal_move(row, column):
white_legal_moves.append((row, column))
if SW_legal_move(row, column):
white_legal_moves.append((row, column))
if west_legal_move(row, column):
white_legal_moves.append((row, column))
if NW_legal_move(row, column):
white_legal_moves.append((row, column))
PLAYER.rotate(1)
#### PURPOSE
# The function determines if any legal moves remain for the human player
# by determining if the list of relevant legal moves is empty or not.
#### SIGNATURE
# black_legal_moves_remain() :: Void => Bool
#### EXAMPLES
# If black_legal_moves = [], black_legal_moves_remain() => False
# If black_legal_moves = [(0,1)], black_legal_moves_remain() => True
def black_legal_moves_remain():
return len(black_legal_moves) != 0
#### PURPOSE
# The function determines if any legal moves remain for the ai player
# by determining if the list of relevant legal moves is empty or not.
#### SIGNATURE
# white_legal_moves_remain() :: Void => Bool
#### EXAMPLES
# If white_legal_moves = [], white_legal_moves_remain() => False
# If white_legal_moves = [(0,1)], white_legal_moves_remain() => True
def white_legal_moves_remain():
return len(white_legal_moves) != 0
#### PURPOSE
# The function determines if any legal moves remain for the ai player
# by determining if the list of relevant legal moves is empty or not.
#### SIGNATURE
# white_legal_moves_remain() :: Void => Bool
#### EXAMPLES
# If white_legal_moves = [], white_legal_moves_remain() => False
# If white_legal_moves = [(0,1)], white_legal_moves_remain() => True
def space_empty(row, column):
return SPACES[row][column] == None
#### PURPOSE
# The function determines if a move is valid by determing if the space
# is both empty and is a legal move in any one of 8 directions (N, NE,
# E, SE, S, SW, W, or NW)
#### SIGNATURE
# validate_move :: (Int, Int) => Bool
#### EXAMPLES
# validate_move(0,2) => True
# validate_move(6,7) => False
def validate_move(row, column):
direction = (
north_legal_move(row, column)
or NE_legal_move(row, column)
or east_legal_move(row, column)
or SE_legal_move(row, column)
or south_legal_move(row, column)
or SW_legal_move(row, column)
or west_legal_move(row, column)
or NW_legal_move(row, column)
)
return space_empty(row, column) and direction
#### PURPOSE
# The function counts the number of black tiles on the board by iterating
# through the SPACES list.
#### SIGNATURE
# count_black_tiles :: Void => Bool
#### EXAMPLES
# If there are 4 black tiles on the board, count_black_tiles() => 4
# If there are no black tiles on the board, count_black_tiles() => 0
def count_black_tiles():
black_tiles = 0
for row in range(BOARD_SIZE):
for column in range(BOARD_SIZE):
if SPACES[row][column] == BLACK:
black_tiles += 1
return black_tiles
#### PURPOSE
# The function counts the number of white tiles on the board by iterating
# through the SPACES list.
#### SIGNATURE
# count_white_tiles :: Void => Bool
#### EXAMPLES
# If there are 10 white tiles on the board, count_black_tiles() => 10
# If there are no whitetiles on the board, count_black_tiles() => 0
def count_white_tiles():
white_tiles = 0
for row in range(BOARD_SIZE):
for column in range(BOARD_SIZE):
if SPACES[row][column] == WHITE:
white_tiles += 1
return white_tiles
#### PURPOSE
# The function compares the number of black tiles with the number of
# white tiles and determines the winner (whoever has more tiles).
#### SIGNATURE
# determine_winner :: Void => Str
#### EXAMPLES
# If black > white, determine_winner() => "Black player wins!"
# If white > black, determine_winner() => "White player wins!"
# If black = white, determine_winner() => "It's a tie!"
def determine_winner():
black_tiles = count_black_tiles()
white_tiles = count_white_tiles()
if black_tiles > white_tiles:
return "Black player wins!"
elif white_tiles > black_tiles:
return "White player wins!"
else:
return "It's a tie!"
#### PURPOSE
# The function reports the winner to the user by writing on the window.
#### SIGNATURE
# report_winner() :: Void => Void
#### EXAMPLES
# n/a
def report_winner():
turn_announcer.clear()
winner = determine_winner()
message = "Close window/exit to terminal to record your score."
x = corner() + PAD
y = corner() - SQUARE*3
text = [winner, message]
for i in range(2):
tile_announcer.setpos(x,y)
tile_announcer.write(text[i], font=FONT)
y -= SQUARE
get_previous_scores("scores.txt")
#### PURPOSE
# The function accesses a list of high scores and adds each score entry
# as a separate element to a list of scores.
#### SIGNATURE
# get_previous_scores :: File => Void
#### EXAMPLES
# n/a
def get_previous_scores(file_path):
scores = []
with open(file_path, "r") as file:
for line in file:
lst = line.split(",")
scores.append([lst[0], int(lst[1].strip())])
capture_user_score(file_path, scores)
#### PURPOSE
# The function captures the user name and accesses their score at
# the end of the game.
#### SIGNATURE
# capture_user_score :: (File, List) => Void
#### EXAMPLES
# n/a
def capture_user_score(file_path, scores_lst):
user = input("Enter your name: ")
score = count_black_tiles()
user_score_entry = [user.replace(" ", ""), score]
add_user_to_scores(file_path, scores_lst, user_score_entry)
#### PURPOSE
# The function adds the user score to the list of scores. The score is
# added above all lower scores. If the score is equal to any of the
# previous scores, it will be added above the first score with which
# it is equal. If the score is lower than all other score previously
# recorded, it will be added to the bottom of the list.
#### SIGNATURE
# add_user_to_scores :: (File, List, List) => Void
#### EXAMPLES
# n/a
def add_user_to_scores(file_path, scores_lst, user_score_entry):
if len(scores_lst) == 0:
scores_lst.append(user_score_entry)
else:
for i in range(len(scores_lst)):
if user_score_entry[1] >= scores_lst[i][1]:
scores_lst.insert(i,user_score_entry)
added = True
break
else:
added = False
if not added:
scores_lst.append(user_score_entry)
save_scores(file_path, scores_lst)
#### PURPOSE
# The function overwrites the scores file using the list of scores,
# which now includes the new score from the last game played.
#### SIGNATURE
# save_scores :: (File, List) => Void
#### EXAMPLES
# n/a
def save_scores(file_path, scores_lst):
with open(file_path, "w") as file:
for entry in scores_lst:
data = "{},{}\n".format(entry[0],entry[1])
file.write(data)
#### PURPOSE
# This function evaluates the validity of a move by looking at existing
# tiles to the NORTH of the space. It will resolve True if placing the
# tile will create a sandwich, a series of the opposing player's tiles
# between two of the current player's tiles.
# Note: NORTH = from bottom to top of board, decreasing row index,
# increasing y-coordinate.
#### SIGNATURE
# north_legal_move :: (Int, Int) => Bool
#### EXAMPLES
# north_legal_move(6, 3) => True
# north_legal_move(2, 4) => False
# north_legal_move(0,0) => False
def north_legal_move(row, column):
next_row = north_next_row(row)
if row >= 2 and SPACES[next_row][column] == PLAYER[1]:
stop_row = north_stop_row(row, column)
if SPACES[stop_row][column] == PLAYER[0]:
return True
return False
#### PURPOSE
# This function returns the index of the row directly north of the
# attempted space.
# Note: NORTH = from bottom to top of board, decreasing row index,
# increasing y-coordinate.
#### SIGNATURE
# north_next_row :: Int => Int
#### EXAMPLES
# north_next_row(6) => 5
# north_next_row(5) => 4
# north_next_row(4) => 3
def north_next_row(row):
return row - 1
#### PURPOSE
# This function returns the index of the row of the second to last tile
# in the sandwich that will be made if the move if chosen (i.e., the last
# of the opposing player's tiles to be flipped.)
# Note: NORTH = from bottom to top of board, decreasing row index,
# increasing y-coordinate.
#### SIGNATURE
# north_stop_row :: (Int, Int) => Int
#### EXAMPLES
# north_stop_row(7,4) => 6
# north_stop_row(5,1) => 2
# north_stop_row(4,4) => 1
def north_stop_row(row, column):
i = 1
while SPACES[row - i][column] == PLAYER[1] and row - i > 0:
i += 1
return row - i
#### PURPOSE
# This function flips the necessary tiles in a given direction based on
# the player's selected move, if and only if the placement of the tile
# should legally flip tiles in said direction.
# Note: NORTH = from bottom to top of board, decreasing row index,
# increasing y-coordinate.
#### SIGNATURE
# north_flip_tiles :: (Int, Int) => Void
#### EXAMPLES
# n/a
def north_flip_tiles(row, column):
if north_legal_move(row, column):
tile_x_coord, tile_y_coord = COORDINATES[row][column]
next_row = north_next_row(row)
stop_row = north_stop_row(row, column)
tile_y_coord += SQUARE
while next_row > stop_row:
draw_tile(tile_x_coord, tile_y_coord)
next_row -= 1
tile_y_coord += SQUARE
#### PURPOSE
# This function evaluates the validity of a move by looking at existing
# tiles to the NORTH EAST of the space. It will resolve True if placing
# the tile will create a sandwich, a series of the opposing player's tiles
# between two of the current player's tiles.
# Note: NORTH EAST = from bottom left to top right, decreasing row index,
# increasing column index, increasing x-coordinate, increasing y-coordinate.
#### SIGNATURE
# NE_legal_move :: (Int, Int) => Bool
#### EXAMPLES
# NE_legal_move(7, 0) => True
# NE_legal_move(5, 4) => True
# NE_legal_move(2, 7) => False
def NE_legal_move(row, column):
next_row = NE_next_row(row)
next_col = NE_next_col(column)
if row >= 2 and column < BOARD_SIZE - 2 and SPACES[next_row][next_col] == PLAYER[1]:
stop_row = NE_stop_row(row, column)
stop_col = NE_stop_col(row, column)
if SPACES[stop_row][stop_col] == PLAYER[0]:
return True
return False
#### PURPOSE
# This function returns the index of the row directly NORTH of the
# attempted space.
# Note: NORTH = from bottom to top of board, decreasing row index,
# increasing y-coordinate.
#### SIGNATURE
# NE_next_row :: Int => Int
#### EXAMPLES
# north_next_row(6) => 5
# north_next_row(5) => 4
# north_next_row(4) => 3
def NE_next_row(row):
return row - 1
#### PURPOSE
# This function returns the index of the column directly EAST of the
# attempted space.
# Note: EAST = from left to right of board, increasing column index,
# increasing x-coordinate.
#### SIGNATURE
# NE_next_col :: Int => Int
#### EXAMPLES
# NE_next_col(5) => 6
# NE_next_col(2) => 3
# NE_next_col(3) => 4
def NE_next_col(column):
return column + 1
#### PURPOSE
# This function returns the index of the row of the second to last tile
# in the sandwich that will be made if the move if chosen (i.e., the last
# of the opposing player's tiles to be flipped.)
# Note: NORTH = from bottom to top of board, decreasing row index,
# increasing y-coordinate.
#### SIGNATURE
# NE_stop_row :: (Int, Int) => Int
#### EXAMPLES
# NE_stop_row(7,4) => 6
# NE_stop_row(5,1) => 2
# NE_stop_row(4,4) => 1
def NE_stop_row(row, column):
i = 1
while SPACES[row - i][column + i] == PLAYER[1] and row - i > 0 and column + i < BOARD_SIZE - 1:
i += 1
return row - i
#### PURPOSE
# This function returns the index of the column of the second to last
# tile in the sandwich that will be made if the move if chosen.
# Note: EAST = from left to right of board, increasing column index,
# increasing x-coordinate.
#### SIGNATURE
# NE_stop_col :: (Int, Int) => Int
#### EXAMPLE
# NE_stop_col(3, 3) => 4
# NE_stop_col(4, 4) => 5
def NE_stop_col(row, column):
i = 1
while SPACES[row - i][column + i] == PLAYER[1] and row - i > 0 and column + i < BOARD_SIZE - 1:
i += 1
return column + i
#### PURPOSE
# This function flips the necessary tiles in a given direction based on
# the player's selected move, if and only if the placement of the tile
# should legally flip tiles in said direction.
#### SIGNATURE
# NE_flip_tiles :: (Int, Int) => Void
#### EXAMPLES
# n/a
def NE_flip_tiles(row, column):
if NE_legal_move(row, column):
tile_x_coord, tile_y_coord = COORDINATES[row][column]
next_row = NE_next_row(row)
next_col = NE_next_col(column)
stop_row = NE_stop_row(row, column)
stop_col = NE_stop_col(row, column)
tile_x_coord += SQUARE
tile_y_coord += SQUARE
while next_row > stop_row and next_col < stop_col:
draw_tile(tile_x_coord, tile_y_coord)
next_row -= 1
next_col += 1
tile_x_coord += SQUARE
tile_y_coord += SQUARE
#### PURPOSE
# This function evaluates the validity of a move by looking at existing
# tiles to the EAST of the space. It will resolve True if placing the
# tile will create a sandwich, a series of the opposing player's tiles
# between two of the current player's tiles.
# Note: EAST = from left to right of board, increasing column index,
# increasing x-coordinate.
#### SIGNATURE
# east_legal_move :: (Int, Int) => Bool
#### EXAMPLES
# east_legal_move(5, 2) => True
# east_legal_move(4, 3) => False
# east_legal_move(7, 7) => False
def east_legal_move(row, column):
next_col = east_next_col(column)
if column < BOARD_SIZE - 2 and SPACES[row][next_col] == PLAYER[1]:
stop_col = east_stop_col(row, column)
if SPACES[row][stop_col] == PLAYER[0]:
return True
return False
#### PURPOSE
# This function returns the index of the column directly east of the
# attempted space.
# Note: EAST = from left to right of board, increasing column index,
# increasing x-coordinate.
#### SIGNATURE
# east_next_col :: Int => Int
#### EXAMPLES
# east_next_col(4) => 5
# east_next_col(5) => 6
# east_next_col(0) => 1
def east_next_col(column):
return column + 1
#### PURPOSE
# This function returns the index of the column of the second to last
# tile in the sandwich that will be made if the move if chosen.
# Note: EAST = from left to right of board, increasing column index,
# increasing x-coordinate.
#### SIGNATURE
# east_stop_col :: (Int, Int) => Int
#### EXAMPLE
# east_stop_col(2, 3) => 4
# east_stop_col(3, 1) => 3
# east_stop_col(0, 7) => 5
def east_stop_col(row, column):
i = 1
while SPACES[row][column + i] == PLAYER[1] and column + i < BOARD_SIZE - 1:
i += 1
return column + i
#### PURPOSE
# This function flips the necessary tiles in a given direction based on
# the player's selected move, if and only if the placement of the tile
# should legally flip tiles in said direction.
#### SIGNATURE
# east_flip_tiles :: (Int, Int) => Void
#### EXAMPLES
# n/a
def east_flip_tiles(row, column):
if east_legal_move(row, column):
tile_x_coord, tile_y_coord = COORDINATES[row][column]
next_col = east_next_col(column)
stop_col = east_stop_col(row, column)
tile_x_coord += SQUARE
while next_col < stop_col:
draw_tile(tile_x_coord, tile_y_coord)
next_col += 1
tile_x_coord += SQUARE
#### PURPOSE
# This function evaluates the validity of a move by looking at existing
# tiles to the SOUTH EAST of the space. It will resolve True if placing
# the tile will create a sandwich, a series of the opposing player's tiles
# between two of the current player's tiles.
# Note: SOUTH EAST = from top left to bottom right, increasing row index,
# increasing column index, increasing x-coordinate, decreasing y-coordinate.
#### SIGNATURE
# SE_legal_move :: (Int, Int) => Bool
#### EXAMPLES
# SE_legal_move(7, 0) => False
# SE_legal_move(3, 4) => True
# SE_legal_move(1, 7) => False
def SE_legal_move(row, column):
next_row = SE_next_row(row)
next_col = SE_next_col(column)
if row < BOARD_SIZE - 2 and column < BOARD_SIZE - 2 and SPACES[next_row][next_col] == PLAYER[1]:
stop_row = SE_stop_row(row, column)
stop_col = SE_stop_col(row, column)
if SPACES[stop_row][stop_col] == PLAYER[0]:
return True
return False
#### PURPOSE
# This function returns the index of the row directly SOUTH of the
# attempted space.
# Note: SOUTH = from top to bottom of board, increasing row index,
# decreasing y-coordinate.
#### SIGNATURE
# SE_next_row :: Int => Int
#### EXAMPLES
# SE_next_row(6) => 7
# SE_next_row(5) => 6
# SE_next_row(4) => 5
def SE_next_row(row):
return row + 1
#### PURPOSE
# This function returns the index of the column directly EAST of the
# attempted space.
# Note: EAST = from left to right of board, increasing column index,
# increasing x-coordinate.
#### SIGNATURE
# SE_next_col :: Int => Int
#### EXAMPLES
# SE_next_col(5) => 6
# SE_next_col(2) => 3
# SE_next_col(3) => 4
def SE_next_col(column):
return column + 1
#### PURPOSE
# This function returns the index of the row of the second to last tile
# in the sandwich that will be made if the move if chosen (i.e., the last
# of the opposing player's tiles to be flipped.)
# Note: SOUTH = from top to bottom of board, increasing row index,
# decreasing y-coordinate.
#### SIGNATURE
# SE_stop_row :: (Int, Int) => Int
#### EXAMPLES
# SE_stop_row(3,4) => 5
# SE_stop_row(5,1) => 7
# SE_stop_row(4,4) => 7
def SE_stop_row(row, column):
i = 1
while SPACES[row + i][column + i] == PLAYER[1] and row + i < BOARD_SIZE - 1 and column + i < BOARD_SIZE - 1:
i += 1
return row + i
#### PURPOSE
# This function returns the index of the column of the second to last
# tile in the sandwich that will be made if the move if chosen.
# Note: EAST = from left to right of board, increasing column index,
# increasing x-coordinate.
#### SIGNATURE
# SE_stop_col :: (Int, Int) => Int
#### EXAMPLE
# SE_stop_col(3, 3) => 6
def SE_stop_col(row, column):
i = 1
while SPACES[row + i][column + i] == PLAYER[1] and row + i < BOARD_SIZE - 1 and column + i < BOARD_SIZE - 1:
i += 1
return column + i
#### PURPOSE
# This function flips the necessary tiles in a given direction based on
# the player's selected move, if and only if the placement of the tile
# should legally flip tiles in said direction.
#### SIGNATURE
# SE_flip_tiles :: (Int, Int) => Void
#### EXAMPLES
# n/a
def SE_flip_tiles(row, column):
if SE_legal_move(row, column):
tile_x_coord, tile_y_coord = COORDINATES[row][column]
next_row = SE_next_row(row)
next_col = SE_next_col(column)
stop_row = SE_stop_row(row, column)
stop_col = SE_stop_col(row, column)
tile_x_coord += SQUARE
tile_y_coord -= SQUARE
while next_row < stop_row and next_col < stop_col:
draw_tile(tile_x_coord, tile_y_coord)
next_row += 1
next_col += 1
tile_x_coord += SQUARE
tile_y_coord -= SQUARE
#### PURPOSE
# This function evaluates the validity of a move by looking at existing
# tiles to the SOUTH of the space. It will resolve True if placing the
# tile will create a sandwich, a series of the opposing player's tiles
# between two of the current player's tiles.
# Note: SOUTH = from top to bottom of board, increasing row index,
# decreasing y-coordinate.
#### SIGNATURE
# south_legal_move :: (Int, Int) => Bool
#### EXAMPLES
# south_legal_move(4, 3) => True
def south_legal_move(row, column):
next_row = south_next_row(row)
if row < BOARD_SIZE - 2 and SPACES[next_row][column] == PLAYER[1]:
stop_row = south_stop_row(row, column)
if SPACES[stop_row][column] == PLAYER[0]:
return True
return False
#### PURPOSE
# This function returns the index of the row directly SOUTH of the
# attempted space.
# Note: SOUTH = from top to bottom of board, increasing row index,
# decreasing y-coordinate.
#### SIGNATURE
# south_next_row :: Int => Int
#### EXAMPLES
# south_next_row(3) => 4
def south_next_row(row):
return row + 1
#### PURPOSE
# This function returns the index of the row of the second to last tile
# in the sandwich that will be made if the move if chosen (i.e., the last
# of the opposing player's tiles to be flipped.)
# Note: SOUTH = from top to bottom of board, increasing row index,
# decreasing y-coordinate.
#### SIGNATURE
# south_stop_row :: (Int, Int) => Int
#### EXAMPLES
# south_stop_row(3,4) => 6
def south_stop_row(row, column):
i = 1
while SPACES[row + i][column] == PLAYER[1] and row + i < BOARD_SIZE - 1:
i += 1
return row + i
#### PURPOSE
# This function flips the necessary tiles in a given direction based on
# the player's selected move, if and only if the placement of the tile
# should legally flip tiles in said direction.
# Note: SOUTH = from top to bottom of board, increasing row index,
# decreasing y-coordinate.
#### SIGNATURE
# south_flip_tiles :: (Int, Int) => Void
#### EXAMPLES
# n/a
def south_flip_tiles(row, column):
if south_legal_move(row, column):
tile_x_coord, tile_y_coord = COORDINATES[row][column]
next_row = south_next_row(row)
stop_row = south_stop_row(row, column)
tile_y_coord -= SQUARE
while next_row < stop_row:
draw_tile(tile_x_coord, tile_y_coord)
next_row += 1
tile_y_coord -= SQUARE
#### PURPOSE
# This function evaluates the validity of a move by looking at existing
# tiles to the SOUTH WEST of the space. It will resolve True if placing
# the tile will create a sandwich, a series of the opposing player's tiles
# between two of the current player's tiles.
# Note: SOUTH WEST = from top right to bottom left, increasing row index,
# decreasing column index, decreasing x-coordinate, decreasing y-coordinate.
#### SIGNATURE
# SW_legal_move :: (Int, Int) => Bool
#### EXAMPLES
# SW_legal_move(1, 6) => True
def SW_legal_move(row, column):
next_row = SW_next_row(row)
next_col = SW_next_col(column)
if row < BOARD_SIZE - 2 and column >= 2 and SPACES[next_row][next_col] == PLAYER[1]:
stop_row = SW_stop_row(row, column)
stop_col = SW_stop_col(row, column)
if SPACES[stop_row][stop_col] == PLAYER[0]:
return True
return False
#### PURPOSE
# This function returns the index of the row directly SOUTH of the
# attempted space.
# Note: SOUTH = from top to bottom of board, increasing row index,
# decreasing y-coordinate.
#### SIGNATURE
# SW_next_row :: Int => Int
#### EXAMPLES
# SW_next_row(5) => 6
def SW_next_row(row):
return row + 1
#### PURPOSE
# This function returns the index of the column directly WEST of the
# attempted space.
# Note: WEST = from right to left of board, decreasing column index,
# decreasing x-coordinate.
#### SIGNATURE
# SW_next_col :: Int => Int
#### EXAMPLES
# SW_next_col(5) => 4
def SW_next_col(column):
return column - 1
#### PURPOSE
# This function returns the index of the row of the second to last tile
# in the sandwich that will be made if the move if chosen (i.e., the last
# of the opposing player's tiles to be flipped.)
# Note: SOUTH = from top to bottom of board, increasing row index,
# decreasing y-coordinate.
#### SIGNATURE
# SW_stop_row :: (Int, Int) => Int
#### EXAMPLES
# SW_stop_row(0,7) => 4
def SW_stop_row(row, column):
i = 1
while SPACES[row + i][column - i] == PLAYER[1] and row + i < BOARD_SIZE - 1 and column - i > 0:
i += 1
return row + i
#### PURPOSE
# This function returns the index of the column of the second to last
# tile in the sandwich that will be made if the move if chosen.
# Note: WEST = from right to left of board, decreasing column index,
# decreasing x-coordinate.
#### SIGNATURE
# SW_stop_col :: (Int, Int) => Int
#### EXAMPLE
# SW_stop_col(1, 7) => 4
def SW_stop_col(row, column):
i = 1
while SPACES[row + i][column - i] == PLAYER[1] and row + i < BOARD_SIZE - 1 and column - i > 0:
i += 1
return column - i
#### PURPOSE
# This function flips the necessary tiles in a given direction based on
# the player's selected move, if and only if the placement of the tile
# should legally flip tiles in said direction.
#### SIGNATURE
# SW_flip_tiles :: (Int, Int) => Void
#### EXAMPLES
# n/a
def SW_flip_tiles(row, column):
if SW_legal_move(row, column):
tile_x_coord, tile_y_coord = COORDINATES[row][column]
next_row = SW_next_row(row)
next_col = SW_next_col(column)
stop_row = SW_stop_row(row, column)
stop_col = SW_stop_col(row, column)
tile_x_coord -= SQUARE
tile_y_coord -= SQUARE
while next_row < stop_row and next_col > stop_col:
draw_tile(tile_x_coord, tile_y_coord)
next_row += 1
next_col -= 1
tile_x_coord -= SQUARE
tile_y_coord -= SQUARE
#### PURPOSE
# This function evaluates the validity of a move by looking at existing
# tiles to the WEST of the space. It will resolve True if placing the
# tile will create a sandwich, a series of the opposing player's tiles
# between two of the current player's tiles.
# Note: WEST = from right to left of board, decreasing column index,
# decreasing x-coordinate.
#### SIGNATURE
# west_legal_move :: (Int, Int) => Bool
#### EXAMPLES
# west_legal_move(5, 2) => True
# east_legal_move(4, 3) => False
def west_legal_move(row, column):
next_col = west_next_col(column)
if column >= 2 and SPACES[row][next_col] == PLAYER[1]:
stop_col = west_stop_col(row, column)
if SPACES[row][stop_col] == PLAYER[0]:
return True
return False
#### PURPOSE
# This function returns the index of the column directly WEST of the
# attempted space.
# Note: WEST = from right to left of board, decreasing column index,
# decreasing x-coordinate.
#### SIGNATURE
# west_next_col :: Int => Int
#### EXAMPLES
# east_next_col(4) => 3
def west_next_col(column):
return column - 1
#### PURPOSE
# This function returns the index of the column of the second to last
# tile in the sandwich that will be made if the move if chosen.
# Note: WEST = from right to left of board, decreasing column index,
# decreasing x-coordinate.
#### SIGNATURE
# west_stop_col :: (Int, Int) => Int
#### EXAMPLE
# west_stop_col(4, 4) => 1
def west_stop_col(row, column):
i = 1
while SPACES[row][column - i] == PLAYER[1] and column - i > 0:
i += 1
return column - i
#### PURPOSE
# This function flips the necessary tiles in a given direction based on
# the player's selected move, if and only if the placement of the tile
# should legally flip tiles in said direction.
#### SIGNATURE
# west_flip_tiles :: (Int, Int) => Void
#### EXAMPLES
# n/a
def west_flip_tiles(row, column):
if west_legal_move(row, column):
tile_x_coord, tile_y_coord = COORDINATES[row][column]
next_col = west_next_col(column)
stop_col = west_stop_col(row, column)
tile_x_coord -= SQUARE
while next_col > stop_col:
draw_tile(tile_x_coord, tile_y_coord)
next_col -= 1
tile_x_coord -= SQUARE
#### PURPOSE
# This function evaluates the validity of a move by looking at existing
# tiles to the NORTH WEST of the space. It will resolve True if placing
# the tile will create a sandwich, a series of the opposing player's tiles
# between two of the current player's tiles.
# Note: NORTH WEST = from bottom left to top right, decreasing row index,
# decreasing column index, decreasing x-coordinate, increasing y-coordinate.
#### SIGNATURE
# NW_legal_move :: (Int, Int) => Bool
#### EXAMPLES
# NW_legal_move(0, 0) => False
# NW_legal_move(7, 7) => True
def NW_legal_move(row, column):
next_row = NW_next_row(row)
next_col = NW_next_col(column)
if row >= 2 and column >= 2 and SPACES[next_row][next_col] == PLAYER[1]:
stop_row = NW_stop_row(row, column)
stop_col = NW_stop_col(row, column)
if SPACES[stop_row][stop_col] == PLAYER[0]:
return True
return False
#### PURPOSE
# This function returns the index of the row directly NORTH of the
# attempted space.
# Note: NORTH = from bottom to top of board, decreasing row index,
# increasing y-coordinate.
#### SIGNATURE
# NW_next_row :: Int => Int
#### EXAMPLES
# north_next_row(6) => 5
def NW_next_row(row):
return row - 1
#### PURPOSE
# This function returns the index of the column directly WEST of the
# attempted space.
# Note: WEST = from right to left of board, decreasing column index,
# decreasing x-coordinate.
#### SIGNATURE
# NW_next_col :: Int => Int
#### EXAMPLES
# NW_next_col(5) => 4
def NW_next_col(column):
return column - 1
#### PURPOSE
# This function returns the index of the row of the second to last tile
# in the sandwich that will be made if the move if chosen (i.e., the last
# of the opposing player's tiles to be flipped.)
# Note: NORTH = from bottom to top of board, decreasing row index,
# increasing y-coordinate.
#### SIGNATURE
# NW_stop_row :: (Int, Int) => Int
#### EXAMPLES
# NW_stop_row(3, 4) => 2
def NW_stop_row(row, column):
i = 1
while SPACES[row - i][column - i] == PLAYER[1] and row - i > 0 and column - i > 0:
i += 1
return row - i
#### PURPOSE
# This function returns the index of the column of the second to last
# tile in the sandwich that will be made if the move if chosen.
# Note: WEST = from right to left of board, decreasing column index,
# decreasing x-coordinate.
#### SIGNATURE
# NW_stop_col :: (Int, Int) => Int
#### EXAMPLE
# NW_stop_col(4, 5) => 3
def NW_stop_col(row, column):
i = 1
while SPACES[row - i][column - i] == PLAYER[1] and row - i > 0 and column - i > 0:
i += 1
return column - i
#### PURPOSE
# This function flips the necessary tiles in a given direction based on
# the player's selected move, if and only if the placement of the tile
# should legally flip tiles in said direction.
#### SIGNATURE
# SE_flip_tiles :: (Int, Int) => Void
#### EXAMPLES
# n/a
def NW_flip_tiles(row, column):
if NW_legal_move(row, column):
tile_x_coord, tile_y_coord = COORDINATES[row][column]
next_row = NW_next_row(row)
next_col = NW_next_col(column)
stop_row = NW_stop_row(row, column)
stop_col = NW_stop_col(row, column)
tile_x_coord -= SQUARE
tile_y_coord += SQUARE
while next_row > stop_row and next_col > stop_col:
draw_tile(tile_x_coord, tile_y_coord)
next_row -= 1
next_col -= 1
tile_x_coord -= SQUARE
tile_y_coord += SQUARE
# MAIN
def main():
# prepare game
init_game()
# update legal moves before first user turn
update_legal_moves()
# update dynamic text before first user turn
update_dynamic_text()
# begin game, user goes first
start_user_move()
if __name__ == "__main__":
main()
turtle.done() |
from typing import List
LengthOfList = 10
########################## Hashing algorithm (Task 2.3(
def hashing(id):
firstpart = ""
for i in range(2):
char = str(ord(id[i]))
firstpart = (firstpart + char)
for i in range(2, 6):
char = id[i]
firstpart = (firstpart + char)
hash = int(firstpart)
return (hash - 65650000) % LengthOfList
########################### Code for Creating Binary tree
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
# Compare the new value with the parent node
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# Print the tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print("Index position:", i, self.data),
if self.right:
self.right.PrintTree()
# findval method to compare the value with nodes
def findval(self,lkpval): #Task(2.5)
if lkpval < self.data:
if self.left is None:
return str(lkpval) + " Not Found"
return self.left.findval(lkpval)
elif lkpval > self.data:
if self.right is None:
return False
return self.right.findval(lkpval)
else:
return True
# Inorder traversal
# Left -> Root -> Right
def inorderTraversal(self, root): #Task(2.5)
res = []
if root:
res = self.inorderTraversal(root.left)
res.append(root.data)
res = res + self.inorderTraversal(root.right)
return res
#####################################
########## ID generator Task(2.4)
def ID_Generator():
import random
# index_for_search_val = random.randint(0, LengthOfList) ######## to test if search function works
IdGenArr = []
for r in range(LengthOfList):
a = str(chr(random.randint(65, 90)))
b = str(chr(random.randint(65, 90)))
c = str(random.randint(65, 90))
d = str(random.randint(65, 90))
e = str(random.randint(65, 90))
f = str(random.randint(65, 90))
if r == 0: ######## to test if search function works
global SearchVal
SearchVal = a + b + c + d + e + f
IdGenArr.append(SearchVal)
if r != 0:
IdGenArr.append(a + b + c + d + e + f) ######## to test if search function works
return IdGenArr
############# Calling ID generator Task(2.4)
IdGenArr = ID_Generator()
############################### Innitialise array
Array = [""] * LengthOfList
for r in range(LengthOfList):
Array[r] = Node(0)
################################# Data Input
for r in range(LengthOfList):
data = IdGenArr[r]
index = hashing(data)
Array[index].insert(data)
for i in range(LengthOfList): #Task(2.5)
print("Index no:",i,":",Array[i].inorderTraversal( Array[i]))
#
#for i in range(LengthOfList): #Task(2.5)
# print(Array[i].inorderTraversal( Array[i]))
#
#
#
print("the search value is ", SearchVal)
searchIndex = hashing(SearchVal)
if Array[searchIndex].findval(SearchVal):
print("The ",SearchVal," is in index no:",searchIndex)
|
# Normal Solution
def addDigits(num):
i = 0
digits = []
sum = 0
while num > 0:
digits.append(num % 10)
num = num // 10
i = i + 1
for i in digits:
sum += i
if sum / 10 >=1:
return addDigits(sum)
else:
return sum
print(addDigits(38))
# Another Solution
# 每步对num /10 然后加上个位上的数字; 然后再对这个加起来的数字处理,其实就可以类比每一步得到大于10的数然后继续处理。
# 分成了 n 个零散物品, 然后这n个零散物品还是可以再继续分类(>10),然后再对这n个零散物品继续分类成n'.....
# 然后最后其实得到的小于10的数字就是我们需要的结果。也其实就是对最后的个位进行处理。
def addDigits_supreme(num):
return (num-1) % 9 +1
|
def maxProfit(prices):
mins = prices[0]
maxs = 0
for i in range(len(prices)):
mins = min(mins,prices[i])
maxs = max(maxs,prices[i] - mins)
return maxs
print(maxProfit([7,1,5,3,6,4]))
|
#!/usr/bin/python3
def main():
testfunc( 1 , 2 ,3 , 4 ,5 )
testfunca(1 ,2, 3 ,4 ,one = 1 , two = 2 , seven = 7)
# multiple arguments rep by *args
def testfunc(that , *args):
print(that , args)
for i in args:
print(i, end = "")
# Key word arguments to a fuction
def testfunca(*args ,**kwargs):
print(args ,kwargs['one'] , kwargs['two'] , kwargs['seven'])
if __name__ == "__main__": main() |
count_w_s=7
count_w_m=6
count_w_l=2
count_b_s=8
count_b_m=5
count_b_l=2
def available(color,size):
global count_w_s
global count_w_m
global count_w_l
global count_b_s
global count_b_m
global count_b_l
if color=="white":
if size=="s" and count_w_s != 0:
count_w_s-=1
print("white small size")
print("order confirm white shirt small size")
elif size=="m" and count_w_m != 0:
count_w_m-=1
print("white medium")
print("order confirm white shirt medium size")
elif size=="l" and count_w_l != 0:
count_w_l
count_w_l -= 1
print(count_w_l)
print("white large")
print("order confirm white shirt large size")
else:
print("required stock is unavailable at the moment")
elif color=="blue":
if size=="s" and count_b_s != 0:
count_b_s-=1
print("blue small size")
print("order confirm blue shirt small size")
elif size=="m" and count_b_m != 0:
count_b_m-=1
print("blue medium")
print("order confirm blue shirt medium size")
elif size=="l" and count_b_l != 0:
count_b_l-=1
print("blue large")
print("order confirm blue shirt large size")
else:
print("required stock is unavailable at the moment")
else:
print("color or size invalid")
while True:
available(input("enter color"),input("enter size"))
|
#Hailstone Sequence
number=input("Give me a number greater than zero!")
if number<=0:
number=input("READ THE INSTRUCTIONS: Give me a number greater than zero!")
while (number!=1):
if number%2==0:
number=number/2
else:
number=(number*3)+1
print number
if number ==0:
break
|
"""A memory/matching game.
Use A and B to move around the screen. Press A+B together to see a card. Try and find
matches.
The code purposely only uses lists and dictionaries as its most advanced data structures.
It's also incomplete in a number of ways - feel free to make changes and see if you can
improve it!
"""
import random
from microbit import *
# Feel free to change the images used in the game. You should have 12 here, and you can
# see after the end ] below the list is "doubled" which makes a copy of each image.
cards = [
Image.HAPPY,
Image.HEART,
Image.TRIANGLE,
Image.DIAMOND,
Image.RABBIT,
Image.PACMAN,
Image.DUCK,
Image.HOUSE,
Image.XMAS,
Image.GHOST,
Image.TORTOISE,
Image.MUSIC_CROTCHET,
] * 2
# This line helps ensure that we have the right number of cards and didn't make a mistake. If
# there are more or less than 24 the program will crash and we'll know there's a problem.
assert len(cards) == 24
# This code populates the board. It loops over the rows and columns of LEDs on the screen
# and places a card at each X and Y position (excluding the very middle since we need an
# even number of cards).
board = []
for row in range(5):
for column in range(5):
if row == 2 and column == 2:
# We have an even number of cards - skip the middle LED
board.append(None)
continue
image = cards.pop(random.randrange(0, len(cards)))
# A dictionary is useful for representing a card. We can keep all of the data about
# it together and reference it by useful names (kind of like variables).
card = {
'image': image,
'x': column,
'y': row,
}
board.append(card)
# This will represent the controller that we move around on the display.
controller = {
'x': 2,
'y': 2,
}
# Now that the board is setup, here's where the game actually runs!
# We keep a variable with the last guess that the player made. To start with we assign it
# the special value of None which means ... nothing.
last_guess = None
# This list will keep the matching cards that the player has found. We'll use that to
# know which LEDs to turn off when showing the board on the display.
matches = []
while True:
# Button presses control the game! The game is constantly looping and checking if there
# were button presses. When it finds them, it does different things.
a_press = button_a.was_pressed()
b_press = button_b.was_pressed()
# First we handle if A and B were both pressed. It's important to do this first because
# checking if either button was pressed individually would hide the fact that both were
# pressed together.
if a_press and b_press:
# Here we do a bit of math to find the card that matches the (x,y) position of the
# controller. Can you figure out why it works?
card = board[controller['y'] * 5 + controller['x']]
# We check and make sure a card was found. When might that be false?
if card:
# Now we show the image for the card so the player can remember it.
display.show(card['image'])
sleep(1000)
# If the player had already made a guess, now we compare it with the card
# that they just chose. Otherwise we assign the card they just chose to last_guess.
if last_guess:
# We check that they aren't guessing the same card in the same spot and then
# check and see if the images match.
if last_guess != card and last_guess['image'] == card['image']:
# Hooray, a match - flash the display in excitement and add it to the
# matches list.
for i in range(10):
display.clear()
sleep(50)
display.show(card['image'])
sleep(50)
matches.append(card['image'])
# Whether they were right or not, reset the last guess and controller positions
# so they can try to find another pair of matches.
last_guess = None
controller['x'] = 2
controller['y'] = 2
else:
last_guess = card
# The A and B button handling below are similar. They handle moving progressively through
# all of the cards on the board. Can you figure out how it works?
elif a_press:
if controller['x'] == 0:
controller['x'] = 4
if controller['y'] == 0:
controller['y'] = 4
else:
controller['y'] -= 1
else:
controller['x'] -= 1
elif b_press:
if controller['x'] == 4:
controller['x'] = 0
if controller['y'] == 4:
controller['y'] = 0
else:
controller['y'] += 1
else:
controller['x'] += 1
# All of the button handling is done. Maybe some new matches were found, maybe the
# controller was moved. We update all of the LEDs based on the state of the board and
# the matches that have been found so far.
for card in board:
if not card:
# This is the no-card position - unless the controller is here it should be turned
# off (brightness == 0).
if controller['x'] != 2 or controller['y'] != 2:
display.set_pixel(2, 2, 0)
elif card['x'] != controller['x'] or card['y'] != controller['y']:
# Now we light up the positions of the cards, so long as the controller doesn't
# have the same (x,y) coordinates. If a card has been matched already, it's LED
# is turned off.
if card['image'] not in matches:
brightness = 1
else:
brightness = 0
display.set_pixel(card['x'], card['y'], brightness)
# Finally we light up the controller nice and bright and sleep briefly to allow time to
# capture button presses.
display.set_pixel(controller['x'], controller['y'], 9)
sleep(100) |
#https://www.w3schools.com/python/python_howto_remove_duplicates.asp
def remove_duplicat(x):
#Create a dictionary, using the List items as keys. This will automatically remove any duplicates because dictionaries cannot have duplicate keys.
return list(dict.fromkeys(x))
my_list=["a","b","c","c"]
print(remove_duplicat(my_list)) |
class Vertex:
def __init__(self, n):
self.name = n
self.neighbors = list()
def add_neighbor(self, v):
if v not in self.neighbors:
self.neighbors.append(v)
self.neighbors.sort()
self.visited = False
class Graph:
vertices = {}
def add_vertex(self, vertex):
if isinstance(vertex, Vertex) and vertex.name not in self.vertices:
self.vertices[vertex.name] = vertex
return True
else:
return False
def add_edge(self, u, v):
if u in self.vertices and v in self.vertices:
self.vertices[u].add_neighbor(v)
self.vertices[v].add_neighbor(u)
return True
else:
return False
def print_graph(self):
for key in sorted(list(self.vertices.keys())):
print(key + str(self.vertices[key].neighbors))
def _dfs(self, vertex, visited):
if(vertex not in visited):
visited[vertex] = vertex
print("Vertices",self.vertices[vertex].name)
print(self.vertices[vertex].neighbors)
for i in self.vertices[vertex].neighbors:
self._dfs(i,visited)
def dfs(self, vertex):
visited = {}
self._dfs(vertex,visited)
def _bfs(self, vertex, visited, q):
if (vertex not in visited):
visited[vertex] = vertex
print("Vertices", self.vertices[vertex].name)
print(self.vertices[vertex].neighbors)
if(len(q) > 0):
q.pop(0)
for i in self.vertices[vertex].neighbors:
if(i not in q):
q.append(i)
for i in q:
self._bfs(i, visited, q)
def bfs(self, vertex):
visited = {}
q = []
self._bfs(vertex, visited, q)
g = Graph()
a = Vertex('A')
g.add_vertex(a)
g.add_vertex(Vertex('B'))
for i in range(ord('A'), ord('K')):
g.add_vertex(Vertex(chr(i)))
edges = ['AB', 'AE', 'BF', 'CG', 'DE', 'DH', 'EH', 'FG', 'FI', 'FJ', 'GJ', 'HI']
for edge in edges:
g.add_edge(edge[:1], edge[1:])
g.bfs("A") |
class battedball:
"""
modularizes the battedball method collection into a class object.
bbclass can only be defined if the valid json, csv, and txt files
are located in the Data subdirectory of the working folder
"""
# initialization routine
def __init__(self):
self.player_dictionary = {}
self.stat_dictionary = {}
self.axes_dictionary = {}
self.__bb_parser()
# remove all auxiliary files created by my program
# list: playersnotindict.txt, player_dictionary.pickle, stat_dictionary.pickle
def cleanfiles(self):
"""
cleanfiles()
- removes all auxiliary files created by the script and recreates them
- e.g. playersnotindict.txt, player_dictionary.pickle, stat_dictionary.pickle
"""
import os
os.chdir('Data')
file_directory = os.listdir()
print("source files currently in directory\n" + str(file_directory))
print("deleting all pickle files + playersnotindict.txt")
# remove pickle files
for a_file in file_directory:
if a_file.endswith(".pickle"):
os.remove(a_file)
elif a_file == 'playersnotindict.txt':
os.remove(a_file)
print('operation complete')
file_directory = os.listdir()
print("files currently in directory\n" + str(file_directory))
os.chdir('..') # get back to home directory
# reinitialize the auxiliary files
self.__init__()
# end cleanfiles()
# given player name, list his stats
def find(self, player_name):
"""
find(player_name)
:param player_name: string (player's name)
:return: player's stats in console output
"""
if player_name in self.player_dictionary:
player = self.player_dictionary[player_name]
i = 0
output_string = []
column_length = 0
for keys in player:
if isinstance(player[keys], float):
key_value = format(player[keys], '.2f')
else:
key_value = player[keys]
key_plus_stats = keys + ": " + str(key_value)
kps_length = len(key_plus_stats)
if kps_length > column_length:
column_length = kps_length
column_length += 2
for keys in player:
if isinstance(player[keys], float):
key_value = format(player[keys], '.2f')
else:
key_value = player[keys]
output_string.append(keys + ": " + str(key_value))
i += 1
if i == 3:
print("".join(word.ljust(column_length) for word in output_string))
output_string = []
i = 0
if output_string:
print("".join(word.ljust(column_length) for word in output_string))
else:
print("player not found: " + player_name)
# end findplayer
# produces scatter plots
def scatter(self, x_stat, y_stat, xy_0_limit):
"""
scatter(x_stat, y_stat, xy_0_limit)
:param x_stat: string, stat to be plotted on x-axis
:param y_stat: string, stat to be plotted on y-axis
:param xy_0_limit: (boolean, boolean)
if xy_0_limit[0] is true, then x is allowed to be 0
if xy_0_limit[1] is true, then y is allowed to be 0
otherwise, they are not allowed to be 0 and tuples that fail the test are ignored
:return: html file with the plotted stats (opens in default web browser)
"""
# sanity checks
# checking if x_stat and y_stat exist in the axes_dictionary
# if they exist, then they will be formatted and put into the title and appear on graph axes
if x_stat in self.axes_dictionary:
x_title = self.axes_dictionary[x_stat]
else:
print("stat for x-axis not found:", x_stat)
return
if y_stat in self.axes_dictionary:
y_title = self.axes_dictionary[y_stat]
else:
print("stat for y-axis not found:", y_stat)
return
if isinstance(xy_0_limit, tuple):
if not(isinstance(xy_0_limit[0], bool)) or not(isinstance(xy_0_limit[0], bool)):
print("xy_0_limit needs to be a tuple of boolean values")
return
else:
print("xy_0_limit needs to be a tuple of boolean values")
return
import numpy as np
from scipy import stats
import plotly
import plotly.graph_objs as go
plot_title = y_title + " versus " + x_title
plot_filename = y_stat + "_vs_" + x_stat + ".html"
full_player_list = []
contracted_player_list = []
free_agent_list = []
max_x_value = 0.0
min_x_value = 0
min_x_value_check = 1
for player_name in self.player_dictionary:
player = self.player_dictionary[player_name]
# set the first dictionary value as the first min value
if min_x_value_check == 1:
min_x_value = player[x_stat]
min_x_value_check = 0
# if xy_0_limit[0] is true, then x is allowed to be 0
# if xy_0_limit[1] is true, then y is allowed to be 0
# otherwise, they are not allowed to be 0 and tuples that fail the test are ignored
xy2 = [True, True]
if not (xy_0_limit[0]):
xy2[0] = player[x_stat] > 0
if not (xy_0_limit[1]):
xy2[1] = player[y_stat] > 0
if xy2[0] and xy2[1]: # if player[yax[0]] > 0 and player[xax[0]] > 0:
if player['freeagent']:
free_agent_list.append([player['name'], player[x_stat], player[y_stat]])
else:
contracted_player_list.append([player['name'], player[x_stat], player[y_stat]])
full_player_list.append([player['name'], player[x_stat], player[y_stat]])
if player[x_stat] > max_x_value:
max_x_value = player[x_stat]
if player[x_stat] < min_x_value:
min_x_value = player[x_stat]
# end loop
# convert FA/contracted player lists to array;
# lists are easy to append, arrays as input to plotly
# normal players
contracted_player_array = np.asarray(contracted_player_list)
contracted_players_names = contracted_player_array[:, 0]
contracted_players_x_array = np.asarray(contracted_player_array[:, 1], dtype='float64')
contracted_players_y_array = np.asarray(contracted_player_array[:, 2], dtype='float64')
# free agents
free_agent_array = np.asarray(free_agent_list)
free_agent_names = free_agent_array[:, 0]
free_agent_x_array = np.asarray(free_agent_array[:, 1], dtype='float64')
free_agent_y_array = np.asarray(free_agent_array[:, 2], dtype='float64')
# full player array - for the line of best fit
players_array = np.asarray(full_player_list)
players_x_array = np.asarray(players_array[:, 1], dtype='float64')
players_y_array = np.asarray(players_array[:, 2], dtype='float64')
# plotting the contracted players
contracted_plot = go.Scatter(
x=contracted_players_x_array,
y=contracted_players_y_array,
name='Contracted Players',
text=contracted_players_names,
mode='markers'
)
# plotting the free agents
free_agent_plot = go.Scatter(
x=free_agent_x_array,
y=free_agent_y_array,
name='Free Agents',
text=free_agent_names,
mode='markers'
)
# line of best fit code
# isinstance(value, type) => boolean, i.e. isinstance(0.5, float) => True
# use this to adjust the xmin/xmax values
linear_regress_array = stats.linregress(players_x_array, players_y_array)
if (max_x_value - min_x_value) > 1:
# hacky way to adjust the line of best fit length to make it stretch less
min_x_value -= 1
max_x_value += 1
else:
min_x_value -= 0.05
max_x_value += 0.05
x_line_of_best_fit_array = np.linspace(min_x_value, max_x_value, 2)
y_line_of_best_fit_array = linear_regress_array.slope * x_line_of_best_fit_array + linear_regress_array.intercept
line_of_best_fit_plot = go.Scatter(
x=x_line_of_best_fit_array,
y=y_line_of_best_fit_array,
name='Line of Best Fit',
mode='lines'
)
# put the correlation coefficient (r) in the title (up to 2 decimal places)
r_value = format(linear_regress_array.rvalue, '.2f')
plot_title = plot_title + " (rvalue: " + r_value + ")"
layout = dict(title=plot_title,
yaxis=dict(
zeroline=False,
title=y_title
),
xaxis=dict(
zeroline=False,
title=x_title
)
)
# contracted_plot: contracted players, free_agent_plot: free agents, line_of_best_fit_plot: line of best fit
# plots line of best fit if there is moderate or better correlation
if linear_regress_array.rvalue > 0.3 or linear_regress_array.rvalue < -0.3: # positive or negative correlation
data = [contracted_plot, free_agent_plot, line_of_best_fit_plot]
else:
data = [contracted_plot, free_agent_plot]
fig = dict(data=data, layout=layout)
plotly.offline.plot(fig, filename=plot_filename)
# printing out the linear regression values
print("rval:", str(linear_regress_array.rvalue), ", slope:", str(linear_regress_array.slope), ", y-intercept:",
str(linear_regress_array.intercept))
# end scatter
# updated histogram plotter - uses pandas and plotly's bar graphs rather than its built-in hist
def hist(self, frequency_stat, hover_stat, bins):
"""
hist(x, y, bins)
:param frequency_stat: string, stat to be binned and plotted
:param hover_stat: string, stat that will be as hoverable text over each bin
:param bins: int, number of bins to be plotted
:return: html file with the plotted stats (opens in default web browser)
"""
# sanity checks
# checking if frequency_stat and hover_stat exist in the axes_dictionary
# if they exist, then they will be formatted and put into the title and appear on graph axes
if frequency_stat in self.axes_dictionary:
x_title = self.axes_dictionary[frequency_stat]
else:
print("stat for x-axis not found:", frequency_stat)
return
if hover_stat in self.axes_dictionary:
y_title = self.axes_dictionary[hover_stat]
else:
print("stat for y-axis not found:", hover_stat)
return
if not(isinstance(bins, int)):
print("enter a positive integer number of bins!!!")
return
elif bins < 2:
print("please enter a valid number of bins (bins > 1)")
return
import numpy as np
import pandas as pd
import plotly
import plotly.graph_objs as go
# the "x-axis list" used for frequency data
# the "y-axis list" used for additional data to appear as hover text
frequency_data_list = []
hover_text_stat_list = []
plot_title = x_title + " histogram"
plot_filename = frequency_stat + "_hist.html"
# populate the frequency/hover text lists
for player_name in self.player_dictionary:
player = self.player_dictionary[player_name]
frequency_data_list.append(player[frequency_stat])
hover_text_stat_list.append(player[hover_stat])
# end loop
# put frequency_data_list and hover_text_stat_list into pandas' dataframe - pandas is very useful!!
raw_data = {frequency_stat: frequency_data_list, hover_stat: hover_text_stat_list}
pandas_dataframe1 = pd.DataFrame(raw_data, columns=[frequency_stat, hover_stat])
#get min/max value for bin sizes
frequency_max = float((pandas_dataframe1.describe()).loc['max', frequency_stat])
frequency_min = float((pandas_dataframe1.describe()).loc['min', frequency_stat])
# bin processing
bin_size = (frequency_max - frequency_min) / bins
bin_list = [] # list of bin ranges
names_of_bins = [] # list of bin names, i.e. bin0,...,binN
bin_ranges = [] # list of bin names by range, i.e. (x0, x1], (x1, x2],..., (xn-1, xn]
num_bins_init = frequency_min # to initialize the bin ranges
for i in range(bins):
bin_name = "bin" + str(i) # bin_name: for names_of_bins
bin_list.append(round(num_bins_init, 2)) # round to two sigfigs; precision unimportant
bin_range_name = "(" + str(round(num_bins_init, 2)) # bin_range_name: for bin_ranges
num_bins_init += bin_size
bin_range_name += ", " + str(round(num_bins_init, 2)) + "]"
names_of_bins.append(bin_name)
bin_ranges.append(bin_range_name)
bin_list.append(round(num_bins_init, 2)) # add the "max" to the bin, adjusted for stupid float vals
# adjust min bin by lowering its threshold, since binned by rightmost, i.e. (x1,x2] (see docs)
bin_list[0] = float(bin_list[0] - np.ceil(bin_list[0]*0.01))
bin_ranges[0] = "(" + str(bin_list[0]) + ", " + str(bin_list[1]) + "]"
# using pandas' cut to bin the values
pandas_dataframe1['bins'] = pd.cut(pandas_dataframe1[frequency_stat], bin_list, labels=names_of_bins)
# groups all the rows in the dataframe by their bin name and gets their count
# pd.value_counts returns a pd.Series, not a dataframe
pandas_series1 = pd.value_counts(pandas_dataframe1['bins'])
pandas_series1 = pandas_series1.sort_index(axis=0) # sorts dataframe by bin name - default is by value
# get the average y-val per bin name and put it in a list
avg_hover_stat_list = []
avg_hover_stat_name = 'avg_' + hover_stat
for some_bin_name in names_of_bins:
# ugly code to get the average y-stat per bin
# 1. get the value, 2. round the value, 3. format the value for hover text
avg_hover_stat = ((pandas_dataframe1[pandas_dataframe1['bins'] == some_bin_name]).describe()).loc['mean', hover_stat]
avg_hover_stat = round(float(avg_hover_stat), 2)
bin_count = "count: " + str(pandas_series1.loc[some_bin_name])
avg_hover_stat = bin_count + ", avg " + y_title + ": " + str(avg_hover_stat)
avg_hover_stat_list.append(avg_hover_stat)
# stat_dictionary['pc'] is the total count of players in the dictionary
pandas_dataframe2 = pd.DataFrame({'bin_pct': pandas_series1 / self.stat_dictionary['pc'],
avg_hover_stat_name: avg_hover_stat_list,
'bin_ranges': bin_ranges})
histogram_plot = go.Bar(
x=pandas_dataframe2['bin_ranges'],
y=pandas_dataframe2['bin_pct'],
text = pandas_dataframe2[avg_hover_stat_name],
marker=dict(
color='rgb(158,202,225)',
line=dict(
color='rgb(8,48,107)',
width=1.5,
)
),
opacity=0.6
)
data = [histogram_plot]
layout = go.Layout(
title=plot_title,
yaxis=dict(
zeroline=False,
title="Frequency"),
xaxis=dict(
zeroline=False,
title="Bin Ranges: "+x_title)
)
fig = go.Figure(data=data, layout=layout)
plotly.offline.plot(fig, filename=plot_filename)
# end hist1
################################
####### PRIVATE ROUTINES #######
################################
# merging list of free agents with dictionary
# if player is a free agent, change their free agent status to True
def __merge_free_agents(self, fa_file):
free_agent_list = open(fa_file)
for free_agent in free_agent_list:
free_agent = free_agent.strip('\r\n')
if free_agent in self.player_dictionary:
player = self.player_dictionary[free_agent]
player['freeagent'] = True
# end merge_fas
# opens the json file and creates a dictionary
# working with static json file 'playerlist.json'
# playerlist.json retrieved from page source at https://baseballsavant.mlb.com/statcast_leaderboard
# query: minimum batted balls events of 30, season 2016
# would be better if json file is specified from user, but this is just for fun :)
def __parse_and_dict(self, json_file):
import json
json1_file = open(json_file)
json1_str = json1_file.read()
# json.loads turns the json into a list of dictionaries
json1_data = json.loads(json1_str) # gets the whole dictionary
player_counter = 0
max_ahs_name = ""
min_ahs_name = ""
max_avg_hit_speed = 0
min_avg_hit_speed = 100
league_ahs = 0
# useful for setting the axes of the brl_pa/avg hit speed graph
max_brl_pa_name = ""
max_brl_pa = 0
# populate the dictionary player_dictionary
for player in json1_data:
pname = player['name']
# to int: avg_distance, avg_hr_distance, batter, max_distance, player_id
player['avg_distance'] = int(player['avg_distance'])
ahd = str(player['avg_hr_distance']) # manually changed null to "null" in list
if ahd.lower() == 'null': # sometimes ahd is null; players w/o hr
player['avg_hr_distance'] = 0
else:
player['avg_hr_distance'] = int(player['avg_hr_distance'])
player['batter'] = int(player['batter'])
player['max_distance'] = int(player['max_distance'])
player['player_id'] = int(player['player_id'])
# to float: avg_hit_speed, brl_pa(%), brl_percent(%), fbld, gb, max_hit_speed, min_hit_speed
player['avg_hit_speed'] = float(player['avg_hit_speed'])
league_ahs = league_ahs + player['avg_hit_speed']
player['brl_pa'] = float(player['brl_pa'].strip('%')) / 100
player['brl_percent'] = float(player['brl_percent'].strip('%')) / 100
player['fbld'] = float(player['fbld'])
player['gb'] = float(player['gb'])
player['max_hit_speed'] = float(player['max_hit_speed'])
player['min_hit_speed'] = float(player['min_hit_speed'])
# to bool: freeagent
if player['freeagent'].lower() == 'true':
player['freeagent'] = True
else:
player['freeagent'] = False
# populating player_dictionary
# sets a player's value in the dictionary
self.player_dictionary[pname] = player
player_counter += 1
# min/max cases for stats
# finding player with max avg hit speed
# finding player with max amount of "barrels"/PA
if player['avg_hit_speed'] > max_avg_hit_speed:
max_avg_hit_speed = player['avg_hit_speed']
max_ahs_name = pname
if player['avg_hit_speed'] < min_avg_hit_speed:
min_avg_hit_speed = player['avg_hit_speed']
min_ahs_name = pname
if player['brl_pa'] > max_brl_pa:
max_brl_pa_name = player['name']
max_brl_pa = player['brl_pa']
# debugging statements go here:
# end loop
# more code
############ league-wide stats!!! ############
self.stat_dictionary['pc'] = player_counter
# name of player with max/min average hitting speed, max/min hitting speed
self.stat_dictionary['max_avg_hs'] = max_avg_hit_speed
self.stat_dictionary['max_avg_hs_name'] = max_ahs_name
self.stat_dictionary['min_avg_hs'] = min_avg_hit_speed
self.stat_dictionary['min_avg_hs_name'] = min_ahs_name
self.stat_dictionary['max_brl_pa_name'] = max_brl_pa_name # :)
self.stat_dictionary['max_brl_pa'] = max_brl_pa
self.stat_dictionary['league_ahs'] = float('%.2f' % (league_ahs / player_counter)) # truncate the float
# end parse_and_dict
# from csv file, add a player's BA to the dictionary
def __fgstats_to_dict(self, csv_filename):
import csv
import os.path
# would be safer to have script determine csv's encoding
# manually determined in linux by "file -bi <filename>"
csv_file = open(csv_filename, 'rt', encoding='utf-8')
csv_reader = csv.reader(csv_file)
not_in_dict = "Data/playersnotindict.txt"
f1 = open(not_in_dict, 'a')
nic = 0
if not (os.path.isfile(not_in_dict)):
nic = 1 # if nic == 1, file only written once
print("creating file that contains players not in dictionary")
f1.write("players not in dictionary:\n")
for row in csv_reader:
# csv file is currently formatted with the first line being "Name, Avg"
# all subsequent elements are of that form
# csv.reader formats each line ("row") as a list of strings
# list indices:
# 0: name, 1: team, 2: games played, 3: plate appearances, 4: HR
# 5: runs, 6: rbi, 7: # stolen bases, 8: BB%, 9: K%, 10: ISO
# 11: BABIP, 12: BA, 13: OBP, 14: SLG, 15: wOBA, 16: wRC+, 17: BsR
# 18: off rating, 19: def rating, 20: fWAR, 21: playerID
player_name = row[0]
if player_name in self.player_dictionary:
bb_percent = float(row[8].strip(' %')) / 100
k_percent = float(row[9].strip(' %')) / 100
iso_str = float(row[10])
BABIP = float(row[11])
BA = float(row[12])
OBP = float(row[13])
SLG = float(row[14])
wOBA = float(row[15])
wRCp = int(row[16])
BsR = float(row[17])
fWAR = float(row[20])
player = self.player_dictionary[player_name]
player['bb%'] = bb_percent
player['k%'] = k_percent
player['iso_str'] = iso_str
player['babip'] = BABIP
player['ba'] = BA
player['obp'] = OBP
player['slg'] = SLG
player['wOBA'] = wOBA
player['wRC+'] = wRCp
player['BsR'] = BsR
player['fWAR'] = fWAR
# if player not found, add his name to the file
elif os.path.isfile(not_in_dict) and nic == 1 and row[0] != 'Name':
to_out = row[0] + '\n'
f1.write(to_out)
# for safety, close the file
f1.close()
# end adding_ba_to_dict
# maps the shorthand key name to its full name
# useful when sending data to the plotter; for the axes
def __key_to_axes(self):
import os
import pickle
filename = "Data/key_to_axes.pickle"
if os.path.isfile(filename):
print(filename, "found")
with open(filename, 'rb') as ktahandle:
self.axes_dictionary = pickle.load(ktahandle)
else:
print(filename, "not found")
self.axes_dictionary['fbld'] = "Average FB/LD Exit Velocity (MPH)"
self.axes_dictionary['k%'] = "K%"
self.axes_dictionary['wRC+'] = "wRC+"
self.axes_dictionary['season'] = "Season"
self.axes_dictionary['brl_pa'] = "Barrels/Plate Appearances"
self.axes_dictionary['fWAR'] = "fWAR"
self.axes_dictionary['max_hit_speed'] = "Maximum Exit Velocity (MPH)"
self.axes_dictionary['brl_percent'] = "Barrels/Batted Ball Events"
self.axes_dictionary['avg_distance'] = "Average Distance (ft)"
self.axes_dictionary['slg'] = "SLG"
self.axes_dictionary['max_distance'] = "Maximum Distance (ft)"
self.axes_dictionary['iso_str'] = "Isolated Power"
self.axes_dictionary['ba'] = "Batting Average"
self.axes_dictionary['obp'] = "On-Base Percentage"
self.axes_dictionary['barrels'] = "Total Barreled Balls"
self.axes_dictionary['attempts'] = "Batted Ball Events"
self.axes_dictionary['babip'] = "BABIP"
self.axes_dictionary['avg_hit_speed'] = "Average Exit Velocity (MPH)"
self.axes_dictionary['avg_hr_distance'] = "Average Home Run Distance (ft)"
self.axes_dictionary['min_hit_speed'] = "Minimum Hit Speed (MPH)"
self.axes_dictionary['gb'] = "Average Groundball Exit Velocity (MPH"
self.axes_dictionary['wOBA'] = "wOBA"
self.axes_dictionary['BsR'] = "BsR"
self.axes_dictionary['bb%'] = "bb%"
with open(filename, 'wb') as ktahandle:
pickle.dump(self.axes_dictionary, ktahandle, protocol=pickle.HIGHEST_PROTOCOL)
# end key_to_axes()
# second initialization routine: calls the parsers
# checks if the source files exist and populates the dictionaries
def __bb_parser(self):
import os.path
import sys
import pickle
# source files located in the Data directory:
# 1. json file used to populate player_dictionary
# 2. list of free agent players for the current offseason
# 3. fangraphs leaderboard stats
json_fname = "Data/playerlist.json"
fa_file = "Data/fullfalist.txt"
csvfname = "Data/fgleaders1.csv"
# exit if source files not found
if not (os.path.isfile(csvfname)):
print("csv not found")
sys.exit(1)
if not (os.path.isfile(json_fname)):
print("battedball json not found")
sys.exit(1)
if not (os.path.isfile(fa_file)):
print("free agent list not found")
sys.exit(1)
# runs the parsers or retrieves the dicts from pickle files
# using pickle to store player_dictionary and stat_dictionary
pickled_player_dict = "Data/player_dictionary.pickle"
pickled_stat_dict = "Data/stat_dictionary.pickle"
self.__key_to_axes() # creates the shorthands for axes creation - has its own pickle checker
if os.path.isfile(pickled_player_dict) and os.path.isfile(pickled_stat_dict):
print('pickled player_dictionary and stat_dictionary found')
with open(pickled_player_dict, 'rb') as pdhandle:
self.player_dictionary = pickle.load(pdhandle)
with open(pickled_stat_dict, 'rb') as sdhandle:
self.stat_dictionary = pickle.load(sdhandle)
else:
print('pickled player_dictionary and stat_dictionary file not found')
self.__parse_and_dict(json_fname) # populate player_dictionary
self.__fgstats_to_dict(csvfname)
self.__merge_free_agents(fa_file) # adds free agent status to players
with open(pickled_player_dict, 'wb') as pdhandle:
pickle.dump(self.player_dictionary, pdhandle, protocol=pickle.HIGHEST_PROTOCOL)
with open(pickled_stat_dict, 'wb') as sdhandle:
pickle.dump(self.stat_dictionary, sdhandle, protocol=pickle.HIGHEST_PROTOCOL)
# end parser
# end battedball class
|
def gcd(m,n):
while m%n != o:
oldm = m
oldn = n
m = oldn
n = oldm%oldn
return n
class Fraction:
def __init__(self,top,bottom):# this is known as constructor
self.num = top
self.den = bottom
def __str__(self):# function that print the exact value without printing the address like 0x40bc...
return str(self.num) + "/" + str(self.den)
def __add__(self, otherfraction):
# a/b + c/d can be written as (ad+bc)/bd hence newnum=(ad+bc) and newden is(bd) respectively
newnum = self.num*otherfraction.den + self.den*otherfraction.num
newden = self.den*otherfraction.den
return Fraction(newnum,newden)
def __eq__(self,other):
firstnum = self.num*other.den
secondnum = self.den*other.num
return firstnum == secondnum
x = Fraction(1,2)
y = Fraction(2,3)
print(x+y)
print(x == y) |
class Solution(object):
def __init__(self):
self.direction=[]
self.direction.append([0,1])
self.direction.append([0,-1])
self.direction.append([1,0])
self.direction.append([-1,0])
self.row = 0
self.col = 0
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if not board:
return
self.row = len(board)
self.col = len(board[0])
if self.row == 0 or self.col == 0:
return
for i in range(self.row):
if board[i][0]=='O':
self.bfs(board,i,0)
if board[i][self.col-1] =='O':
self.bfs(board,i,self.col-1)
for j in range(self.col):
if board[0][j] == 'O':
self.bfs(board,0,j)
if board[self.row-1][j] =='O':
self.bfs(board,self.row-1,j)
for i in range(self.row):
for j in range(self.col):
if board[i][j] == 'O':
board[i][j] = 'X'
if board[i][j] =='#':
board[i][j] = 'O'
def bfs(self,board,i,j):
"""
从board 的i j位置开始广搜,将 O的位置都置为,#
:param board:
:param i:
:param j:
:return:
"""
queue = []
if self.posIsValid(i,j) and board[i][j] == 'O':
board[i][j] = '#'
queue.append([i,j])
while len(queue) > 0:
i,j = queue.pop(0)
for k in range(4):
newI = i +self.direction[k][0]
newJ = j + self.direction[k][1]
if self.posIsValid(newI,newJ) and board[newI][newJ]=='O':
queue.append([newI,newJ])
board[newI][newJ] = '#'
def posIsValid(self,i,j):
if i > -1 and i < self.row and j > -1 and j < self.col:
return True
return False
if __name__ == '__main__':
so = Solution()
board = [list("XXX"),list("XOX"),list("XXX")]
so.solve(board)
print(board)
|
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
diff = 0xffffffff
nums = sorted(nums)
for i in range(len(nums)):
low = i + 1
high = len(nums) - 1
while low < high:
sum = nums[low] + nums[high] + nums[i]
temp = sum - target
if abs(temp) < abs(diff):
diff = temp
if temp == 0:
return sum
if temp < 0:
low += 1
if temp > 0:
high -= 1
return target + diff
if __name__ == '__main__':
nums = [0,2,1,-3]
solution = Solution()
print solution.threeSumClosest(nums, 1)
|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
@staticmethod
def inOrderRec(root):
"""
递归中根遍历
:param root: TreeNode
:return:
"""
if not root:
return
TreeNode.inOrderRec(root.left)
print(str(root.val)+",",end="")
TreeNode.inOrderRec(root.right)
@staticmethod
def preOrder(root):
"""
传入一棵二叉树,对其先根遍历
:param root: TreeNode
:return:
"""
if not root:
return
print(str(root.val),end=",")
TreeNode.preOrder(root.left)
TreeNode.preOrder(root.right)
@staticmethod
def buildBinaryTreeFromSer(nums):
"""
给定数组{3,9,20,#,#,15,7},返回相应的二叉树
:param nums: List[]
:return: TreeNode
"""
if not nums:
return None
queue = []
root = TreeNode(nums[0])
queue.append(root)
i =1
size = len(nums)
while queue:
top = queue.pop(0)
if i < size:
if nums[i]!='#':
top.left = TreeNode(nums[i])
queue.append(top.left)
i+=1
if i < size:
if nums[i] != '#':
top.right = TreeNode(nums[i])
queue.append(top.right)
i+=1
return root
@staticmethod
def levelOrder(root):
"""
层次遍历
:param root: TreeNode
:return:
"""
if not root:return
queue = []
queue.append(root)
while queue:
top = queue.pop(0)
print(top.val,end=",")
if top.left:
queue.append(top.left)
if top.right:
queue.append(top.right)
if __name__ == '__main__':
root = TreeNode.buildBinaryTreeFromSer([1,2,3])
TreeNode.inOrderRec(root)
TreeNode.preOrder(root)
TreeNode.levelOrder(root)
|
'''
Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
'''
# Tags: Tree Traversal (Level Order)
"""
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if not root: return []
cur = root
queue = [[cur, 0]]
level = [[cur.val]]
while queue:
cur, l = queue.pop(0)
l += 1
for child in cur.children:
queue.append([child, l])
if len(level) < l + 1: level.append([])
level[l].append(child.val)
return level |
'''
Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.
Example 1:
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
Output: 23
Note:
The number of nodes in the tree is at most 10000.
The final answer is guaranteed to be less than 2^31.
'''
# Tags: Tree Traversal
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
if not root: return 0
ret = 0
stack = []
cur = root
while 1:
if cur:
if cur.val>=L and cur.val<=R:
ret+=cur.val
stack.append(cur)
if cur.val<L:
cur.left = None
cur = cur.left
else:
if not stack:
break
cur = stack.pop()
if cur.val>R:
while stack:
cur = stack.pop()
cur = cur.right
return ret |
# Your code here
def finder(files, queries):
"""
YOUR CODE HERE
"""
files_found = []
directory = {}
for file in files:
# keyName is last part of path
parts = file.split("/")
keyName = parts[-1]
# create a new entry in the dictionary if needed
if keyName not in directory:
directory[keyName] = []
# add current path to dictionary with the keyName as the key
directory[keyName].append(file)
# go through each query
for query in queries:
# if the file was found, add all the paths to the result to return
if query in directory:
files_found.append(directory[query])
return files_found
if __name__ == "__main__":
files = [
'/bin/foo',
'/bin/bar',
'/usr/bin/baz'
]
queries = [
"foo",
"qux",
"baz"
]
print(finder(files, queries))
|
"""
Задача D. Сумма факториалов
По данному натуральном n вычислите сумму факториалов.
В решении этой задачи можно использовать только один цикл.
Вводится натуральное число n.
"""
n = int(input())
previous_factorial = 1
sum_factorials = 0
for i in range(1, n+1):
current_factorial = previous_factorial * i
sum_factorials += current_factorial
previous_factorial = current_factorial
print(sum_factorials)
|
"""
Задача B. Обнулить последние биты
Напишите программу, которая обнуляет заданное количество последних бит числа
"""
number, i = [int(i) for i in input().split()]
# обнуляю i последние бит
result = number >> i << i
print(result) |
from data_structure.stack import Stack
def test_push():
stack = Stack()
stack.push(1)
assert stack.back() == 1
assert stack.size == 1
stack.push(3)
assert stack.back() == 3
def test_pop():
stack = Stack()
stack.push(1)
assert stack.size == 1
assert stack.pop() == 1
assert stack.size == 0
stack.push(3)
stack.push(1)
assert stack.pop() == 1
assert stack.size == 1
assert stack.pop() == 3
assert stack.size == 0
|
"""
Задача A. Установить значение бита в 1
Напишите программу, которая в заданном числе устанавливает
определенный бит в 1 (биты при этом нумеруются с нуля, начиная от младших).
"""
a, i = [int(i) for i in input().split()]
result = (1 << i) | a
|
"""
Задача A
Даны два списка A и B упорядоченных по неубыванию.
Объедините их в один упорядоченный список С
(то есть он должен содержать len(A)+len(B) элементов).
Решение оформите в виде функции merge(A, B), возвращающей новый список.
Алгоритм должен иметь сложность O(len(A)+len(B)).
Модифицировать исходные списки запрещается.
Использовать функцию sorted и метод sort запрещается.
"""
from algoritms.sorting.merge_sort import merge
if __name__ == '__main__':
arr_1 = [int(i) for i in input().strip().split()]
arr_2 = [int(i) for i in input().strip().split()]
merged_arrays = merge(arr_1, arr_2)
for val in merged_arrays:
print(val, end=" ") |
"""
Задача G. Ручная сортировка
Вам необходимо реализовать алгоритм сортировки merge-sort.
"""
from algoritms.sorting.merge_sort import merge_sort
if __name__ == '__main__':
_ = input()
arr = [int(i) for i in input().strip().split()]
sorted_arr = merge_sort(arr)
for val in sorted_arr:
print(val, end=" ") |
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
###################################################
# INSTRUCTOR INPUT BLOCK
# THIS CELL WILL BE REPLACED BY GRADER INPUTS
# DO NOT CHANGE THE NAMES OR SIGNATURES OF THESE VARIABLES
# SAMPLE DATA AND OUTPUTS ARE GIVEN AT THE END OF THIS ASSIGNMENT
###################################################
POINTS = [(6, 6), (4, 7), (17, 3), (6, 18), (2, 13), (12, 5), (5, 10), (18, 16), (2, 20), (13, 1)]
# POINTS = [(6, 4), (6, 32), (6, 25), (6, 27), (6, 14)]
# POINTS = [(6, 4), (32, 4), (25, 4), (27, 4), (14, 4)]
# POINTS = [(-12, 5), (-11, 5), (24, 5), (26, 5)]
# POINTS = [(-5, 5), (10, 14), (-12, -2), (8, -6)]
M = 3
# Each point is a tuple (x,y)
# POINTS is a list of all points (i.e. a list of tuples)
# The data we're expecting as a result is also list of tuples with three elements:
# point #1, point #2, and the distance between them: ( (x1,y1),(x2,y2),distance) )
# These are then stacked into a list with up to M entries in it: M_closest = [(tuple1), (tuple2), ... (tupleM)]
import math
def call_counter(f):
def wrapped(*args, **kwargs): # deal with any/all arguments
wrapped.calls += 1
return f(*args, **kwargs)
wrapped.calls = 0
return wrapped
'''
Closest Distance, returns the m closest pairs between the points
Parameter: points - A list of tuples which represent a point.
m - the number of closest points we are looking for
Return: m_closest - A list of tuples which each contain (Point1, Point2, distance) ordered on ascending order
by distance. If m is equal or smaller than 0, or if points have less than 1 point it returns an empty list
Otherwise it will returns m tuples. If there there isn't enough to return m tuples it will return
the maximum amount it can.
'''
@call_counter
def closestDistance(points, m):
m_closest = list()
# If m <= exit because no pairs are being queried
if m > 0:
# Pre-sort Points by X to define lines
sorted_points = merge_sort(points)
# Call recursive code to get M closest points
m_closest = closest_pairs(sorted_points, m)
return m_closest
''' A merge sort that sorts points in ascending order using the coordiantes '''
@call_counter
def merge_sort(points):
# Base case 1: There is one or no elements in the given list
if len(points) <= 1:
return points
# Recursive case 1: Divide list into two lists cut by the middle
left_sub_points = merge_sort(points[0:len(points)//2])
right_sub_points = merge_sort(points[len(points)//2:])
# Merge the returning sub lists
sorted_points = merge(left_sub_points, right_sub_points)
return sorted_points
''' Merge sort helper to merge the given arrays '''
@call_counter
def merge(left_sub_points, right_sub_points):
merged_points = list()
# Choose the smallest point from the leading elements and add it to the merge list
while (len(left_sub_points) > 0) and (len(right_sub_points) > 0):
if left_sub_points[0] < right_sub_points[0]:
merged_points.append(left_sub_points.pop(0))
elif left_sub_points[0] > right_sub_points[0]:
merged_points.append(right_sub_points.pop(0))
else:
if left_sub_points[1] < right_sub_points[1]:
merged_points.append(left_sub_points.pop(0))
else:
merged_points.append(right_sub_points.pop(0))
# If there are points left on left add them to the sorted list
while len(left_sub_points) > 0:
merged_points.append(left_sub_points.pop(0))
# If there are points right on left add them to the sorted list
while len(right_sub_points) > 0:
merged_points.append(right_sub_points.pop(0))
return merged_points
''' Implements a divide and conquer tactic to find the closest points '''
@call_counter
def closest_pairs(points, m):
# Get number of points in list to choose a recursive or a base case.
point_count = len(points)
# Base Case 1: If there is none or 1 point there are no close points
if point_count <= 1:
# Return empty list
return list()
# Base Case 2: If there are two points return the only pair possible
elif point_count == 2:
# Return the only distance pair
m_closest = closes_points(points, m)
return m_closest
# Recursive Case 1: If there are enough combination of points to get m pairs
elif (math.factorial(point_count)/(2*math.factorial(point_count-2))) > m:
# Assuming points is sorted, divide the list in 2 sub lists
left_points = points[0:point_count//2]
right_points = points[point_count//2:point_count]
# Keep dividing the sub lists to start finding the m closest pairs
closest_left = closest_pairs(left_points, m)
closest_right = closest_pairs(right_points, m)
# Get the number of pairs achieved from the sublists
closest_left_count = len(closest_left)
closest_right_count = len(closest_right)
# Get the minimum range needed to decide if there are middle points that we need to check
if (closest_left_count > 0) and (closest_right_count > 0):
if closest_left[closest_left_count-1][2] > closest_right[closest_right_count-1][2]:
middle_points_threshold = closest_left[closest_left_count-1][2]
else:
middle_points_threshold = closest_right[closest_right_count-1][2]
else:
if closest_left_count > 0:
middle_points_threshold = closest_left[closest_left_count-1][2]
else:
middle_points_threshold = closest_right[closest_right_count-1][2]
# Create a list with points that are horizontally close enough to make distances shorter than the current max
middle_left = list()
middle_right = list()
for point in left_points:
if (point[0] > points[point_count//2][0] - middle_points_threshold) & (point[0] < points[point_count//2][0] + middle_points_threshold):
middle_left.append(point)
for point in right_points:
if (point[0] > points[point_count//2][0] - middle_points_threshold) & (point[0] < points[point_count//2][0] + middle_points_threshold):
middle_right.append(point)
# Get the m distances possible from middle points
middle_closest = middle_closest_pairs(middle_left, middle_right, m)
# Get the m closest points from between the corner pairs
corner_closest = list()
for count in range(0, m):
if (len(closest_left) > 0) and (len(closest_right) > 0):
if closest_left[0][2] < closest_right[0][2]:
corner_closest.append(closest_left.pop(0))
else:
corner_closest.append(closest_right.pop(0))
elif len(closest_left) > 0:
corner_closest.append(closest_left.pop(0))
elif len(closest_right) > 0:
corner_closest.append(closest_right.pop(0))
else:
break
# Get the m closest points from all the found distances
m_closest = list()
for count in range(0, m):
if (len(corner_closest) > 0) and (len(middle_closest) > 0):
if corner_closest[0][2] < middle_closest[0][2]:
m_closest.append(corner_closest.pop(0))
else:
m_closest.append(middle_closest.pop(0))
elif len(corner_closest) > 0:
m_closest.append(corner_closest.pop(0))
elif len(middle_closest) > 0:
m_closest.append(middle_closest.pop(0))
else:
break
# Return the m closest points
return m_closest
# Base Case 3: If there aren't enough points to get m pairs
else:
# Calculate and return closest points possible
m_closest = closes_points(points, m)
return m_closest
''' Finds the closest points between the points of a list '''
@call_counter
def closes_points(points, m):
# Prepare variables for search
m_points = list()
m_count = 0
point_count = len(points)
# Iterate for each possible combination of points
for point_num in range(0, point_count):
for distance_to in range(1 + point_num, point_count):
# Calculate distance
distance = math.sqrt(pow(points[point_num][0] - points[distance_to][0], 2) + pow(points[point_num][1] - points[distance_to][1], 2))
# If there is no distance registered, add the first one as the smallest distance
if m_count == 0:
m_count = 1
m_points.append((points[point_num], points[distance_to], distance))
else:
# Check registered distances and make sure it contains the minimum m distances
for m_point_index in range(0, len(m_points)):
# If the new distance is smaller than one that is already in the closest list, insert it there
if distance < m_points[m_point_index][2]:
m_points.insert(m_point_index, (points[point_num], points[distance_to], distance))
# If we have exceeded the maximum number of closest (m) remove the largest distance registered
if m_count >= m:
m_points.pop()
break
# If there aren't yet m closest points add the newest distance as the largest
elif (m_count <= m) and (m_count == m_point_index+1):
m_points.append((points[point_num], points[distance_to], distance))
break
# Count that we reached m closest points
if m_count < m:
m_count = m_count + 1
return m_points
''' Finds the closest points between two list of points '''
@call_counter
def middle_closest_pairs(left_points, right_points, m):
# Prepare variables for search
m_points = list()
m_count = 0
left_point_count = len(left_points)
right_points_count = len(right_points)
# Iterate for each possible combination of points between two lists
for left_point_num in range(0, left_point_count):
for right_point_num in range(0, right_points_count):
# Calculate distance
distance = math.sqrt(pow(left_points[left_point_num][0] - right_points[right_point_num][0], 2) + pow(left_points[left_point_num][1] - right_points[right_point_num][1], 2))
# If there is no distance registered, add the first one as the smallest distance
if m_count == 0:
m_count = 1
m_points.append((left_points[left_point_num], right_points[right_point_num], distance))
else:
# Check registered distances and make sure it contains the minimum m distances
for m_point_index in range(0, m_count):
# If the new distance is smaller than one that is already in the closest list, insert it there
if distance < m_points[m_point_index][2]:
m_points.insert(m_point_index, (left_points[left_point_num], right_points[right_point_num], distance))
# If we have exceeded the maximum number of closest (m) remove the largest distance registered
if m_count >= m:
m_points.pop()
break
# If there aren't yet m closest points add the newest distance as the largest
if (m_count <= m) & (m_count == m_point_index+1):
m_points.append((left_points[left_point_num], right_points[right_point_num], distance))
break
# Count that we reached m closest points
if m_count < m:
m_count = m_count + 1
return m_points
# This block should run your function and produce output that matches the input and output given in the Instructor
# Input Block and the sample data at the end of this assignment
M_closest = closestDistance(POINTS, M)
print("closest {}-{} pairs of points are: ".format(M, len(M_closest)))
for pair in M_closest:
print("Points {} and {}, distance = {}".format(pair[0], pair[1], pair[2]))
import random
import math
# Data creation
x1_number_of_points = list()
y1_number_of_calls = list()
y1_assymtotic_time = list()
x2_changes_in_m = list()
y2_number_of_calls = list()
y2_assymtotic_time = list()
dummy = list()
dummy.append((random.random()*1000, random.random()*1000))
# May take a few seconds
m = 1
for quantity in range(1,1000):
dummy.append((random.random()*1000, random.random()*1000))
if (quantity % 50) == 0:
x1_number_of_points.append(quantity)
closests = closestDistance(dummy, m)
y1_number_of_calls.append(closestDistance.calls + merge_sort.calls + merge.calls + closest_pairs.calls + closes_points.calls + middle_closest_pairs.calls)
y1_assymtotic_time.append((quantity*math.log10(quantity)) + (m*math.log10(quantity)) + (m*math.pow(quantity, 2)*math.log10(quantity)))
for quantity in range(0,50):
dummy.append((random.random()*1000, random.random()*1000))
for m_increment in range(0, 1000, 50):
x2_changes_in_m.append(m+m_increment)
closests = closestDistance(dummy, m+m_increment)
y2_number_of_calls.append(closestDistance.calls + merge_sort.calls + merge.calls + closest_pairs.calls + closes_points.calls + middle_closest_pairs.calls)
y2_assymtotic_time.append((50*math.log(50)) + ((m+m_increment)*math.log(50)) + ((m+m_increment)*math.pow(50, 2)*math.log(50))) |
'''
Um funcionário recebe um salário fixo mais 4% de comissão sobre as vendas. Faça um programa
que receba o salário fixo do funcionário e o valor de suas vendas, calcule e mostre a comissão e seu
salário final.
'''
salario_fixo = float(input('Digite o salário fixo: '))
valor_vendas = float(input('Digite o valor de vendas: '))
valor_comissao = (valor_vendas * 4)/ 100
salario_final = salario_fixo + valor_comissao
print('Valor final do salário: ')
print(salario_final)
print('Valor de comissão: ')
print(valor_comissao)
|
#pegar a distância
distancia = float(input())
if(distancia >0 and distancia <= 200):
op1 = distancia * 0.50
print(op1)
elif(distancia > 200):
op2 = distancia * 0.45
print(op2)
else:
print('Possivelmente o valor é negativo.')
|
''' Q7
Elabore um programa que preencha uma matriz M de ordem
6x4 e uma segunda matriz N de ordem 6x4, calcule
e imprima a soma das linhas de M com as colunas de N.
'''
'''
m = []
n = []
#criando a matriz m
for i in range(3):
linha = []
for j in range(2):
linha.append(int(input()))
m.append(linha)
#criando a matriz n
for i in range(3):
linha = []
for j in range(2):
linha.append(int(input()))
n.append(linha)
'''
m = [[6,4],[8,3],[7,2]]
n = [[10,5],[9,1],[11,0]]
soma_linha = 0
soma_coluna = 0
for i in range(3):
soma_linha = 0
for j in range(2):
soma_linha = soma_linha + m[i][j]
soma_f = 0
for i in range(2):
soma_coluna = 0
for j in range(3):
soma_coluna = soma_coluna + n[j][i]
soma_f = soma_linha + soma_coluna
print(soma_f)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.