text stringlengths 37 1.41M |
|---|
#echo function
def echo(self, args):
out = ''
for word in args:
out += word+' '
print(out)
#function reference, min args, max args, help info, case sensitive?, function name
func_alias = 'echo'
func_info = (echo,
0,
-1,
'Prints all arguments back to the user.',
False,
)
|
#!/usr/bin/env python
import auth
import argparse
def get_playlist(playlist_name, spotify_client, username):
for playlist in spotify_client.spotify.user_playlists(username)['items']:
if playlist['name'] == playlist_name:
print "Playlist gia esistente"
return playlist
#Playlist not present, so create it
print "Playlist da creare"
playlist = spotify_client.spotify.user_playlist_create(username, playlist_name)
return playlist
def get_track(string_to_search, spotify_client):
try:
result = spotify_client.spotify.search(string_to_search)
id = result["tracks"]["items"][0]
except Exception, e:
return None
return id
def argument():
parser = argparse.ArgumentParser(description="Search and add song to a spotify playlist from a list in file.")
parser.add_argument("-i", "--input-file", required=True,
help="Input file with list of songs")
parser.add_argument("-p", "--playlist", required=True,
help="Name of playlist")
parser.add_argument("-u", "--username", required=True,
help="Name of user")
args = parser.parse_args()
return args
##Main function
if __name__ == '__main__':
args = argument()
spotify_client = auth.Client()
playlist = get_playlist(args.playlist, spotify_client, args.username)
not_found = []
count = 1
with open(args.input_file, 'r') as f:
content = f.readlines()
for line in content:
track = get_track(line, spotify_client)
if track:
print("Track {} found! {}/{}").format(line, count, len(content))
results = spotify_client.spotify.user_playlist_add_tracks(USERNAME, playlist["id"], [track["id"]])
else:
not_found.append(line)
count = count + 1
print not_found |
# 7. Create a list of tuples of first name, last name, and age for your friends
# and colleagues. If you don't know the age, put in None. Calculate the
# average age, skipping over any None values. Print out each name,
# followed by old or young if they are above or below the average age.
list_=[]
tuple_1=('sita ','Dahal',27)
list_.append(tuple_1)
tuple_2=('Anit ','Basnet',32)
list_.append(tuple_2)
tuple_3=('kendra','Regmi','none')
list_.append(tuple_3)
tuple_4=('Bikalpa','Dhakal',24)
list_.append(tuple_4)
print(list_)
|
# 2. Write an if statement to determine whether a variable holding a year is
# a leap year.
a=int (input("enter input:"))
if a%4==0 and a%100 !=0:
print(a," is leap year")
elif a%100==0:
print(a,'is not leap year')
elif a%4==0:
print(a,"is leap year")
else:
print("given year is not leap year") |
# coding=utf-8
from decimal import Decimal
INFINITY = float('Infinity')
class Node:
def __init__(self, label):
self.label = label
class Edge:
def __init__(self, to_node, length):
self.to_node = to_node
self.length = length
class Graph:
def __init__(self):
self.nodes = set()
self.edges = dict()
def add_node(self, node):
self.nodes.add(node)
def add_edge(self, from_node, to_node, length):
edge = Edge(to_node, length)
if from_node.label in self.edges:
from_node_edges = self.edges[from_node.label]
else:
self.edges[from_node.label] = dict()
from_node_edges = self.edges[from_node.label]
from_node_edges[to_node.label] = edge
def min_dist(q, dist):
"""
Returns the node with the smallest distance in q.
Implemented to keep the main algorithm clean.
"""
min_node = None
for node in q:
if min_node == None:
min_node = node
elif dist[node] < dist[min_node]:
min_node = node
return min_node
def dijkstra(graph, source):
q = set()
dist = {}
prev = {}
for v in graph.nodes: # initialization
dist[v] = INFINITY # unknown distance from source to v
prev[v] = INFINITY # previous node in optimal path from source
q.add(v) # all nodes initially in q (unvisited nodes)
# distance from source to source
dist[source] = 0
while q:
# node with the least distance selected first
u = min_dist(q, dist)
q.remove(u)
if u.label in graph.edges:
for _, v in graph.edges[u.label].items():
alt = dist[u] + v.length
if alt < dist[v.to_node]:
# a shorter path to v has been found
dist[v.to_node] = alt
prev[v.to_node] = u
return dist, prev
def to_array(prev, from_node):
"""Creates an ordered list of labels as a route."""
previous_node = prev[from_node]
route = [from_node.label]
while previous_node != INFINITY:
route.append(previous_node.label)
temp = previous_node
previous_node = prev[temp]
route.reverse()
return route
graph = Graph()
states = [
'城北枢纽',
'赞服国际机场',
'出生点',
'漆黑之翼',
'未名阁',
'中央枢纽'
]
node_a = Node('城北枢纽')
graph.add_node(node_a)
node_b = Node('赞服国际机场')
graph.add_node(node_b)
node_c = Node('出生点')
graph.add_node(node_c)
node_d = Node('漆黑之翼')
graph.add_node(node_d)
node_f = Node('未名阁')
graph.add_node(node_f)
node_g = Node('中央枢纽')
graph.add_node(node_g)
paths = [
[node_a, node_b, 466],
[node_b, node_a, 466],
[node_b, node_c, 204],
[node_c, node_b, 204],
[node_c, node_d, 700],
[node_d, node_c, 700],
[node_f, node_c, 810],
[node_c, node_f, 810],
[node_c, node_g, 1277],
[node_g, node_c, 127]
]
for f, t, d in paths:
graph.add_edge(f, t, d)
dist, prev = dijkstra(graph, node_a)
print("从 {} 到 {} 的最短路径是 [{}] ,距离为 {}".format(
node_a.label,
node_g.label,
" -> ".join(to_array(prev, node_g)),
str(dist[node_g])
)
)
|
import unicodedata
def remove_accented_chars(text):
text = unicodedata.normalize('NFKD',text).encode('ascii','ignore')\
.decode('utf-8','ignore')
return text
#The normal form KD (NFKD) will apply the compatibility decomposition, i.e. \
# replace all compatibility characters with their equivalents.
accented_text = 'Sómě Áccěntěd těxt'
non_accent_text = remove_accented_chars(accented_text)
print(non_accent_text) |
def is_isogram(string):
string = string.lower()
ns = "".join(c for c in string if c.isalpha())
return len(ns) == len(set(ns))
|
# Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and
# 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
# Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky digits in it is a lucky number. He wonders whether
# number n is a nearly lucky number.
def nearly_lucky(number):
lucky_count = number.count('4') + number.count('7')
if lucky_count == 4 or lucky_count == 7:
return 'YES'
else:
return 'NO'
print(nearly_lucky(input()))
|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, left, right):
self.val = x
self.left = left
self.right = right
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
print root.val, ": ", self.valid_node(root)
return self.valid_node(root) and self.isValidBST(root.left) and self.isValidBST(root.right)
def valid_node(self, node):
if node == None:
return True
if node.left == None and node.right == None:
return True
elif node.left != None and node.right != None:
return self.get_max(node.left) < node.val < self.get_min(node.right)
elif node.left != None:
return self.get_max(node.left) < node.val
else:
return node.val < self.get_min(node.right)
def get_min(self, root):
"""
assumes root not null
:type root: TreeNode
:rtype: int
"""
if root.left != None:
return self.get_min(root.left)
return root.val
def get_max(self, root):
"""
assumes root not null
:type root: TreeNode
:rtype: int
"""
if root.right != None:
return self.get_max(root.right)
return root.val
# if __name__=="__main__":
# # ls = [10,5,15,None,None,6,20, None, None, None, None]
# # for i in range() |
"""
use Counter
88 ms
"""
from collections import Counter
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
return [pair[0] for pair in Counter(nums).most_common(k)]
if __name__ == '__main__':
s = Solution()
print s.topKFrequent([1, 1, 1, 1, 2, 3, 4, 5, 6, 6, 6], 3) |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
def recurse(nums):
if not nums:
return None
maxn = max(nums)
maxi = nums.index(maxn)
node = TreeNode(maxn)
node.left = recurse(nums[:maxi])
node.right = recurse(nums[maxi+1:])
return node
return recurse(nums)
|
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num):
class Solution(object):
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
i = 1
j = n
mid = i+(j-i)/2
res = guess(mid)
while True:
if res == 0:
return mid
elif res == -1:
j = mid-1
else:
i = mid+1
if i == j:
return i if guess(i) == 0 else 0
mid = i+(j-i)/2
res = guess(mid) |
class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
next_board = [[cell for cell in row] for row in board]
m = len(board)
n = len(board[0])
for i in range(m):
for j in range(n):
cell = board[i][j]
neighbours = self.get_neighbours(board, i, j)
n_live_neighbours = sum([1 for neighbour in neighbours.values() if neighbour==1])
n_dead_neighbours = len(neighbours) - n_live_neighbours
# if live cell
if cell == 1:
if n_live_neighbours < 2 or n_live_neighbours > 3:
# die
next_board[i][j] = 0
if n_live_neighbours == 2 or n_live_neighbours == 3:
# continue to live
next_board[i][j] = 1
# dead cell
else:
if n_live_neighbours == 3:
# come back to life
next_board[i][j] = 1
# update board
for i in range(m):
for j in range(n):
board[i][j] = next_board[i][j]
def get_neighbours(self, board, i, j):
neighbours = {}
m = len(board)
n = len(board[0])
if j > 0:
neighbours['W'] = board[i][j-1]
if j < n-1:
neighbours['E'] = board[i][j+1]
if i > 0:
neighbours['N'] = board[i-1][j]
if i < m-1:
neighbours['S'] = board[i+1][j]
if i > 0 and j > 0:
neighbours['NW'] = board[i-1][j-1]
if i < m-1 and j < n-1:
neighbours['SE'] = board[i+1][j+1]
if i > 0 and j < n-1:
neighbours['NE'] = board[i-1][j+1]
if i < m-1 and j > 0:
neighbours['SW'] = board[i+1][j-1]
return neighbours
if __name__=="__main__":
s = Solution()
s.gameOfLife([[0,0,1,1], [0,1,1,0], [1,0,1,1], [0,0,0,1]])
|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# iterative
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None: return None
if head.next == None: return head
prev = None
curr = head
next = curr.next
while next:
curr.next = prev
prev = curr
curr = next
next = curr.next
curr.next = prev
return curr
def ll_print(ll):
while ll:
print ll.val,
ll = ll.next
print ""
if __name__ == '__main__':
s = Solution()
l1 = ListNode(1)
l1.next = ListNode(2)
l1.next.next = ListNode(3)
l1.next.next.next = ListNode(4)
l1.next.next.next.next = ListNode(5)
l2 = ListNode(1)
l3 = ListNode(1)
l3.next = ListNode(2)
l4 = None
ll_print(l1)
ll_print(s.reverseList(l1))
ll_print(l2)
ll_print(s.reverseList(l2))
ll_print(l3)
ll_print(s.reverseList(l3))
ll_print(l4)
ll_print(s.reverseList(l4)) |
class DoublyLinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def push(self, node):
"""
push to the end of list
"""
if self.tail != None:
self.tail.next = node
node.prev = self.tail
self.tail = node
return
self.tail = node
self.head = node
def pop(self):
"""
pop the front of list
"""
if self.head != None:
ret = self.head
if self.head.next == None:
self.tail = None
self.head = self.head.next
ret.next = None
ret.prev = None
return ret
return None
def kick(self, node):
assert(node != None)
if node.prev == None and node.next == None:
return
if node.next == None:
return
if node.prev == None:
assert(node.next != None)
self.head = node.next
self.head.prev = None
node.prev = self.tail
self.tail.next = node
self.tail = node
node.next = None
return
# print "node.prev: ", node.prev
# print "node.next: ", node.next
# print "tail: ", self.tail
# print "tail.prev: ", self.tail.prev
node.prev.next = node.next
node.next.prev = node.prev
self.tail.next = node
node.prev = self.tail
node.next = None
self.tail = node
# print " ======== "
# print "node.prev: ", node.prev
# print "node.next: ", node.next
# print "tail: ", self.tail
# print "tail.prev: ", self.tail.prev
def print_list(self):
ret = []
curr = self.head
while curr != None:
ret.append(curr.val)
curr = curr.next
print ret
class DoublyLinkedNode(object):
def __init__(self, key, x):
self.val = x
self.key = key
self.prev = None
self.next = None
def __str__(self):
return "<{}>".format(self.val)
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.n = capacity
self.cache = dict()
self.q = DoublyLinkedList()
def get(self, key):
"""
:rtype: int
"""
if key not in self.cache.keys():
return -1
ret = self.cache[key]
# update the linked list so that referenced node is push to the end
self.q.kick(ret)
return ret.val
def set(self, key, value):
"""
:type key: int
:type value: int
:rtype: nothing
"""
assert(self.n >= len(self.cache))
if len(self.cache) == self.n:
# evict
least_recent = self.q.pop()
# print [(item[0], item[0]) for item in self.cache.items()]
# print "pop"
# # self.cache.pop(least_recent.val, None)
# print "del self.cache[{}]".format(least_recent.key)
self.print_cache()
print "======="
self.q.print_list()
print "======="
print "======="
del self.cache[least_recent.key]
# print [(item[0], item[0]) for item in self.cache.items()]
if key in self.cache.keys():
# temp = self.cache[key]
return
node = DoublyLinkedNode(key, value)
self.q.push(node)
self.cache[key] = node
def print_cache(self):
for k, v in self.cache.items():
print "[ {} --> {} ]".format(k, v)
# if __name__=="__main__":
# cache = LRUCache(1)
# 1,[set(2,1),get(2),set(3,2),get(2),get(3)]
# cache.set(2, 1)
# cache.get(2)
# cache.set(3, 2)
# cache.get(2)
# cache.get(3)
# cache.print_cache()
# print cache.get(1)
# # for i in range(15):
# # cache.set(i, i)
# cache.print_cache()
# cache = LRUCache(10)
# ret = [cache.set(10,13),cache.set(3,17),cache.set(6,11),cache.set(10,5),cache.set(9,10),cache.get(13),cache.set(2,19),
# cache.get(2),cache.get(3),cache.set(5,25),cache.get(8),cache.set(9,22),cache.set(5,5),cache.set(1,30),cache.get(11),
# cache.set(9,12),cache.get(7),cache.get(5),cache.get(8),cache.get(9),cache.set(4,30),cache.set(9,3),cache.get(9),cache.get(10),
# cache.get(10),cache.set(6,14),cache.set(3,1),cache.get(3),cache.set(10,11),cache.get(8),cache.set(2,14),cache.get(1),
# cache.get(5),cache.get(4),cache.set(11,4),cache.set(12,24),cache.set(5,18),cache.get(13),cache.set(7,23),cache.get(8),
# cache.get(12),cache.set(3,27),cache.set(2,12),cache.get(5),cache.set(2,9),cache.set(13,4),cache.set(8,18),cache.set(1,7),
# get(6),set(9,29),set(8,21),get(5),set(6,30),set(1,12),get(10),set(4,15),
# set(7,22),set(11,26),set(8,17),set(9,29),get(5),set(3,4),set(11,30),
# get(12),set(4,29),get(3),get(9),get(6),set(3,4),get(1),get(10),
# set(3,29),set(10,28),set(1,20),set(11,13),get(3),set(3,12),set(3,8),
# set(10,9),set(3,26),get(8),get(7),get(5),set(13,17),set(2,27),set(11,15),
# get(12),set(9,19),set(2,15),set(3,16),get(1),set(12,17),set(9,1),
# set(6,19),get(4),get(5),get(5),set(8,1),set(11,7),set(5,2),set(9,28),
# get(1),set(2,2),set(7,4),set(4,22),set(7,24),set(9,26),set(13,28),set(11,26)]
# dll = DoublyLinkedList()
# dll.
# [ 1 --> <30> ]
# [ 2 --> <19> ]
# [ 3 --> <17> ]
# [ 4 --> <30> ]
# [ 5 --> <25> ]
# [ 6 --> <11> ]x
# [ 9 --> <10> ]
# [ 10 --> <13> ]
# [ 11 --> <4> ]
# [ 12 --> <24> ]
# =======
# [ 1 --> <30> ]
# [ 2 --> <19> ]x
# [ 3 --> <17> ]
# [ 4 --> <30> ]
# [ 5 --> <25> ]
# [ 7 --> <23> ]
# [ 9 --> <10> ]
# [ 10 --> <13> ]
# [ 11 --> <4> ]
# [ 12 --> <24> ]
# =======
# [ 1 --> <30> ]
# [ 3 --> <17> ]
# [ 4 --> <30> ]
# [ 5 --> <25> ]
# [ 7 --> <23> ]
# [ 9 --> <10> ]
# [ 10 --> <13> ]
# [ 11 --> <4> ]
# [ 12 --> <24> ]
# [ 13 --> <4> ]
# =======
# [ 1 --> <30> ]
# [ 3 --> <17> ]
# [ 4 --> <30> ]
# [ 5 --> <25> ]
# [ 7 --> <23> ]
# [ 8 --> <18> ]
# [ 10 --> <13> ]
# [ 11 --> <4> ]
# [ 12 --> <24> ]
# [ 13 --> <4> ]
# ======= |
'''
Brute Force + Memoize
Time: O(n)
Space: O(n)
'''
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
self.d = dict()
return self.climb(0, n)
def climb(self, i, n):
if i in self.d:
return self.d[i]
if i > n:
return 0
if i == n:
return 1
self.d[i] = self.climb(i + 1, n) + self.climb(i + 2, n)
return self.d[i]
|
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __str__(self):
return "N({})".format(self.val)
def traverse_inorder(self):
if self == None:
return
traverse_inorder(self.left)
print self.val
traverse_inorder(self.right)
def addNode(root, treenode):
if root == None:
root = treenode
return
if treenode.val <= root.val:
addNode(root.left, treenode)
else:
addNode(root.right, treenode) |
class Vector2D(object):
def __init__(self, vec2d):
"""
Initialize your data structure here.
:type vec2d: List[List[int]]
"""
# self.size = sum([sum([1 for x in row]) for row in vec2d])
assert(len(vec2d) != 0)
self.m = vec2d
self.i = 0
self.j = 0
def next(self):
"""
:rtype: int
"""
if self.j >= len(self.m[self.i])-1:
self.j = 0
self.i += 1
else:
self.j += 1
i = self.i
j = self.j
# print (i, j),
return self.m[i][j]
def hasNext(self):
"""
:rtype: bool
"""
i = self.i
j = self.j
# last row, last column
if i >= len(self.m)-1 and j >= len(self.m[i])-1:
return False
if j >= len(self.m[i])-1:
k = i
while k < len(self.m):
if self.m[k] != []:
return True
k += 1
self.i = k
return False
return True
def flatten(self, m):
return [x for x in row for row in m]
# Your Vector2D object will be instantiated and called as such:
# i, v = Vector2D(vec2d), []
# while i.hasNext(): v.append(i.next())
if __name__=="__main__":
m = [[y*10+x for x in range(10)] for y in range(10)]
m = [[1, 2, 3], []]
v = Vector2D(m)
print v.m
# print v.size
while v.hasNext():
e = v.next()
print e, |
# Definition for a binary tree node.
class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def __init__(self, x, left, right):
self.val = x
self.left = left
self.right = right
def __str__(self):
return "N({})".format(self.val)
class Stack(object):
def __init__(self):
self.ls = []
def push(self, x):
self.ls.append(x)
def pop(self):
return self.ls.pop()
def empty(self):
return len(self.ls) == 0
def peek(self):
return self.ls[len(self.ls) - 1]
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = Stack()
if root == None:
return
curr = root
self.stack.push(curr)
self.root = root
print "init: ", [n.val for n in self.stack.ls]
# push to stack all the way to bottom left
self.push_alltheway_left(curr)
def hasNext(self):
"""
:rtype: bool
"""
return not self.stack.empty()
def next(self):
"""
:rtype: int
"""
if not self.hasNext():
return None
ret = self.stack.pop()
curr = ret
if curr.right == None:
pass
else:
curr = curr.right
self.stack.push(curr)
self.push_alltheway_left(curr)
return ret.val
def push_alltheway_left(self, curr):
while curr.left != None:
self.stack.push(curr.left)
curr = curr.left
class Solution(object):
def inorderSuccessor(self, root, p):
"""
:type root: TreeNode
:type p: TreeNode
:rtype: TreeNode
"""
if root == None:
return None
it = BSTIterator(root)
while it.hasNext():
curr = it.next()
if curr == p.val:
return it.next()
# if __name__=="__main__":
# s = Solution()
# |
from heapq import heapify, heappop
class Task:
def __init__(self, s, e, order):
self.s = int(s)
self.e = int(e)
self.order = order
self.assignee = None
def __lt__(self, other):
if self.s != other.s:
return self.s < other.s
return self.e < other.e
def __str__(self):
line = ''
for i in range(0, self.e, 1):
if i < self.s:
line += '_'
else:
line += '*'
return line
def __repr__(self):
return '(s={}, e={}, order={})'.format(self.s, self.e, self.order)
def solve(tasks):
tasks = [Task(t[0], t[1], i) for i, t in enumerate(tasks)]
heap = [t for t in tasks]
heapify(heap)
#print(tasks)
t = heappop(heap)
maxendc = max(t.e, 0)
maxendj = 0
#print(t)
t.assignee = 'C'
i = 0
while heap:
t = heappop(heap)
#print(t)
#print('t.s={}, maxendc={}, maxendj={}'.format(t.s, maxendc, maxendj))
if t.s >= maxendc:
t.assignee = 'C'
elif t.s >= maxendj:
t.assignee = 'J'
else:
return 'IMPOSSIBLE'
if t.assignee == 'J':
maxendj = max(maxendj, t.e)
else:
maxendc = max(maxendc, t.e)
i += 1
tasks.sort(key=lambda t: t.order)
result = [t.assignee for t in tasks]
return ''.join(result)
if __name__ == '__main__':
T = int(input())
for t in range(1, T+1):
N = int(input())
tasks = []
for n in range(N):
s, e = input().split(' ')
tasks.append((s, e,))
print('Case #{}: {}'.format(t, solve(tasks)))
|
# -*- coding: utf-8 -*-
from com.salesianostriana.sge.cifrado_cesar.utiles_cifrado import *
opcion = -1
texto = ""
while(opcion != 0):
opcion = int(input("\nOPCIONES"
"\n--------"
"\n1. Encriptar texto"
"\n2. Desencriptar texto"
"\n0. Salir"
"\n\nElige opcion: "))
if opcion == 1:
texto = input("Escribe el texto: ")
llave = int(input("Introduce la llave (1-26): "))
texto = encriptar(llave,texto)
print("Resultado: ",texto)
elif opcion == 2:
llave = int(input("Introduce la llave (1-26): "))
texto = desencriptar(llave,texto)
print("Resultado: ",texto)
|
import Weapon
from Weapon import weapon_list
class Character:
#создает игрока и дает ему базовые функции
def __init__(self):
self.health = 100
self.armor = 0
self.money = 6000
self.height = 1
self.speed = 2
self.noise = 1
self.ammunition = 0
def moving(self):
# иммитирует перемещение игрока по карте
if self.height == 0.5:
print('Присел и крадусь к противнику')
elif self.noise == 0:
print('Kрадусь')
else:
print('Бегу')
def sit(self):
# меняет положение игрока на положение сидя
self.height = 0.5
self.speed = 1
self.noise = 0
print('так меня не видно из-за укрытия')
def stand(self):
# меняет положение игрока на положение стандартное
self.height = 1
self.speed = 2
self.noise = 1
print('ничто меня не остановит ')
def sneak(self):
# делает перемещение бесшумным
self.speed = 1
self.noise = 0
print('надеюсь, меня не заметят')
def buy_weapon(self):
# выбирает оружие из списка доступных и вооружается им
print('Выберите оружие')
for item in weapon_list:
print(f'{item.name} стоит {item.cost}')
choice = input('введите название оружия\n')
for item in weapon_list:
if choice == item.name:
self.money -= item.cost
self.ammunition = item
print('Осталось', self.money)
def shooting(self, aim):
# иммитация стрельбы
# aim - указывает на игрока, по которому будет произведен выстрел
if self.ammunition == 0:
print('надо купить оружие')
else:
self.ammunition.shot()
aim.health -= self.ammunition.damage
def reloading(self):
self.ammunition.reload()
class SWAT(Character):
# один из типов игроков, может обезвреживать бомбы
def __init__(self):
super().__init__()
self.defuse_ability = 0
print('Я - солдат, я не спал пять лет...\n')
def defuse(self):
#иммитация обезвреживания бомы
if self.defuse_ability == 0:
print('обезвреживаю бомбу, справлюсь за 10 сек')
else:
print('обезвреживаю бомбу, справлюсь за 5 сек')
class Terrorist(Character):
# один из типов игроков, может обезвреживать бомбы
def __init__(self):
super().__init__()
print('Бомбим,чувачки\n')
def plant_bomb(self):
print('Бомба установлена')
|
#要求三:演算法 找出至少包含兩筆整數的列表 (Python) 或陣列 (JavaScript) 中,兩兩數字相乘後的最大值。
#由大到小排序,找出最大值跟第二大值的數,再讓它們相乘。
def maxProduct(nums):
re_nums = sorted(nums, reverse = True)
result = re_nums[0] * re_nums[1]
print("兩兩相乘的最大值為: ", result)
# 請用你的程式補完這個函式的區塊
maxProduct([5, 20, 2, 6]) # 得到 120 因為 20 和 6 相乘得到最大值
maxProduct([10, -20, 0, 3]) # 得到 30 因為 10 和 3 相乘得到最大值 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 1 13:31:44 2019
@author: ashutosh.k
{ 25 Projects } Fashion MNIST
Fashion MNIST Classification using Keras
"""
from __future__ import print_function
import keras
from keras.datasets import fashion_mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
## Data Import
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
## Check shapes and vizualize
print("X_train Shape",x_train.shape)
print("Y_train Shape",y_train.shape)
print("X_test Shape",x_test.shape)
print("Y_test Shape",y_test.shape)
## 60000 train images, 28x28 image size
set(y_train)
# 10 Classes
#Model Parameters
BATCH_SIZE = 128
NUM_CLASSES = 10
EPOCHS = 12
### SIMPLE NEURAL NETWORK - No Convolution ####
#Reshape input images
# Train: 60000x784 ; Test: 10000x784
x_train_ = x_train.reshape(x_train.shape[0],784)
x_test_ = x_test.reshape(x_test.shape[0],784)
## Convert to float and normalize
x_train_ = x_train_.astype('float32')
x_test_ = x_test_.astype('float32')
## Normalize
x_train_ /= 255
x_test_ /= 255
x_train_.shape
## Convert class vectors to binary one hot encoded
y_train_ = keras.utils.to_categorical(y_train, NUM_CLASSES)
y_test_ = keras.utils.to_categorical(y_test, NUM_CLASSES)
### Build Model
model = Sequential()
model.add(Dense(512, activation = 'relu', input_shape = (784,)))
model.add(Dropout(0.2))
model.add(Dense(512, activation = 'relu'))
model.add(Dropout(0.2))
model.add(Dense(NUM_CLASSES, activation = 'softmax'))
#print Model Summary
model.summary()
#Compile Model
model.compile(loss= 'categorical_crossentropy', optimizer = 'rmsprop', metrics = ['accuracy'])
## Run Model and save metrices after each epoch in history
history = model.fit(x_train_, y_train_, batch_size = BATCH_SIZE, epochs = EPOCHS,
verbose =1, validation_data = (x_test_, y_test_))
#Score Model against test data
score = model.evaluate(x_test_, y_test_, verbose=1)
print('Test loss:', score[0])
print('Test accuracy:', score[1]) #88.67
## Plot Accuracy and Loss stored in the 'history'
import matplotlib.pyplot as plt
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
############# Convolution Neural Network
#input image dimensions : 28x28 images (predefined)
img_rows, img_cols = 28,28
#Datasets: x_train, x_test, y_train, y_test
## Reshape Data - Channels Check
# X_train.shape = (60000,28,28) - to be converted to (60000,28,28,1)
# Check the format: channel first or last
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0],1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0],1, img_rows, img_cols)
input_shape = (1,img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols,1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols,1)
input_shape = (img_rows, img_cols,1)
## Normalize the inputs and convert to float
x_train = x_train.astype('float64')
x_test = x_test.astype('float64')
x_train/=255
x_test/=255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
## Convert class vectors to binary class metrics
y_train = keras.utils.to_categorical(y_train,NUM_CLASSES)
y_test = keras.utils.to_categorical(y_test,NUM_CLASSES)
### CNN Model
model = Sequential()
model.add(Conv2D(32, kernel_size=(3,3), activation='relu', input_shape = input_shape))
model.add(Conv2D(64, kernel_size = (3,3), activation = 'relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation = 'relu'))
model.add(Dropout(0.2))
model.add(Dense(NUM_CLASSES, activation = 'softmax'))
model.summary()
#Compile model
model.compile(loss = keras.losses.categorical_crossentropy, optimizer = keras.optimizers.adam(),
metrics = ['accuracy'])
#Fit Model
history = model.fit(x_train,y_train, batch_size=BATCH_SIZE, epochs = 7,
verbose=1, validation_data = (x_test, y_test))
#Score Model
score = model.evaluate(x_test, y_test, verbose=0)
print("Test Loss:", score[0])
print("Test Accuracy", score[1])
#Test Accuracy 0.9266 after 12 epochs
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
|
with open("newfile.txt") as f:
print(f.read())
"""
file = open("newfile.txt","r")
print(file.read())
file.close()
"""
"""
An alternative way of doing this is using with statements.
This creates a temporary variable (often called f),
which is only accessible in the indented block of the with statement.
with open("filename.txt") as f:
print(f.read())
The file is automatically
closed at the end of the with statement, even if exceptions occur within it.""" |
from typing import Iterable, List, Any
__all__ = ['Language']
class Language(object):
"""
Represents a programming language that is supported by boggart.
"""
@staticmethod
def from_dict(d: dict) -> 'Language':
assert 'name' in d
assert 'file-endings' in d
assert isinstance(d['name'], str)
assert isinstance(d['file-endings'], list)
assert all(isinstance(e, str) for e in d['file-endings'])
name = d['name']
file_endings = d['file-endings']
return Language(name, file_endings)
def __init__(self,
name: str,
file_endings: List[str]
) -> None:
self.__name = name
self.__file_endings = frozenset(file_endings)
def __eq__(self, other: Any) -> bool:
return isinstance(other, Language) and \
self.name == other.name and \
list(self.file_endings) == list(other.file_endings)
def __repr__(self) -> str:
return "Language({self.name})".format(self=self)
@property
def name(self) -> str:
"""
The name of the language.
"""
return self.__name
@property
def file_endings(self) -> Iterable[str]:
"""
A list of known file endings used by this language. These are used to
automatically detect the language used by a given file when language
information is not explicitly provided.
"""
return self.__file_endings.__iter__()
def to_dict(self) -> dict:
"""
Provides a dictionary-based description of this language, ready to be
serialized.
"""
return {
'name': self.name,
'file-endings': list(self.file_endings)
}
|
import math
class Matrix:
def __init__(self, matrix, name):
self.name = name
self.setmatrix(matrix)
self.len = [len(self.matrix), len(self.matrix)]
def copy(self):
matrix = []
for row in self.matrix:
r = []
for item in row:
r.append(item)
pass
matrix.append(r)
return Matrix(matrix, self.name + " copy")
def setmatrix(self, matrix):
self.matrix = []
for row in matrix:
r = []
for item in row:
r.append(item)
pass
self.matrix.append(r)
def showmatrixold(self):
print('')
sh = self.copy()
print(self.name)
for row in self.matrix:
print(row)
print('')
def showmatrix(self):
print('')
#sh = self.copy()
matrix = self.matrix
print(self.name)
#for row in self.matrix:
#print(row)
s = [[str(e) for e in row] for row in matrix]
lens = [max(map(len, col)) for col in zip(*s)]
fmt = '\t'.join('{{:{}}}'.format(x) for x in lens)
table = [fmt.format(*row) for row in s]
print('\n'.join(table))
print('')
def showmatrixaccuracy3(self):
print('')
#sh = self.copy()
accuracy = 3
matrix = self.matrix
print(self.name)
#for row in self.matrix:
#print(row)
s = [[str(round(e, accuracy)) for e in row] for row in matrix]
lens = [max(map(len, col)) for col in zip(*s)]
fmt = '\t'.join('{{:{}}}'.format(x) for x in lens)
table = [fmt.format(*row) for row in s]
print('\n'.join(table))
print('')
def showmatrixaccuracy(self, accuracy):
print('')
#sh = self.copy()
matrix = self.matrix
print(self.name)
#for row in self.matrix:
#print(row)
s = [[str(round(e, accuracy)) for e in row] for row in matrix]
lens = [max(map(len, col)) for col in zip(*s)]
fmt = '\t'.join('{{:{}}}'.format(x) for x in lens)
table = [fmt.format(*row) for row in s]
print('\n'.join(table))
print('')
def appendrow(self, rowlen):
self.matrix.append([0 for i in range(0, rowlen)])
self.len[0] = len(self.matrix)
self.len[1] = len(self.matrix[-1])
def appenderow(self):
self.matrix.append([])
self.len[0] = len(self.matrix)
self.len[1] = len(self.matrix[-1])
def appendnrow(self, row):
array = [item for item in row]
self.matrix.append(array)
self.len[0] = len(self.matrix)
self.len[1] = len(self.matrix[-1])
def append_column(self, column):
array = [item for item in column]
if self.len[0] < len(array):
while self.len[0] < len(array):
self.matrix.append([None])
self.len[0] = len(self.matrix)
for i in range(self.len[0]):
self.matrix[i].append(array[i])
self.len[0] = len(self.matrix)
self.len[1] = len(self.matrix[-1])
def chel(self, i, j, item):
if (i >= 0 and j >= 0):
if (i < self.len[0] and j < self.len[1]):
self.matrix[i][j] = item
else:
print("change el: List assignment index out of range!")
elif (i < 0 and j < 0):
if (i >= -self.len[0] and j >= -self.len[1]):
self.matrix[i][j] = item
else:
print("change el: List assignment index out of range!")
else:
print("change el: List assignment index out of range! (sign)")
def getel(self, i, j):
if (i >= 0 and j >= 0):
if (i < self.len[0] and j < self.len[1]):
return self.matrix[i][j]
else:
print("get el: List assignment index out of range!")
elif (i < 0 and j < 0):
if (i >= -self.len[0] and j >= -self.len[1]):
return self.matrix[i][j]
else:
print("get el: List assignment index out of range!")
else:
print("get el: List assignment index out of range! (sign)")
def appendel(self, i, item):
if (i >= 0):
if (i < self.len[0]):
self.matrix[i].append(item)
else:
print("append el: List assignment index out of range!")
elif (i < 0):
if (i >= -self.len[0]):
self.matrix[i].append(item)
else:
print("append el: List assignment index out of range!")
else:
print("append el: List assignment index out of range! (sign)")
def delel(self,i,j):
if (i >= 0 and j >= 0):
if (i < self.len[0] and j < len(self.matrix[i])):
return self.matrix[i].pop(j)
else:
print("del el: List assignment index out of range!")
elif (i < 0 and j < 0):
if (i >= -self.len[0] and j >= -len(self.matrix[i])):
return self.matrix[i].pop(j + len(self.matrix[i]))
else:
print("del el: List assignment index out of range!")
else:
print("del el: List assignment index out of range! (sign)")
def delrow(self,i):
if (i >= 0):
if (i < self.len[0]):
row = self.matrix.pop(i)
self.len[0] = len(self.matrix)
return row
else:
print("del row: List assignment index out of range!")
elif (i < 0):
if (i >= -self.len[0]):
row = self.matrix.pop(i + self.len[0])
self.len[0] = len(self.matrix)
return row
else:
print("del row: List assignment index out of range!")
else:
print("del row: List assignment index out of range! (sign)")
def getrow(self,i):
if (i >= 0):
if (i < self.len[0]):
row = Vector(self.matrix[i],"Row" + str(i) + "of " + self.name)
return row
else:
print("get row: List assignment index out of range!")
elif (i < 0):
if (i >= -self.len[0]):
row = Vector(self.matrix[i + self.len[0]], "Row" + str(i + self.len[0]) + "of " + self.name)
return row
else:
print("get row: List assignment index out of range!")
else:
print("get row: List assignment index out of range! (sign)")
def setrowm(self, i, row):
if (i >= 0 and row.len == self.len[1]):
if (i < self.len[0]):
for j in range(0, self.len[1]):
self.matrix[i][j] = row.vector[j]
else:
print("set row: List assignment index out of range!")
elif (i < 0 and row.len == self.len[1]):
if (i >= -self.len[0]):
for j in range(0, self.len[1]):
self.matrix[i + self.len[0]][j] = row.vector[j]
else:
print("set row: List assignment index out of range!")
else:
print("set row: List assignment index out of range! (sign)")
def rowmnumber(self, i, num, accuracy):
if (i >= 0):
if (i < self.len[0]):
j = 0
while j < self.len[1]:
self.matrix[i][j] = round(self.matrix[i][j] * num, accuracy)
j += 1
else:
print("rowmnumber: List assignment index out of range!")
elif (i < 0):
if (i >= -self.len[0]):
j = 0
while j < self.len[1]:
self.matrix[i + self.len[0]][j] = round(self.matrix[i + self.len[0]][j] * num, accuracy)
j += 1
else:
print("rowmnumber: List assignment index out of range!")
else:
print("rowmnumber: List assignment index out of range! (sign)")
def matrixmnum(self, num, accuracy):
i = 0
while i < self.len[0]:
self.rowmnumber(i, num, accuracy)
i += 1
def rowdnumber(self, i, num, accuracy):
if (i >= 0):
if (i < self.len[0]):
j = 0
while j < self.len[1]:
self.matrix[i][j] = round(self.matrix[i][j] / num, accuracy)
j +=1
else:
print("rowdnumber: List assignment index out of range!")
elif (i < 0):
if (i >= -self.len[0]):
j = 0
while j < self.len[1]:
self.matrix[i + self.len[0]][j] = round(self.matrix[i + self.len[0]][j] / num, accuracy)
j += 1
else:
print("rowdnumber: List assignment index out of range!")
else:
print("rowdnumber: List assignment index out of range! (sign)")
def rowsubtract(self, i, i2, accuracy):
if (i >= 0 and i2 >=0):
if (i < self.len[0] and i2 < self.len[0]):
for j in range(0, self.len[1]):
self.matrix[i][j] = round(self.matrix[i][j] - self.matrix[i2][j], accuracy)
else:
print("rowsubtract: List assignment index out of range!")
elif (i < 0 and i2 < 0):
if (i >= -self.len[0] and i2 >= -self.len[0]):
for j in range(0, self.len[1]):
self.matrix[i + self.len[0]][j] = round(self.matrix[i + self.len[0]][j] - self.matrix[i2 + self.len[0]][j], accuracy)
else:
print("rowsubtract: List assignment index out of range!")
else:
print("rowsubtract: List assignment index out of range! (sign)")
pass
def rowsummarize(self, i, i2, accuracy):
if (i >= 0 and i2 >= 0):
if (i < self.len[0] and i2 < self.len[0]):
j = 0
while j < self.len[1]:
self.matrix[i][j] = round(self.matrix[i][j] + self.matrix[i2][j], accuracy)
j += 1
else:
print("rowsubtract: List assignment index out of range!")
elif (i < 0 and i2 < 0):
if (i >= -self.len[0] and i2 >= -self.len[0]):
j = 0
while j < self.len[1]:
self.matrix[i + self.len[0]][j] = round(
self.matrix[i + self.len[0]][j] + self.matrix[i2 + self.len[0]][j], accuracy)
j += 1
else:
print("rowsubtract: List assignment index out of range!")
else:
print("rowsubtract: List assignment index out of range! (sign)")
pass
def makezeromatrix(self, dim):
if (dim > 0):
self.matrix = [[0 for i in range(0, dim)] for i in range(0, dim)]
self.len[0] = len(self.matrix)
self.len[1] = len(self.matrix[0])
else:
print("Make zero-matrix: dim is < 0")
def makedimatrix(self, dim):
if (dim > 0):
self.makezeromatrix(dim)
for i in range(0, dim):
self.matrix[i][i] = 1
self.len[0] = len(self.matrix)
self.len[1] = len(self.matrix[0])
else:
print("Make dimatrix: dim is < 0")
def makedimatrix_f(self, dim):
if (dim > 0):
self.makezeromatrix(dim)
for i in range(0, dim):
self.matrix[i][i] = 1.0
self.len[0] = len(self.matrix)
self.len[1] = len(self.matrix[0])
else:
print("Make dimatrix: dim is < 0")
def makedimatrix_f_ex(self, dim, d_num):
if (dim > 0):
self.makezeromatrix(dim)
for i in range(0, dim):
self.matrix[i][i] = float(d_num)
self.len[0] = len(self.matrix)
self.len[1] = len(self.matrix[0])
else:
print("Make dimatrix: dim is < 0")
def join(self, jm):
for i in range(0, self.len[0]):
for j in range(0, jm.len[1]):
self.appendel(i, jm.getel(i, j))
self.len[0] = len(self.matrix)
self.len[1] = len(self.matrix[0])
def copypart(self, param):
# param = [i,j,sizei,sizej]
result = []
for i in range(param[0], param[2]):
result.append([])
for j in range(param[1], param[3]):
result[-1].append(self.getel(i, j))
return Matrix(result, "part copy")
def reverseim(self):
self.matrix = self.matrix[::-1]
def rename(self, name):
self.name = name
def zerodown(self):
for i in range(0,self.len[0]):
pass
self.matrix.append(self.matrix.pop(0))
def transpose(self):
if (self.len[0] == self.len[1]):
for i in range(0, self.len[0]):
for j in range(i, self.len[1]):
a = self.matrix[i][j]
self.matrix[i][j] = self.matrix[j][i]
self.matrix[j][i] = a
elif (self.len[0] >= self.len[1]):
for i in range(0, self.len[0]):
if (i == self.len[1]):
pass
for j in range(0, self.len[1]):
a = self.matrix[i][j]
self.matrix[i][j] = self.matrix[j][i]
self.matrix[j][i] = a
pass
def matrixm(self, B, accuracy):
if (self.len[1] == B.len[0]):
R = Matrix([], "Result")
n = 0
while n < self.len[0]:
R.appendrow(B.len[1])
m = 0
while m < B.len[1]:
i = 0
while i < self.len[1]:
sum = R.matrix[n][m]
R.matrix[n][m] += round(self.matrix[n][i] * B.matrix[i][m], accuracy)
#print("C[",n,m,"]+=","A[",n,i,"]*","B[",i,m,"]")
#print(R.matrix[n][m]," is sum of ", sum,"+", self.matrix[n][i],"*", B.matrix[i][m], " n: ", n," i: ", i, " i: ", i," m: ", m)
#R.showmatrix()
#print("Row [",n,"] is done")
i += 1
m += 1
n += 1
return R
else:
print("Matrixm: error j != m")
return 0
def matrixmv(self, V, accuracy):
if self.len[0] == V.len:
R = Vector([], "Result")
R.makezero(self.len[0])
i = 0
while i < self.len[0]:
j = 0
while j < V.len:
R.vector[i] += round(self.matrix[i][j] * V.vector[j], accuracy)
j += 1
i += 1
return R
else:
print("Matrixmv: error j != m")
return 0
def matrixsubtract(self, B, accuracy):
if self.len[0] == B.len[0] and self.len[1] == B.len[1]:
R = self.copy()
R.rename("Result")
i = 0
while i < self.len[0]:
j = 0
while j < B.len[1]:
#R.matrix[i][j] -= B.matrix[i][j]
R.matrix[i][j] = round(R.matrix[i][j] - B.matrix[i][j], accuracy)
#round(R.matrix[i][j], accuracy)
j += 1
i += 1
return R
else:
print("Matrix subtract: error j != m")
return 0
def matrixsum(self, B, accuracy):
if (self.len[0] == B.len[0] and self.len[1] == B.len[1]):
R = self.copy()
R.rename("Result")
i = 0
while i < self.len[0]:
j = 0
while j < B.len[1]:
#R.matrix[i][j] += B.matrix[i][j]
R.matrix[i][j] = round(R.matrix[i][j] + B.matrix[i][j], accuracy)
#round(R.matrix[i][j], accuracy)
j += 1
i += 1
return R
else:
print("Matrix subtract: error j != m")
return 0
def getcol(self,j):
r = Vector([],"Column #" + str(j + 1) + "of " + self.name)
i = 0
while i < self.len[0]:
r.appendel(self.getel(i, j))
i += 1
return r
def getminor2(self, i, j, vh_r):
minor = 0
if vh_r != None:
c = [i, j, i + 1 + vh_r[0], j + 1 + vh_r[1], i, j + 1 + vh_r[1], i + 1 + vh_r[0], j]
else:
c = [i, j, i + 1, j + 1, i, j + 1, i + 1, j]
minor = self.getel(c[0], c[0]) * self.getel(c[1], c[1]) - (self.getel(c[0], c[1]) * self.getel(c[1], c[0]))
return minor
def inverse_dim_2(self):
inverse_matrix = self.copy()
inverse_matrix.rename(self.name + " inverted")
minor_matrix = [[self.matrix[1][1], self.matrix[1][0]], [self.matrix[0][1], self.matrix[0][0]]]
al_matrix = [[minor_matrix[0][0], -minor_matrix[0][1]],[-minor_matrix[1][0], minor_matrix[1][1]]]
inverse_matrix.matrix = al_matrix
inverse_matrix.transpose()
det_a = self.matrix[0][0] * self.matrix[1][1] - self.matrix[0][1] * self.matrix[1][0]
print(det_a)
#for item in al_matrix:
# for el in item:
# try:
# print("Before ", el)
# el /= det_a
# print("After ", el)
# except ZeroDivisionError:
# el /= float('Inf')
i = 0
j = 0
while i < len(al_matrix):
j = 0
while j < len(al_matrix):
try:
#print("Before ", al_matrix[i][j])
al_matrix[i][j] /= det_a
#print("After ", al_matrix[i][j])
except ZeroDivisionError:
al_matrix[i][j] /= float('Inf')
j += 1
i += 1
#print("Result ", al_matrix)
inverse_matrix.matrix = al_matrix
return inverse_matrix
def get_characteristic_polynomial_dim_2(self):
#x**2 - TR(A)*t + DET(A) = 0
result = [0.0, 0.0]
trace = self.matrix[0][0] + self.matrix[1][1]
det_a = self.matrix[0][0] * self.matrix[1][1] - self.matrix[0][1] * self.matrix[1][0]
d = math.sqrt(math.pow(trace, 2.0) - 4.0 * float(det_a))
result[0] = 0.5 * (trace + d)
result[1] = 0.5 * (trace - d)
return result
class Vector:
def __init__(self, vector, name):
self.name = name
self.setvector(vector)
self.len = len(self.vector)
def rename(self, name):
self.name = name
def setvector(self, vector):
self.vector = []
i = 0
while i < len(vector):
self.vector.append(vector[i])
i += 1
self.len = len(self.vector)
def makezero(self,size):
self.vector = []
i = 0
while i < size:
self.vector.append(0)
i += 1
self.len = len(self.vector)
def makezero_f(self, size):
self.vector = []
i = 0
while i < size:
self.vector.append(0.0)
i += 1
self.len = len(self.vector)
def makeivector(self, size):
self.vector = []
i = 0
while i < size:
self.vector.append(1)
i += 1
self.len = len(self.vector)
def makeivector_f(self, size):
self.vector = []
i = 0
while i < size:
self.vector.append(1.0)
i += 1
self.len = len(self.vector)
def copy(self):
return Vector(self.vector, self.name + " copy")
def reverse(self):
self.vector = self.vector[::-1]
def getel(self, i):
if (i >= 0):
if (i < self.len):
return self.vector[i]
else:
print("get el: List assignment index out of range!")
elif (i < 0):
if (i >= -self.len):
return self.vector[i]
else:
print("get el: List assignment index out of range!")
else:
print("get el: List assignment index out of range! (sign)")
def chel(self, i, item):
if (i >= 0):
if (i < self.len):
self.vector[i] = item
else:
print("change el: List assignment index out of range!")
elif (i < 0):
if (i >= -self.len):
self.vector[i] = item
else:
print("change el: List assignment index out of range!")
else:
print("change el: List assignment index out of range! (sign)")
def appendel(self, item):
self.vector.append(item)
self.len = len(self.vector)
def showvector(self):
print('')
# sh = self.copy()
vector = self.vector
print(self.name)
# for row in self.matrix:
# print(row)
#s = [[str(e) for e in row] for row in vector]
s = [str(row) for row in vector]
print('\n'.join(s))
print('')
def rowsubtract(self, B, accuracy):
if (self.len == B.len):
R = self.copy()
R.rename("Result")
for i in range(0, B.len):
#R.vector[i] -= B.vector[i]
R.vector[i] = round(R.vector[i] - B.vector[i], accuracy)
#round(R.vector[i], accuracy)
return R
else:
print("Row subtract: error i != n")
return False
def rowsummarize(self, B, accuracy):
if (self.len == B.len):
R = self.copy()
R.rename("Result")
for i in range(0, B.len):
#R.vector[i] += B.vector[i]
R.vector[i] = round(R.vector[i] + B.vector[i], accuracy)
#round(R.vector[i], accuracy)
return R
else:
print("Row subtract: error i != n")
return False
def compare(self, B, accuracy):
c = True
if (self.len == B.len):
for i in range(0, self.len):
if (math.fabs(round(self.vector[i], accuracy) - round(B.vector[i], accuracy)) >= round(1 / (10**accuracy), accuracy)):
c = False
break
return c
else:
print("Row subtract: error i != n")
return False
def mnumber(self, num, accuracy):
for i in range(0, self.len):
self.vector[i] = round(self.vector[i] * num, accuracy)
# horizontal vector by vertical vector
def hvm(self, v, accuracy):
i = 0
summ = 0
while i < self.len:
summ += round(self.vector[i] * v.vector[i], accuracy)
i += 1
return summ
def vhm(self, v, accuracy):
if self.len == v.len:
R = Matrix([], "Result")
n = 0
while n < self.len:
R.appendrow(v.len)
m = 0
while m < v.len:
R.matrix[n][m] += round(self.vector[n] * v.vector[m], accuracy)
m += 1
n += 1
return R
else:
print("vhm: error j != m")
return 0
def dnumber(self, num, accuracy):
for i in range(0, self.len):
self.vector[i] = round(self.vector[i] / num, accuracy)
def tomatrix(self, accuracy):
m = Matrix([], self.name)
for i in range(0, self.len):
m.matrix.append([round(self.vector[i], accuracy)])
m.len[0] = len(m.matrix)
m.len[1] = 1
return m |
#!/usr/bin/env python
# coding: utf-8
# The excel file used is found at:
# http://college.cengage.com/mathematics/brase/understandable_statistics/7e/students/datasets/tvds/frames/frame.html
#
# According to the website description, a random sample of male/female assitant professor pairs was taken from 22 U.S. universities. The file shows yearly income divided by 1000.
#
# ***USING A T Test, let's see what the average male and female assistant professor salaries are in the U.S. with 95% confidence***
# In[50]:
import pandas as pd
from scipy.stats import t
import numpy as np
import statistics
data = pd.read_excel('./SalaryTest.xls')
# In[51]:
data.head(), data.shape, data.isnull().sum()
# In[52]:
#SAMPLE MEAN FOR EACH MALES AND FEMALES
mean_males = statistics.mean(data['MALES'])
mean_females = statistics.mean(data['FEMALES'])
mean_males, mean_females
# In[53]:
#SAMPLE STD's
std_males = statistics.stdev(data["MALES"])
std_females = statistics.stdev(data["FEMALES"])
std_males, std_females
# In[54]:
#Critical t
t = t.ppf(0.95, len(data)-1)
t
# In[55]:
#calculating confidence intervals
male_confidence = [(mean_males - t*(std_males/np.sqrt(len(data['MALES'])))),
(mean_males + t*(std_males/np.sqrt(len(data['MALES']))))]
female_confidence = [(mean_females - t*(std_females/np.sqrt(len(data['FEMALES'])))),
(mean_females + t*(std_females/np.sqrt(len(data['FEMALES']))))]
# In[56]:
print(male_confidence)
print(female_confidence)
# **USING A T TEST ON THIS DATA, WE CAN SAY WITH 95% CONFIDENCE THAT:**
#
# >1. The average male assistant professor at a U.S. university earns between 32,130 and 34,732 dollars
# >2. The average female assistant professor at a U.S. university earns between 31,878 and 34,521 dollars
# In[ ]:
|
#!/usr/bin/env python3
import argparse
import os
from PIL import Image
def main() -> None:
parser = argparse.ArgumentParser(
description="""\
\"Compress\" an image for the boot-splash.
The boot-splash is a two-color image."""
)
parser.add_argument("image", help="Boot-splash image")
parser.add_argument("-n", "--name", help="Name of the data-block")
parser.add_argument("output", help="Output file name")
args = parser.parse_args()
im = Image.open(args.image)
assert im.size[0] == 160, "Image must be 160 pixels wide"
assert im.size[1] == 80, "Image must be 80 pixels high)"
if args.name is not None:
name = args.name
else:
name = os.path.splitext(os.path.basename(args.image))[0].replace("-", "_")
with open(args.output, "w") as f:
tmp = """\
#include <stdint.h>
/*
* This is the splash-screen image, compressed using a very primitive algorithm:
*
* Each byte encodes up to 127 pixels in either white or black. The most
* significant bit determines the color, the remaining 7 bits determine the
* amount.
*/
const uint8_t {name}[] = {{
"""
f.write(tmp.format(name=name))
total = 0
start = 0
previous_white = False
for i in range(160 * 80):
x = i % 160
y = i // 160
white = im.getpixel((x, y))[0] > 0
if white != previous_white or i - start == 127:
length = i - start
assert length < 128, "Internal error"
value = (length & 0x7F) | (0x80 if previous_white else 0x00)
tmp = """\
/* {length} pixels in {color} */
0x{value:x},
"""
f.write(
tmp.format(
length=length,
color="white" if previous_white else "black",
value=value,
)
)
previous_white = white
start = i
total += length
tmp = """\
}};
"""
f.write(tmp.format())
assert total < (160 * 80), "Internal error"
if __name__ == "__main__":
main()
|
import sys_display
import color
# font enumeration
FONT8 = 0
FONT12 = 1
FONT16 = 2
FONT20 = 3
FONT24 = 4
class Display:
"""
The display class provides methods to allow the lcd display
in card10 to be used in a safe way. All draw methods return
the display object so that it is possible to chain calls.
It is recommended to use a context manager as following:
.. code-block:: python
import display
with display.open() as disp:
disp.clear().update()
"""
def __init__(self):
"""
Opens the display. Will fail the display can't be locked
"""
sys_display.open()
def __enter__(self):
return self
def __exit__(self, _et, _ev, _t):
self.close()
@classmethod
def open(cls):
"""
Opens the display. Will fail the display can't be locked
"""
return cls()
@staticmethod
def close():
"""
Closes and unlocks the display. To be able to use it again,
it is necessary to open and lock it again with Display.open()
"""
sys_display.close()
def update(self):
"""
Updates the display based on the changes previously made by
various draw functions
"""
sys_display.update()
def clear(self, col=None):
"""
Clears the display using the color provided, or the default
color black
:param col: Clearing color (expects RGB triple)
"""
col = col or color.BLACK
sys_display.clear(col)
return self
def print(self, text, *, fg=None, bg=None, posx=0, posy=0, font=FONT20):
"""
Prints a string on the display.
:param text: Text to print
:param fg: Foreground color (expects RGB triple)
:param bg: Background color (expects RGB triple) or None for transparent background
:param posx: X-Position of the first character
:param posy: Y-Position of the first character
:param font: 0 <= font <= 4 (currently) selects a font
Avaiable Fonts:
- :py:data:`display.FONT8`
- :py:data:`display.FONT12`
- :py:data:`display.FONT16`
- :py:data:`display.FONT20`
- :py:data:`display.FONT24`
**Example:**
.. code-block:: python
with display.open() as d:
d.clear()
d.print('Hello Earth!', font=display.FONT24)
d.update()
.. versionchanged:: 1.11
Added transparent background printing.
"""
fg = fg or color.WHITE
bg = bg or fg
sys_display.print_adv(text, posx, posy, fg, bg, font)
return self
def pixel(self, x, y, *, col=None):
"""
Draws a pixel on the display
:param x: X coordinate
:param y: Y coordinate
:param col: color of the pixel (expects RGB tripple)
"""
col = col or color.WHITE
sys_display.pixel(x, y, col)
return self
def backlight(self, brightness):
"""
Set display backlight brightness
:param brightness: backlight brightness 0 <= brightness <= 100
"""
sys_display.backlight(brightness)
return self
def line(self, xs, ys, xe, ye, *, col=None, dotted=False, size=1):
"""
Draws a line on the display.
:param xs: X start coordinate
:param ys: Y start coordinate
:param xe: X end coordinate
:param ye: Y end coordinate
:param col: color of the line (expects RGB triple)
:param dotted: whether the line should be dotted or not
(questionable implementation: draws every other pixel white, draws
white squares at higher pixel sizes)
:param size: size of the individual pixels, ranges from 1 to 8
"""
col = col or color.WHITE
sys_display.line(xs, ys, xe, ye, col, dotted, size)
return self
def rect(self, xs, ys, xe, ye, *, col=None, filled=True, size=1):
"""
Draws a rectangle on the display.
:param xs: X start coordinate
:param ys: Y start coordinate
:param xe: X end coordinate
:param ye: Y end coordinate
:param col: color of the outline and fill (expects RGB triple)
:param filled: whether the rectangle should be filled or not
:param size: size of the individual pixels, ranges from 1 to 8
"""
col = col or color.WHITE
sys_display.rect(xs, ys, xe, ye, col, filled, size)
return self
def circ(self, x, y, rad, *, col=None, filled=True, size=1):
"""
Draws a circle on the display.
:param x: center x coordinate
:param y: center y coordinate
:param rad: radius
:param col: color of the outline and fill (expects RGB triple)
:param filled: whether the rectangle should be filled or not
:param size: size of the individual pixels, ranges from 1 to 8
"""
col = col or color.WHITE
sys_display.circ(x, y, rad, col, filled, size)
return self
open = Display.open
close = Display.close
|
"""
Text Reader Script
=================
This script will list and display text files
"""
import buttons
import color
import display
import os
import utime
STATE_LIST = "List"
STATE_SHOW = "Show"
SPECIAL_NO_FILES = "# no txt files"
SPECIAL_EXIT = "[ exit ]"
SPECIAL_EMPTY = "# empty file"
BUTTON_TIMER_POPPED = -1
def list_files():
"""Create a list of available text files."""
files = sorted(os.listdir("/"))
# Filter for text files
files = [txt for txt in files if txt.endswith(".txt")]
return files
def triangle(disp, x, y, left):
"""Draw a triangle to show there's more text in this line"""
yf = 1 if left else -1
scale = 6
disp.line(x - scale * yf, int(y + scale / 2), x, y, col=[255, 0, 0])
disp.line(x, y, x, y + scale, col=[255, 0, 0])
disp.line(x, y + scale, x - scale * yf, y + int(scale / 2), col=[255, 0, 0])
def button_events(timeout=0):
"""Iterate over button presses (event-loop)."""
yield 0
button_pressed = False
count = 0
while True:
v = buttons.read(buttons.BOTTOM_LEFT | buttons.BOTTOM_RIGHT | buttons.TOP_RIGHT)
if timeout > 0 and count > 0 and count % timeout == 0:
yield BUTTON_TIMER_POPPED
if timeout > 0:
count += 1
if v == 0:
button_pressed = False
if not button_pressed and v & buttons.BOTTOM_LEFT != 0:
button_pressed = True
yield buttons.BOTTOM_LEFT
if not button_pressed and v & buttons.BOTTOM_RIGHT != 0:
button_pressed = True
yield buttons.BOTTOM_RIGHT
if not button_pressed and v & buttons.TOP_RIGHT != 0:
button_pressed = True
yield buttons.TOP_RIGHT
utime.sleep_ms(10)
COLOR1, COLOR2 = (color.CHAOSBLUE_DARK, color.CHAOSBLUE)
def file_len(filename):
i = -1
with open(filename) as fh:
for i, l in enumerate(fh):
pass
return i + 1
def draw_filecontent(disp, filename, pos, linecount, lineoffset=0):
disp.clear()
with open(filename) as fh:
# stop if file is empty
if linecount <= 0:
disp.print(SPECIAL_EMPTY, posy=20, bg=color.BLACK)
return
# calc start position
start = 0
if pos > 0:
start = pos - 1
if start + 4 > linecount:
start = linecount - 4
if start < 0:
start = 0
# loop throuhg all lines
for i, line in enumerate(fh):
if i >= start + 4 or i >= linecount:
break
if i >= start:
disp.rect(
0,
(i - start) * 20,
159,
(i - start) * 20 + 20,
col=COLOR1 if i == pos else COLOR2,
)
off = 0
linelength = len(line)
if i == pos and linelength > 11 and lineoffset > 0:
off = (
lineoffset if lineoffset + 11 < linelength else linelength - 11
)
if lineoffset > linelength:
off = 0
disp.print(
line[off : (off + 11)],
posy=(i - start) * 20,
bg=COLOR1 if i == pos else COLOR2,
)
if linelength > 11 and off < linelength - 11:
triangle(disp, 153, (i - start) * 20 + 6, False)
if off > 0:
triangle(disp, 6, (i - start) * 20 + 6, True)
disp.update()
def draw_filelist(disp, filelist, pos, filecount, lineoffset):
disp.clear()
start = 0
if pos > 0:
start = pos - 1
if start + 4 > filecount:
start = filecount - 4
if start < 0:
start = 0
for i, line in enumerate(filelist):
if i >= start + 4 or i >= filecount:
break
if i >= start:
disp.rect(
0,
(i - start) * 20,
159,
(i - start) * 20 + 20,
col=COLOR1 if i == pos else COLOR2,
)
off = 0
linelength = len(line)
if i == pos and linelength > 10 and lineoffset > 0:
off = lineoffset if lineoffset + 10 < linelength else linelength - 10
if lineoffset > linelength:
off = 0
disp.print(
" " + line[off : (off + 10)],
posy=(i - start) * 20,
bg=COLOR1 if i == pos else COLOR2,
)
if i == pos:
disp.print(">", posy=(i - start) * 20, fg=color.COMMYELLOW, bg=COLOR1)
if linelength > 10 and off < linelength - 10:
triangle(disp, 153, (i - start) * 20 + 6, False)
if off > 0:
triangle(disp, 24, (i - start) * 20 + 6, True)
disp.update()
def main():
disp = display.open()
current_state = STATE_LIST
# list files variables
filelist = list_files()
if len(filelist) == 0:
filelist.append(SPECIAL_NO_FILES)
filelist.append(SPECIAL_EXIT)
numfiles = len(filelist)
current_file = 0
# show files variables
filename = ""
linecount = 0
linepos = 0
lineoffset = 0
lineoffdir = 0
timerscrollspeed = 1
timerstartscroll = 5
timercountpopped = 0
for ev in button_events(10):
# list files
if current_state == STATE_LIST:
if ev == buttons.BOTTOM_RIGHT:
# Scroll down
current_file = (current_file + 1) % numfiles
lineoffset = 0
timercountpopped = 0
elif ev == buttons.BOTTOM_LEFT:
# Scroll up
current_file = (current_file + numfiles - 1) % numfiles
lineoffset = 0
timercountpopped = 0
elif ev == BUTTON_TIMER_POPPED:
timercountpopped += 1
if (
timercountpopped >= timerstartscroll
and (timercountpopped - timerstartscroll) % timerscrollspeed == 0
):
lineoffset += 1
elif ev == buttons.TOP_RIGHT:
filename = filelist[current_file % numfiles]
# exit or ignore
if filename == SPECIAL_EXIT:
os.exit()
elif filename == SPECIAL_NO_FILES:
continue
# show file, switch state and draw
current_state = STATE_SHOW
disp.clear().update()
# reset variables
linepos = 0
lineoffset = 0
timercountpopped = 0
linecount = file_len(filename)
# draw
draw_filecontent(disp, filename, linepos, linecount, lineoffset)
continue
draw_filelist(disp, filelist, current_file, numfiles, lineoffset)
# show files
elif current_state == STATE_SHOW:
if ev == buttons.BOTTOM_RIGHT:
if linepos < (linecount - 1):
# Scroll down
linepos += 1
else:
# goto first line
linepos = 0
lineoffset = 0
timercountpopped = 0
elif ev == buttons.BOTTOM_LEFT:
if linepos > 0:
# Scroll up
linepos -= 1
else:
# got to last line
linepos = linecount - 1
lineoffset = 0
timercountpopped = 0
elif ev == BUTTON_TIMER_POPPED:
timercountpopped += 1
if (
timercountpopped >= timerstartscroll
and (timercountpopped - timerstartscroll) % timerscrollspeed == 0
):
lineoffset += 1
elif ev == buttons.TOP_RIGHT:
# go back to file menu
current_state = STATE_LIST
lineoffset = 0
timercountpopped = 0
draw_filelist(disp, filelist, current_file, numfiles, 0)
continue
draw_filecontent(disp, filename, linepos, linecount, lineoffset)
if __name__ == "__main__":
main()
|
def mergeSkyline(left, right):
# 2D array of x-coordinate, height sorted by x
# traverse through each element and its next
# print(left, right)
if left is None:
return right
elif right is None:
return left
res = []
h1, h2 = 0, 0
i, j = 0, 0
while i < len(left) and j < len(right):
x = left[i]
y = right[j]
if x[0] < y[0]:
h1 = x[1]
res.append([x[0], max(h1, h2)])
i += 1
elif x[0] > y[0]:
h2 = y[1]
res.append([y[0], max(h1, h2)])
j += 1
else:
h1 = x[1]
h2 = y[1]
res.append([x[0], max(h1, h2)])
i += 1
j += 1
try:
if res[-1][1] == res[-2][1]:
res.pop()
except:
pass
if i != len(left):
while i != len(left):
res.append(left[i])
i += 1
if j != len(right):
while j != len(right):
res.append(right[j])
j += 1
print(res)
return res
def skyline(buildings):
print(buildings)
arr_len = len(buildings)
if arr_len == 1:
return [[buildings[0][0], buildings[0][2]], [buildings[0][1], 0]]
if arr_len > 1:
left = skyline(buildings[:arr_len//2])
right = skyline(buildings[arr_len//2:])
res = mergeSkyline(left, right)
return res
res = skyline([[1,2,1],[1,2,2],[1,2,3]])
print(res)
|
import re
import sys
user_regex = r'(?:/user/show/)(\d+-[a-zA-Z0-9-]+)'
def parse(data):
users = re.findall(user_regex, data)
return set(users)
def main():
if len(sys.argv) < 3:
print("[+] Usage: user_parser.py INPUT_FILE OUTPUT_FILE")
exit()
users = parse(open(sys.argv[1], 'r', encoding='utf-8').read())
with open(sys.argv[2], 'w') as fp:
fp.write("\n".join(users))
print(f"[+] {len(users)} users found")
# print(users)
main()
|
import RPi.GPIO as GPIO
import time
from threading import Timer
class LED():
def __init__(self, channel, input_output):
"""
Control an LED given a GPIO channel
"""
self.channel = channel
if input_output == 'input':
self.input_output = GPIO.IN
elif input_output == 'output':
self.input_output = GPIO.OUT
else:
raise ValueError('Invalid parameter, please choose "input" or "output"')
def setUp(self):
"""set up input/output channel"""
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.channel, self.input_output)
def on(self):
"""turn on an LED"""
self.setUp()
GPIO.output(self.channel, GPIO.HIGH)
def off(self):
"""turn off an LED"""
self.setUp()
GPIO.output(self.channel, GPIO.LOW)
def flicker(self, interval):
"""turn on/off on an interval"""
self.on()
time.sleep(interval)
self.off()
|
import os #for reading all smali files in a given directory
import pickle # for reading the list of apks stored as a pickle
import csv #for packaging the op-code:count dictionary into a csv
import collections
#location of the folder where all of the smali files of the disassembled apk is present
def std_codes_list(standard_codes):
std_codes = [] #empty list which will later contain all the standard op-codes read from the ops.txt file
with open(standard_codes,'r') as fp:
for cnt, line in enumerate(fp): # reading each op-code in the txt file
read_lines = fp.read();
read_lines = read_lines.split("\n")
std_codes = read_lines
std_codes.pop() #last element is '' blank, so pop it and return the final list
return std_codes
def parse_smalis(app_dir,each_apk):
smali_content = [] #Empty list that will later contain all of the content of all of the smali files.
temp = []
for root, dirs, files in os.walk(app_dir+ "/" + each_apk +"/smali"): #Scanning through each file in each sub-directory
for file in files:
if file.endswith(".smali"):
file_dest= os.path.join(root, file)
with open(file_dest,'r' , encoding="utf8") as fp:
temp = fp.readlines()
temp = [line.rstrip('\n').split(" ") for line in temp] #store the contents of a file
smali_content.append(temp)
return smali_content
def match_op_codes(std_codes, smali_content, each_apk):
onegrams = []
for each_smali in smali_content:
for each_line in each_smali:
for each_word in each_line:
if(each_word==''):
continue
for each_code in std_codes:
if (each_word)==(each_code):
onegrams.append(each_code)
return onegrams
def onegramDictionary(onegram, each_apk, label):
onegramfreq= collections.defaultdict(str)
onegramfreq["Apk_name"] = each_apk
onegramfreq["1gram"] = onegram
onegramfreq["Label"] = label
return onegramfreq
def onegram_csv(onegramfreq):
with open('1gramTest.csv', 'a') as f:
writer = csv.writer(f)
if(os.stat("1gramTest.csv").st_size == 0):
writer.writerow(list(onegramfreq.keys()))
writer.writerow(list(onegramfreq.values()))
def Test_csvlabel(each_apk, label):
labeldic= collections.defaultdict(str)
labeldic["Apk_name"] = each_apk
labeldic["label"] = label
with open('TestLabel.csv', 'a') as f:
writer = csv.writer(f)
if(os.stat("TestLabel.csv").st_size == 0):
writer.writerow(list(labeldic.keys()))
writer.writerow(list(labeldic.values()))
def GramOpcodes(fq, n):
ngrams_list = []
for num in range(0, len(fq)):
ngram = ' '.join(fq[num:num + n])
ngrams_list.append(ngram)
return ngrams_list
def bigramDictionary(bigrams, each_apk, label):
bigramfreq= collections.defaultdict(str)
bigramfreq["Apk_name"] = each_apk
bigramfreq["Bigram"] = bigrams
bigramfreq["Label"] = label
return bigramfreq
def bigram_csv(bigramfreq):
with open('Bigram.csv', 'a') as f:
writer = csv.writer(f)
if(os.stat("Bigram.csv").st_size == 0):
writer.writerow(list(bigramfreq.keys()))
writer.writerow(list(bigramfreq.values()))
def trigramDictionary(trigrams, each_apk):
trigramfreq= collections.defaultdict(str)
trigramfreq["Apk_name"] = each_apk
trigramfreq["Trigram"] = trigrams
return trigramfreq
def trigram_csv(trigramfreq):
with open('trigram.csv', 'a') as t:
writer = csv.writer(t)
if(os.stat("trigram.csv").st_size == 0):
writer.writerow(list(trigramfreq.keys()))
writer.writerow(list(trigramfreq.values()))
def fourgramDictionary(fourgrams, each_apk):
fourgramfreq= collections.defaultdict(str)
fourgramfreq["Apk_name"] = each_apk
fourgramfreq["Fourgram"] = fourgrams
return fourgramfreq
def fourgram_csv(fourgramfreq):
with open('fourgram.csv', 'a') as four:
writer = csv.writer(four)
if(os.stat("fourgram.csv").st_size == 0):
writer.writerow(list(fourgramfreq.keys()))
writer.writerow(list(fourgramfreq.values()))
def fivegramDictionary(fivegrams, each_apk):
fivegramfreq= collections.defaultdict(str)
fivegramfreq["Apk_name"] = each_apk
fivegramfreq["fivegram"] = fivegrams
return fivegramfreq
def fivegram_csv(fivegramfreq):
with open('fivegram.csv', 'a') as five:
writer = csv.writer(five)
if(os.stat("fivegram.csv").st_size == 0):
writer.writerow(list(fivegramfreq.keys()))
writer.writerow(list(fivegramfreq.values()))
standard_codes = "ops.txt"
app_dir = "F:\FYP CONTENTS\Data\APK Testing Datasets\All Smali Files"
std_codes = std_codes_list(standard_codes)
apk_list_Adware = pickle.load(open('adwareTest.pkl', 'rb'))
apk_list_Ransomware = pickle.load(open('ransomewareTest.pkl', 'rb'))
apk_list_Trojan = pickle.load(open('trojanTest.pkl', 'rb'))
apk_list_Benign = pickle.load(open('benignTest.pkl', 'rb'))
for each_apk in apk_list_Adware:
adwarelabel= "Adware"
smali_content = parse_smalis(app_dir,each_apk)
fq = match_op_codes(std_codes,smali_content,each_apk)
bigrams= GramOpcodes(fq , 2)
trigrams= GramOpcodes(fq , 3)
fourgrams= GramOpcodes(fq , 4)
fivegrams= GramOpcodes(fq , 5)
onegramfreq= onegramDictionary(fq , each_apk, adwarelabel)
onegramcsv= onegram_csv(onegramfreq)
bigramfreq= bigramDictionary(bigrams , each_apk)
bigramcsv= bigram_csv(bigramfreq)
trigramfreq= trigramDictionary(trigrams , each_apk)
trigramcsv= trigram_csv(trigramfreq)
fourgramfreq= fourgramDictionary(fourgrams , each_apk)
fourgramcsv= fourgram_csv(fourgramfreq)
fivegramfreq= fivegramDictionary(fivegrams , each_apk)
fivegramcsv= fivegram_csv(fivegramfreq)
csvlabel= Test_csvlabel(each_apk, adwarelabel)
for each_apk in apk_list_Ransomware:
Ransomewarelabel= "Ransomware"
smali_content = parse_smalis(app_dir,each_apk)
fq = match_op_codes(std_codes,smali_content,each_apk)
bigrams= GramOpcodes(fq , 2)
trigrams= GramOpcodes(fq , 3)
fourgrams= GramOpcodes(fq , 4)
fivegrams= GramOpcodes(fq , 5)
onegramfreq= onegramDictionary(fq , each_apk, Ransomewarelabel)
onegramcsv= onegram_csv(onegramfreq)
bigramfreq= bigramDictionary(bigrams , each_apk)
bigramcsv= bigram_csv(bigramfreq)
trigramfreq= trigramDictionary(trigrams , each_apk)
trigramcsv= trigram_csv(trigramfreq)
fourgramfreq= fourgramDictionary(fourgrams , each_apk)
fourgramcsv= fourgram_csv(fourgramfreq)
fivegramfreq= fivegramDictionary(fivegrams , each_apk)
fivegramcsv= fivegram_csv(fivegramfreq)
csvlabel= Test_csvlabel(each_apk, Ransomewarelabel)
for each_apk in apk_list_Trojan:
Trojanlabel= "Trojan"
smali_content = parse_smalis(app_dir,each_apk)
fq = match_op_codes(std_codes,smali_content,each_apk)
bigrams= GramOpcodes(fq , 2)
trigrams= GramOpcodes(fq , 3)
fourgrams= GramOpcodes(fq , 4)
fivegrams= GramOpcodes(fq , 5)
onegramfreq= onegramDictionary(fq , each_apk, Trojanlabel)
onegramcsv= onegram_csv(onegramfreq)
bigramfreq= bigramDictionary(bigrams , each_apk)
bigramcsv= bigram_csv(bigramfreq)
trigramfreq= trigramDictionary(trigrams , each_apk)
trigramcsv= trigram_csv(trigramfreq)
fourgramfreq= fourgramDictionary(fourgrams , each_apk)
fourgramcsv= fourgram_csv(fourgramfreq)
fivegramfreq= fivegramDictionary(fivegrams , each_apk)
fivegramcsv= fivegram_csv(fivegramfreq)
csvlabel= Test_csvlabel(each_apk, Trojanlabel)
for each_apk in apk_list_Benign:
Benignlabel= "Benign"
smali_content = parse_smalis(app_dir,each_apk)
fq = match_op_codes(std_codes,smali_content,each_apk)
bigrams= GramOpcodes(fq , 2)
trigrams= GramOpcodes(fq , 3)
fourgrams= GramOpcodes(fq , 4)
fivegrams= GramOpcodes(fq , 5)
onegramfreq= onegramDictionary(fq , each_apk, Benignlabel)
onegramcsv= onegram_csv(onegramfreq)
bigramfreq= bigramDictionary(bigrams , each_apk)
bigramcsv= bigram_csv(bigramfreq)
trigramfreq= trigramDictionary(trigrams , each_apk)
trigramcsv= trigram_csv(trigramfreq)
fourgramfreq= fourgramDictionary(fourgrams , each_apk)
fourgramcsv= fourgram_csv(fourgramfreq)
fivegramfreq= fivegramDictionary(fivegrams , each_apk)
fivegramcsv= fivegram_csv(fivegramfreq)
csvlabel= Test_csvlabel(each_apk, Benignlabel)
print("Completed!")
|
import types
class Strategy:
""" Strategy pattern class """
def __init__(self, function=None):
self.name = "Default Strategy"
if function is not None:
self.execute = types.MethodType(function, self)
def execute(self):
print("{} is used!".format(self.name))
# replacement method 1
def strategy_one(self):
print("{} is used to execute method 1".format(self.name))
# replacement method 2
def strategy_two(self):
print("{} is used to execute method 2".format(self.name))
# Create our default strategy
s0 = Strategy()
# Execute
s0.execute()
s1 = Strategy(strategy_one)
# Set name
s1.name = "Strategy 1"
# Execute
s1.execute()
s2 = Strategy(strategy_two)
# Set name
s2.name = "Strategy 2"
# Execute
s2.execute()
|
from tkinter import *
from tkinter import ttk
# http://blog.csdn.net/maillibin/article/details/46954223
#计算程序
def calculate(* args):
value=float(feet_entry.get())
meters=(0.3048*value*10000.0+0.5)/10000.0
ttk.Label(mainframe,text=meters).grid(column=2,row=2,sticky=W)
print(meters)
#界面设计
root=Tk()
root.title("英尺转换为米")
mainframe=ttk.Frame(root,padding="150 30 10 30")
mainframe.grid(column=0,row=0,sticky=(N,W,E,S))
feet_entry=ttk.Entry(mainframe,width=5)
feet_entry.grid(column=2,row=1,sticky=(W,E))
ttk.Label(mainframe,text="英尺").grid(column=3,row=1,sticky=W)
ttk.Label(mainframe,text="等于").grid(column=1,row=2,sticky=E)
ttk.Label(mainframe,text="米").grid(column=3,row=2,sticky=W)
ttk.Button(mainframe,text="计算",command=calculate).grid(column=3,row=3,sticky=W)
for child in mainframe.winfo_children():
child.grid_configure(padx=3,pady=7)
feet_entry.focus()
#绑定事件
root.bind("<Return>",calculate)
root.mainloop() |
# Things you should be able to do.
number_list = [-5, 6, 4, 8, 15, 16, 23, 42, 2, 7]
word_list = [ "What", "about", "the", "Spam", "sausage", "spam", "spam", "bacon", "spam", "tomato", "and", "spam"]
# Write a function that takes a list of numbers and returns a new list with only the odd numbers.
def all_odd(number_list):
odd_list = []
for i in range(len(number_list)):
if number_list[i] % 2 != 0:
odd_list.append(number_list[i])
return odd_list
# Write a function that takes a list of numbers and returns a new list with only the even numbers.
def all_even(number_list):
even_list = []
for i in range(len(number_list)):
if number_list[i] % 2 == 0:
print(number_list[i])
even_list.append(number_list[i])
return even_list
# Write a function that takes a list of strings and a new list with all strings of length 4 or greater.
def long_words(word_list):
strings_longer_4 = []
for i in range(len(word_list)):
if len(word_list[i]) >= 4:
strings_longer_4.append(word_list[i])
return strings_longer_4
# Write a function that finds the smallest element in a list of integers and returns it.
def smallest(number_list):
smallest_current = number_list[0]
for i in range(1,len(number_list)):
if number_list[i] < smallest_current:
smallest_current = number_list[i]
return smallest_current
# Write a function that finds the largest element in a list of integers and returns it.
def largest(number_list):
largest_current = number_list[0]
for i in range(1,len(number_list)):
if number_list[i] > largest_current:
largest_current = number_list[i]
return largest_current
# Write a function that takes a list of numbers and returns a new list of all those numbers divided by two.
def halvesies(number_list):
halved_list = []
for i in range(len(number_list)):
halved_list.append(number_list[i]/2.0)
return halved_list
# Write a function that takes a list of words and returns a list of all the lengths of those words.
# def word_lengths(word_list):
# len_words = []
# for i in range(len(word_list)):
# len_words.append(len(word_list[i]))
# return len_words
def word_lengths(word_list):
len_words = []
lengthwordlist = 0
for aword in word_list:
lengthwordlist+=1
for i in range(lengthwordlist):
stringcount = 0
word = word_list[i]
for j in word:
stringcount += 1
len_words.append(stringcount)
return len_words
print(word_lengths(word_list))
assert(word_lengths(word_list) == [4, 5, 3, 4, 7, 4, 4, 5, 4, 6, 3, 4])
# Write a function (using iteration) that sums all the numbers in a list.
def sum_numbers(number_list):
summation = number_list[0]
for i in range(1,len(number_list)):
summation = summation + number_list[i]
return summation
print(sum_numbers(number_list))
# Write a function that multiplies all the numbers in a list together.
def mult_numbers(number_list):
prod = number_list[0]
for i in range(1,len(number_list)):
prod = prod*number_list[i]
return prod
print(mult_numbers(number_list))
# Write a function that joins all the strings in a
#list together (without using the join method) and returns a single string.
def join_strings(word_list):
joinedstring = ""
for i in range(len(word_list)):
joinedstring = joinedstring+word_list[i]
return joinedstring
print(join_strings(word_list))
# Write a function that takes a list of integers and returns the average (without using the avg method)
def average(number_list):
summation = number_list[0]
for i in range(1,len(number_list)):
summation = summation + number_list[i]
mean = float(summation)/float(i+1)
return mean
print(average(number_list)) |
import pickle
import os.path
import datetime
from user import User
from record import Record
from day import Day
def console_interface():
"""Top-level function for console interface.
Handles user creation, user login, and quitting.
Responsible for loading and saving binary files."""
done_with_program = False
QUIT = "QUIT" # Sentinel value
extension = ".dbhat"
# While the program has yet do finish:
while not done_with_program:
# Get the username
username = input("Enter name ('QUIT' to quit): ").replace(" ", "")
# If the username is the sentinel value of "QUIT", exit the program.
if username == QUIT:
return
# Otherwise, if the user's file exists:
elif os.path.isfile(username+extension):
# Open, read data from, and close the user's file
userfile = open(username+extension, "rb")
the_user = pickle.load(userfile)
userfile.close()
# Run a quick update function on the data
the_user._update_days()
# Enter into the console interface's main menu
done_with_program = console_main_menu(the_user)
# When the user has finished, remove all empty days from the data
the_user._cleanup_empty_days()
# Open, write data to, and close the user's file
userfile = open(username+extension, "wb")
pickle.dump(the_user, userfile)
userfile.close()
# Otherwise, inform the user that the file wasn't found.
else:
# Inform and prompt user.
print("User file not found. Enter '1' to create a new one.")
choice = input()
# If the user input "1", create a User and start the main menu.
if choice == "1":
the_user = User(username)
done_with_program = console_main_menu(the_user)
# When the user is done, remove all empty days from their data.
the_user._cleanup_empty_days()
# Create, read data into, and close the user's file.
userfile = open(username+extension, "wb+")
pickle.dump(the_user, userfile)
userfile.close()
def console_main_menu(a_user) -> bool:
"""Main menu of the console interface. Called by top-level function.
User may choose to add or view/edit records, calculate averages, quit, or just log out.
:param a_user: User
:return: bool
"""
QUIT = 5
choice = 0
while choice != QUIT:
print("MAIN MENU")
print("1. Add record")
print("2. View/Edit records")
print("3. Calculate averages")
print("4. Change user")
print("5. Quit")
choice = int(input("\nEnter number: "))
if choice == 1:
console_add_record(a_user)
elif choice == 2:
console_view_records(a_user)
elif choice == 3:
console_view_averages(a_user)
# If choice is 4, return to top-level function, but do not close the program.
elif choice == 4:
return False
# If choice is 5, return to top-level function, and close the program.
elif choice == 5:
return True
else:
print("Number out of range.")
def console_view_averages(a_user):
"""Displays the averages and ratings of the user's glucose, carbs,
missed meals, and activity over the last user-entered number of days.
:param a_user: User
"""
# If the user has no days, inform them of this fact.
if a_user.first_day is None:
print("No records found. Averages unavailable.\n")
# Otherwise, get number of days back.
else:
days_back = int(input("Enter days to go back (0 means today): "))
# If days back is negative, do nothing. If it's valid, calculate averages.
if days_back >= 0:
glucose_average = a_user.calculate_average_glucose(days_back)
carbs_per_meal_average = a_user.calculate_average_carbs_per_meal(days_back)
time_active_average = a_user.calculate_average_time_active(days_back)
average_meals_missed = a_user.calculate_average_meals_missed(days_back)
# Print labels, averages, and ratings.
print(str.format("Glucose: {:9} Rating: {}", glucose_average,
a_user.get_glucose_rating(glucose_average)))
print(str.format("Activity: {:5} min Rating: {}", time_active_average,
a_user.get_time_active_rating(time_active_average)))
print(str.format("Carbs/meal: {:9} Rating: {}", carbs_per_meal_average,
a_user.get_carbs_per_meal_rating(carbs_per_meal_average)))
print(str.format("Meals missed: {:9} Rating: {}", average_meals_missed,
a_user.get_meals_missed_rating(average_meals_missed)))
print()
def console_view_records(a_user):
"""Allows the user to view records one day at a time.
Calls console_choose_record_to_edit methood if edits are to be made.
:param a_user: User
"""
current_day = a_user.last_day # Start at the user's last day.
QUIT = 4 # Sentinel value
choice = 0 # Initialize choice variable
# If there are no days, inform the user.
if a_user.last_day is None:
print("No days found.\n")
# Otherwise, as long as choice isn't the sentinel value, print the day and menu.
else:
while choice != QUIT:
print(current_day)
print("1. Previous day")
print("2. Edit a record")
print("3. Next day")
print("4. Back")
choice = int(input("\nEnter number: "))
while choice < 1 or choice > 4:
print("Number not in range.")
choice = int(input("Enter number: "))
if choice == 1:
# If there are no prior days, inform the user they can't go back anymore.
if current_day.previous_day is None:
print("Currently at earliest recorded day.")
# Otherwise, move to previous day.
else:
current_day = current_day.previous_day
elif choice == 3:
# If there are no future days, inform the user they can't go forward anymore.
if current_day.next_day is None:
print("Currently at latest recorded day.")
# Otherwise, move to next day.
else:
current_day = current_day.next_day
elif choice == 2:
console_choose_record_to_edit(current_day)
else:
return
def console_choose_record_to_edit(a_day):
"""Lets the user choose which record to edit.
:param a_day: Day
"""
QUIT = 4 # Sentinel value
print("1. Morning record")
print("2. Afternoon record")
print("3. Evening record")
print("4. Back")
choice = int(input("\nEnter number: "))
while choice < 1 or choice > 4:
print("Number not in range.")
choice = int(input("Enter number: "))
if choice == 1:
console_edit_record(a_day.morning_record)
elif choice == 2:
console_edit_record(a_day.afternoon_record)
elif choice == 3:
console_edit_record(a_day.evening_record)
else:
return
def console_edit_record(a_record):
"""Allows the user to choose and edit parts of a record.
Unable to edit the date or time of day.
:param a_record: Record
"""
QUIT = 5 # sentinel value
choice = 0 # initialize choice variable
# Until the user decides to quit, print the record and menu.
while choice != QUIT:
print(a_record)
print("1. Edit glucose")
print("2. Edit meal & Carbs")
print("3. Edit activity information")
print("4. Edit mood")
print("5. Back")
choice = int(input("\nEnter number: "))
while choice < 1 or choice > 5:
print("Number out of range.")
choice = int(input("Enter number: "))
if choice == 1:
a_record.glucose = int(input("Enter new glucose: "))
elif choice == 2:
meal = input("Enter new meal (0 for nothing): ")
# If the user enetered a meal, also have them enter carbs.
if meal != "0":
a_record.carbs = int(input("Enter new carb amount: "))
# Otherwise, if the user did not enter a meal, set the meal to "" and the carbs to 0.
else:
a_record.carbs = 0
meal = ""
a_record.meal = meal
elif choice == 3:
activity = input("Enter new activity (0 for nothing): ")
# If the user did not enter an activity, set the activity to "" and the times to None.
if activity == "0":
activity = ""
activity_start_time = None
activity_end_time = None
# Otherwise, have the user enter the start and end times.
else:
activity_start_time = datetime.datetime.strptime(input("Enter start time (h:m AM/PM): "), "%I:%M %p")
activity_end_time = datetime.datetime.strptime(input("Enter end time (h:m AM/PM): "), "%I:%M %p")
a_record.activity = activity
a_record.activity_start_time = activity_start_time
a_record.activity_end_time = activity_end_time
elif choice == 4:
a_record.mood = input("Enter new mood:")
else:
return
def console_add_record(a_user):
"""Allows the user to add a Record to a day. Calls the console_create_record function to do so.
:param a_user: User
"""
good_format = False # Will not allow the user to continue without a valid date format.
while not good_format:
date_string = input("Enter date for record (MM/DD/YYYY, 0 for today: ")
# If the user entered a date of their own, check it for validity.
if date_string != "0":
try:
date_obj = datetime.datetime.strptime(date_string, '%m/%d/%Y').date()
good_format = True
except ValueError:
print("Accepted inputs are 0 or the format MM/DD/YYYY. Try again.")
# Otherwise, set the date to today's date.
else:
good_format = True
date_obj = datetime.datetime.today().date()
current_day = Day(date_of_day=date_obj) # Create a new Day object.
# Attempt to insert the day into the user's doubly-linked list of Days.
if not a_user.insert_day_in_list(current_day):
# If the date was already there, find the appropriate day instead of inserting a new one.
current_day = a_user.last_day
while current_day.date_of_day != date_obj:
current_day = current_day.previous_day
# Display menu for adding records.
print("Add record for:")
print("1. Morning")
print("2. Afternoon")
print("3. Evening")
print("4. Back")
choice = int(input("\nEnter number: "))
while choice < 1 or choice > 4:
print("Invalid entry.")
choice = int(input("Enter number:"))
if choice != 4:
if choice == 1:
current_day.morning_record = console_create_record()
elif choice == 2:
current_day.afternoon_record = console_create_record()
else:
current_day.evening_record = console_create_record()
def console_create_record() -> Record:
"""Allows the user to create a Record.
:return: Record
"""
# Get the glucose value.
glucose = int(input("Enter glucose: "))
# Get the meal
meal = input("Enter meal (0 for none): ")
# If there was a meal, get the carbs
if meal != "0":
carbs = int(input("Enter carbs: "))
# If there wasn't a meal, set meal to "" and carbs to 0
else:
meal = ""
carbs = 0
# Get the activity
activity = input("Enter activity (0 for none): ")
# If there was an activity...
if activity != "0":
good_format = False # Does not allow the user to continue until the time formats are good
while not good_format:
try:
activity_start_time = datetime.datetime.strptime(input("Enter start time (h:m AM/PM): "), "%I:%M %p")
activity_end_time = datetime.datetime.strptime(input("Enter end time (h:m AM/PM): "), "%I:%M %p")
good_format = True
except ValueError:
print("Invalid time formats. Please enter in hh:mm AM/PM format.")
# Otherwise, set activity to "" and both times to None
else:
activity = ""
activity_start_time = None
activity_end_time = None
# Get the mood
mood = input("Enter mood: ")
# Create and return a new Record object
return Record(glucose=glucose, meal=meal, carbs=carbs, activity=activity,
activity_start_time=activity_start_time,
activity_end_time=activity_end_time, mood=mood)
|
def factorial(n):
fact = 1
for i in range(1,n+1):
fact = fact*i
return fact
def combinatorics():
count = 0
for i in range(1,101):
for r in range(1,i+1):
if(factorial(i)/(factorial(r)*factorial(i-r)) >1000000):
count = count+1
print(count)
combinatorics()
|
def factorial(n):
fact = 1
for i in range(1,n+1):
fact = fact*i
return fact
def sum_factorial(n):
s = 0
while (n > 0):
r = n%10
s = s+factorial(r)
n = n//10
return s
def sum():
s = 0
for i in range(10,1000000):
if(sum_factorial(i) == i):
s = s+i
print(s)
sum()
|
from string import ascii_lowercase
from itertools import cycle
alphabet = ascii_lowercase
def encrypt(plain, key):
cipher = ''
key = cycle(key)
for i in plain:
char = i
i = alphabet.find(i.lower())
if i == -1:
cipher += char
continue
j = next(key)
j = alphabet.find(j.lower())
c = alphabet[(i + j) % 26]
if char.isupper():
c = c.upper()
cipher += c
return cipher
def decrypt(cipher, key):
plain = ''
key = cycle(key)
for i in cipher:
char = i
i = alphabet.find(i.lower())
if i == -1:
plain += char
continue
j = next(key)
j = alphabet.find(j.lower())
c = alphabet[(i - j) % 26]
if char.isupper():
c = c.upper()
plain += c
return plain
def crack(plain, cipher):
key = ''
for i, j in zip(plain, cipher):
i = alphabet.find(i.lower())
j = alphabet.find(j.lower())
if i == -1:
continue
for k in range(26):
if (i + k) % 26 == j:
key += alphabet[k]
break
for i in range(1, len(key)):
if key[:i] == key[i:i+i]:
if key[i-1] == key[i]:
continue
else:
key = key[:i]
break
return key
if __name__ == '__main__':
plain = 'HelLo W0rLd a Ala ma k0T4'
key = 'secret'
print('plaintext: ', plain)
print('key: ', key)
print('-'*40)
cipher = encrypt(plain, key)
print('ciphertext: ', cipher)
plain = decrypt(cipher, key)
print('decrypted: ', plain)
key = crack(plain, cipher)
print('cracked key: ', key)
|
fact = 1
n = int(input("Enter a number: "))
for i in range(n,0,-1):
if (i == 0):
fact = 1
else:
fact = fact * i
#print(fact)
print(fact)
def factorial(k):
if(k==0):
return 1
else:
fact1 = k * factorial(k - 1)
return fact1
print(factorial(5))
|
# coding:utf-8
__author__ = 'yinzishao'
# dic ={}
class operation():
def GetResult(self):
pass
class operationAdd(operation):
def GetResult(self):
return self.numberA + self.numberB
class operationDev(operation):
def GetResult(self):
# if(self.numberB!=0):
# return self.numberA /self.numberB
# else:
# raise "被除数不能为0"
try :
return self.numberA /self.numberB
except Exception,e:
print "error:divided by zero"
return 0
class operationMul(operation):
def GetResult(self):
return self.numberA*self.numberB
class operationSub(operation):
def GetResult(self):
return self.numberA-self.numberB
class operationFac():
dic ={}
def __init__(self):
self.dic ={"+":operationAdd(),"-":operationSub(),"/":operationDev(),"*":operationDev()}
def creatOpe(self,sign):
if sign in self.dic:
return self.dic[sign]
else:
return "faise"
if __name__ =="__main__":
fuhao = raw_input("operator:")
nA= input("a:")
nB= input("b:")
a =operationFac().creatOpe(fuhao)
a.numberA=nA
a.numberB=nB
print a.GetResult()
# dic ={"+":operationAdd(),"-":operationSub(),"/":operationDev(),"*":operationDev()}
# print dic
|
import random
"""
populate outlist with character using values in in_list as index
"""
def populate_list(out_list, in_list, character):
for i in range(0,len(in_list)):
out_list[in_list[i]] = character
"""
print a tic-tac-toe frame
"""
def print_list(inlist):
print(inlist[0],inlist[1],inlist[2])
print(inlist[3],inlist[4],inlist[5])
print(inlist[6],inlist[7],inlist[8])
"""
occupy a position pos in list l, freeing the position in flist
"""
def occupy_list(l, flist, pos):
l.append(pos)
flist.remove(pos)
"""
check if list has a winning combination
"""
def winner(list):
comb = [{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}]
for item in comb:
if(item.issubset(set(list))):
return True
return False
"""
Find a position that can complete a triple
"""
triples = [(0,1,2),(1,2,0),(2,0,1),(3,4,5),(4,5,3),(5,3,4),(6,7,8),(7,8,6),(8,6,7),(0,3,6),(3,6,0),(6,0,3),(1,4,7),(4,7,1),(7,1,4),(2,5,8),(5,8,2),(8,2,5),(0,4,8),(4,8,0),(8,0,4),(2,4,6),(4,6,2),(6,2,4)]
def find_third(l, flist):
for i in triples:
if({i[0],i[1]}.issubset(l)):
if i[2] in flist:
return i[2]
return None
"""
Find a position that can complete a double, providing an opportunity to complete
a triple in the next play
"""
def find_second(clist, flist):
for i in triples:
if ({i[0]}.issubset(clist)):
if ({i[1],i[2]}.issubset(flist)):
pos = random.choice([i[1],i[2]])
return pos
return None
"""
Main loop
"""
def main_loop():
clist =[]
flist = [i for i in range(9)]
ulist = []
plist = ['-' for i in range(9)]
print ("Welcome to the game tic tac toe")
for i in range (9):
if (i%2 == 0):
a = find_third(clist, flist)
if (a == None ):
a = find_third(ulist, flist)
if(a == None):
a= find_second(clist, flist)
if(a == None):
a = random.choice(flist)
print("[Play",i,"] Computer occupied position",a)
occupy_list(clist,flist,a)
populate_list(plist,clist,'o')
print_list(plist)
if i >= 4:
if(winner(clist)):
print ("Computer won")
return
else:
position = input("Your position is:")
p1 = int(position)
if p1 < 0:
print ("Invalid choice: It should be a number between 0 and 8")
elif p1>8:
print ("Invalid choice: It should be a number between 0 and 8")
elif p1 not in (flist):
print ("Invalid choice: choose the unoccupied position")
else:
print("[Play",i,"]Your position is",p1)
occupy_list(ulist,flist,p1)
populate_list(plist,ulist,'X')
print_list(plist)
if i > 4:
if(winner(ulist)):
print ("You won")
return
print ("No winner")
if __name__ == '__main__':
main_loop()
|
revenue = int(input("Hello! Write your company's revenue "))
costs = int(input("Write your company's costs."))
if revenue>costs:
print("Great job! Revenue is bigger than costs!")
profit = revenue/costs
print(f"Your profitability is {profit}. ")
staff = int(input("How many staff in your company?"))
personal_rev =revenue/staff
print(f"revenue for person is {personal_rev}.")
elif revenue<costs
print("Unfortunetly, buzies in your company isn't great...")
|
#Profile
#--------------------------------------------Version1-------------------------------------------------------------------
def profile(name, surname, year, city, email, number):
print(name, surname, year, city, email, number)
profile("Masha", "Ivanova", "1910", "Moskow", "MI@mail.ru", "89102223322" )
#--------------------------------------------Version2-------------------------------------------------------------------
def profile(name, surname, year, city, email, number):
print(name, surname, year, city, email, number)
name1 = input("Input your name")
surname1 = input("Input your surname")
year1 = input("Input year")
city1 = input("Input city")
email1 = input("Input email")
number1 = input("Input your phone number")
profile(name1, surname1, year1, city1, email1, number1)
|
#--------------------------------------Version1-------------------------------------------------------------------------
the_list = []
"""
while True:
user_answer = input("Input numbers with space:").split(" ")
if user_answer == ["$"]:
print(sum(the_list))
break
elif "$" in user_answer:
is_enter = input("Press Enter to continue")
for i, item in enumerate(user_answer[:user_answer.index("$")]):
user_answer[i] = int(item)
total = sum(user_answer[:user_answer.index("$")])
the_list.append(total)
else:
is_enter = input("Press Enter to continue")
for i, item in enumerate(user_answer):
user_answer[i] = int(item)
total = sum(user_answer)
the_list.append(total)
print(sum(the_list))
"""
#--------------------------------------------------Version2-------------------------------------------------------------
def integer(inputin):
for i, item in enumerate(inputin):
inputin[i] = int(item)
the_list = []
while True:
user_answer = input("Input numbers with space:").split(" ")
if user_answer == ["$"]:
print(sum(the_list))
break
elif "$" in user_answer:
is_enter = input("Press Enter to continue")
integer(user_answer)
total = sum(user_answer[:user_answer.index("$")])
the_list.append(total)
else:
is_enter = input("Press Enter to continue")
integer(user_answer)
total = sum(user_answer)
the_list.append(total)
print(sum(the_list))
|
#TimeConverter
#Demonstrates sting format
sec = int(input("Whelcom to the TimeConverter! How many seconds would you like to convert? Please, don't write more 86399 seconds."))
hours = ((sec // 3600)) % 24
min = (sec // 60) % 60
sec_ = sec % 60
print('{0}:{1:=02}:{2:=02}'.format(hours, min, sec_)) |
class Worker:
def _init_(self, name, surname, profit, position, bonus):
self.name = name
self.surname = surname
self.position = position
self._income = {"profit": profit, "bonus": bonus}
class Position(Worker):
def get_full_name(self, name, surname):
name = name
surname = surname
full_name = (name + " " + surname)
def get_total_income(self):
total = sum(self._income.values())
return(total)
mr_worker = Position("Vasya", "Poopkin", 31000, "office_plankton", 15000)
print(f"{mr_worker.get_full_name()} is {mr_worker.position} earn {mr_worker.get_total_income()}") |
class Matrix:
def __init__(self, matr):
self.matr = matr
def __str__(self):
return str((([str[i] for i in k]).split("\t") for i in self.matr).split("\n"))
def __add__(self, other):
return Matrix([sum([self.matr[i][k]], [self.other[i][k]]) for i in range(len(self.matr))]
for k in range(len(self.matr[0])))
try:
stroki = int(input("Введите кол-во строк и столбцов матрицы"))
stolbiki = stroki
matrix1 = ([[i * k for k in range(stroki)] for i in range(stolbiki)])
matrix2 = ([[i + k for k in range(stroki)] for i in range(stolbiki)])
# print("\n", matrix1, "\n")
#print("\n", matrix2, "\n")
except:
ValueError
print("Пожалуйста, введите 1 число.") |
def main(): # 메뉴 선택 및 함수호출을 위한 메인함수
rows=3 # 행 값 3으로 지정
cols=5 # 열 값 5로 지정
kor_score=[] #
math_score=[] # 과목별 점수를 담아두기 위한 리스트
eng_score=[] #
midterm_score=[kor_score,math_score,eng_score] # 모든 점수를 담아두기 위한 리스트
midterm_score=[([0]*cols)for rows in range(rows)] # 리스트의 2차원 배열 크기 지정, 리스트 초기화
student_score=[0,0,0,0,0] # 평균 값을 담아두기 위한 리스트
menu = 0 # 메뉴 선택을 위한 변수
while True: # 종료 (9) 를 입력하기 전까지 반복하는 반복문
print("-----------------")
print("1. 성적입력") #
print("2. 평균계산") # 메뉴 선택 화면
print("3. 전체성적출력") #
print("9. 종료") #
menu=int(input("메뉴를 선택하시오: ")) # 선택 값을 입력받음
if menu==1: # 1을 입력받은 경우
kor_score,math_score,eng_score,midterm_score=add(kor_score,math_score,eng_score,midterm_score)
# add 함수를 불러와 return 값으로 각 과목별 성적과 모든 점수를 담은 리스트값을 반환받음
elif menu==2: # 2를 입력받은 경우
student_score=avg(midterm_score) # avg 함수에 앞에서 반환받은 점수 리스트를 대입하여 호출. 평균값을 반환받음
print(student_score) # 평균값 출력
elif menu==3: # 3을 입력받은 경우
print(midterm_score) # 모든 점수 출력
elif menu==9: # 9를 입력받은경우
print("프로그램을 종료합니다.")
break # 반복 루프 탈출, 프로그램 종료
else: # 이외의 값을 입력받은 경우
print("잘못된 입력입니다.")
def avg(a): # 평균값을 계산하는 함수, 인수로 전체 점수 사용
rows=5 # 행 값 5로 지정
cols=3 # 열 값 3으로 지정
s=[0,0,0,0,0] # 점수의 합을 담아두기 위한 리스트
average=[0,0,0,0,0] # 평균값을 담아두기 위한 리스트
for i in range(rows): #
for j in range(cols): # 반복문을 통해 점수 리스트에서
value=a[j][i] # 필요한 점수들을 불러와 합하여
s[i]+=value # s 리스트에 저장.
val=s[i]/3 # 저장된 s 리스트의 합을 3으로 나누어 구한
average[i]+=val # 평균값을 average에 저장
return average # 평균값 반환
def add(k,m,e,a): # 성적을 입력하는 함수
k=[] #
m=[] # 과목별 성적을 담아두는 리스트
e=[] #
a=[k,m,e] # 전체 성적을 담아두는 리스트
t=['국어','수학','영어'] # 성적을 입력받을 때 출력할 과목명 리스트
for i in range(3): #
print(t[i]) # 주기별로 과목명 출력
for j in range(5): #
print("성적 [",j,end="") #
value=int(input(" ] 입력:")) # 성적 입력받음
a[i].append(value) # 입력받은 성적을 a리스트에 저장
print("") # 줄바꿈을 위한 공백 출력
return k,m,e,a # 과목별 성적 리스트와 전체 성적 리스트를 반환
if __name__=="__main__":
main() # 메인함수 호출 |
#mad lib game.
#you add a random word where prompted. A paragraph is then printed out using these random words, can be very funny.
verb = input("verb: ")
verb2 = input("verb: ")
verb3 = input("verb: ")
verb4 = input("verb: ")
verb5 = input("verb: ")
verb6 = input("verb: ")
noun = input("noun: ")
noun2 = input("noun: ")
noun3 = input("noun: ")
noun4 = input("noun: ")
noun5 = input("noun: ")
noun6 = input("noun: ")
adj = input("adjective: ")
adj2 = input("adjective: ")
adj3 = input("adjective: ")
instrument = input("name a musical instrument: ")
instrument2 = input("name a musical instrument: ")
animal = input("name an animal: ")
#using string concatenation the paragraph will be returned with the new inputted words in it.
music_class = f"Make some noise in music class... I like music class because we get to {verb} and {verb2} really loudly.
There are all sorts of {noun} to play, like the {adj} {noun2} and the {noun3}. My instrument is the {adj2} {instrument},
which sounds a lot like a {animal}. We are learning to {verb3} a song by The {noun4} called, I {verb4} to {verb5} with You,
using {instrument2} and {noun5}. When we all {verb6} together, it sounds like a {adj3} group of {noun6}."
print(music_class) |
print('{:=^40}'.format(' PROGRESSÃO ARITMÉTICA '))
primeiro = int(input('Informe o primeiro termo: '))
razão = int(input('Informe a razão da PA: '))
termo = primeiro
cont = 1
while cont <= 10:
print('{} → '.format(termo), end='')
termo += razão
cont += 1
print('Fim')
|
salario = float(input('Qual é o salário? '))
if salario > 1250:
nsalario = salario * 1.10
else:
nsalario = salario * 1.15
print('Quem ganhava R${:.2f} passa a ganhar R${:.2f} agora.'.format(salario, nsalario))
|
from random import randint
from time import sleep
computador = randint(0,10)
print('-=-' * 20)
print('Vou pensar em um número entre 0 a 10. Tente adivinhar...')
print('-=-' * 20)
acertou = False
tentativas = 0
while not acertou:
jogador = int(input('Em que número eu pensei? '))
tentativas += 1
if computador == jogador:
acertou = True
elif jogador < computador:
print('Mais... Tente novamente.')
elif jogador > computador:
print('Menos... Tente novamente.')
print('\nVocê ACERTOU! E precisou de {} tentativas.'.format(tentativas))
|
print('{:=^40}'.format('TABUADA'))
n = int(input('Digite um número para ver a sua tabuada: '))
print('-' * 13)
for c in range (1, 11, 1):
print('{} x {:2} = {}'.format(n, c, n * c))
print('-' * 13) |
from random import randint
from time import sleep
print('-=-' * 20)
print('Vou pensar em um número entre 0 e 5. Tente adivinha...')
print('-=-' * 20)
computador = randint(0, 5) #Computador "pensa" em um número
jogador = int(input('Em que número eu pensei? ')) #jogador tenta adivinhar
print('PROCESSANDO...')
sleep(3)
if jogador == computador:
print('PARABÉNS! Você me venceu!')
else:
print('GANHEI! Eu pensei no número {} e não no número {}'.format(computador, jogador))
|
from operator import add
from functools import reduce
prices = [
(6.99, 5),
(2.94, 15),
(156.99, 2),
(99.99, 4),
(1.82, 102)
]
# We have a bunch of prices and sales numbers and wee need to find out our total earnings.
# Let's start by writing a function named product_sales that takes a single two-member tuple made up of a price
# and a number of units sold.
# product_sales should return the product of the price and the number of units
def product_sales(info):
return info[0] * info[1]
# We need to add two numbers together.
# We could write a function that does this but that seems silly.
# Import add from the operator module.
# Import reduce() from functools
# We're ready to find out totals
# Create a variable named total
# Use map() to find the per-product totals for each item in prices
# Then use reduce(and add) to find the total value
total = reduce(add, map(product_sales, prices)) |
from timeit import default_timer
import re
def is_match(scramble, word):
word = list(word)
for letter in scramble:
if letter in word:
word.remove(letter)
if len(word) == 0:
return True
return False
def parse_dictionary(filename, scramble):
anagrams = list(list() for i in range(len(scramble) - 1))
with open(filename) as dictionary:
for word in dictionary:
word = word.rstrip()
if len(scramble) >= len(word):
if is_match(scramble, word):
anagrams[len(word) - 2].append(word)
return anagrams
def main():
scramble = input("Enter up to nine letters: ")
if not scramble.isalpha():
print("Enter letters only.")
return
if len(scramble) > 9:
print("Enter up to nine letters only.")
return
start = default_timer()
anagrams = parse_dictionary("dictionary.txt", scramble)
end = default_timer()
j = 0
for i in range(len(anagrams) - 1, -1, -1):
if j < 3:
if anagrams[i]:
j += 1
print(i + 2, "letter words:", ', '.join(anagrams[i]))
if j == 0:
print("There were no anagrams found for those letters.")
else:
print("Time taken: {}{}".format(end - start, 's'))
if __name__ == "__main__":
main() |
# coding: utf-8
# Task description
"""
A zero-indexed array A consisting of N different integers is given.
The array contains integers in the range [1..(N + 1)], which means that exactly
one element is missing.
Your goal is to find that missing element.
Write a function:
def solution(A)
that, given a zero-indexed array A, returns the value of the missing element.
For example, given array A such that:
A[0] = 2
A[1] = 3
A[2] = 1
A[3] = 5
the function should return 4, as it is the missing element.
Assume that:
N is an integer within the range [0..100,000];
the elements of A are all distinct;
each element of array A is an integer within the range [1..(N + 1)].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
"""
# Code
def solution(A):
return sum(xrange(1, len(A) + 2)) - sum(A)
# Verification
if __name__ == "__main__":
from random import choice, shuffle
def seq_without_one_element(count):
""" Function for generated sequence without random element.
:return: sequence, random number
"""
seq = range (1, count + 1)
shuffle(seq)
random_elem = choice(seq)
seq.remove(random_elem)
return seq, random_elem
assert solution([2, 3, 1, 5]) == 4
assert solution([]) == 1
assert solution([2]) == 1
assert solution([3, 5, 4, 1, 2]) == 6
assert solution([3, 5, 4, 2]) == 1
assert solution([1, 3]) == 2
seq, number = seq_without_one_element(10000)
assert solution(seq) == number
seq, number = seq_without_one_element(100000)
assert solution(seq) == number
|
#ΕΡΓΑΣΙΑ: 9
#Γράψτε ένα πρόγραμμα σε Python το οποίο παίρνει έναν αριθμό τον τριπλασιάζει, προσθέτει ένα και στην συνέχεια προσθέτει τα ψηφία του. Η διαδικασία επαναμβάνεται μέχρι ο αριθμός να γίνει μονοψήφιος
num =int( input('Give a number:'))
digitsum = 0
num = num * 3 + 1
while len(str(num)) > 1 :
listnum=str(num)
listnum=list(listnum)
for i in listnum:
digitsum= digitsum + int(i)
num = digitsum
digitsum=0
print(num)
print ('to teliko noymero einai:',num)
|
#1- Ler uma variável numérica n e imprimi-la somente se a mesma for maior que 100, caso contrário imprimi-la com o
#valor zero.
n=int(input('Insira um número: '))
while n <= 100:
print('Numero menor que 100')
n=int(input('Insira um número: '))
else:
print('OK, número maior que 100, o número é {0}'.format(n))
|
##6- Faça um algorítmo que pergunte quanto você ganha por hora e o número de horas trabalhadas ao mês.
##Calcule e mostre o total do seu salário no referido mês.
#Insira a quantidade de horas que você trabalha por mês
#Insira o valor que você ganha por hora trabalhadas
#Multiplique a quantidade de horas pelo valor da hora
#Mostre o resultado
horas=input('Insira a quantidade de horas que você trabalha por mês: ')
valor=input('Insira o quanto você ganha por hora trabalhada: ')
salário=int(horas)*int(valor)
print('Seu salário mensal deve ser de R$',salário)
print('Seu salário mensal deve ser de R$ {0}'.format(salário))
|
#5- Faça um programa que leia um nome de usuário e sua senha e não aceite a senha igual ao nome de usuário, mostrando uma mensagem de erro
#e voltando a pedir as informações.
nome=input('Digite seu nome: ')
senha=input('Digite sua senha: ')
while senha == nome:
print('Senha não pode ser igual ao seu nome.')
nome=input('Digite seu nome: ')
senha=input('Digite sua senha: ')
else:
print('Login efetuado!')
|
##3- Teste o algorítmo anterior com os dados definidos por você
#estoquemédio= quantminima + quantmaxima) / 2
#_________________________________________________________
#| Quantidade mínima | Quantidade máxima | Estoque médio |
#|--------------------------------------------------------
#| 10 | 10 | 10 |
#|--------------------------------------------------------
#| 13 | 87 | 50 |
#---------------------------------------------------------
quantminima=input('Insira a quantidade mínima do estoque: ')
quantmaxima=input('Insira a quantidade máxima do estoque: ')
média=(int(quantminima)+int(quantmaxima))/2
print('A média do estoque é: {0}'.format(int(média)))
|
class Bank:
def __init__(self,customers:[],numberOfCustomers:int,bankName:str):
self.__customers = customers
self.__numberOfCustomers = numberOfCustomers
self.__bankName = bankName
def Bank(self):
return self.__bankName
def addCustomer(self,firstName,lastname):
self.__customers.append(firstName + " " + lastname)
return self.__customers
def getNumOfCustomers(self):
return self.__numberOfCustomers
def getCustomer(self,index):
return self.__customers[index]
class Customer:
def __init__(self,firstName:str,lastname:str):
self.__firstName = firstName
self.__lastname = lastname
self.__account = Account(0)
def getFirstName(self):
return self.__firstName
def getLastName(self):
return self.__lastname
def getAccount(self):
return self.__account
def setAccount(self,account):
self.__account = account
class Account:
def __init__(self,balance:float):
self.__balance = balance
def getBalance(self):
return self.__balance
def deposit(self,ammount):
self.__balance += ammount
def withdraw(self,ammount):
if self.__balance < ammount:
return False
else:
self.__balance -= ammount
return True
Account1 = Account(100.0)
Customer1 = Customer('anjay','asyik')
Bank1 = Bank([],3,'ashiap')
print(Bank1.getNumOfCustomers())
print(Bank1.addCustomer('wkwkw','hehe'))
|
#!/usr/bin/env python3
import numpy as np
from matplotlib import image, pyplot
def shift(red: int, green: int, blue: int):
scalars = np.array([red, green, blue])
def func(rgb: np.array):
rgb[:] = np.multiply(rgb, scalars)
return func
def experiment():
trees = "resource/smaller.jpg"
trees = np.array(image.imread(trees), dtype=float)
np.apply_along_axis(shift(0.8, 0.5, 1.2), 2, trees)
trees = trees.astype(int)
# print(trees)
pyplot.imshow(trees)
pyplot.show()
if __name__ == "__main__":
experiment()
|
print('Задание № 1')
def hello_user():
try:
while True:
user_say = input('Как дела ? ')
user_say = user_say.capitalize()
if user_say == 'Хорошо':
break
else:
print(f'Сам ты {user_say}')
except KeyboardInterrupt:
print('Пока', end= print())
hello_user()
print('Задание № 2')
faq = {
'Как дела': 'Хорошо!',
'Что делаешь':'Прогриммирую',
}
def ask_user():
while True:
question = input('Спроси меня: ')
if question in faq:
print(faq[question])
break
else:
print('Спроси еще что нибудь')
ask_user() |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 24 19:03:43 2020
@author: Asifulla K
"""
#pattern
print("*")
print("* * *")
print("* * * *")
print("* * *")
print("*")
print()
#for any number of input
str1="6"
str2=str1*2
str3=str1*3
str4=str1*4
str5=str1*3
str6=str1*1
print(str1)
print(str2)
print(str3)
print(str4)
print(str5)
print(str6)
|
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 13 09:22:21 2020
@author: Asifulla K
"""
#Write a function that prints out the odd numbers 1 through 99. Bonus: Use list comprehension.
# list of numbers
list1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,6263,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99]
only_odd = [num for num in list1 if num % 2 == 1]
print(only_odd)
print()
#Write a function that takes in a dictionary and outputs the most frequent value in the dictionary.
input_dict = {'A': 1963, 'B': 1963,
'C': 1964, 'D': 1964, 'E': 1964,
'F': 1965, 'G': 1965, 'H': 1966,
'I': 1967, 'J': 1967, 'K': 1968,
'L': 1969 ,'M': 1969,
'N': 1970}
trk={}
for key,value in input_dict.items():
if value not in trk:
trk[value]=0
else:
trk[value]+=1
print(max(trk,key=trk.get))
print()
#Write a function to reverse a string. The string can be of any length and might be empty. Bonus: Implement recursively.
def reverse(string):
if len(string) == 0:
return string
else:
return reverse(string[1:]) + string[0]
a = str(input("Enter the string to be reversed: "))
print(reverse(a))
print()
#Write a function that takes in two sorted lists and merges them (don’t use any Python built in functions or methods, such as the list.sort method). So the input ([1, 5, 8], [4, 7, 10, 12]) should yield the output [1, 4, 5, 7, 8, 10, 12]. The lists may not be of the same length, and one or both may be empty.
a = [1, 5, 8]
b = [4, 7, 10, 12]
c=a+b
c.sort()
print(a)
print(b)
print(c) |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 8 20:25:50 2020
@author: Asifulla K
"""
result_str=""
for row in range(0,7):
for column in range(0,7):
if(((column==1 or column==5) and row!=0) or ((row==0 or row==3) and (column>1 and column<5))):
result_str=result_str+"*"
else:
result_str=result_str+" "
result_str=result_str+"\n"
print(result_str) |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 21:46:22 2020
@author: Asifulla K
"""
str1="Abc"
str2="Xyz"
print(str1)
print(str2)
print(str1[0])
print(str2[2])
print(str1[1])
print(str2[1])
print(str1[2])
print(str2[0])
|
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 13 20:41:35 2020
@author: Asifulla K
"""
#inbuilt functions in lists
a=[10,50,30,40,20]
print(min(a))
print(max(a))
print(len(a))
print(all(a))
b=[5,99,88,0,77]
#all
print(all(a))
#any
print(any(b))
c=[0,0,0,0,0]
print(any(c))
#sorted func
sorted(a)
print(a)
sorted(b, reverse = True)
print(b)
|
a=int(input("A:"))
b=int(input("B:"))
c=int(input("C:"))
if((a>=b)and(a>=c)):
print("A is larger than B and C")
elif((b>=a)and(b>=c)):
print("B is larger than A and C")
else:
print("C is larger than A and B") |
# 条件判断和循环语句
# 逻辑运算符:and or not 两个表达式进行判断
# 1,and:两个表达式都为真的时候,才为真,否则为假
# print(40<60 and 60>40)
# print(40>60 and 60>40)
# 2,or:两个表达式只要一个条件为真,就为真
# print(40<60 and 60>40)
# 3,not:a表达式,a为真的时候,输出的就是假,全部为假的时候就为真
# print(not 70<60)
# 成员运算符: in not in 在字符中找值 in 在...里面, not in 不在.....里面
# 身份运算符: is not is 对于标识符是不是同一对象 id() 内存地址
# if判断:如果条件满足的话,就这这件事情,否则,就做另外一件事,或者什么都不做
'''
if 条件:
条件满足的事情
else:
条件不满足的事情
'''
# 条件:如果年龄达到18岁,就允许进入网吧,否则就回家睡觉
# age = 19
# if age >= 18:
# print('允许网吧上网')
# else:
# print('回家睡觉')
# 对这个判断进行升级,想在控制台输出年龄 input()实现
# age = int(input('请输入年龄:'))
# if age >= 18:
# print('允许网吧上网')
# else:
# print('回家睡觉')
# 字符串 ’yuchen' 判断yu是否在其中,用in
# a = 'yuchen'
# if 'yu' in a:
# print('真可爱')
# else:
# print('真讨厌')
# 判断是不是同一个内存地址 is 内存地址不是同一个
# a = 123
# b = 123
# if a is b:
# # if '123' is '123':
# print('我们是同一个人')
# else:
# print('搞错了,再来')
# 多重if判断:多个条件判断
'''
if 条件1:
执行的事情
elif 条件2:
执行的事情
...
else:
执行的事情
'''
# grade = int(input('请输入成绩:'))
# if grade >= 90:
# print('你是厉害的')
# elif grade>=80:
# print('你就是优秀的')
# elif grade >=70:
# print('你就是中等的')
# elif grade >60:
# print('你还需继续努力')
# else:
# print('不及格')
# if嵌套:在条件满足的时候再加条件
# 格式:
'''
if 条件:
if 条件:
要执行的事情
else:
要执行的事情
else:
要执行的事情
'''
# grade = int(input('请输入成绩:'))
# if grade >60:
# if grade >90:
# print('你是优秀的')
# elif grade >80:
# print('你是中等的')
# else:
# print('你是及格的')
# else:
# print('你是不及格的')
# 循环:特定的一些事情重复执行
# 两种格式:while for
'''
while格式:
while 条件:
循环的内容
'''
# 第一个简单的while循环 打印5次hello world
# i = 1
# while i <= 5:
# print('hello world')
# i = i+1
# 联系:0+1+2+3+。。。。+100
# i=0
# sum = 0
# while i <= 100:
# sum = sum+i
# i = i+1
# print(sum)
# 在循环中有break和continue
# break 当某一个条件满足时,退出循环,不执行后面的代码
# continue 当某一个条件满足时,退出循环,执行后面的代码,continue中要加逻辑
# 如:打印1-10的数字,循环7时,就不打印,不打印3
# i= 0
# while i <=10:
# if i == 7:
# break
# i = i+1
# print(i)
# i= 0
# while i <=10:
# if i == 3:
# i = i+1
# continue
# print(i)
# i = i+1
# for i in range(10):
# if i ==3:
# continue
# print(i)
# 嵌套循环:循环中加循环 while for
# 题目
'''
*
**
***
****
*****
'''
# 第一种:
# for i in range(5):
# i = i + 1
# print('*'*i)
# 第二种:
# i = 0
# while i <5:
# i = i + 1
# print('*'*i)
# 嵌套循环
# i = 0
# while i <=5:
# j = 0
# while j < i:
# print('*',end='')
# j = j+1
# print('*')
# i = i+1
# for i in range(5):
# for j in range(i):
# print('*',end='')
# print('*')
# while后面加else
'''
while 条件:
循环语句
else:
语句
'''
# i = 0
# while i <=5:
# j = 0
# while j < i:
# print('*',end='')
# j = j+1
# print('*')
# i = i+1
# else:
# print('循环结束,我就执行')
# 如果循环终止了,就不会打印else
# i = 1
# while i <=5:
# if i == 3:
# i = i + 1
# break
# print(i)
# i = i + 1
# else:
# print('循环终止,就不打印else语句')
# for 循环
# 集合包括:元组,列表,字典 range(开始值,结束值)左闭右开
'''
格式:
for 变量名 in 集合:
循环体
'''
# 循环5次 hello world
# for i in range(5):
# print('hello world')
# list = ['a,','b','c']
# for i in list:
# print(i)
# tou = ('a,','b','c',[1,2,3])
# for i in tou:
# print(i)
# while循环不知道次数,for循环知道次数,集合
# 题目:求和 1+2+3+....+100
sum = 0
for i in range(1,101):
sum = sum+i
print(sum)
|
#异常:在程序运行过程中,如果报错了,就会停止,抛出错误信息
# 程序停止并且提示错误信息这个过程就叫做抛出异常
#异常:为了程序的稳定性和健壮性 异常处理:针对突发情况做集中的处理
'''
语法结构:
try:
尝试代码
except:
出现错误的处理
except Exception as e:
错误处理
程序中不确定会不会出现问题的代码,就写try
如果程序出现问题,就执行except里面的代码
'''
#题目:要求用户输入整数
# 用户输入 input 默认string字符串格式,int转型
# try:
# num = int(input('请输入数字:'))
# print(num)
# except:
# print('请输入正确数字')
# 输入一个数字进行整除
# try:
# num = int(input('请输入数字:'))
# res = 2/num
# print(res)
# except ZeroDivisionError:
# print('不能除0')
# except ValueError:
# print('请输入正确的数字')
from time import time
'''
类型:
indexError 下标索引出现问题
keyError 字典里面的键有问题
TypeError 对象的类型有问题
IOError 文件打开或关闭流错误有问题
'''
# 对未知的异常进行处理 Exception
# try:
# num = int(input('请输入数字:'))
# res = 2/num
# print(res)
# except Exception as e:
# print(e)
#异常可以进行传递
# def demo1():
# a = int(input('请输入数字:'))
# return a
#
# try:
# res = demo1()
# print(res)
# except Exception as e:
# print(e)
# 异常在函数里面处理
# def demo2():
# try:
# a = int(input('请输入数字:'))
# return a
# except Exception as e:
# return e
#
# print(demo2())
#try except 作用就是用来捕获错误信息,捕获到错误的信息,会保存在日志中
'''
完整的语法结构: 用的少
try:
尝试代码
except:
出现错误的处理
except Exception as e:
错误处理
else:
没有异常的代码会执行
finally:
无论程序有没有问题都会被执行
'''
'''
语法结构: raise异常,主动抛异常,用于特定的需求
需求:定义一个函数,函数提示输入用户密码
如果用户输入的密码长度<8,抛出异常
如果用户出入的长度>=8,返回输入的密码
'''
# def input_pwd():
# pwd = input('请输入密码:')
# if len(pwd) >=8:
# return pwd
# exx = Exception('密码错误')
# raise exx
#
# a = input_pwd()
# print(a)
# 时间 :用于日志,测试报告,订单生成
# 时间:时间戳--描述从某一个时间点到另一个时间相隔的描述 某个时间指的是:1970年1月1日0时0分0秒
# 导包 time
import time
import datetime
import calendar
# 获取当前时间戳
# print('当前时间戳:',time.time())
# 做日期运算
# 时间元组:用9个数字表示起来的,放在元组中,(年,月,日,时,分,秒,一周第几天(0-6,0指周一),一年的第几天,夏令时)
t = (2021,7,3,22,37,30,3,322,0)
# print(t)
# 用代码表示,(tm_year=, tm_mon=, tm_mday=, tm_hour=, tm_min=, tm_sec=, tm_wday=, tm_yday=, tm_isdst=)
# print('当前元组:',time.localtime())
# print('当前元组:',time.localtime(time.time()))
# 元组转换为时间 time.asctime()
# print('以英文的方式转换为时间:',time.asctime(time.localtime()))
# print('以英文的方式转换为时间:',time.asctime(time.localtime(time.time())))
# 时间改为系统时间 time.strftime()
# print('当前系统时间:',time.strftime('%Y-%m-%d %H:%M:%S'))
# 元组转为时间戳 time.mktime()
# 指定时间转换为时间戳 2021 3 12
# print('指定时间转换为时间戳:',time.mktime((2021,7,3,0,0,0,0,0,0)))
# 当前时间转换为时间戳
# print('当前时间转换为时间戳:',time.mktime(time.localtime(time.time())))
# print('当前时间转换为时间戳:',time.mktime(time.localtime()))
# 时间戳转为元组 time.time()时间戳
# print('当前时间戳转为元组',time.localtime(time.time()))
# 指定日期转为时间格式 2021-07-03 22:56:40 datetime 扩展
# time_str = '2021 07 03 22:56:40'
# print(datetime.datetime.strptime(time_str,'%Y-%m-%d %H:%M:%S'))
# 日历 Calendar模块 日历年历月历
# 月历
mon = calendar.month(2021,4)
# print(mon)
# 年历
cal = calendar.calendar(2021)
# print(cal)
'''
局部变量和全局变量:
局部变量:定义在方法中
全局变量:定义在方法外,公共的,都可以使用
变量的生命周期:
从函数执行开始,变量创建,函数执行完了,生命周期没了,变量就死了
'''
num = 20
def demo1():
# 希望局部变量能修改全局变量,用关键字global
global num
num = 10
print('函数demo1:',num)
def demo2():
print('函数demo2:',num)
demo1()
demo2()
|
# factorial
def factorial(number):
result = 1
while(number>0):
result = result * number
number = number - 1
return result
print factorial(5)
|
def formula(a,b):
if(b == 0):
print "You can not divide by zero"
else:
return (a+b)/b
print formula(4,4)
print formula(2,0)
|
file_obj = open("file.txt","r")
word_list=file_obj.read().lower().split()
print sorted(word_list)
|
import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
a = 0
b = 1
c = 0
logging.debug("a,b successfully initialized")
no = input("Enter range ")
if(no>100 or no<10):
logging.warning('no. too big .....will take some time')
logging.error("Technical error!")
exit()
else:
logging.info('no. in range, execution started')
while(c < no):
a = b
b = c
print c
c = a+b
logging.info("Finished")
|
import pygame
from pygame.locals import *
import random, math, sys
import time
pygame.init()
#initialize and create some variables
songs = ['Elevator Music.mp3', 'Finisher_2.mp3']
pygame.mixer.music.load('assets/audio/' + songs[0])
pygame.mixer.music.play()
width, height = 800, 500
Surface = pygame.display.set_mode((800,500))
bg = pygame.image.load("assets/images/pooltable.png")
bg = pygame.transform.scale(bg,(800,500))
#colors
red = (255,0,0)
green = (0,200,0)
white = (255,255,255)
black = (0,0,0)
blue = (0,0,250)
brown = (165,42,42)
pink = (255,200,200)
#defining what a ball is
#JAMES'S CODE ---------------------------------------------------
class Ball:
def __init__(self,x,y,c):
self.radius = 10
self.color = c
self.position = Vector(x, y)
self.velocity = Vector(0, 0)
self.mass = 1
#here we define a vector class which will make our lives much easier, here we can rewrite operators that deal with these vectors and make our own
#much thanks to a CS student named Dhruba Ghosh who recommended the idea of utilizing a vector based approach. Will be acknowledged in
#our write up.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
#all the properties of vectors and the tools we can use with them. We could use numpy, but this made more intuitive sense to make our own
#class, and rewrite our own operators. It is nice to stay consistent with the class and object style from before with the balls.
def len(self):
return math.sqrt(self.x*self.x + self.y*self.y)
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return Vector(self.x * other, self.y * other)
def __rmul__(self, other):
return Vector(self.x * other, self.y * other)
def __truediv__(self, other):
return Vector(self.x / other, self.y / other)
def angle(self):
return math.atan2(self.y, self.x)
def norm(self):
if self.x == 0 and self.y == 0:
return Vector(0, 0)
return self / self.len()
def dot(self, other):
return self.x*other.x + self.y*other.y
#make a list of balls
queball = Ball(222,250,white)
queball.mass = 0.9
striped_1 = Ball(410,250,red)
striped_2 = Ball(483,295,red)
striped_3 = Ball(429,239,red)
striped_4 = Ball(447,272,red)
striped_5 = Ball(483,205,red)
striped_6 = Ball(465,217,red)
striped_7 = Ball(483,250,red)
solid_1 = Ball(465,261,blue)
solid_2 = Ball(465,239,blue)
solid_3 = Ball(447,228,blue)
solid_4 = Ball(429,261,blue)
solid_5 = Ball(483,273,blue)
solid_6 = Ball(465,283,blue)
solid_7 = Ball(483,227,blue)
solid_8 = Ball(447,250,black)
Balls = [queball,
striped_1,
striped_2,
striped_3,
striped_4,
striped_5,
striped_6,
striped_7,
solid_1,
solid_2,
solid_3,
solid_4,
solid_5,
solid_6,
solid_7,
solid_8]
def Game_won():
if len(Balls) == 1:
return True
else:
return False
def play_next():
global songs
songs = songs[1:] + [songs[0]]
pygame.mixer.music.load(songs[0])
pygame.mixer.music.play()
#JAMES'S CODE ---------------------------------------------------
#FRENLY'S CODE --------------------------------------------------
class QueStick:
def __init__(self):
self.color = brown
self.position1 = Vector(0,0)
self.position2 = Vector(0,0)
self.position3 = Vector(0,0)
self.position4 = Vector(0,0)
que = QueStick()
#FRENLY'S CODE --------------------------------------------------
#DARBY'S CODE ---------------------------------------------------
class Pocket:
def __init__(self,x,y):
self.radius = 20
self.x = x
self.y = y
#setting the pocket's locations
rtpocket = Pocket(50,50)
mtpocket = Pocket(400,40)
ltpocket = Pocket(750,50)
rbpocket = Pocket(50,450)
mbpocket = Pocket(400,460)
lbpocket = Pocket(750,450)
pockets = [rtpocket, mtpocket, ltpocket, rbpocket, mbpocket, lbpocket]
def pocket_collision():
for ball in Balls:
x2,y2 = ball.position.x, ball.position.y
if ball != queball and ball != solid_8:
for poc in pockets:
distance = math.hypot(poc.x-x2, poc.y-y2)
if distance <= (poc.radius)+(ball.radius):
Balls.remove(ball)
elif ball == queball:
for poc in pockets:
distance = math.hypot(poc.x-x2, poc.y-y2)
if distance <= (poc.radius)+(ball.radius):
ball.position = Vector(222,250)
ball.velocity = Vector(0,0)
elif ball == solid_8:
if len(Balls) >= 1:
for poc in pockets:
distance = math.hypot(poc.x-x2, poc.y-y2)
if distance <= (poc.radius)+(ball.radius):
print("GAME OVER!")
Balls.remove(ball)
queball.position = Vector(100,250)
striped_1.position = Vector(410,250)
striped_2.position = Vector(483,295)
striped_3.position = Vector(429,239)
striped_4.position = Vector(447,272)
striped_5.position = Vector(483,205)
striped_6.position = Vector(465,217)
striped_7.position = Vector(483,250)
solid_1.position = Vector(465,261)
solid_2.position = Vector(465,239)
solid_3.position = Vector(447,228)
solid_4.position = Vector(429,261)
solid_5.position = Vector(483,273)
solid_6.position = Vector(465,283)
solid_7.position = Vector(483,227)
solid_8.position = Vector(447,250)
queball.velocity = Vector(0,0)
striped_1.velocity = Vector(0,0)
striped_2.velocity = Vector(0,0)
striped_3.velocity = Vector(0,0)
striped_4.velocity = Vector(0,0)
striped_5.velocity = Vector(0,0)
striped_6.velocity = Vector(0,0)
striped_7.velocity = Vector(0,0)
solid_1.velocity = Vector(0,0)
solid_2.velocity = Vector(0,0)
solid_3.velocity = Vector(0,0)
solid_4.velocity = Vector(0,0)
solid_5.velocity = Vector(0,0)
solid_6.velocity = Vector(0,0)
solid_7.velocity = Vector(0,0)
solid_8.velocity = Vector(0,0)
elif len(Balls) == 0:
for poc in pockets:
distance = math.hypot(poc.x-x2, poc.y-y2)
if distance <= (poc.radius)+(ball.radius):
print("YOU WIN!")
Balls.remove(ball)
#calculate the number of sunk balls by color (prints on screen)
red_balls = []
blue_balls = []
for ball in Balls:
if ball.color == red:
red_balls.append(ball)
if ball.color == blue:
blue_balls.append(ball)
def score():
x = len(red_balls)
y = len(blue_balls)
pocket_collision()
red_balls_2 = []
blue_balls_2 = []
for ball in Balls:
if ball.color == red:
red_balls_2.append(ball)
if ball.color == blue:
blue_balls_2.append(ball)
x_new = len(red_balls_2)
y_new = len(blue_balls_2)
score_red = x - x_new
score_blue = y - y_new
return score_red, score_blue
#DARBY'S CODE -------------------------------------------------
#JAMES'S CODE -------------------------------------------------
#resolve collisions between 2 balls, the most confusing part of project, so lots of comments will be added to guide the reader.
def BallsCollide(C1,C2):
#these factors are to add realism. Ellasticity is usually a little less than 1 because of the loss of energy
#due to friction, sound, and heat.
#for fun try and manipulate this factor, will deviate from real collision mechanics
ELASTICITY = 0.95
#we define the center to be the average of the two positions
#diff is just a unit vector of the difference between their position vectors. Diagram will make more sense in write up
center = (C1.position + C2.position) / 2
diff = (C2.position - C1.position).norm()
C1.position = center - diff * C1.radius
C2.position = center + diff * C1.radius
#update their positions according to this new frame
#we calculate the new speeds that are attributing to the collision (see diagram) to be just a dot product of velocity vector with the
#difference unit vector
speed_1 = C1.velocity.dot(diff)
speed_2 = C2.velocity.dot(diff)
#the effective impulse from the collision is just the other balls effective speed (times the mass and ellasticity factors) - that balls speed
Impulse_1 = speed_2 * (2*C2.mass)/(C1.mass+C2.mass) - speed_1
Impulse_2 = speed_1 * (2*C1.mass)/(C2.mass+C1.mass) - speed_2
#the new velocity vectors are just the effective impulse (time ellasticity factor) in the unit difference vector added to the original velocity vector
C1.velocity = C1.velocity + diff * Impulse_1 * ELASTICITY
C2.velocity = C2.velocity + diff * Impulse_2 * ELASTICITY
#the function we call to calculate movement
def Move(secs):
for ball in Balls:
friction = 1200 #friction is a big value simply because we are multiplying by seconds
#basically if if a ball is moving with a magnitude v, then if v < friction stop moving. if v >= friction*secs(fraction of a second)
#then we multiply friction factor to the unit vector in the direction of v and subtract
ball.position = ball.position + ball.velocity * secs
speed = ball.velocity.len()
if speed < friction * secs:
ball.velocity = Vector(0, 0)
else:
ball.velocity = ball.velocity - ball.velocity * (friction / speed * secs)
#this function is the way we detect a collision has occured
def CollisionDetect():
for ball in Balls:
Circle = ball
#collision with a wall, checks if ball is out of bounds and flips it back. So the balls dont roll off screen (50 is the edge of table)
if Circle.position.x < Circle.radius + 50 and Circle.velocity.x < 0:
Circle.velocity.x *= -1
if Circle.position.x > width-Circle.radius-50 and Circle.velocity.x > 0:
Circle.velocity.x *= -1
if Circle.position.y < Circle.radius + 50 and Circle.velocity.y < 0:
Circle.velocity.y *= -1
if Circle.position.y > height-Circle.radius-50 and Circle.velocity.y > 0:
Circle.velocity.y *= -1
#loop through all the balls and check if there was a collision between that ball and another, careful not to over account for it by counting twice
for i in range(len(Balls)):
for j in range(i+1,len(Balls)):
Circle = Balls[i]
Circle2 = Balls[j]
#we find the length of the vector between the two balls, if that is greater than both their radii then dont collide, otherwise
#we call our collision function to tell the balls what to do
if (Circle.position - Circle2.position).len() <= (Circle.radius+Circle2.radius):
BallsCollide(Circle,Circle2)
#JAMES'S CODE -------------------------------------------------------
#DARBY'S CODE -------------------------------------------------------
sound1 = pygame.mixer.Sound("assets/audio/poolballhit.wav")
sound2 = pygame.mixer.Sound("assets/audio/billiards+2.wav")
sound3 = pygame.mixer.Sound("assets/audio/Billiards+3.wav")
sound4 = pygame.mixer.Sound("assets/audio/poolhall.wav")
sounds = [sound1, sound2, sound3, sound4]
random_num = random.randrange(0,3)
random_sound = sounds[random_num]
pygame.mixer.Sound.play(random_sound)
#DARBY'S CODE -------------------------------------------------------
#JAMES'S CODE -------------------------------------------------------
#Our drawing function
def Draw():
clock = pygame.time.Clock()
Surface.blit(bg,(0,0))
for ball in Balls:
pygame.draw.circle(Surface,ball.color,(int(ball.position.x),int(ball.position.y)),ball.radius)
queball = Balls[0]
speed = queball.velocity.len()
if speed == 0:
pygame.draw.line(Surface,que.color,[que.position1.x,que.position1.y],[que.position2.x,que.position2.y],7)
pygame.draw.line(Surface,white,[que.position3.x,que.position3.y],[que.position4.x,que.position4.y],1)
if Balls[len(Balls)-1] != solid_8:
if len(Balls) > 1:
font = pygame.font.Font('assets/fonts/batmfa__.ttf', 80)
text = font.render('GAME OVER!', True, black)
textRect = text.get_rect()
textRect.center = (400,250)
Surface.blit(text, textRect)
elif len(Balls) == 1:
font = pygame.font.Font('assets/fonts/batmfa__.ttf', 80)
text = font.render('YOU WIN!', True, black)
textRect = text.get_rect()
textRect.center = (400,250)
Surface.blit(text, textRect)
#JAMES'S CODE ------------------------------------------------------
#DARBY'S CODE ------------------------------------------------------
x,y = score()
font = pygame.font.Font('assets/fonts/batmfa__.ttf', 18)
text = font.render('Score of red balls: {0:1.0f}'.format(x), True, red,black)
textRect = text.get_rect()
textRect.center = (210,25)
Surface.blit(text, textRect)
font2 = pygame.font.Font('assets/fonts/batmfa__.ttf', 18)
text2 = font.render('Score of blue balls: {0:1.0f}'.format(y), True, blue,black)
textRect2 = text2.get_rect()
textRect2.center = (590,25)
Surface.blit(text2, textRect2)
secs = clock.tick(100) / 1000
pygame.display.flip()
#DARBY'S CODE -------------------------------------------------------
#we return the amount of seconds it takes to draw to the screen, very small number. This will essentially be what tells the
#move function how fast the balls need to move and change their positions and velocities.
return secs
#our main game loop function that the heart of the game runs on
def Game_won():
if len(Balls) == 1:
return True
else:
return False
def main():
#this deltaTime variable allows us to update our game in a way that is movement per second instead of pixels per frame; makes our game smoother
deltaTime = 1000 / 60
check = 0
while True:
#FRENLY'S CODE ---------------------------------------------
keystate = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == QUIT or keystate[K_ESCAPE]:
pygame.quit(); sys.exit()
queball = Balls[0]
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
print("CHEAT CODE")
solid_8.position = Vector(50,50)
solid_8.velocity = Vector(0,0)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
for ball in Balls[0:len(Balls)-1]:
print("CHEAT CODE")
ball.position = Vector(50,50)
ball.velocity = Vector(0,0)
if event.type == pygame.MOUSEMOTION:
cursor_position = pygame.mouse.get_pos() #this records the position of the mouse on the window
x = cursor_position[0]
y = cursor_position[1]
dx = x - queball.position.x
dy = y - queball.position.y
theta = math.atan2(dy,dx)
que.position1.x = 20*math.cos(theta) + queball.position.x
que.position1.y = 20*math.sin(theta) + queball.position.y
que.position2.x = 350*math.cos(theta) + queball.position.x
que.position2.y = 350*math.sin(theta) + queball.position.y
que.position3.x = 20*math.cos(theta + math.pi) + queball.position.x
que.position3.y = 20*math.sin(theta + math.pi) + queball.position.y
que.position4.x = 700*math.cos(theta + math.pi) + queball.position.x
que.position4.y = 700*math.sin(theta + math.pi) + queball.position.y
speed = queball.velocity.len()
if speed == 0:
if event.type == pygame.KEYDOWN: #space bar is pressed down here
if event.key == pygame.K_SPACE:
t_0 = time.process_time() #time is recorded when space bar is pressed down
if event.type == pygame.KEYUP: #space bar is released here, space bar gets unpressed
if event.key == pygame.K_SPACE:
t_1 = time.process_time() #time is recorded when space bar is released/unpressed
power = 50*(t_1 - t_0) #this makes the power of cue ball hit depend on how long you hold the space bar for, its up to the player
queball.velocity.x += -power*math.cos(theta) *40 #the power has a factor of 50 because any number lower, then the ball would either go too slow or you'd have to hold the space bar fot a very long time, which is boring
queball.velocity.y += -power*math.sin(theta) *40
#FRENLY'S CODE -----------------------------------------------
if check == 0:
if Game_won() == True:
play_next()
check += 1
Move(deltaTime)
CollisionDetect()
deltaTime = Draw()
if __name__ == '__main__': main()
|
def len_check(x):
length = len(str((x)))
if (length == 15) or (length == 16):
return True
else:
return False
def is_valid(x):
card = x
num_list= list((str(card)))
sum_odd = 0
sum_even = 0
even_count = 0
odd_count = 0
total_sum = 0
length = 0
for i in num_list:
length += 1
print(length)
count = 0
if length == 16:
odd_count = 15
even_count = 14
if total_sum % 10 == 0:
return True
else:
return False
def main():
cc_num = int(input('Enter at 15 or 16-digit credit card number: '))
if not len_check(cc_num):
print('Not a 15 or 16-digit number')
else:
if not is_valid(cc_num):
print('Invalid credit card number')
else:
print('valid card number')
main()
|
def binary_search(input_list, target):
if len(input_list) == 0:
return 'Not Found'
else:
midpoint = len(input_list) // 2
if input_list[midpoint] == target:
return 'Found'
elif input_list[midpoint] < target:
return binary_search(input_list[midpoint+1:], target)
else:
return binary_search(input_list[:midpoint], target)
input_list = [1,2,3,4,5,6,7,8,9,10]
target = 2
print(binary_search(input_list, target))
|
def test(x):
if(state[(x+1)%5]!=2 and state[(x+4)%5]!=2 and state[x]==1):
state[x]=2
flag[x]=1
def initialisation():
for k in range(5):
state[k]=0
flag[k]=0
def pickup(x):
state[x]=1
test(x)
if(state[x]!=2):
flag[x]=0
if(flag[x]==1):
print("\n Philo is eating"+str(x+1)+"")
else:
print("\n Philo %d cannot eat now"+str(x+1)+"")
def putdown(x):
state[x]=0
test((x+1)%5)
test((x+4)%5)
print("\n Philo %d is thinking"+str(x+1))
state=[0]*5
flag=[0]*5
initialisation()
while(1):
print(" \n Menu \n 1)Start Eat \n 2)Stop Eating \n 3)EXIT \n Enter Choice : ")
ch=int(input())
print("Enter the philosopher you want to interact with : ")
n=int(input())
if ch==1:
pickup(n-1)
elif ch==2:
putdown(n-1)
else:
exit(0)
|
Task
Given names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for is not found, print Not found instead.
Note: Your phone book should be a Dictionary/Map/HashMap data structure.
Input Format
The first line contains an integer, , denoting the number of entries in the phone book.
Each of the subsequent lines describes an entry in the form of space-separated values on a single line. The first value is a friend's name, and the second value is an -digit phone number.
After the lines of phone book entries, there are an unknown number of lines of queries. Each line (query) contains a to look up, and you must continue reading lines until there is no more input.
Note: Names consist of lowercase English alphabetic letters and are first names only.
Output Format
On a new line for each query, print Not found if the name has no corresponding entry in the phone book; otherwise, print the full and in the format name=phoneNumber.
Sample Input
3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry
Sample Output
sam=99912222
Not found
harry=12299933
Explanation
We add the following (Key,Value) pairs to our map so it looks like this:
We then process each query and print key=value if the queried is found in the map; otherwise, we print Not found.
Query 0: sam
Sam is one of the keys in our dictionary, so we print sam=99912222.
Query 1: edward
Edward is not one of the keys in our dictionary, so we print Not found.
Query 2: harry
Harry is one of the keys in our dictionary, so we print harry=12299933.
solution in python
well it'll be easy to solve it in python hence c++ or c have dictionaries and maps in a deeper concept
n=int(input())
ddict={} //defining the dictionary
for i in range(n):
a=input()
a.split() //splitting is used because input given is after one whitespace
ddict[a[0]]=a[1]
While True: //infite loop run to find unlimited names in dictionary
try:
x=input()
if x in ddict:
print('{0}={1}'.format(x,ddict[x]))
else:
print("Not found")
except: //to catch the end of file error
break
PS- for more flexibilty use "except EOFerror: to only catch end of file error otherwise "except: will catch necessary errors
break" break"
|
class UserInput:
def __init__(self, airports_dict):
# Variables to store OWM connection data:
self.airports_dict = airports_dict
self._itinerary_dict = {}
self.size_loop = True
self.itinerary_loop = True
self.input_size = None
def itinerary_size(self):
while self.size_loop:
try:
self.input_size = int(input("Enter the number of places you would like to visit:"))
if 1 < self.input_size <= 4:
self.size_loop = False
else:
print()
print('The size of your itinerary must be four or less!')
print()
except ValueError as e:
print()
print('That\'s not an integer:')
print(e)
print()
except Exception as e:
print(e)
@staticmethod
def desc_program():
print("Please enter up to four destinations.")
print()
print("Note:")
print("- Destinations must be in the format of IATA airport codes")
print("- IATA codes consist of three alphabetic capital letters")
print("- This program calculates a round trip. The first code you enter is both your starting point and destination")
print()
return 0
def itinerary_input(self):
while self.itinerary_loop:
input_icao = str(input("Input code:"))
if len(input_icao) == 3 and input_icao.isalpha():
if (input_icao not in self.itinerary_dict) and (len(self.itinerary_dict) < (self.input_size-1)):
if input_icao in self.airports_dict:
self.itinerary_dict[input_icao] = None
print("Dictionary", self.itinerary_dict, "Size:", len(self.itinerary_dict))
else:
print("Airport code not in dictionary")
# raise ValueError("Airport code not in dictionary")
elif len(self.itinerary_dict) == (self.input_size-1) and (input_icao not in self.itinerary_dict):
if input_icao in self.airports_dict:
self.itinerary_dict[input_icao] = None
print("Dictionary", self.itinerary_dict, "Size:", len(self.itinerary_dict))
print()
print("Thank-you, I will now calculate the shortest path (fuel price weighted)")
self.itinerary_loop = False
else:
print("Airport code does not exist")
else:
print("Sorry that one is already in the dictionary")
# raise ValueError("Sorry, I don't understand your input")
else:
print('Inputted ICAO code is invalid. It must be four alphabetic characters')
return 0
# Getters and setters start here:
@property
# Pythonic way of doing a "getter"
def itinerary_dict(self):
return self._itinerary_dict
'''
except ValueError as e:
print(e)
self.user_input()
except KeyboardInterrupt:
print()
print("Goodbye!!")
exit()
except Exception as e:
print(e)
''' |
import xml.etree.ElementTree as etree
myXML = '''
<current>
<temperature value="289.731" min="289.731" max="289.731" unit="kelvin"/>
</current>
'''
tree = etree.fromstring(myXML)
temperatureInfo = tree.find('temperature')
degrees = temperatureInfo.attrib['value']
print(degrees)
|
# encoding: utf-8
from threading import Thread, Lock
from time import sleep
a = 0
b = 0
lock = Lock()
def value():
while True:
sleep(0.2)
lock.acquire()
if a != b:
print('a = %d, b = %d' % (a, b))
lock.release()
t = Thread(target=value)
t.start()
while True:
# with方式上锁
with lock:
a += 1
b += 1
t.join()
|
s = input() #reads input string
n= int(input()) #a number which is used to convert string to cipher
s1 = ""
for x in s: #used to convert the string to a cipher
if(x.isalnum()):
ass = ord(x)
if(ass>=65 and ass<=90):
ass+=n
if(ass>90):
ass = 64+n-1
if(ass>=97 and ass<=122):
ass+=n
if(ass>122):
ass = 96+n
if(ass>=48 and ass<=57):
ass+=n
if(ass>57):
ass = 47+n
s1+=chr(ass)
else:
s1+=x
print(s1) #printing the converted coded string.
|
"""
New exercise:
Given a file with this format (you can use via my github account
https://github.com/jpfnice/OctPyFunDay2AM "data2.txt" for instance):
x1:0.34;x2:0.56
x1:0.24;x2:0.45
x1:0.27;x2:0.55
...
extract out of it the numerical values associated with x1 and x2.
The values associated with x1 will be stored in a list with the name X1.
The values associated with x2 will be stored in a list with the name X2.
Create a list Y1 that will contain the cosine of each value stored in X1
(use the math.cos() function)
Create a list Y2 that will contain the sine of each value stored in X2
(use the math.sin() function)
Once the 4 lists will be created I will show you how to plot the
corresponding points (X1,Y1, X2,Y2).
"""
import math
afile=open("data2.txt")
X1=[]
X2=[]
for line in afile:
pos1=line.index(":")
pos2=line.index(";")
pos3=line.index(":", pos2)
X1.append(float(line[pos1+1:pos2]))
X2.append(float(line[pos3+1:]))
afile.close()
print(X1)
print(X2)
Y1=[]
for e in X1:
Y1.append(math.cos(e))
# or
# Y1=[math.cos(e) for e in X1]
Y2=[]
for e in X2:
Y2.append(math.sin(e))
print(Y1)
print(Y2)
import matplotlib.pyplot as plt
plt.plot(X1, Y1, "-r", label="Cosine")
plt.plot(X2, Y2, "--g", label="Sine")
plt.legend()
plt.show()
|
#-*- encoding:utf-8 -*-
#1.静态方法和类方法
#1.1静态方法
#1.2类方法
class washer(object):
#定义类属性
company="Le Xi"
#1.11定义静态方法
@staticmethod
def spins_ml(spins):
#1.13静态方法只能访问类属性不能访问实例属性
print("company:",washer.company)
return spins*0.4
#1.21定义类方法
@classmethod
def get_washer(cls,water,scour):
#1.23类方法只能访问类属性不能访问实例属性
print("company:",washer.company)
return cls(water,cls.spins_ml(scour))
def __init__(self,water=10,scour=2):
self._water=water
self.scour=scour
self.year=2010
@property
def water(self):
return self._water
@property
def total_year(self):
return 2015-self.year
@water.setter
def water(self,water):
self._water = water
def set_water(self,water):
self.water=water
def set_scour(self,scour):
self.scour=scour
def add_water(self):
print("add water",self.water)
def add_scour(self):
print("add scour",self.scour)
def start_wash(self):
self.add_water()
self.add_scour()
print("start wash ...")
# if __name__ == '__main__':
# #1.12访问静态方法
# print(washer.spins_ml(8))
# w=washer(100,washer.spins_ml(8))
# w.start_wash()
#1.22访问类方法
# w = washer.get_washer(100, 9)
# w.start_wash()
#
#2.类的继承和方法重载
class washerDry(washer):
def dry(self):
print("dry clothes...")
#重载父类方法
def start_wash(self):
print("......")
#使用super一定要指定其父类继承自object
super(washerDry,self).start_wash()
print("......")
if __name__ == '__main__':
w = washerDry()
w.start_wash()
w.dry()
|
#!/usr/bin/env python3
# coding: utf-8
import copy
def headers_add_host(headers, address):
"""
If there is no Host field in the headers, insert the address as a Host into the headers.
:param headers: a 'dict'(header name, header value) of http request headers
:param address: a string represents a domain name
:return: headers after adding
"""
headers.setdefault('Host', address)
return headers
def request_add_host(request, address):
"""
If the request has no headers field, or request['headers'] does not have a Host field, then add address to Host.
:param request: a dict(request key, request name) of http request
:param address: a string represents a domain name
:return: request after adding
"""
request.setdefault('headers', {})
request['headers'].setdefault('Host', address)
return request
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 20 18:27:13 2017
@author: Leszek
"""
# Ulubiona liczba - wczytanie danych do pliku
import json
filename = 'favorite_number.json'
num = input("What's your favorite number? ")
with open(filename, 'w') as f_obj:
json.dump(num, f_obj)
# Kod wg książki
import json
# bez wiersza dedykowanego - filename = "xxx.json'
number = input("What's your favorite number? ")
with open('favorite_number.json', 'w') as f:
json.dump(number, f)
print("Thanks, I'll remember that.")
|
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 11 15:47:44 2017
@author: Leszek
"""
#Pętla while w działaniu
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1 #difference between loops while and for:
#while is running until it is False when
#loop for is running through given sequence of numbers
#Wyjscie z pętli aby zakończyć działanie programu
prompt = "\nPowiedz mi cos o sobie, a wyswietlę to na ekranie:"
prompt += "\nNapisz koniec, aby zakończyć działanie programu. "
message = ""
while message != 'koniec':
message = input(prompt)
print(message) #program się nie skończy nawet po wpisaniu Koniec
prompt = "\nPowiedz mi cos o sobie, a wyswietlę to na ekranie:"
prompt += "\nNapisz koniec, aby zakończyć działanie programu. "
message = ""
while message != 'koniec':
message = input(prompt)
if message != 'koniec': #po użyciu 'koniec' program nie wykonuje
#polecenia print a tym samym nie ładuje input
print(message)
# Użycie flagi
prompt = "\nPowiedz mi cos o sobie, a wyswietlę to na ekranie:"
prompt += "\nNapisz 'koniec', aby zakończyć działanie programu. "
active = True #flagą jest zmienna active
while active:
message = input(prompt)
if message == 'koniec':
active = False # active jako flaga z wartoscią False
#przerywa pętlę while
else:
print(message)
#Użycie polecenia break do opuszczenia pętli
prompt = "\nPodaj nazwy miast, ktore chciałbys odwiedzić:"
prompt += "\n(Gdy zakończysz podawanie miast, napisz 'koniec'.) "
while True:
city = input(prompt)
if city == 'koniec':
break #przerywa działaie pętli while i tym samym input
else:
print("Chciałbym odwiedzić " + city.title() + "!")
#Użycie polecenia continue
current_number = 0
while current_number < 10:
current_number += 1
if current_number %2 == 0:
continue #continue wraca na początek pętli
else:
print("\n", current_number)
#Unikanie pętli działającej w nieskończonosc - klawisze ctrl + c
x = 1
while x < 5:
print(x) #pętla nie zatrzymuje się (1,1,1,1,..)
x = 0
while x < 5:
x += 1
if x == 5:
break
else:
print(x)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 22 21:05:09 2017
@author: Leszek
"""
#Wartosć zwrotna
def get_formatted_name(first_name, last_name):
"""Zwraca elegancko sformatowane imię i nazwisko"""
full_name = first_name + " " + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix') #wywołanie funkcji
#zwracającej wartosć wymaga dostarczenia zmiennej w celu przechowania wartosci
print("\n\t", musician)
#Definiowanie argumentu jako opcjonalnego
def get_formatted_name(first_name, middle_name, last_name):
"""Zwraca elegancko sformatowane pełne imię i nazwisko"""
full_name = first_name + " " + middle_name + " " + last_name
return full_name.title()
musician = get_formatted_name('john', 'lee', 'hooker')
print(musician) #kod funkcji nie jest opcjonalny
# Z argumentem opcjonalnym
def get_formatted_name(first_name, last_name, middle_name=''):
"""Zwraca elegancko sformatowane pełne imię i nazwisko"""
if middle_name:
full_name = first_name + ' ' + middle_name + ' ' + last_name
return full_name.title()
else:
full_name = first_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
#Zwrot słownika
def build_person(first_name, last_name):
"""Zwraca słownik informacji o danej osobie"""
person = {'first': first_name, 'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
#dodatkowe wartosci dodane do słownika
def build_person(first_name, last_name, age=''): #dodano pusty argum. opcjona.
"""Zwraca słownik informacji o danej osobie"""
person = {'first': first_name, 'last': last_name,}
if age:
person['age'] = age
return person
musician = build_person('jimi', 'hendrix', '27')
print(musician)
#Używanie funkcji wraz pętlą while
def get_formatted_name(first_name, last_name):
"""Zwraca elegancko sformatowane pełne imię i nazwisko"""
full_name = first_name + ' ' + last_name
return full_name.title()
while True:
print("\nProszę podać imię i nazwisko:")
print("(wpisz 'q', aby zakończyć pracę w dowolnym momencie)")
f_name = input("Imię: ")
if f_name == 'q':
break
l_name = input("Nazwisko: ")
if l_name == 'q':
break
formatted_name = get_formatted_name(f_name, l_name)
print("\nWitaj, " + formatted_name + "!")
|
def _forward_mapper(student_answer):
return {
'very much like me' : 5,
'mostly like me' : 4,
'somewhat like me' : 3,
'not much like me' : 2,
'not like me at all' : 1
}[student_answer.lower()]
def _reverse_mapper(student_answer):
return {
'very much like me' : 1,
'mostly like me' : 2,
'somewhat like me' : 3,
'not much like me' : 4,
'not like me at all' : 5
}[student_answer.lower()]
def _get_question_number(question):
questions = {
1 : "New ideas and projects sometimes distract me from previous ones",
2 : "Setbacks don’t discourage me",
3 : "I often set a goal but later choose to pursue a different one",
4 : "I am a hard worker",
5 : "I have difficulty maintaining my focus on projects that take more than a few months to complete",
6 : "I finish whatever I begin",
7 : "My interests change from year to year",
8 : "I am diligent. I never give up",
9 : "I have been obsessed with a certain idea or project for a short time but later lost interest",
10 : "I have overcome setbacks to conquer an important challenge",
}
question = question.lower()
for number, match_question in questions.items():
if match_question.lower() in question:
return number
raise Exception(f"could not find question number for:\n\t{question}")
def get_question_score_map_function(question:str):
"""returns a function tht takes in a student's answer to the above question and returns a score according to the Duckworth Grit Scale"""
num = _get_question_number(question)
if num in [2, 4, 6, 8, 10]:
return _forward_mapper
elif num in [1, 3, 5, 7, 9]:
return _reverse_mapper
else:
raise Exception(f"Question number {num} not recognised ({question})")
def append_final_test_score(df,DGS,column_list):
"""once all the answers have individual scores, we find the average"""
assert len(column_list) == 10
df[DGS] = df[column_list].mean(axis=1)
def _human_friendly_map_function(final_score:int) -> str:
if final_score == 5:
return "high grit"
if final_score <= 2:
return "low grit"
return "medium grit"
def append_human_friendly_test_score(df,DGS,column_list):
"""
high grit: = 5
low grit: <= 2
"""
df[f"human_{DGS}"] = df[DGS].map(_human_friendly_map_function)
|
# Let's make a turtle race
from turtle import *
from random import randint
speed(10)
penup()
goto(-140, 140)
for step in range(16):
write(step, align='center')
right(90)
forward(10)
pendown()
forward(150)
penup()
backward(160)
left(90)
forward(20)
ada = Turtle()
ada.color('red')
ada.shape('turtle')
ada.penup()
ada.right(360)
ada.goto(-160, 100)
ada.pendown()
bob = Turtle()
bob.color('blue')
bob.shape('turtle')
bob.penup()
bob.right(360)
bob.goto(-160, 70)
bob.pendown()
jim = Turtle()
jim.color('green')
jim.shape('turtle')
jim.penup()
jim.right(360)
jim.goto(-160, 40)
jim.pendown()
sam = Turtle()
sam.color('yellow')
sam.shape('turtle')
sam.penup()
sam.right(360)
sam.goto(-160, 10)
sam.pendown()
for turn in range(100):
ada.forward(randint(1,5))
bob.forward(randint(1,5))
jim.forward(randint(1,5))
sam.forward(randint(1,5)) |
class TestClass: # 类的定义
DESCRIPTION = "class introduction of sample" # 类变量,可直接通过类名调用
__test = "test" # 属于私有,不可在类外部直接调用以“__”开头
_single = "single" # 属于私有,不可使用from module import *导入使用
def __init__(self, name):
'测试类' # 注释文档
self.name = name # 通过self可以创建类的实例变量
print(TestClass.__test)
print(TestClass._single)
def getName(self): # 类的成员方法
return self.name
def __getName(self): # 类的私有方法
return TestClass._single
@staticmethod
def getsingle(): # 类的静态方法
return TestClass.__test
print(TestClass.DESCRIPTION)
print(TestClass.getsingle())
test = TestClass("sample")
print(test.name)
print(test.getName)
print(TestClass.getName)
|
def is_float(x):
'''
This function takes a string as parameter and checks whether it is a Number or not (Integer or Float).
'''
try:
# only integers and float converts safely
num = float(x)
return True
except ValueError as e: # not convertable to float
return False
def Calculate_Simple_Interest(principal_amount: float, time_duration: float, rate_in_percentage: float) -> float:
print('The Principal Amount is: ', principal_amount)
print('The Time duration is: ', time_duration)
print('The Rate of Interest (in percentage) is', rate_in_percentage)
si = (principal_amount * time_duration * rate_in_percentage) / 100
print('The Simple Interest is:', str(si))
return si
def Question_01():
"""
Q1. Write a program that computes simple interest. Prompt for the principal amount, the
rate as a percentage, and the time, and display the amount accrued (principal + interest).
The formula for simple interest is A = P(1 + rt), where P is the principal amount, r is the
annual rate of interest, t is the number of years the amount is invested, and A is the amount
at the end of the investment.
Example Output:
Enter the principal: 1500
Enter the rate of interest: 4.3
Enter the number of years: 4
“After 4 years at 4.3%, the investment will be worth $1758.”
"""
# Driver code
Prin = input("Enter the principal: ")
if str.isdigit(Prin) == True:
Rate = input("Enter the rate of interest: ")
if is_float(Rate) == True:
Time = input("Enter the number of years: ")
if str.isdigit(Time) == True:
print("----------------------------------------------------------------------------")
Simple_Interest_ = Calculate_Simple_Interest(float(Prin), float(Time), float(Rate))
# Simple_Interest_ = (Prin * Time * Rate)/100
print("Sum of Principal Amount and Simple Interest is: " + str(int(Simple_Interest_) + int(Prin)))
else:
print("Invalid number of years.")
else:
print("Invalid rate of interest.")
else:
print("Invalid principal amount.")
print("-- ... Question # 01 Ends here ... --") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.