text
stringlengths 37
1.41M
|
---|
class strReplace:
def strReplace(self,str1,reStr):
str1 = str1.replace(" ", reStr, 1)
return str1
str1 = "hello world"
str1 =strReplace().strReplace(str1,"$")
print(str1) |
from typing import List
g_list: List[str] = []
while True:
person = input()
if person == '.':
break
else:
g_list.append(person)
print(g_list)
print(len(g_list))
|
while True:
current_number = int(input())
if 10 <= current_number <= 100:
print(current_number)
elif current_number < 10:
continue
else:
break
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 3 18:58:29 2018
@author: seele
"""
import sys
from random import seed, randrange
from queue_adt import *
def display_grid():
for i in range(len(grid)):
print(' ', ' '.join(str(grid[i][j]) for j in range(len(grid[0]))))
def find_next_point(need_queue,direction):
nextstep=[]
(row,colume)=need_queue[-1]
if direction==(1,0):
moving=[(0,-1),(1,0),(0,1)]
elif direction==(-1,0):
moving=[(0,1),(-1,0),(0,-1)]
elif direction==(0,1):
moving=[(1,0),(0,1),(-1,0)]
else:
moving=[(-1,0),(0,-1),(1,0)]
for (i,j) in moving:
r,c=row+i,colume+j
if r>=0 and r<10 and c>=0 and c<10 and grid[r][c]==1:
if (r,c) in need_queue:
pass
else:
possible_path=need_queue[:]
possible_path.append((r,c))
nextstep.append(possible_path)
return nextstep
def leftmost_longest_path_from_top_left_corner():
queue=Queue()
need_queue = []
if grid[0][0] == 1 :
queue.enqueue([(0,0)])
while not queue.is_empty():
need_queue=queue.dequeue()
if len(need_queue)>1:
direction=(need_queue[-1][0]-need_queue[-2][0],need_queue[-1][1]-need_queue[-2][1])
else:
direction=(0,1)
nextpath=find_next_point(need_queue,direction)
for i in range(len(nextpath)):
queue.enqueue(nextpath[i])
return need_queue
# Replace pass above with your code
provided_input = input('Enter one integer: ')
try:
for_seed = int(provided_input)
except ValueError:
print('Incorrect input, giving up.')
sys.exit()
seed(for_seed)
grid = [[randrange(2) for _ in range(10)] for _ in range(10)]
print('Here is the grid that has been generated:')
display_grid()
path = leftmost_longest_path_from_top_left_corner()
if not path:
print('There is no path from the top left corner.')
else:
print(f'The leftmost longest path from the top left corner is: {path}')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 8 14:32:46 2018
@author: seele
"""
import sys
import statistics
file_name = input('Which data file do you want to use? ')
L1=[]
L2=[]
try:
f = open(file_name)
R = f.readlines()
#read is look at every line in the file
if (R==[]):
raise ValueError
sys.exit()
for line in R:
data = line.split()
for i in range(len(data)):
if i % 2 == 0:
L1.append(int(data[i]))#距离
else:
L2.append(int(data[i])) #鱼数量
except IOError:
print("Your file not be founded,give up!")
sys.exit()
except ValueError:
print("Your file not be founded,give up!")
sys.exit()
max_value = int(statistics.mean(L2))
min_value= int(min(L2))
me = int((max_value+min_value)/2)
def check(me):
L=L2[:]
for i in range(len(L)-1):
if(L[i]<me):
L[i+1] = L[i+1] - (me-L[i]) - (L1[i+1]-L1[i])
if(L[i]>me):
if( L[i]-me > (L1[i+1]-L1[i])):
L[i+1]=L[i+1] + (L[i]-me) - ((L1[i+1]-L1[i]))
if( L[i]-me <= (L1[i+1]-L1[i])):
pass
if(L[i]==me):
pass
if(L[-1]>me):
# me can be achieved
return 1
if(L[-1]<me):
# me cannot be reached
return 2
if(L[-1]==me):
#this is what we want
return 0
last = 0
while check(me)!=0:
if(check(me)==2):
if max_value != me:
max_value= me
me= int((max_value+min_value)/2)
else:
last = me
break
if(check(me)==1):
if min_value != me:
min_value= me
me= int((max_value+min_value)/2)
else:
last = me
break
last = me
shuchu = int(last)
print(f'The maximum quantity of fish that each town can have is {shuchu}.')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 10 18:32:17 2018
@author: seele
"""
def fibo(n):
if n <= 1:
return n
return fibo(n-1)+fibo(n-2)
#复杂每次都要算前面 指数级增长
def fibo_1(n):
if n <= 1:
return n
previours, current = 0, 1
for _ in range(2,n+1):
previours, current = current ,previours+current
return current
def fibo_2(n,fibonacci = {0:0,1:1}):
if n not in fibonacci:
fibonacci[n] = fibo_2(n-1) + fibo_2(n-2)
return fibonacci[n]
|
# Written by Eric Martin for COMP9021
import re
from functools import partial
from binary_tree_adt import BinaryTree
'''
Builds a parse tree for an expression generated by the grammar:
EXPRESSION --> EXPRESSION TERM_OPERATOR TERM
EXPRESSION --> TERM
TERM --> TERM FACTOR_OPERATOR FACTOR
TERM --> FACTOR
FACTOR --> NUMBER
FACTOR --> (EXPRESSION)
NUMBER --> DIGIT NUMBER | DIGIT
DIGIT --> 0 | ... | 9
TERM_OPERATOR --> + | -
FACTOR_OPERATOR --> * | /
with all operators associating to the left.
'''
def parse_tree(expression):
'''
Checks whether an expression can be generated by the grammar,
and in case the answer is yes, returns a parse tree for the expression.
Note that all operators associate to the left.
>>> parse_tree('100').print_binary_tree()
100
>>> parse_tree('1 - 20 + 300').print_binary_tree()
1
-
20
+
<BLANKLINE>
300
<BLANKLINE>
>>> parse_tree('1 - (20 + 300)').print_binary_tree()
<BLANKLINE>
1
<BLANKLINE>
-
20
+
300
>>> parse_tree('20 * 4 / 5').print_binary_tree()
20
*
4
/
<BLANKLINE>
5
<BLANKLINE>
>>> parse_tree('20 * (4 / 5)').print_binary_tree()
<BLANKLINE>
20
<BLANKLINE>
*
4
/
5
>>> parse_tree('1 + 20 * (30 - 400)').print_binary_tree()
<BLANKLINE>
<BLANKLINE>
<BLANKLINE>
1
<BLANKLINE>
<BLANKLINE>
<BLANKLINE>
+
<BLANKLINE>
20
<BLANKLINE>
*
30
-
400
>>> parse_tree('(1 + 20) * (30 - 400)').print_binary_tree()
1
+
20
*
30
-
400
'''
if any(not (c.isdigit() or c.isspace() or c in '()+-*/') for c in expression):
return
# Tokens can be natural numbers, (, ), +, -, *, and /
tokens = re.compile('(\d+|\(|\)|\+|-|\*|/)').findall(expression)
tokens.reverse()
parse_tree = parse_tree_for_expression_or_term('+-', tokens)
if len(tokens):
return
return parse_tree
def parse_tree_for_expression_or_term(operators, tokens):
parse_tree_function = (partial(parse_tree_for_expression_or_term, '*/') if '+' in operators
else parse_tree_for_factor
)
tree = parse_tree_function(tokens)
if tree is None:
return
parse_tree = None
while len(tokens) and tokens[-1] in operators:
operator = tokens.pop()
other_tree = parse_tree_function(tokens)
if other_tree is None:
return
parse_tree = BinaryTree(operator)
parse_tree.left_node = tree
parse_tree.right_node = other_tree
tree = parse_tree
if not parse_tree:
return tree
return parse_tree
def parse_tree_for_factor(tokens):
try:
token = tokens.pop()
return BinaryTree(int(token))
# No token was left
except IndexError:
return
except ValueError:
if token != '(':
return
parse_tree = parse_tree_for_expression_or_term('+-', tokens)
if len(tokens) and tokens.pop() == ')':
return parse_tree
return
if __name__ == '__main__':
import doctest
doctest.testmod()
|
# Written by Eric Martin for COMP9021
'''
A Doubly Linked List abstract data type
'''
from copy import deepcopy
class Node:
def __init__(self, value = None):
self.value = value
self.next_node = None
self.previous_node = None
class DoublyLinkedList:
def __init__(self, L = None, key = lambda x: x):
'''Creates an empty list or a list built from a subscriptable object,
the key of each value being by default the value itself.
>>> DoublyLinkedList().print_from_head_to_tail()
>>> DoublyLinkedList().print_from_tail_to_head()
>>> DoublyLinkedList([]).print_from_head_to_tail()
>>> DoublyLinkedList([]).print_from_tail_to_head()
>>> DoublyLinkedList((0,)).print_from_head_to_tail()
0
>>> DoublyLinkedList((0,)).print_from_tail_to_head()
0
>>> DoublyLinkedList(range(4)).print_from_head_to_tail()
0, 1, 2, 3
>>> DoublyLinkedList(range(4)).print_from_tail_to_head()
3, 2, 1, 0
'''
self.key = key
if L is None:
self.head = None
self.tail = None
return
# If L is not subscriptable, then will generate an exception that reads:
# TypeError: 'type_of_L' object is not subscriptable
if not len(L[: 1]):
self.head = None
self.tail = None
return
node = Node(L[0])
self.head = node
for e in L[1: ]:
node.next_node = Node(e)
node.next_node.previous_node = node
node = node.next_node
self.tail = node
def print_from_head_to_tail(self, separator = ', '):
'''
>>> DoublyLinkedList().print_from_head_to_tail(':')
>>> DoublyLinkedList(range(1)).print_from_head_to_tail(':')
0
>>> DoublyLinkedList(range(2)).print_from_head_to_tail(':')
0:1
>>> DoublyLinkedList(range(3)).print_from_head_to_tail('--')
0--1--2
'''
if not self.head:
return
nodes = []
node = self.head
while node:
nodes.append(str(node.value))
node = node.next_node
print(separator.join(nodes))
def print_from_tail_to_head(self, separator = ', '):
'''
>>> DoublyLinkedList().print_from_tail_to_head(':')
>>> DoublyLinkedList(range(1)).print_from_tail_to_head(':')
0
>>> DoublyLinkedList(range(2)).print_from_tail_to_head(':')
1:0
>>> DoublyLinkedList(range(3)).print_from_tail_to_head('--')
2--1--0
'''
if not self.tail:
return
nodes = []
node = self.tail
while node:
nodes.append(str(node.value))
node = node.previous_node
print(separator.join(nodes))
def duplicate(self):
'''
>>> L = DoublyLinkedList(L = [[[1]], [[2]]])
>>> L1 = L.duplicate()
>>> L1.head.value[0][0] = 0
>>> L1.print_from_head_to_tail()
[[0]], [[2]]
>>> L1.print_from_tail_to_head()
[[2]], [[0]]
>>> L.print_from_head_to_tail()
[[1]], [[2]]
'''
if not self.head:
return
node = self.head
node_copy = Node(deepcopy(node.value))
L = DoublyLinkedList(key = self.key)
L.head = node_copy
L.tail = node_copy
node = node.next_node
while node:
node_copy.next_node = Node(deepcopy(node.value))
node_copy.next_node.previous_node = node_copy
node_copy = node_copy.next_node
L.tail = node_copy
node = node.next_node
return L
def __len__(self):
'''
>>> len(DoublyLinkedList())
0
>>> len(DoublyLinkedList([0]))
1
>>> len(DoublyLinkedList((0, 1)))
2
'''
length = 0
node = self.head
while node:
length += 1
node = node.next_node
return length
def apply_function(self, function):
'''
>>> L = DoublyLinkedList(range(3))
>>> L.apply_function(lambda x: 2 * x)
>>> L.print_from_head_to_tail()
0, 2, 4
'''
node = self.head
while node:
node.value = function(node.value)
node = node.next_node
def is_sorted(self):
'''
>>> DoublyLinkedList().is_sorted()
True
>>> DoublyLinkedList([0]).is_sorted()
True
>>> DoublyLinkedList([0, 0]).is_sorted()
True
>>> DoublyLinkedList([0, 1]).is_sorted()
True
>>> DoublyLinkedList([1, 0]).is_sorted()
False
>>> DoublyLinkedList([0, 1, 2, 3]).is_sorted()
True
>>> DoublyLinkedList([0, 2, 1, 3]).is_sorted()
False
>>> DoublyLinkedList([0, 1, 2, 3], lambda x: -x).is_sorted()
False
>>> DoublyLinkedList([3, 2, 1, 0], lambda x: -x).is_sorted()
True
'''
node = self.head
while node and node.next_node:
if self.key(node.value) > self.key(node.next_node.value):
return False
node = node.next_node
return True
def extend(self, L):
'''
>>> L = DoublyLinkedList()
>>> L.extend(DoublyLinkedList(range(2)))
>>> L.print_from_head_to_tail()
0, 1
>>> L.print_from_tail_to_head()
1, 0
>>> L = DoublyLinkedList(range(2))
>>> L.extend(DoublyLinkedList())
>>> L.print_from_head_to_tail()
0, 1
>>> L.print_from_tail_to_head()
1, 0
>>> L = DoublyLinkedList((0,))
>>> L.extend(DoublyLinkedList((1,)))
>>> L.print_from_head_to_tail()
0, 1
>>> L.print_from_tail_to_head()
1, 0
>>> L = DoublyLinkedList(range(2))
>>> L.extend(DoublyLinkedList(range(2, 4)))
>>> L.print_from_head_to_tail()
0, 1, 2, 3
>>> L.print_from_tail_to_head()
3, 2, 1, 0
'''
if not L.head:
return
if not self.head:
self.head = L.head
self.tail = L.tail
return
self.tail.next_node = L.head
L.head.previous_node = self.tail
self.tail = L.tail
def reverse(self):
'''
>>> L = DoublyLinkedList()
>>> L.reverse()
>>> L.print_from_head_to_tail()
>>> L = DoublyLinkedList([0])
>>> L.reverse()
>>> L.print_from_head_to_tail()
0
>>> L.print_from_tail_to_head()
0
>>> L = DoublyLinkedList([0, 1])
>>> L.reverse()
>>> L.print_from_head_to_tail()
1, 0
>>> L.print_from_tail_to_head()
0, 1
>>> L = DoublyLinkedList(range(4))
>>> L.reverse()
>>> L.print_from_head_to_tail()
3, 2, 1, 0
>>> L.print_from_tail_to_head()
0, 1, 2, 3
'''
if not self.head:
return
self.tail = self.head
node = self.head.next_node
self.head.next_node = None
while node:
next_node = node.next_node
node.previous_node = None
node.next_node = self.head
self.head.previous_node = node
self.head = node
node = next_node
def recursive_reverse(self):
'''
>>> L = DoublyLinkedList()
>>> L.recursive_reverse()
>>> L.print_from_head_to_tail()
>>> L = DoublyLinkedList([0])
>>> L.recursive_reverse()
>>> L.print_from_head_to_tail()
0
>>> L.print_from_tail_to_head()
0
>>> L = DoublyLinkedList([0, 1])
>>> L.recursive_reverse()
>>> L.print_from_head_to_tail()
1, 0
>>> L.print_from_tail_to_head()
0, 1
>>> L = DoublyLinkedList(range(4))
>>> L.recursive_reverse()
>>> L.print_from_head_to_tail()
3, 2, 1, 0
>>> L.print_from_tail_to_head()
0, 1, 2, 3
'''
if not self.head or not self.head.next_node:
return
self.tail = self.head
node = self.head
while node.next_node.next_node:
node = node.next_node
last_node = node.next_node
last_node.previous_node = None
node.next_node = None
self.recursive_reverse()
last_node.next_node = self.head
self.head.previous_node = last_node
self.head = last_node
def index_of_value(self, value):
'''
>>> L = DoublyLinkedList()
>>> L.index_of_value(0)
-1
>>> L = DoublyLinkedList(range(10, 15))
>>> L.index_of_value(10)
0
>>> L.index_of_value(14)
4
>>> L.index_of_value(12)
2
>>> L.index_of_value(16)
-1
'''
index = 0
node = self.head
while node:
if node.value == value:
return index
index += 1
node = node.next_node
return -1
def value_at(self, index):
'''
>>> L = DoublyLinkedList()
>>> L.value_at(0)
>>> L = DoublyLinkedList([0])
>>> L.value_at(0)
0
>>> L.value_at(1)
>>> L = DoublyLinkedList(range(10, 15))
>>> L = DoublyLinkedList(range(10, 15))
>>> L.value_at(0)
10
>>> L.value_at(2)
12
>>> L.value_at(4)
14
>>> L.value_at(6)
'''
if index < 0:
return
node = self.head
while node and index:
node = node.next_node
index -= 1
if node:
return node.value
return
def prepend(self, value):
'''
>>> L = DoublyLinkedList()
>>> L.prepend(0)
>>> L.print_from_head_to_tail()
0
>>> L.print_from_tail_to_head()
0
>>> L = DoublyLinkedList([1])
>>> L.prepend(0)
>>> L.print_from_head_to_tail()
0, 1
>>> L.print_from_tail_to_head()
1, 0
'''
if not self.head:
self.head = Node(value)
self.tail = self.head
return
head = self.head
self.head = Node(value)
self.head.next_node = head
head.previous_node = self.head
def append(self, value):
'''
>>> L = DoublyLinkedList()
>>> L.append(0)
>>> L.print_from_head_to_tail()
0
>>> L.print_from_tail_to_head()
0
>>> L = DoublyLinkedList([0])
>>> L.append(1)
>>> L.print_from_head_to_tail()
0, 1
>>> L.print_from_tail_to_head()
1, 0
>>> L = DoublyLinkedList(range(2))
>>> L.append(2)
>>> L.print_from_head_to_tail()
0, 1, 2
>>> L.print_from_tail_to_head()
2, 1, 0
'''
if not self.head:
self.head = Node(value)
self.tail = self.head
return
self.tail.next_node = Node(value)
self.tail.next_node.previous_node = self.tail
self.tail = self.tail.next_node
def insert_value_at(self, value, index):
'''
>>> L = DoublyLinkedList()
>>> L.insert_value_at(0, 3)
>>> L.print_from_head_to_tail()
0
>>> L.print_from_tail_to_head()
0
>>> L = DoublyLinkedList([1])
>>> L.insert_value_at(0, -1)
>>> L.print_from_head_to_tail()
0, 1
>>> L.print_from_tail_to_head()
1, 0
>>> L = DoublyLinkedList([1])
>>> L.insert_value_at(0, 0)
>>> L.print_from_head_to_tail()
0, 1
>>> L.print_from_tail_to_head()
1, 0
>>> L = DoublyLinkedList([0])
>>> L.insert_value_at(1, 1)
>>> L.print_from_head_to_tail()
0, 1
>>> L.print_from_tail_to_head()
1, 0
>>> L = DoublyLinkedList([0])
>>> L.insert_value_at(1, 2)
>>> L.print_from_head_to_tail()
0, 1
>>> L.print_from_tail_to_head()
1, 0
>>> L = DoublyLinkedList([0, 2])
>>> L.insert_value_at(1, 1)
>>> L.print_from_head_to_tail()
0, 1, 2
>>> L.print_from_tail_to_head()
2, 1, 0
'''
new_node = Node(value)
if not self.head:
self.head = new_node
self.tail = new_node
return
if index <= 0:
new_node.next_node = self.head
self.head.previous_node = new_node
self.head = new_node
return
node = self.head
while node.next_node and index > 1:
node = node.next_node
index -= 1
next_node = node.next_node
node.next_node= new_node
new_node.previous_node = node
if next_node:
new_node.next_node = next_node
next_node.previous_node = new_node
else:
self.tail = new_node
def insert_value_before(self, value_1, value_2):
'''
>>> L = DoublyLinkedList([1, 2])
>>> L.insert_value_before(0, 1)
True
>>> L.print_from_head_to_tail()
0, 1, 2
>>> L.print_from_tail_to_head()
2, 1, 0
>>> L = DoublyLinkedList([0, 2])
>>> L.insert_value_before(1, 2)
True
>>> L.print_from_head_to_tail()
0, 1, 2
>>> L.print_from_tail_to_head()
2, 1, 0
>>> L = DoublyLinkedList([0, 1])
>>> L.insert_value_before(2, 3)
False
'''
if not self.head:
return False
if self.head.value == value_2:
self.insert_value_at(value_1, 0)
return True
node = self.head
while node.next_node and node.next_node.value != value_2:
node = node.next_node
if not node.next_node:
return False
new_node = Node(value_1)
new_node.next_node = node.next_node
node.next_node.previous_node = new_node
node.next_node = new_node
new_node.previous_node = node
return True
def insert_value_after(self, value_1, value_2):
'''
>>> L = DoublyLinkedList([0, 1])
>>> L.insert_value_after(2, 1)
True
>>> L.print_from_head_to_tail()
0, 1, 2
>>> L.print_from_tail_to_head()
2, 1, 0
>>> L = DoublyLinkedList([0, 2])
>>> L.insert_value_after(1, 0)
True
>>> L.print_from_head_to_tail()
0, 1, 2
>>> L.print_from_tail_to_head()
2, 1, 0
>>> L = DoublyLinkedList([0, 1])
>>> L.insert_value_after(3, 2)
False
'''
if not self.head:
return False
node = self.head
while node and node.value != value_2:
node = node.next_node
if not node:
return False
next_node = node.next_node
new_node = Node(value_1)
node.next_node = new_node
new_node.previous_node = node
if next_node:
new_node.next_node = next_node
next_node.previous_node = new_node
else:
self.tail = new_node
return True
def insert_sorted_value(self, value):
'''
>>> L = DoublyLinkedList()
>>> L.insert_sorted_value(1)
>>> L.print_from_head_to_tail()
1
>>> L.print_from_tail_to_head()
1
>>> L.insert_sorted_value(0)
>>> L.print_from_head_to_tail()
0, 1
>>> L.print_from_tail_to_head()
1, 0
>>> L.insert_sorted_value(2)
>>> L.print_from_head_to_tail()
0, 1, 2
>>> L.print_from_tail_to_head()
2, 1, 0
>>> L.insert_sorted_value(1)
>>> L.print_from_head_to_tail()
0, 1, 1, 2
>>> L.print_from_tail_to_head()
2, 1, 1, 0
'''
new_node = Node(value)
if not self.head:
self.head = new_node
self.tail = new_node
return
if value <= self.key(self.head.value):
new_node.next_node = self.head
self.head.previous_node = new_node
self.head = new_node
return
node = self.head
while node.next_node and value > self.key(node.next_node.value):
node = node.next_node
next_node = node.next_node
node.next_node = new_node
new_node.previous_node = node
if next_node:
new_node.next_node = next_node
next_node.previous_node = new_node
else:
self.tail = new_node
def delete_value(self, value):
'''
>>> L = DoublyLinkedList([0, 1, 1, 2])
>>> L.delete_value(3)
False
>>> L.delete_value(1)
True
>>> L.print_from_head_to_tail()
0, 1, 2
>>> L.print_from_tail_to_head()
2, 1, 0
>>> L.delete_value(0)
True
>>> L.print_from_head_to_tail()
1, 2
>>> L.print_from_tail_to_head()
2, 1
>>> L.delete_value(2)
True
>>> L.print_from_head_to_tail()
1
>>> L.print_from_tail_to_head()
1
>>> L.delete_value(1)
True
>>> L.print_from_head_to_tail()
>>> L.print_from_tail_to_head()
>>> L.delete_value(0)
False
'''
if not self.head:
return False
if self.head.value == value:
if self.tail == self.head:
self.head = None
self.tail = None
else:
self.head = self.head.next_node
self.head.previous_node = None
return True
node = self.head
while node.next_node and node.next_node.value != value:
node = node.next_node
if node.next_node:
node.next_node = node.next_node.next_node
if node.next_node:
node.next_node.previous_node = node
else:
self.tail = node
return True
return False
if __name__ == '__main__':
import doctest
doctest.testmod()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 28 11:07:17 2018
@author: seele
"""
# Uses National Data on the relative frequency of given names in the population of U.S. births,
# stored in a directory "names", in files named "yobxxxx.txt with xxxx being the year of birth.
#
# Prompts the user for a first name, and finds out the first year
# when this name was most popular in terms of frequency of names being given,
# as a female name and as a male name.
#
# Written by *** and Eric Martin for COMP9021
import os
from collections import defaultdict
first_name = input('Enter a first name: ')
directory = 'names'
min_male_frequency = 0
male_first_year = None
min_female_frequency = 0
female_first_year = None
# Replace this comment with your code
names_years_count_male = defaultdict(list)
names_years_count_female = defaultdict(list)
years_sum_count_M = defaultdict(list)
years_sum_count_F = defaultdict(list)
for filename in os.listdir(directory):
if not filename.endswith('txt'):
continue
year = int(filename[3:7])
with open(directory + '/' + filename) as data_file:
for line in data_file:
name,gender,count = line.split(',')
if gender == 'M':
years_sum_count_M[year].append(int(count))
couple_M = (year,int(count))
names_years_count_male[name].append(couple_M)
else:
years_sum_count_F[year].append(int(count))
couple_F = (year,int(count))
names_years_count_female[name].append(couple_F)
l = []
k = []
for year_M in years_sum_count_M:
years_sum_count_M[year_M] = sum( years_sum_count_M[year_M])
for year_F in years_sum_count_F:
years_sum_count_F[year_F] = sum( years_sum_count_F[year_F])
if first_name in names_years_count_female:
for i in range(len(names_years_count_female[first_name])):
female_frequency = names_years_count_female[first_name][i][1]/years_sum_count_F[names_years_count_female[first_name][i][0]]
cou = (female_frequency,names_years_count_female[first_name][i][0])
l.append(cou)
min_female_frequency = sorted(l,reverse = True)[0][0]*100
female_first_year = sorted(l,reverse = True)[0][1]
if first_name in names_years_count_male:
for j in range(len(names_years_count_male[first_name])):
male_frequency = names_years_count_male[first_name][j][1]/years_sum_count_M[names_years_count_male[first_name][j][0]]
co = (male_frequency,names_years_count_male[first_name][j][0])
k.append(co)
min_male_frequency = sorted(k,reverse = True)[0][0]*100
male_first_year = sorted(k,reverse = True)[0][1]
if not female_first_year:
print(f'In all years, {first_name} was never given as a female name.')
else:
print(f'In terms of frequency, {first_name} was the most popular '
f'as a female name first in the year {female_first_year}.\n'
f' It then accounted for {min_female_frequency:.2f}% of all female names.'
)
if not male_first_year:
print(f'In all years, {first_name} was never given as a male name.')
else:
print(f'In terms of frequency, {first_name} was the most popular '
f'as a male name first in the year {male_first_year}.\n'
f' It then accounted for {min_male_frequency:.2f}% of all male names.'
)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 8 23:47:15 2018
@author: seele
"""
# Randomly generates a binary search tree whose number of nodes
# is determined by user input, with labels ranging between 0 and 999,999,
# displays it, and outputs the maximum difference between consecutive leaves.
#
# Written by *** and Eric Martin for COMP9021
import sys
from random import seed, randrange
from binary_tree_adt import *
# Possibly define some functions
leaves_list = []
def traversal(tree):
if tree.value is None:
return
else:
if tree.left_node.value is None and tree.right_node.value is None:
leaves_list.append(tree.value)
traversal(tree.left_node)
traversal(tree.right_node)
return leaves_list
def max_diff_in_consecutive_leaves(tree):
traversal(tree)
print(leaves_list)
max_difference = 0
for i in range(0, len(leaves_list)-1):
more_big = abs(leaves_list[i] - leaves_list[i+1])
if more_big > max_difference:
max_difference = more_big
return max_difference
# Replace pass above with your code
provided_input = input('Enter two integers, the second one being positive: ')
try:
arg_for_seed, nb_of_nodes = provided_input.split()
except ValueError:
print('Incorrect input, giving up.')
sys.exit()
try:
arg_for_seed, nb_of_nodes = int(arg_for_seed), int(nb_of_nodes)
if nb_of_nodes < 0:
raise ValueError
except ValueError:
print('Incorrect input, giving up.')
sys.exit()
seed(arg_for_seed)
tree = BinaryTree()
for _ in range(nb_of_nodes):
datum = randrange(1000000)
tree.insert_in_bst(datum)
print('Here is the tree that has been generated:')
tree.print_binary_tree()
print('The maximum difference between consecutive leaves is: ', end = '')
print(max_diff_in_consecutive_leaves(tree)) |
class User:
#fields and method definitions
def __init__ (self,name,number):
self.name=name
self.genders=[]
self.countries=[]
self.age=number
self.hungry=False
def password(self,password):
self.password=password
input_name= input('What is your name?')
input_age=input('What is your age?')
myuser= User(input_name,input_age)
input_user=input("Choose a username.")
myuser.add_username(input_user)
input_password=input('Choose a password.')
myuser.add_password(input_password)
input_friends=input('Add friends')
myuser.add_friends(input_friends)
while 0<1:
decision = input('Do you wanna make another user? Y for ye; N for no.')
|
i=int(input("Enter Score: "))
while(i>-1):
print(i)
i=int(input("Enter Score: "))
if i ==-1:
break |
#!/usr/bin/python
# Import the required modules
import cv2
import os
import numpy as np
from PIL import Image
from utils import Utilities as uti
face_size = 70
# For face detection we will use the Haar Cascade provided by OpenCV.
cascadePath = "/home/daniel/opencv/data/haarcascades/haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath)
# For face recognition we will the the LBPH Face Recognizer
recognizer = cv2.createFisherFaceRecognizer()
def get_images_and_labels(path):
# Append all the absolute image paths in a list image_paths
# We will not read the image with the .sad extension in the training set
# Rather, we will use them to test our accuracy of the training
image_paths = [os.path.join(path, f) for f in os.listdir(path) if not f.endswith('.sad')]
# images will contains face images
images = []
# labels will contains the label that is assigned to the image
labels = []
for image_path in image_paths:
# Read the image and convert to grayscale
image_pil = Image.open(image_path).convert('L')
# Convert the image format into numpy array
image = np.array(image_pil, 'uint8')
# Get the label of the image
nbr = int(os.path.split(image_path)[1].split(".")[0].replace("subject", ""))
# Detect the face in the image
faces = faceCascade.detectMultiScale(image)
# If face is detected, append the face to images and the label to labels
for (x, y, w, h) in faces:
faceImg= image[y: y + h, x: x + w]
faceImg = cv2.resize(faceImg, (face_size, face_size))
images.append(faceImg)
labels.append(nbr)
# cv2.imshow("Adding faces to traning set...", image[y: y + h, x: x + w])
# cv2.waitKey(50)
# return the images list and labels list
return images, labels
def get_images_and_labels2(path, train=True):
# Append all the absolute image paths in a list image_paths
# We will not read the image with the .sad extension in the training set
# Rather, we will use them to test our accuracy of the training
# images will contains face images
images = []
# labels will contains the label that is assigned to the image
labels = []
images_ = uti.getAllPhotos(path)
for img in images_:
if train :
if '001' in img.path:
continue
# Read the image and convert to grayscale
image_pil = Image.open(img.path).convert('L')
# Convert the image format into numpy array
image = np.array(image_pil, 'uint8')
# Get the label of the image
print(img.album_name)
nbr = int(img.album_name)
#int(os.path.split(img.path)[1].split(".")[0].replace("subject", ""))
# Detect the face in the image
faces = faceCascade.detectMultiScale(image)
# If face is detected, append the face to images and the label to labels
for (x, y, w, h) in faces:
images.append(image[y: y + h, x: x + w])
labels.append(nbr)
# cv2.imshow("Adding faces to traning set...", image[y: y + h, x: x + w])
# cv2.waitKey(50)
else:
if '001' not in img.path:
continue
# Read the image and convert to grayscale
image_pil = Image.open(img.path).convert('L')
# Convert the image format into numpy array
image = np.array(image_pil, 'uint8')
# Get the label of the image
nbr = int(img.album_name) #int(os.path.split(img.path)[1].split(".")[0].replace("subject", ""))
# Detect the face in the image
faces = faceCascade.detectMultiScale(image)
# If face is detected, append the face to images and the label to labels
for (x, y, w, h) in faces:
images.append(image[y: y + h, x: x + w])
labels.append(nbr)
# return the images list and labels list
return images, labels
# Path to the Yale Dataset
# path = '/home/daniel/workspace/Project/Images/yalefaces/jpeg/'
path = '/home/daniel/workspace/Project/Images/Test/1/'
# Call the get_images_and_labels function and get the face images and the
# corresponding labels
images, labels = get_images_and_labels(path)
for n in images:
# print (n)
print "x = {} y = {} pixels = {}".format(len(n), len(n[0]), len(n) * len(n[0]))
pass
cv2.destroyAllWindows()
# Perform the tranining
recognizer.train(images, np.array(labels))
print recognizer.getMat("eigenvectors")
help(recognizer)
print(recognizer.__str__())
print dir(recognizer)
# Append the images with the extension .sad into image_paths
image_paths = uti.getAllPhotos(path)
for image_path in image_paths:
# if '001.' not in image_path.path:
# continue
predict_image_pil = Image.open(image_path.path).convert('L')
print(image_path.path)
predict_image = np.array(predict_image_pil, 'uint8')
print(predict_image)
faces = faceCascade.detectMultiScale(predict_image)
for (x, y, w, h) in faces:
# nbr_predicted, conf = recognizer.predict(predict_image[y: y + h, x: x + w])
nbr_predicted = recognizer.predict(predict_image[y: y + h, x: x + w])
nbr_actual = image_path.album_name #int(os.path.split(image_path)[1].split(".")[0].replace("subject", ""))
if nbr_actual == nbr_predicted:
# print ("{0} is Correctly Recognized with confidence {}".format(nbr_actual, conf))
print ("{0} is Correctly Recognized with confidence".format(nbr_actual))
else:
print ("{0} is Incorrect Recognized as {1}".format(nbr_actual, nbr_predicted))
cv2.imshow("Recognizing Face", predict_image[y: y + h, x: x + w])
cv2.waitKey(1000) |
class Node:
def __init__(self,value):
self.value=value
self.next=None
class LinkedList:
def __init__(self):
self.head = None
def add(self, data):
node = Node(data)
if not self.head:
self.head = node
else:
current = self.head
while current.next:
current = current.next
current.next = node
def __iter__(self):
if self.head:
current = self.head
while current:
yield current.value
current = current.next
def __str__(self) -> str:
result = ""
current = self.head
while current:
result += str(current.value)
return f"{result} > None"
class HashMap:
def __init__(self, size=1024):
self.size=size
self._bucket = self.size * [None]
def _hash(self, key):
sum = 0
for char in key:
sum += ord(char)
return sum*19 % self.size
def __setitem__(self,key,value):
index = self._hash(key)
if not self._bucket[index]:
self._bucket[index] = LinkedList()
current = self._bucket[index].head
while current:
if current.value[0] == key:
current.value[1] = value
return
current = current.next
self._bucket[index].add([key, value])
def __getitem__(self,key):
index = self._hash(key)
if self._bucket[index]:
current = self._bucket[index].head
while current:
if current.value[0] == key:
return current.value[1]
current = current.next
# raise KeyError('Key is not found')
return 'Null'
def __contains__(self,key):
index = self._hash(key)
if self._bucket[index]:
current = self._bucket[index].head
while current:
if current.value[0] == key:
return True
current = current.next
return False
def __iter__(self):
for items in self._bucket:
if items:
for item in items:
yield item
def __eq__(self, other):
self.result = []
for items in self._bucket:
if items:
for item in items:
self.result += item
print('inside eq res', self.result)
print('inside eq oth', other)
return other == self.result
def __str__(self) -> str:
result = ''
for ni in self._bucket:
if ni:
for item in ni:
result += str(item)
return result
if __name__ == '__main__':
test = HashMap()
test['faisal'] = 'abuzaid'
test['ayah'] = 'abuhammad'
test['raad'] = 'abuzaid'
print(test)
# for tst in test:
# print(tst)
if test == ['raad', 'abuzaid', 'faisal', 'abuzaid', 'ayah', 'abuhammad']:
print('it worked')
|
import numpy
import math
#import pyfftw
def power( x, dt = 1., nbin = 1, binsize = 0, detrend = False,
Bartlett = False, Welch = False, Hann = False,
useRegular = False):
"""
Take the power spectrum of input x.
dt is the time sample spacing (seconds).
Can break a long input up into sections or "bins" before transforming.
Frankly, bin seems like a crap name for this, but it's in the interface,
so I guess we are stuck with it. Read "section" wherever you see "bin".
nbin is the number of sections to take.
binsize is the number of samples per section.
Caller can specify either nbin or binsize but not both.
When you ask for 2 sections, actually average power over the 1st 50%
of data, the middle 50%, and the last 50%; in general, averages power
over (2nbin-1) half-offset ranges.
Returns (power, nu, window) where power is the power spectrum in
units of x^2 per Hz, nu is the frequency sample vector in Hz,
and window is the window function weight applied to the timestream.
"""
if binsize and nbin != 1:
raise ValueError, "Please specify either binsize or nbin, but not both"
nsamp = numpy.shape(x)[-1]
if binsize == 0:
binsize = int(nsamp/nbin) # length of a bin
else:
nbin = int(nsamp/binsize)
if nbin <= 0:
raise ValueError, "You have requested %d bins (len = %d)" % \
(nbin, nsamp)
if detrend: detrendData(x, window = 200)
if Bartlett + Hann + Welch > 1:
raise ValueError, "Please choose at most one type of window"
if Bartlett:
window = 1 - abs((numpy.arange(binsize) - binsize/2.0)/(binsize/2.0))
elif Hann:
window = 0.5*(1-numpy.cos(2*math.pi*(numpy.arange(binsize))/binsize))
elif Welch:
window = 1 - pow((numpy.arange(binsize) - binsize/2.0)/(binsize/2.0), 2)
else:
window = 1.0*numpy.ones(binsize)
one_d = x.ndim == 1
if one_d:
x.shape = (1,-1)
if useRegular:
nt = nextregular(binsize)
else:
nt = binsize
power = 0
if nbin != 1:
for b in xrange(2*nbin - 1):
y = x[:,b*binsize/2 : b*binsize/2 + binsize].copy()
detrendData(y, window = 200)
fx = numpy.fft.rfft(window[numpy.newaxis,:]*y,nt)
power += (fx.real*fx.real + fx.imag*fx.imag)
#fx = numpy.fft.fft(window[numpy.newaxis,:]*y)
#fx = pyfftw.interfaces.numpy_fft.fft(window*y)
#power += (fx.real*fx.real + fx.imag*fx.imag)[:,:binsize/2+1]
else:
y = x.copy()
detrendData(y, window = 200)
fx = numpy.fft.rfft(window[numpy.newaxis,:]*y,nt)
power = (fx.real*fx.real + fx.imag*fx.imag)
#fx = numpy.fft.fft(window[numpy.newaxis,:]*x)
#fx = pyfftw.interfaces.numpy_fft.fft(window*x)
#power = (fx.real*fx.real + fx.imag*fx.imag)[:,:binsize/2+1]
# Normalizations
power_scale = 2.0 # 1-sided power
power_scale /= (2.*nbin - 1.) # Allow for multiple 'bins'
power_scale /= pow(sum(window),2) # Allow for window
power_scale *= float(nt)*dt # per unit time (total time in a bin)
#power_scale *= float(binsize)*dt # per unit time (total time in a bin)
power *= power_scale
# 1-sided power double-counts at 0 and Nyquist frequency. Correct that.
#power[0] /= 2.
#power[-1] /= 2.
nf = power.shape[-1]
nu = numpy.arange(nf) / float(nf) / (2*dt)
nu[0] = 0.5*nu[1] # Make sure the x=0 isn't killing power
if one_d:
x.shape = -1
power.shape = -1
return power, nu, window
def detrendData(y, window = 1000):
"""
@brief Remove the trend and mean from a data vector
@param y Data to detrend
@param window Number of elements to consider at each end of vector
"""
n = y.shape[-1]
one_d = y.ndim == 1
if one_d: y.shape = (1,-1)
if window > n/2: window = n/2
y0 = numpy.mean(y[:,:window],axis=1)
y1 = numpy.mean(y[:,-window:],axis=1)
m1 = (y1+y0)/2.0
m2 = numpy.mean(y,axis=1)
slope = (y1-y0)/(n-1)
x = numpy.arange(n)
y -= (y0 - m1 + m2)[:,numpy.newaxis].repeat(n,1) + slope[:,numpy.newaxis] * x[numpy.newaxis,:]
if one_d: y.shape = -1
def nextregular(n):
while not checksize(n): n+=1
return n
def checksize(n):
while not (n%16): n/=16
while not (n%13): n/=13
while not (n%11): n/=11
while not (n%9): n/=9
while not (n%7): n/=7
while not (n%5): n/=5
while not (n%3): n/=3
while not (n%2): n/=2
return (1 if n == 1 else 0)
|
# Importing tkinter
from tkinter import *
# creating the window instance
win = Tk()
# We dont want the window to be resizeable
win.resizeable(0, 0)
# Giving a geometry to our window
win.geometry("400*300")
# Title of the application
win.title("MEGA-CALCULATOR")
# Defining all our needed functions to make the calculator work effectively
# Creating a button to update our text field anytime a number is keyed in or any button is pressed
def btnClick( item ):
global expression # Using global to expose the expression variable outside of the function
expression += str( item )
txtExpression.set( expression )
# Creating a button to clear the data on the text field
def btnClear():
global expression # Using global to expose the expression variable of the function
expression = ""
txtExpression.set( expression )
# Creating an equal to button to calculate whatever expression is given in teh field
def btnEqual():
global expression # Usingglobal to expose the expression variable outisde of the function
result = str( eval( expression ) ) # eval to evaluate the expression in the string for calaculation
txtExpression.set ( expression)
expression = ""
expression = ""
txtExpression = StringVar() # Create an instance of the text field
# Designing the layout of the calculator
txtFrame = Frame( win, width = 400, height = 50, bd = 0, highlightbackground = "black", highlightcolor = "black", highlightthickness = 1 )
txtFrame.pack( side = TOP )
# Setting the input field for calculator and aligning it to the right
txtField = Entry( txtFrame, font = ( 'arial', 18, 'bold' ), textvariable = txtExpression, width = 50, bg = "#eee" , bd = 0, justify = RIGHT )
txtField.grid(row = 0, column = 0 ) # Setting it to the very first row and column
txtField.pack( ipady = 10 ) # ipady increases te height for us by the number we set
# Creating a frame to hold all buttons
btnsFrame = Frame(win, width = 400, height = 280, bg = "grey" )
btnsFrame.pack()
# Setting the clear and divide buttons of the first row
btnClear = Button( btnsFrame, text = "C", fg = "black", width = 32, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btnClear() )
btnClear.grid( row = 0, column = 0, columnspan = 3, padx = 1, pady = 1 )
btnDivide = Button( btnsFrame, text = "C", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btnClick( "/") )
btnDivide.grid( row = 0, column = 3, padx = 1, pady = 1 )
# Setting the 7, 8, 9, and * buttons on the second row
btnSeven = Button( btnsFrame, text = "7", fg = "black", width = 10, height = 3, bg = "#fff", cursor = "hand2", comand = lambda: btnClick( 7 ) )
btnSeven.grid( row = 1, column = 0, padx = 1, pady = 1 )
btnEight = Button( btnsFrame, text = "8", fg = "black", width = 10, height = 3, bg = "#fff", cursor = "hand2", comand = lambda: btnClick( 8 ) )
btnEight.grid( row = 1, column = 1, padx = 1, pady = 1 )
btnNine = Button( btnsFrame, text = "9", fg = "black", width = 10, height = 3, bg = "#fff", cursor = "hand2", comand = lambda: btnClick( 9 ) )
btnNine.grid( row = 1, column = 3, padx = 1, pady = 1 )
btnMultiply = Button( btnsFrame, text = "*", fg = "black", width = 10, height = 3, bg = "#eee", cursor = "hand2", comand = lambda: btnClick( "*" ) )
btnMultiply.grid( row = 1, column = 3, padx = 1, pady = 1 )
# Setting the 4, 5, 6, and - buttons on the third row
btnFour = Button( btnsFrame, text = "4", fg = "black", width = 10, height = 3, bg = "#fff", cursor = "hand2", comand = lambda: btnClick( 4 ) )
btnFour.grid( row = 2, column = 0, padx = 1, pady = 1 )
btnFive = Button( btnsFrame, text = "5", fg = "black", width = 10, height = 3, bg = "#fff", cursor = "hand2", comand = lambda: btnClick( 5 ) )
btnFive.grid( row = 2, column = 1, padx = 1, pady = 1 )
btnSix = Button( btnsFrame, text = "6", fg = "black", width = 10, height = 3, bg = "#fff", cursor = "hand2", comand = lambda: btnClick( 6 ) )
btnSix.grid( row = 2, column = 2, padx = 1, pady = 1 )
btnMinus = Button( btnsFrame, text = "*", fg = "black", width = 10, height = 3, bg = "#eee", cursor = "hand2", comand = lambda: btnClick( "-" ) )
btnMinus.grid( row = 2, column = 3, padx = 1, pady = 1 )
# Setting the 1, 2, 3, and + buttons on the fourth row
btnOne = Button( btnsFrame, text = "1", fg = "black", width = 10, height = 3, bg = "#fff", cursor = "hand2", comand = lambda: btnClick( 1 ) )
btnOne.grid( row = 3, column = 0, padx = 1, pady = 1 )
btnTwo = Button( btnsFrame, text = "2", fg = "black", width = 10, height = 3, bg = "#fff", cursor = "hand2", comand = lambda: btnClick( 2 ) )
btnTwo.grid( row = 3, column = 1, padx = 1, pady = 1 )
btnThree = Button( btnsFrame, text = "3", fg = "black", width = 10, height = 3, bg = "#fff", cursor = "hand2", comand = lambda: btnClick( 3 ) )
btnThree.grid( row = 3, column = 2, padx = 1, pady = 1 )
btnMinus = Button( btnsFrame, text = "*", fg = "black", width = 10, height = 3, bg = "#eee", cursor = "hand2", comand = lambda: btnClick( "+" ) )
btnMinus.grid( row = 3, column = 3, padx = 1, pady = 1 )
# Setting the 0, ., and = buttons on the fifth row
btnZero = Button( btnsFrame, text = "0", fg = "black", width = 10, height = 3, bg = "#fff", cursor = "hand2", comand = lambda: btnClick( 0 ) )
btnZero.grid( row = 4, column = 0, columnspan = 2, padx = 1, pady = 1 )
btnDot = Button( btnsFrame, text = ".", fg = "black", width = 10, height = 3, bg = "#eee", cursor = "hand2", comand = lambda: btnClick( "." ) )
btnDot.grid( row = 4, column = 2, padx = 1, pady = 1 )
btnEqual = Button( btnsFrame, text = "=", fg = "black", width = 10, height = 3, bg = "#eee", cursor = "hand2", comand = lambda: btnClick( "=" ) )
btnEqual.grid( row = 4, column = 3, padx = 1, pady = 1 )
win.mainloop() # Calling up our loop |
# JESUS SALVADOR VALLES MACIEL
#CARRERA: INFORMATICA
#DESARROLLO DE APLICACIONES WEB
#PRACTICA 2.1 VOTOS
#mostramos las opciones que tienen
print("""
1) AMARILLO 3) MORADO
2) ROJO
""")
#definimos las variables que usaremos, asi como las librerias
import random
A = (0)
B = (0)
C = (0)
voto = (0)
candi = [1,2,3,4]
#luego definiremos el numero de veces que queremos que se repita la eleccion
while voto <= 2000:
#usaremos la libreria random para que sea una eleccion impracial
eleccion = random.choice(candi)
#definira cual fue la eleccion de la computadora
if eleccion == 1:
print ("A votado por PARTIDO AMARILLO")
#esta varaible contabilizara los votos de cada uno de los candidatos
A=(A+1)
#y esta hara avanzar el ciclo
voto = (voto+1)
elif eleccion == 2:
print ("A votado por PARTIDO MORADO")
B=(B+1)
voto = (voto+1)
elif eleccion == 3:
print ("A votado por PARTIDO ROJO")
C=(C+1)
voto = (voto+1)
else:
print("OPCION NO VALIDA")
#una vez terminado el ciclo se mostraran los resultados
print("""Los resultados son:
""")
print((A)," Votaron por PARTIDO AMARILLO")
print((B)," Votaron por PARTIDO MORADO")
print((C)," Votaron por PARTIDO ROJO")
#luego buscara el resultado que cumpla las dos condiciones para saber quien fue el ganador
if A > B and C:
print("El ganador es el PARTIDO AMARILLO con: ",(A), " votos")
elif B > C and A:
print("El ganador es el PARTIDO MORADO con: ",(B), " votos")
elif C > B and A:
print("El ganador es el PARTIDO ROJO con: ",(C), " votos")
else:
print("Ha habido un empate")
|
class Card:
def __init__(self, figure, color):
self.figure = figure
self.color = color
@property
def value(self):
if self.figure in ['K', 'Q', 'J']:
return 10
elif self.figure in ['2', '3', '4', '5', '6', '7', '8', '9', '10']:
return int(self.figure)
elif self.figure == 'A':
return 1, 11
def __str__(self):
return f'{self.figure}{self.color}'
class Deck:
FIGURES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
COLORS = ['\u2661 (hearts)', '\u2660 (spades)', '\u2666 (diamonds)', '\u2667 (clubs)']
def __init__(self, num_of_decks=1):
self.cards = []
for i in range(num_of_decks):
for color in self.COLORS:
for figure in self.FIGURES:
self.cards.append(Card(figure, color))
class Player:
def __init__(self):
self.hand = []
self.hand_2 = []
self.bet = 0
self.bet_2 = 0
self.bank = 0
def deposit_money(self, amount):
self.bank += amount
def draw_card(self, deck, hand=None):
if hand is None:
hand = self.hand
top_card = deck.pop()
hand.append(top_card)
def split(self):
self.hand_2.append(self.hand.pop())
self.bet_2 = self.bet
self.bank -= self.bet_2
def double(self, bet=None):
if bet is None:
self.bank -= self.bet
self.bet += self.bet
else:
self.bank -= self.bet_2
self.bet_2 += self.bet_2
def print_hand(self, hand=None):
if hand is None:
hand = self.hand
print(f'Hand: ', end='')
for card in hand:
print(card, end='')
if hand == self.hand:
print(f' Hand value: {self.hand_value}, bet: {self.bet}')
elif hand == self.hand_2:
print(f' Second hand value: {self.hand_2_value}, bet: {self.bet_2}')
def print_croupiers_hand(self):
print(f'Croupiers hand: ', end='')
for card in self.hand:
print(card, end='')
print(f' Hand value: {self.hand_value}')
@staticmethod
def count_hand_value(hand):
ret_val = 0
num_of_aces = 0
for card in hand:
if card.figure != 'A':
ret_val += card.value
else:
num_of_aces += 1
if num_of_aces != 0:
while num_of_aces > 1:
ret_val += 1
num_of_aces -= 1
if ret_val + 11 > 21:
ret_val += 1
else:
ret_val += 11
return ret_val
@property
def hand_value(self):
return self.count_hand_value(self.hand)
@property
def hand_2_value(self):
return self.count_hand_value(self.hand_2)
def player_turn(deck, player, hand, bet=None):
player_turn = None
double = False
while player_turn != 'stand':
player_turn = None
while player_turn not in ['hit', 'stand', 'double']:
player_turn = input('What do you want to do? [hit / stand / double]\n')
if player_turn == 'hit':
player.draw_card(deck, hand)
elif player_turn == 'double':
if player.bet > player.bank:
print("You don't have enough money to double the bet")
else:
double = True
player.double(bet)
print('Bet doubled')
player.draw_card(deck, hand)
if player_turn != 'stand':
player.print_hand(hand=hand)
if double or player.hand_value > 21:
break
if __name__ == '__main__':
deck = Deck()
for card in deck.cards:
print(card)
print(len(deck.cards))
|
import csv
import os
file_to_load = "budget_data.csv"
file_to_output = "budget_analysis.txt"
#defining
total_months = 0
month_of_change = []
revenue_change_list = []
greatest_increase = ["", 0]
greatest_decrease = ["", 9999999999999999999]
total_revenue = 0
# Read and convert it into a list
with open(file_to_load) as revenue_data:
#reader = csv.DictReader(revenue_data)
reader = csv.reader(revenue_data)
header = next(reader)
firstrow = next(reader)
total_months = total_months + 1
prev_revenue = int(firstrow[1])
total_revenue = total_revenue + int(firstrow[1])
for row in reader:
# The total
total_months = total_months + 1
total_revenue = total_revenue + int(row[1])
revenue_change = int(row[1]) - prev_revenue
prev_revenue = int(row[1])
revenue_change_list = revenue_change_list + [revenue_change]
month_of_change = month_of_change + [row[0]]
# The greatest increase
if revenue_change > greatest_increase[1]:
greatest_increase[0] = row[0]
greatest_increase[1] = revenue_change
# The greatest decrease
if revenue_change < greatest_decrease[1]:
greatest_decrease[0] = row[0]
greatest_decrease[1] = revenue_change
#Average Revenue Change
revenue_avg = sum(revenue_change_list) / len(revenue_change_list)
# Generate Output Summary
output = (
f"\nFinancial Analysis\n"
f"----------------------------\n"
f"Total Months: {total_months}\n"
f"Total Revenue: ${total_revenue}\n"
f"Average Revenue Change: ${revenue_avg}\n"
f"Greatest Increase in Revenue: {greatest_increase[0]} (${greatest_increase[1]})\n"
f"Greatest Decrease in Revenue: {greatest_decrease[0]} (${greatest_decrease[1]})\n")
# Print output
print(output)
# Explort to .txt
with open(file_to_output,"w") as txt_file:
txt_file.write(output)
|
# coding: utf-8
import pandas as pd
df1 = pd.DataFrame([[1,2],[2,3],[9,4]], columns=['a','b'])
df2 = pd.DataFrame([[9,2],[2,3],[1,4]], columns=['a','b'])
print "original : df1"
print df1
print "original : df2"
print df2
print "corr ( col <-> col )"
print df1['a'].corr(df2['b'])
print "corrwith ( df <-> df )"
print df1.corrwith(df2)
|
Below is code with a link to a happy or sad dataset which contains 80 images, 40 happy and 40 sad. Create a convolutional neural network that trains to 100% accuracy on these images, which cancels training upon hitting training accuracy of >.999
Hint -- it will work best with 3 convolutional layers.
import tensorflow as tf
import os
import zipfile
from os import path, getcwd, chdir
# DO NOT CHANGE THE LINE BELOW. If you are developing in a local
# environment, then grab happy-or-sad.zip from the Coursera Jupyter Notebook
# and place it inside a local folder and edit the path to that location
path = f"{getcwd()}/../tmp2/happy-or-sad.zip"
zip_ref = zipfile.ZipFile(path, 'r')
zip_ref.extractall("/tmp/h-or-s")
zip_ref.close()
# GRADED FUNCTION: train_happy_sad_model
def train_happy_sad_model():
# Please write your code only where you are indicated.
# please do not remove # model fitting inline comments.
DESIRED_ACCURACY = 0.999
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self,epoch,logs={}):
if(logs.get('acc') > DESIRED_ACCURACY):
print("\nReached 99.9% accuracy so cancelling training!")
self.model.stop_training=True
# This Code Block should Define and Compile the Model. Please assume the images are 150 X 150 in your implementation.
model = tf.keras.models.Sequential([
# Your Code Here
tf.keras.layers.Conv2D(16,(3,3),activation=tf.nn.relu,input_shape=(150,150,3)),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(32,(3,3),activation=tf.nn.relu),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(64,(3,3),activation=tf.nn.relu),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512,activation=tf.nn.relu),
tf.keras.layers.Dense(1,activation='sigmoid')
])
from tensorflow.keras.optimizers import RMSprop
model.compile(
loss='binary_crossentropy',
optimizer=RMSprop(lr = 0.001),
metrics=['acc']
)
# This code block should create an instance of an ImageDataGenerator called train_datagen
# And a train_generator by calling train_datagen.flow_from_directory
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale=1./255)
# Please use a target_size of 150 X 150.
train_generator = train_datagen.flow_from_directory(
# Your Code Here
"/tmp/h-or-s",
target_size=(150,150),
batch_size=4,
class_mode='binary'
)
callbacks=myCallback()
history = model.fit_generator(
# Your Code Here
train_generator,
steps_per_epoch=2,
epochs=18,
verbose=1,
callbacks=[callbacks])
# model fitting
return history.history['acc'][-1]
# The Expected output: "Reached 99.9% accuracy so cancelling training!""
train_happy_sad_model()
WARNING: Logging before flag parsing goes to stderr.
W0622 01:56:21.299214 140118618986304 deprecation.py:506] From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
W0622 01:56:21.707204 140118618986304 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/nn_impl.py:180: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.where in 2.0, which has the same broadcast rule as np.where
Found 80 images belonging to 2 classes.
Epoch 1/18
2/2 [==============================] - 5s 2s/step - loss: 5.7566 - acc: 0.3750
Epoch 2/18
2/2 [==============================] - 0s 5ms/step - loss: 0.9629 - acc: 0.6250
Epoch 3/18
2/2 [==============================] - 0s 47ms/step - loss: 0.6619 - acc: 0.7500
Epoch 4/18
2/2 [==============================] - 0s 48ms/step - loss: 0.9454 - acc: 0.6250
Epoch 5/18
2/2 [==============================] - 0s 48ms/step - loss: 0.6626 - acc: 0.6250
Epoch 6/18
2/2 [==============================] - 0s 6ms/step - loss: 0.6487 - acc: 0.7500
Epoch 7/18
2/2 [==============================] - 0s 44ms/step - loss: 0.4382 - acc: 0.8750
Epoch 8/18
2/2 [==============================] - 0s 5ms/step - loss: 0.6215 - acc: 0.6250
Epoch 9/18
2/2 [==============================] - 0s 42ms/step - loss: 0.6779 - acc: 0.5000
Epoch 10/18
2/2 [==============================] - 0s 5ms/step - loss: 0.5135 - acc: 0.7500
Epoch 11/18
1/2 [==============>...............] - ETA: 0s - loss: 0.2715 - acc: 1.0000
Reached 99.9% accuracy so cancelling training!
2/2 [==============================] - 0s 8ms/step - loss: 0.2050 - acc: 1.0000
1.0
# Now click the 'Submit Assignment' button above.
# Once that is complete, please run the following two cells to save your work and close the notebook
%%javascript
<!-- Save the notebook -->
IPython.notebook.save_checkpoint();
%%javascript
IPython.notebook.session.delete();
window.onbeforeunload = null
setTimeout(function() { window.close(); }, 1000);
|
from typing import List
# TODO Revise
# class Node:
# def __init__(self, data: int):
# self.data = data
# self.parent = None
#
#
# class TreeAncestor:
#
# def __init__(self, n: int, parent: List[int]):
# self.root, self.node_dict = self.populateTree(parent)
# self.total_nodes = n
#
# def populateTree(self, parent: List[int]) -> Tuple:
# node_dict = {}
# root = None
# for i, elem in enumerate(parent):
# new_node = Node(i)
# node_dict[i] = new_node
# if elem == -1:
# root = new_node
# elif elem in node_dict:
# new_node.parent = node_dict[elem]
# return root, node_dict
#
# def getKthAncestor(self, node: int, k: int) -> int:
# tree_node = self.node_dict[node]
# while k:
# ancestor = tree_node.parent
# k -= 1
# if k == 0 and ancestor:
# return ancestor.data
# elif not ancestor:
# break
# else:
# tree_node = ancestor
# return -1
class TreeAncestor:
def __init__(self, n: int, parent: List[int]):
self.pars = [parent]
for k in range(self.getLogRange(n)):
row = []
for i in range(n):
p = self.pars[-1][i]
if p != -1:
p = self.pars[-1][p]
row.append(p)
self.pars.append(row)
def getLogRange(self, n: int):
return len(bin(n)) - 2
def getKthAncestor(self, node: int, k: int) -> int:
i = 0
while k:
if node == -1:
break
if k & 1: # checking if it is an odd number
node = self.pars[i][node]
i += 1
k >>= 1
print(i, k)
return node
lst = [x for x in range(-1, 64, 1)]
obj = TreeAncestor(len(lst), lst)
print(obj.getKthAncestor(45, 41))
print(obj.getKthAncestor(56, 32))
print(obj.getKthAncestor(6, 5))
print("-----")
obj = TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2])
print(obj.getKthAncestor(3, 1))
print(obj.getKthAncestor(5, 2))
print(obj.getKthAncestor(6, 3))
print(obj.getKthAncestor(5, 1))
print("-----")
obj = TreeAncestor(5, [-1, 0, 0, 0, 3])
print(obj.getKthAncestor(1, 5))
print(obj.getKthAncestor(3, 2))
print(obj.getKthAncestor(0, 1))
print(obj.getKthAncestor(3, 1))
print(obj.getKthAncestor(3, 5))
print("-----") |
#*******
#* Read input from STDIN
#* Use: echo or print to output your result to STDOUT, use the /n constant at the end of each result line.
#* Use: sys.stderr.write() to display debugging information to STDERR
#* ***/
import sys
lines = []
for line in sys.stdin:
lines.append(line.rstrip('\n'))
numbers = lines[1:]
acc = 1
res = 0
previous = numbers[0]
sys.stderr.write("Begin\n")
for number in numbers[1:]:
sys.stderr.write(number + "\n")
if number == previous:
acc += 1
if acc > res:
res = acc
else:
acc = 1
previous = number
print(res) |
#Import os and csv modules so that we can find and import the csv
import os
import csv
#Create os path for csv to be read and the text file to written.
csvpath = os.path.join('Resources', 'election_data.csv')
text_file = os.path.join('Analysis', 'election_results.txt')
#Setup our list for finding total votes, the dictionary to hold the candidate names and votes they receieved, and set the votecount to 0 for our loop.
total_votes_list = []
candidates_names_dict = {}
vote_count = 0
#Open CSV file
with open(csvpath, newline='') as csvfile:
# CSV reader specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile, delimiter=',')
# Read the header row first and skip
csv_header = next(csvreader)
# Find the total number of votes cast
for row in csvreader:
total_votes_list.append(row[0])
total_votes = len(total_votes_list)
#https://realpython.com/iterate-through-dictionary-python/
#Set candidate variable to column containing names. Create dictionary with candidate as the key and the value to the number occurences of the candidate's name.
candidate = row[2]
if candidate in candidates_names_dict:
candidates_names_dict[candidate] = candidates_names_dict[candidate] + 1
else:
candidates_names_dict[candidate] = 1
# https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops
#Iterate over dictionary to find which candidate had the most votes and declare them the winner.
for key, val in candidates_names_dict.items():
if val > vote_count:
vote_count = val
winner = key
#Print the results to the terminal
print("Election Results")
print("------------------------")
print(f"Total Votes: {total_votes}")
print("------------------------")
#Iterate over dictionary to print candidate (key), calculate the percent of votes, and the value.
#I could not find a better way to calculate the percent of votes and have it displayed with the correct candidate.
for key, val in candidates_names_dict.items():
print(f"{key}: {round(val/total_votes * 100, 2)}% ({val})")
print("------------------------")
print(f"Winner: {winner}")
print("------------------------")
#Write the results to election_results.txt in the specifed file path.
with open(text_file, "w") as file:
# \n creates a break so that the results are displayed correctly in the text file
file.write("Election Results \n")
file.write("------------------------\n")
file.write(f"Total Votes: {total_votes}\n")
file.write("------------------------\n")
for key, val in candidates_names_dict.items():
file.write(f"{key}: {round(val/total_votes * 100, 2)}% ({val}) \n")
file.write("------------------------\n")
file.write(f"Winner: {winner}\n")
file.write("------------------------\n")
file.close() |
#!/usr/bin/python
import csv, json, os, sys
# pass the filename as an argument when calling this script
if len(sys.argv) < 2:
sys.exit('Usage: json-to-csv.py /path/to/file.json')
fileIn = sys.argv[1]
fileOnly = os.path.basename(fileIn)
try:
fileOut = sys.argv[2]
except IndexError:
fileList = [fileIn.split('.')[0], 'csv']
fileOut = ".".join(fileList)
# read in the json file
input = open(fileIn)
data = json.load(input)
input.close()
# write the output csv
with open(fileOut, "wb+") as file:
csv_file = csv.writer(file)
csv_file.writerow(data[0].keys()) # header row
for item in data:
csv_file.writerow(item.values()) |
import re
def star_one():
lines_parsed = []
for line in (y for y in get_input_as_strings() if len(y) > 0):
parsed = re.search("(\d+)-(\d+) (.): (.*)", line).groups()
lines_parsed.append([int(parsed[0]), int(parsed[1]), parsed[2], parsed[3]])
valid_count = 0
for line in lines_parsed:
letter_count = line[3].count(line[2])
if line[0] <= letter_count <= line[1]:
valid_count += 1
print(f'star one answer: {valid_count}')
def star_two():
answer = None
input = get_input_as_strings()
lines_parsed = []
for line in (y for y in input if len(y) > 0):
parsed = re.search("(\d+)-(\d+) (.): (.*)", line).groups()
lines_parsed.append([int(parsed[0]), int(parsed[1]), parsed[2], parsed[3]])
valid_count = 0
for line in lines_parsed:
num_match = 0
if line[3][line[0]-1] == line[2]:
num_match += 1
if line[3][line[1]-1] == line[2]:
num_match += 1
if num_match == 1:
valid_count += 1
answer = valid_count
print(f'star two answer: {answer}')
def get_input_as_strings():
with open('input.txt', 'r') as fd:
return fd.read().splitlines()
if __name__ == '__main__':
star_one()
star_two()
|
#匿名函数及函数做参数
def test(a,b,func):
return func(a,b)
print(test(10,20,lambda x,y:x+y))
print(test(10,20,lambda x,y:x-y)) |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 4 20:34:16 2020
@author: David Stanley
"""
def tobogganTrajectory(slopes):
# Read input text file and store contents
inputText = open("input.txt", "r")
inputContent = inputText.read()
# Close opened file
inputText.close()
# Split input into a list where each list entry is a single line from the
# input text file. Each list entry of a single line to be split to a
# secondary list of characters contained within that line in the input text
geoList1 = inputContent.split("\n")
geoList2 = []
for i in geoList1:
geoList2.append(list(i))
# Set the maximum bounds for both the x and y axis.
# Although the geological pattern repeats an unknown number of the times to
# the right of the start position, it repeats in the SAME pattern.
# The max bound will be used to enable us to loop back to the horizontal
# start position of the pattern.
# The max x axis bound will be the length of the list held in the first
# position of the geoList2 list.
# The maximum bound of the y axis will be used to identify when the bottom
# of the slope is reached. This will be the lenght of geoList2
# As we're moving through indexes in a list, subtract 1 from the lengths
# as indexes begin at 0
maxX = len(geoList2[0]) - 1
maxY = len(geoList2) - 1
# Initialise slopes interations counter to 0
slopesIters = 0
# Create a list to contain the number of trees hit on each trajectory test
# Results to be appended to list after slopes tested later in code
slopeTestResults = []
# Iterate over sets of coordinates passed in when function is called
# Coordinates held in slopes tuple
while slopesIters <= len(slopes) - 1:
moveX = slopes[slopesIters][0]
moveY = slopes[slopesIters][1]
# geoList2 is an array of coordinates. Entries in geoList2
# constitute the vertical axis (y), entries within each sub-slist constitute
# the horizontal axis (x). The start position will be y = 0, x = 0.
x = 0
y = 0
# Initialise count of trees hit to 0
trees = 0
# Iterate through geoList2 until the number of steps taken down the slope
# equals the value for maxY
while y < maxY:
# If moving x exceeds the max bound for x, loop back to the beginning
# Subtract 1 to account for 0 indexing in lists
if x + moveX > maxX:
x = ((x + moveX) - maxX) - 1
# Move x by the passed in value if it does not exceed the max value
# for x
else:
x = x + moveX
# Move y by the value passed in
y += moveY
# Check character at the coordinates given by x and y
if geoList2[y][x] == "#":
# Increment count of trees hit if character is #
trees += 1
# If character is not #, do nothing and continue loop
# Append number of trees hit on this slope to the slopeTestResults
slopeTestResults.append(trees)
slopesIters += 1
# Multiply the number of trees hit on each slope test together and return
# value
treesProduct = 1
for j in slopeTestResults:
treesProduct = treesProduct * j
return treesProduct
print(tobogganTrajectory(((1,1), (3, 1), (5, 1), (7, 1), (1, 2))))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0
root = node = ListNode(0)
while l1 or l2 or carry:
v1 = v2 = 0
if l1:
v1 = l1.val
l1 = l1.next
if l2:
v2 = l2.val
l2 = l2.next
carry, val = divmod(v1+v2+carry, 10)
node.next = ListNode(val)
node = node.next
return root.next
# if l1 and l2:
# return self.calc_list(l1,l2,0)
#
# def calc_list(self, l1, l2, flag):
# s1 = l1.val if l1 else 0
# s2 = l2.val if l2 else 0
# s = s1 + s2
# if s > 9:
# l3 = ListNode(s + flag - 10)
# flag = 1
# else:
# l3 = ListNode(s + flag)
# flag = 0
#
# if l1.next and l2.next:
# l1 = l1.next
# l2 = l2.next
# l3.next = self.calc_list(l1, l2, flag)
# else:
# if l1.next:
# l4 = l1.next
# l4.val += flag
# l3.next = l4
# elif l2.next:
# l4= l2.next
# l4.val += flag
# l3.next = l4
# elif flag:
# l3.next = ListNode(1)
#
# return l3
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_sum = -2**31
for head in range(len(nums)):
for tail in range(head+1, len(nums)+1):
print(nums[head:tail])
now_sum = sum(nums[head: tail])
if now_sum > max_sum:
max_sum = now_sum
return max_sum
def maxSubArray2(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
max_sum = cur_sum = nums[0]
for tail in range(1,len(nums)):
cur_sum = max(nums[tail], cur_sum+nums[tail])
max_sum = max(max_sum, cur_sum)
return max_sum
if __name__ == '__main__':
solution = Solution()
result = solution.maxSubArray2([-2,4,-1])
print(result)
|
class Stack():
def __init__(self):
self.items = []
def push(self, items):
self.items.append(items)
def pop(self):
return self.items.pop()
def isEmpty(self):
return self.items == []
def peek(self):
if not self.isEmpty():
return self.items[-1]
def get_stack(self):
return self.items
def reverse_string(stack, input_str):
for i in range(len(input_str)):
stack.push(input_str[i])
rev_str = ""
while not stack.isEmpty():
rev_str += stack.pop()
return rev_str
stack = Stack()
input_str = "hello"
print(reverse_string(stack, input_str))
|
# BasicCommands.py
# To check Python version (at command prompt)
#1) At command prompt, type python
#python
#2) At command prompt, type python -V (capital V)
# python -V
# -or-
# python --version
#3) in code
import sys
print(sys.version) # Human readable -> 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)]
print(sys.version_info) # sys.version_info(major=3, minor=6, micro=2, releaselevel='final', serial=0)
"""
triple double-quote string should be used for doc string
"""
'''
triple single-quote string = comment ?
'''
'''
print()
> it provides a simple interface to the sys.stdout object
> print is function in Python 3.X
> print was Statement in Python 2.X
'''
#print 'Hello Ranbir (python 2.x)'
print("Hello Ranbir (python 3)")
# This is equivalent to
import sys
sys.stdout.write("Hello Ranbir (python 3) using sys.stdout \n") # hello world
#print error messages to the standard error stream
sys.stderr.write(('Bad!' * 8) + '\n')
#
# Variable declaration
#
# Define three variables at once:
count, result, total = 0, 0, 0
# This is equivalent to:
count = 0
result = 0
total = 0
|
#ReadingWritingCsvFile.py
import csv
#The csv module’s reader and writer objects read and write sequences.
#Programmers can also read and write data in dictionary form using the DictReader and DictWriter classes.
# csv.reader(csvfile, dialect='excel', **fmtparams)¶
# csv.writer(csvfile, dialect='excel', **fmtparams)¶
#csvFileReader = csv.reader(open('xSampleCsvFile.csv', newline=''), delimiter=' ', quotechar='|')
#spamWriter = csv.writer(open('xSampleCsvFile.csv', 'w', newline=''), delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
#dataToWrite=[[1,'steve',9999]]
dataToWrite=[[1,'steve',9999],[2,'bill',9090]]
targetFileName='xSampleCsvFile2.csv'
fileToWrite=open(targetFileName, 'w')
spamWriter = csv.writer(fileToWrite)
#spamWriter = csv.writer(open('xSampleCsvFile2.csv', 'w'), delimiter=',')
spamWriter.writerows(dataToWrite)
fileToWrite.close()
for row in csv.reader(open(targetFileName, newline='\n'), delimiter=','):
print(row)
|
# ScopeRulesLEGB.py
'''
LEGB lookup rule
A reference (X) looks for the name X
> first in the current [L]ocal scope (function); then
> in the local scopes of any lexically [E]nclosing functions in your source code, from inner to outer;
(also referred as statically nested scopes), then
> in the current [G]lobal scope (the module file); and finally
> in the [B]uilt-in scope (the module builtins).
Global declarations make the search begin in the global (module file) scope instead.
* (X = value) creates or changes the name X in the current local scope, by default.
* If X is declared 'global' within the function,
the assignment creates or changes the name X in the enclosing module’s scope instead.
* If, on the other hand, X is declared 'nonlocal' within the function in 3.X (only),
the assignment changes the name X in the closest enclosing function’s local scope.
'''
X1 = 99 # Global scope name: not used
def fa():
X1 = 88 # Enclosing def local
def fb():
print(X1) # Reference made in nested def
fb()
fa() # Prints 88: enclosing def local
def f1():
X2 = 88
def f2():
print(X2) # Remembers X2 in enclosing def scope
return f2 # Return f2 but don't call it
action = f1() # Make, return function
action() # Call it now: prints 88
'''
Factory functions (a.k.a. closures)
closure - describing a functional programming technique, and
factory function— denoting a design pattern
'''
|
# IterationsAndComprehensions.py
'''
> Python’s iteration protocol, a method call model used by the for loop,
> list comprehensions, which are a close cousin to the for loop that applies an expression to items in an iterable.
'''
input_numbers = [1,2,3,4]
print(type(input_numbers)) # <class 'list'>
# print uses end='' here to suppress adding a \n, because line strings already have one
# without this, our output would be double-spaced;
# for loop can work on any sequence type in Python, including lists, tuples, and strings
for n in input_numbers:
print(n ** 2, end=' ')
print()
for x in (1, 2, 3, 4):
print(x ** 3, end=' ')
print()
for x in 'spam':
print(x * 2, end=' ')
print()
# The built-in function iter()
# takes an iterable object and returns an iterator.
#
# Each time we call the next method on the iterator gives us the next element. If there are no more elements,
# it raises a StopIteration.
iterator1 = iter(input_numbers)
print('Type of iterator :', type(iterator1))
print('Next item :', next(iterator1))
print('Next item :', next(iterator1))
print('Next item :', next(iterator1))
print('Next item :', next(iterator1))
# StopIteration as no more element to iterate
#print('Next item :', next(iterator1))
#
# The enumerate() method
# > syntax: enumerate(iterable, start=0)
# start (optional) - enumerate() starts counting from this number.
#
# > The enumerate() method adds counter to an iterable and returns it(the enumerate object).
# The returned object is a enumerate object.
# eg1
grocery = ['bread', 'milk', 'butter']
'''
(0, 'bread')
(1, 'milk')
(2, 'butter')
'''
for item in enumerate(grocery):
print(item)
''' Output of below loop is;
0 bread
1 milk
2 butter
'''
print('\n')
for count, item in enumerate(grocery):
print(count, item)
''' output for below example is :
100 bread
101 milk
102 butter
'''
print('\n')
# changing default start value
for count, item in enumerate(grocery, 100):
print(count, item)
# List Comprehension
# List comprehensions are written in square brackets because they are ultimately a way to construct a new list.
print('-----')
L1 = [11, 12, 13, 14, 15]
for n in L1:
print (n)
# alternate approach
# list comprehension expression
L2 = [x + 10 for x in L1]
print('L2 :', L2) # L2 : [21, 22, 23, 24, 25]
'''
21
22
23
24
25
'''
for x in L2:
print(x)
# Convert to uppercase
X2 =['This', 'is', 'a', 'sample', 'input']
for n2 in X2:
print(n2.upper())
# collects all the ordered combinations of the characters in two strings:
'''
Output is :
['1a', '1b', '2a', '2b', '3a', '3b', '4a', '4b']
'''
print([firstLoopVar + secondLoopVar for firstLoopVar in '1234' for secondLoopVar in 'ab'])
print('Printing Non __X names only')
import sys
print(len([x for x in dir(sys) if not x.startswith('__')])) |
# Tuples.py
# To run from python interpreter
# > cd D:\dev\python\Python101\basics\
# > python
# > exec(open('Tuples.py').read())
# -OR-
# python Tuples.py
'''
Tuples are roughly like a list that cannot be changed
—tuples are sequences, like lists,
but they are immutable, like strings.
tuples are not generally used as often as lists in practice, but their immutability is the whole point.
If you pass a collection of objects around your program as a list, it can be changed anywhere;
if you use a tuple, it cannot.
Tuples can also be used in places that lists cannot—for example, as dictionary keys
'''
# >>> List (uses [] )
# L = [1, 'apple', 1.23]
# >>> Dictionary (uses {} )
# D = {'id': 1, 'name': 'apple', 'price': 1.23}
# >>> Tuples (use () )
# myTuple1 = (1, 2, 3, 4)
myEmptyTuple=()
print('myEmptyTuple:', myEmptyTuple)
print('total elements in myEmptyTuple:', len(myEmptyTuple))
tupleUsingFunctionFromSet = tuple({'key1':'value1', 'k2':'v2'})
print('tupleUsingFunctionFromSet :', tupleUsingFunctionFromSet) #('key1', 'k2')
tupleUsingFunctionFromList = tuple(['value1','v2'])
print('tupleUsingFunctionFromList :', tupleUsingFunctionFromList) #('value1', 'v2')
myTuple1 = (1, 2, 3, 4)
print('myTuple1:', myTuple1)
print('total elements:', len(myTuple1))
print('2nd element:', myTuple1[1])
#Add some more
myTuple1 += (5, 6, 1, 1)
print('myTuple1 (after adding elements):', myTuple1)
print('myTuple1.index(1) :', myTuple1.index(1));
print('myTuple1.count(1) : ', myTuple1.count(1))
#Without explicit assiging to (+=) myTuple1, the contents will not change
print('myTuple1 :::', myTuple1 +('temp1', 'temp2'))
print('myTuple1', myTuple1)
# List inside Tuple
TupleWithListAsElement = (1, [2, 3], 4)
print('!!!! TupleWithListAsElement[1] :', TupleWithListAsElement[1]) # [2, 3]
# below line throws error 'TypeError: 'tuple' object does not support item assignment'
#TupleWithListAsElement[1] = 'somethingElse'
# but, we can change the list contents
TupleWithListAsElement[1][0] =222
print('>>> TupleWithListAsElement[1] :', TupleWithListAsElement[1]) # [222, 3]
print('>>> TupleWithListAsElement :', TupleWithListAsElement) # (1, [222, 3], 4)
# Test for immutability of Tuples
# uncomment below line and running will return error -> TypeError: 'tuple' object does not support item assignment
#myTuple1[0] = 2
# Create new tuple
myTuple1 = (99,) + myTuple1[1:] # Make a new tuple for a new value
print('myTuple1:', myTuple1)
# Like lists and dictionaries, tuples support mixed types and nesting,
#but they don’t grow and shrink because they are immutable
T = 'spam', 3.0, [11, 22, 33]
print('T[1] :', T[1]) #3.0
print('T[2][1] :', T[2][1]) # 22
#sorting
myUnsortedTuple = ('samsung', 'VU', 'Sony', 'Chroma', 'onida')
print('myUnsortedTuple :', myUnsortedTuple)
print('type of myUnsortedTuple is :', type(myUnsortedTuple)) #<class 'tuple'>
mySortedTuple=sorted(myUnsortedTuple)
print('mySortedTuple :', mySortedTuple)
print('type of sortedTuple is :', type(mySortedTuple)) #<class 'list'>
# Tuple to List
tuple2 = (1,2,3,4,5)
listFromTuple2 = [ n*10 for n in tuple2]
print('listFromTuple2 :', listFromTuple2) #[10, 20, 30, 40, 50]
#>>> from collections import namedtuple |
# Files02.py
'''
>> xDummyFile.txt
This is 1st line without line break This is 2nd line with line break
This is last line
'''
print('\n ----- printing content using for loop')
for line in open('xDummyFile.txt'):
# print(type(line)) # <class 'str'>
# line[0] = 'T'
print(line, end='')
print('\n *** Done printing content using for loop.')
# 2 : Print only if first character in line is T
print('print if line starts with t')
# OUTPUT : case sensitive, only 2nd line gets printed
lines = [line.rstrip() for line in open('xDummyFile.txt') if line[0] == 't']
print(lines) |
# MapReduceFilter.py
# map and filter are key members of Python’s early functional programming toolset
# map() function
# => Mapping Functions over Iterables: map
# Syntax : r = map(func, seq)
# The map function applies a passed-in function to each item in an iterable object
# and returns a list containing all the function call results.
#
# map applies a 'function' call to each item instead of an arbitrary 'expression',
# it is a somewhat less general tool, and often requires extra helper functions or lambdas.
'''
map calls funcIncrementBy10 on each list item
and collects all the return values into a new list
map is an iterable in Python 3.X
'''
inputList = [1, 2, 3, 4]
def funcIncrementBy10(x):
return x + 10
# ----------------------------------------------------------------
# MAP : Mapping Functions over Iterables
# iterator = map(function, listOrTupleSeqnc)
#
# note;
# * (to verify) If function is None, the identity function is assumed;
# * the iterable arguments may be a sequence or any iterable object;
# * the result is always a list
#
# ----------------------------------------------------------------
# Output : [11, 12, 13, 14]
print(list(map(funcIncrementBy10, inputList)))
# (Option-2) using list comprehension
# Output : [11, 12, 13, 14]
print(list(funcIncrementBy10(x) for x in inputList))
# Output : [11, 12, 13, 14]
print( [funcIncrementBy10(x) for x in inputList] )
# Output : {11, 12, 13, 14}
print( {funcIncrementBy10(x) for x in inputList} )
#
# (Option-3) Using Lambda instead of function
# Note : body of a lambda has to be a single expression (not a series of statements)
# Output : [11, 12, 13, 14]
print(list(map((lambda x: x + 10), inputList)))
# ----------------------------------------------------------------
# FYI : lambda example 2
#
# The general syntax of a lambda function is quite simple:
# lambda argument_list: expression
# ----------------------------------------------------------------
#e.g.,1
lower = (lambda x, y: x if x < y else y)
print(lower('a', 'b')) # a
print(lower(10,1)) # 1
#e.g.#2
showall = lambda input1: [print(line, end='') for line in input1]
# Not clear why Output : 1234>> [None, None, None, None]
print('>>', showall(inputList))
# ----------------------------------------------------------------
# FILTER : Selecting Items in Iterables
# filter(function, sequence)
# > filter out all the elements of a sequence "sequence", for which the function function returns True
# > function is its first argument. function has to return a Boolean value, i.e. either True or False.
# !!! With filter function as None, the function defaults to Identity function, and each element in randomList is checked if it's true or not.
# > sequence : iterable which is to be filtered, could be sets, lists, tuples, or containers of any iterators
# > Only if function returns True will the element be produced by the iterator, which is the return value of filter(function, sequence).
# ----------------------------------------------------------------
# list of alphabets
alphabets = ['a', 'b', 'd', 'e', 'i', 'j', 'o']
# function that filters vowels
def filterVowels(alphabet):
vowels = ['a', 'e', 'i', 'o', 'u']
if(alphabet in vowels):
return True
else:
return False
filteredVowels = filter(filterVowels, alphabets)
print('The filtered vowels are:')
for vowel in filteredVowels:
print(vowel)
''' output:
The filtered vowels are:
a
e
i
o
'''
# filter with None as function
# random list
randomList = [1, 'a', 0, False, True, '0']
filteredList = filter(None, randomList)
print('The filtered elements are:')
for element in filteredList:
print(element)
''' Output :
The filtered elements are:
1
a
True
0
'''
# ----------------------------------------------------------------
# REDUCE: Combining Items in Iterables
# > Present in functools module, so we need to import as below:
# from functools import reduce
#
# > reduces a list to a single value by combining elements via a supplied function.
#
# Note:
# At each step, reduce passes the current sum or product, along with the next item from the list,
# to the passed-in lambda function. By default, the first item in the sequence
# initializes the starting value.
# ----------------------------------------------------------------
# option-1
from functools import reduce # Import in 3.X, not in 2.X
#option-2
#import functools
# functools.reduce(...)
print(reduce((lambda x, y: x + y), [1, 2, 3, 4])) #10
print(reduce((lambda x, y: x * y), [1, 2, 3, 4])) #24
# e.g.#2
print(reduce(lambda x,y: x+y, [47,11,42,13])) # 113
|
#ClassAttributes.py
'''
Every time we use an expression of the form 'object.attr' (where object is an instance or class object),
Python searches the namespace tree from bottom to top,
beginning with object, looking for the first attr it can find.
This includes references to self attributes in your methods.
'''
class ClassA:
attrib1 = '>> Default Value for Class Attribute'
obj1 = ClassA()
obj2 = ClassA()
print('ClassA.attrib1 :', ClassA.attrib1)
print('obj1.attrib1 :', obj1.attrib1)
print('obj2.attrib1 :', obj2.attrib1)
print('----------\n ')
ClassA.attrib1 = '<<< Updated Default Value for Class Attribute'
print('ClassA.attrib1 :', ClassA.attrib1)
print('obj1.attrib1 :', obj1.attrib1)
print('obj2.attrib1 :', obj2.attrib1)
print('----------\n ')
# This creates a new instance attribute attrib1 for obj1
obj1.attrib1 = '!!! Updated Value for instance variable Obj1'
print('ClassA.attrib1 :', ClassA.attrib1)
print('obj1.attrib1 :', obj1.attrib1)
print('obj2.attrib1 :', obj2.attrib1)
## -------------------------------------------
class MixedNames: # Define class
data = 'spam' # Assign class attr
def __init__(self, value): # Assign method name
self.data = value # Assign instance attr
def display(self):
print(self.data, MixedNames.data) # Instance attr, class attr
x = MixedNames(1) # Make two instance objects
y = MixedNames(2) # Each has its own data
# self.data differs, MixedNames.data is the same
x.display() # 1 spam
y.display() # 2 spam |
#!/usr/bin/env python
# Tui Popenoe
# challenge206E.py - Recurrence Relation
import ast
import operator as op
import sys
operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
ast.USub: op.neg}
def eval_expr(expr):
"""
Evaluate the arithmetic expression and return a value
Args:
expr: A string representation of an arithmetic expression
Rets:
A numeric value as the result of the expression
"""
return eval_(ast.parse(expr, mode='eval').body)
def eval_(node):
if isinstance(node, ast.Num):
return node.n
elif isinstance(node, ast.BinOp):
return operators[type(node.op)](eval_(node.left), eval_(node.right))
elif isinstance(node, ast.UnaryOp):
return operators[type(node.op)](eval_(node.operand))
else:
raise TypeError(node)
def recurrence(n, expr):
"""Return the literal eval of the given expr and n"""
# print('Evaluating: %s%s' % (str(n), expr))
expr = expr.split()
n = str(n)
for i in expr:
n = str(eval_expr('%s%s' % (n, i)))
# print(n)
# print('= %s' % n)
return n
def get_nth_term(expr, first_term, n, count):
print('Term %s: %s' % (n, recurrence(first_term, expr)))
if n == count:
return first_term
else:
return get_nth_term(expr, recurrence(first_term, expr), n + 1, count)
def main():
if len(sys.argv) > 1:
print(get_nth_term(sys.argv[1], sys.argv[2], sys.argv[3]), sys.argv[3])
else:
print(get_nth_term(sys.stdin.readline(),
int(sys.stdin.readline()),
0,
int(sys.stdin.readline())))
if __name__ == '__main__':
main() |
#!python2
# Tui Popenoe
# Challenge104E.py - Powerplant Simulation
import sys
def power_plant(n):
l = []
for i in range(1, n+1):
if i % 3 == 0:
pass
elif i % 14 == 0:
pass
elif i % 100 == 0:
pass
else:
l.append(i)
return len(l)
def main():
if len(sys.argv) > 1:
print(power_plant(int(sys.argv[1])))
else:
print("Enter the number of days to simulate: ")
print(power_plant(int(raw_input())))
if __name__=='__main__':
main()
|
#!python2
# Tui Popenoe
# Challenge28E.py - Duplicates
def detect_duplicate(lst):
hashtable = {}
for i, v in enumerate(lst):
if v in hashtable:
print("Duplicate detected, array[%r] and array[%r] are both equal \
to %r" % (hashtable[v], i, array[i]))
hashtable[v] = i
def main():
with open(argv[1], 'r') as f:
l = f.read().split()
l = map(int, l)
detect_duplicate(l)
if __name__ == '__main__':
main() |
#!python2
# Tui Popenoe
# Challenge34E.py - Max Squares
from sys import argv
def max_squares(lst):
lst = map(int, lst)
lst.sort(reverse=True)
return (lst[0] ** 2 + lst[1] ** 2)
def main():
if len(argv) > 1:
print(max_squares(argv[1:]))
else:
print(max_squares(list(raw_input())))
if __name__ == '__main__':
main()
|
#!python2
# Tui Popenoe
# challenge105E.py Word Unscrambler
import sys
def unscramble_words(scrambled_words, word_list):
"""Unscramble the words in a wordfile passed in and match wordlist"""
output = []
for i in scrambled_words:
for k in word_list:
if len(i) > len(k):
if anagram(i, k):
output.append(k)
else:
if(anagram(k, i)):
output.append(k)
print(output)
return output
def anagram(word1, word2):
for i, item1 in enumerate(word1):
for j, item2 in enumerate(word2):
if item1 == item2:
word1.pop(i)
if not word1:
return True
else:
return False
def main():
if len(sys.argv) > 1:
unscramble_words(sys.argv[1], sys.argv[2])
else:
unscramble_words(raw_input('Enter a file: '),
raw_input('Enter a wordlist: '))
if __name__=='__main__':
main() |
#!/usr/bin/env python
# Tui Popenoe
# challenge198E.py - Words With Enemies
import sys
def battle_words(word1, word2):
winner = bust_words(word1, word2)
if len(winner[0]) > len(winner[1]):
return 'Left: %s' % ''.join(winner)
elif len(winner[1]) > len(winner[0]):
return 'Right: %s' % ''.join(winner)
else:
return 'Tie: %s' % ''.join(winner)
def bust_words(word1, word2):
if len(word1) > len(word2):
for i in word1:
if i in word2:
word1 = word1.replace(i, '')
word2 = word2.replace(i, '')
else:
for i in word2:
if i in word1:
word1 = word1.replace(i, '')
word2 = word2.replace(i, '')
return [word1, word2]
def main():
if len(sys.argv) > 1:
print(battle_words(sys.argv[1], sys.argv[2]))
else:
words = sys.stdin.readline().split()
print(battle_words(words[0], words[1]))
if __name__ == '__main__':
main() |
#!python2
# Tui Popenoe
# challenge187E.py - A Flagon of Flags
from sys import argv
def read_flags(filename):
flags = {}
output = []
with open(filename, 'r') as f:
num_flags = int(f.readline().strip())
for i in range(num_flags):
flag = f.readline().strip().split(':')
flags[flag[0]] = flag[1]
inp = f.readline().strip().split()
for i in inp:
# Check longform first
if i[0:2] == '--':
output.append('flag: ' + i[2:])
# Check shortform, loop through combined arguments
elif i[0:1] == '-':
for j in i[1:]:
output.append('flag: ' + flags[j])
# Otherwise is an argument
else:
output.append('parameter: ' + i)
return '\n'.join(output)
def main():
if len(argv) > 1:
print(read_flags(argv[1]))
else:
print(read_flags(raw_input('Enter an input file: ')))
if __name__ == '__main__':
main() |
#!python2
# Tui Popenoe
# Challenge47I.py - Number Translate
from sys import argv
cipher = {
'ze' : 0,
'on' : 1,
'tw' : 2,
'th' : 3,
'fo' : 4,
'fi' : 5,
'si' : 6,
'se' : 7,
'ei' : 8,
'ni' : 9
}
def translate_number(num):
output = list()
#for i in num:
output.append(cipher[num[:2]])
return output
def main():
if len(argv) > 1:
print(translate_number(argv[1]))
else:
print(translate_number(raw_input("Enter an english number: ")))
if __name__ == '__main__':
main() |
#!python2
# Tui Popenoe
# Challenge38E.py - Line and Word Count
from sys import argv
def counts(filename):
with open(filename, 'r') as f:
x = len(f.readlines())
y = len(f.read().split())
print("Number of lines: ", x)
print("Number of words: ", y)
def main():
if len(argv) > 1:
counts(argv[1])
else:
counts(raw_input("Enter a filename: "))
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# Tui Popenoe
# challenge221E.py Word Snake
from sys import argv
def word_snake(lst):
if lst:
print(lst[0])
space_length = len(lst[0]) - 1
turn = False
down = True
for word in lst[1:]:
if not turn and space_length + len(word) > 80:
turn = True
if turn and space_length - len(word) < 0:
turn = False
if not down:
if not turn:
print('%s%s' % (' ' * space_length, word))
space_length += len(word) - 1
else:
space_length -= len(word) - 1
print('%s%s' % (' ' * space_length, word[::-1]))
down = True
else:
for letter in word[1:-1]:
print('%s%s' % (' ' * space_length, letter))
down = False
def main():
if len(argv) > 1:
word_snake(argv[1:])
else:
word_snake(raw_input('Enter a list of words: ').split())
if __name__ == '__main__':
main() |
#!python2
# Tui Popenoe
# Challenge15E.py - Left/right justify
from ast import literal_eval
from sys import argv
import string
def justify(filename, right=False):
with open(filename, 'r+') as f:
text = f.readlines()
f.seek(0)
for i in text:
if right == True:
i = i.rjust(80, ' ')
else:
i = i.ljust(80, ' ')
f.write(i)
print(i)
f.truncate()
def main():
if len(argv) > 1:
justify(argv[1], literal_eval(argv[2]))
else:
justify(raw_input("Filename: "),
literal_eval(raw_input("Right Justify (True/False): ")))
if __name__ == '__main__':
main()
|
# Tui Popenoe
# Challenge 166b Planetary Gravity
"""Calculate the weight of an object upon the surface of a planet."""
import sys
import math
def calcVolume(r):
return (4/3) * (math.pi * pow(r, 3))
def calcMass(v, d):
return v*d
def calcForce(m1, m2, d):
g = (m1 * m2) / pow(d, 2)
def calcWeight(planets):
f = open("input.txt", 'r')
mass = int(f.readline())
planets = int(f.readline())
weight = []
for i in range(planets):
p = f.readline().split(',')
m2 = calcMass(calcVolume(p[1]), p[2])
force = calcForce(mass, m2, p[1])
weight.append(force)
return weight
def main():
calcWeight()
if __name__=='__main__':
main() |
#!python2
# Tui Popenoe
# challenge185E.py - Generated Twitter Handles
from sys import argv
def find_handles(filename):
output = []
with open(filename, 'r') as f:
wordlist = f.read().splitlines()
for i in wordlist:
if i[0:2] == 'at':
output.append(('@' + i[2:] + ' : ' + i))
elif i[0:1] == 'a':
output.append('@' + i[1:] + ' : ' + i)
output.sort(key = len)
return '\n'.join([' '.join(output[0:10]), ' '.join(output[-10:])])
def main():
if len(argv) > 1:
print(find_handles(argv[1]))
else:
print(find_handles(raw_input('Enter a word file: ')))
if __name__ == '__main__':
main() |
#!python2
# Tui Popenoe
# challenge190E.py - Webscraping Sentiments
import lxml
import logging
import urllib2
import sys
import lxml.html
def parse_page(url):
try:
# Fetch the url
doc = urllib2.urlopen(url)
if doc:
# parse the tree.
tree = lxml.html.parse(doc)
# use xpath to find nodes
nodes = tree.xpath('//div[@class="Ct"')
for node in nodes:
print(node)
except Exception, ex:
logging.error(ex)
def main():
if len(sys.argv) > 1:
parse_page(sys.argv[1])
else:
parse_page(raw_input("Enter a URL to parse: "))
if __name__ == '__main__':
main() |
# Tui Popenoe
# Challenge 161 Blackjack
""" Implementatoin of a simulation of blackjack hands. Calculates the
percentage of hands dealt that are blackjack (21) given a variable number
of decks of cards. Accepts input as a text file or a command line argument.
"""
import random
import sys
deck = [
'2S', '2C', '2D', '2H',
'3S', '3C', '3D', '3H',
'4S', '4C', '4D', '4H',
'5S', '5C', '5D', '5H',
'6S', '6C', '6D', '6H',
'7S', '7C', '7D', '7H',
'8S', '8C', '8D', '8H',
'9S', '9C', '9D', '9H',
'10S', '10C', '10D', '10H',
'JS', 'JC', 'JD', 'JH',
'QS', 'QC', 'QD', 'QH',
'KS', 'KC', 'KD', 'KH',
'AS', 'AC', 'AD', 'AH'
]
def dealHand(deck):
count1 = random.randint(0, len(deck)-1)
card1 = deck.pop(count1)
print(card1)
count2 = random.randint(0, len(deck)-1)
card2 = deck.pop(count2)
print(card2)
hand = [card1, card2]
print(hand)
return hand
def shuffleDecks(n, deck):
decks = []
for i in range(int(n)):
decks.extend(deck)
return decks
def calculateBlackjack(n, deck):
hands = []
count = 0
total = 0
for i in range(int(n)*26):
hands.extend(dealHand(deck))
card1 = hands[i][:-1]
print('Hand: ' + hands[i])
#print('Card1: ' + card1)
card2 = hands[i][:-1]
#print('Card2: ' + card2)
if card1 == '10':
if card2 == 'A':
count += 1
if card2 == 'A':
if card2 == '10':
count += 1
total += 1
print(count/total)
return count / total
def main():
random.seed()
n = sys.argv[1]
print(n)
decks = shuffleDecks(n, deck)
calculateBlackjack(n, decks)
if __name__=='__main__':
main() |
# Tui Popenoe
# Challenge 163 Probability Distribution of six sided die
"""Simulate various numbers of rolls of a six-sided die, and display the
distribution of the numbers rolled. """
import sys
import random
import math
def printGrid(grid):
print(grid)
def createGrid():
grid = list()
for i in range(8):
grid.append(list())
rolls = simulateRolls(10**i)
for j in range(7):
if i == 0:
grid[i].append(10**i)
else:
grid[i].append(rolls[j-1])
return grid
def simulateRolls(n):
rolls = [0, 0, 0, 0, 0, 0]
for k in range(n):
r = random.randint(0,5)
rolls[r] += 1
for k in range(len(rolls)):
rolls[k] /= float(n)
print(rolls)
return rolls
def main():
random.seed()
grid = createGrid()
print(grid)
if __name__=='__main__':
main() |
#!python2
# Tui Popenoe
# challenge179e.py - Convert Image to Grayscale
from PIL import Image
def grayscale(imagefile='image.jpg'):
"""Convert the image file to grayscale."""
im = Image.open(imagefile)
pix = im.load()
print('Image Size: ' + str(im.size))
for i in range(im.size[0]):
for j in range(im.size[1]):
gray = sum(pix[i, j]) /3
pix[i, j] = (gray, gray, gray)
grayscale = im.save(imagefile, 'JPEG')
def main():
grayscale()
if __name__ == '__main__':
main() |
#!python2
# Tui Popenoe
# Challenge55I.py - Validating Input
from sys import argv
def display_sum(user_input):
inp = user_input.split(' ')
if int(inp[0]) >= 0 and int(inp[0]) <= 9:
if int(inp[1]) >= 1 and int(inp[1]) <= 9:
s = int(inp[0]) + int(inp[1])
print(inp[0] + ' + ' + inp[1] + ' = ' + str(s))
return
print('Invalid')
return
def main():
if len(argv) > 1:
display_sum(argv[1])
else:
display_sum(raw_input("Enter two integers 0 - 9 on one line: "))
if __name__ == '__main__':
main() |
# basic implementation of music playing functionality!
from os import system
def play_music(commands):
song = raw_input("What song was it that you wanted to hear?\n")
if not 'by' in song:
system('spotify play [' + song + ']')
def main(commands):
print ('Entering DJ mode...')
active = True
current_commands = commands;
while active:
for word in current_commands:
if word == 'quit':
system('spotify quit')
print ('Leaving DJ mode...')
return
elif word == 'play':
play_music(commands)
break
elif word == 'resume':
system('spotify play')
break
elif word == 'pause':
system('spotify pause')
break
elif word == 'back':
system('spotify prev')
break
elif word == 'skip':
system('spotify next')
break
# current_commands = raw_input('What\'s next?\n').split(' ')
|
print("\nDame un numero del 1 al 100")
Num = int(input())
if Num < 100:
print("\nEse numero es menor a 100")
else:
print("\nEse numero es mayor a 100")
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# import all the required libraries
#Author: Arun Kumar and Rahul Noronha
#Date:
#23/09/2020
#->Encoding function worked for png only, RGB_To_Grayscale and JPEG_To_PNG throwing IOError
#24/09/2020
#->Encoding function worked for png and jpg only RGB_To_Grayscale worked succesfully,
#->JPEG_To_PNG works only for JPG and fails for JPEG
import cv2
import numpy as np
import types
from Convert_Image import * # User defined module to Convert JP(E)G to PNG and RGB to Grayscale
# Has two functions RGB_To_Grayscale and JPEG_To_PNG which take parameters input file name and output file name
DELIMETER = '#####'
def to_binary(message):
'''
Function to convert the message to be encoded to Binary
'''
if type(message) == str:
try: # Have to do this because either hide_data or unhide_data doesn't work for non-ascii chars
message.encode('ascii')
except UnicodeEncodeError:
raise TypeError('Input type not supported')
return ''.join([format(ord(i), '08b') for i in message])
elif type(message) == bytes or type(message) == np.ndarray:
return [format(i, '08b') for i in message]
elif type(message) == int or type(message) == np.uint8:
return format(message, '08b')
else:
raise TypeError('Input type not supported')
def hide_data(image, secret_message):
'''
Function to Hide the binary data into the Image
Hidden one bit in LSB of red, green and blue pixel
LSB technique causes minor change in the pixel values
TODO: Consider encrypting the hidden message before encoding and decrypting the decoded message later to provide additional security
'''
# calculate the maximum bytes that can be encoded
n_bytes = image.shape[0] * image.shape[1] * 3 // 8
print('Maximum bytes to encode:', n_bytes)
# Check if the number of bytes to encode is less than the maximum bytes in the image
if len(secret_message) > n_bytes:
raise ValueError('Error: Insufficient bytes. Need bigger image or less data')
secret_message += DELIMETER # you can use any string as the delimeter
secret_message = to_binary(secret_message)
data_index = 0
data_len = len(secret_message)
for values in image:
for pixel in values:
# convert RGB values to binary format
(r, g, b) = to_binary(pixel)
# modify the least significant bit only if there is still data to store
if data_index < data_len:
# hide the data into least significant bit of red pixel
pixel[0] = int(r[:-1] + secret_message[data_index], base=2)
data_index += 1
if data_index < data_len:
# hide the data into least significant bit of green pixel
pixel[1] = int(g[:-1] + secret_message[data_index], base=2)
data_index += 1
if data_index < data_len:
# hide the data into least significant bit of blue pixel
pixel[2] = int(b[:-1] + secret_message[data_index], base=2)
data_index += 1
# if data is encoded, just break out of the loop
if data_index >= data_len:
break
return image
def unhide_data(image):
'''
This function is used to decode the message from the png image file by checking for our preset delimiter DELIMETER which can be changed to anything we want.
'''
binary_data = ''
for values in image:
for pixel in values:
(r, g, b) = to_binary(pixel) # convert the red, green and blue values into binary format
# extracting data from the least significant bit of red, green and blue pixels
binary_data += r[-1] + g[-1] + b[-1]
# split by 8-bits
all_bytes = [binary_data[i:i + 8] for i in range(0,
len(binary_data), 8)]
# convert from bits to characters
decoded_data = ''
for byte in all_bytes:
decoded_data += chr(int(byte, base=2))
if decoded_data[-5:] == DELIMETER: # check if we have reached the delimeter which is "#####"
break
# print(decoded_data)
return decoded_data[:-5] # remove the delimeter to show the original hidden message
def display_image(image, title):
print('The shape of the image is', image.shape) # check the shape of image to calculate size in bytes
resized_image = cv2.resize(image, (500, 500)) # resize the image as per your requirement
cv2.imshow(title, resized_image) # display the image
cv2.waitKey(0)
cv2.destroyAllWindows()
def encode_text():
'''
This function is used to read the message to be encoded and the image file to hide the message in and then decode the message into the image using hide_data.
TODO: Fails for jpeg images, so fix this.
'''
input_image_path = input('Enter image path: ')
input_image_path = os.path.abspath(input_image_path)
image = cv2.imread(input_image_path) # Read the input image using OpenCV-Python.
if image is None:
raise FileNotFoundError()
display_image(image, 'Resized Input Image')
data = input('Enter data to be encoded : ')
if len(data) == 0:
raise ValueError('Data is empty')
output_image_path = input('Enter path for output image (PNG recommended) : ')
output_image_path = os.path.abspath(output_image_path)
encoded_image = hide_data(image, data)
cv2.imwrite(output_image_path, encoded_image)
print("Output image has been generated at", output_image_path)
def decode_text():
# Decode the data in the image
# read the image that contains the hidden image
input_image_path = input('Enter image path: ')
input_image_path = os.path.abspath(input_image_path)
image = cv2.imread(input_image_path) # Read the input image using OpenCV-Python.
display_image(image, 'Resized Image with Hidden text')
text = unhide_data(image)
print('Decoded message is ' + text)
return text
def menu():
choice = int(input("Encode (1) or Decode (2): "))
if choice == 1:
encode_text()
elif choice == 2:
print('Decoded message is ' + decode_text())
else:
raise Exception('Invalid input.')
def THmain():
while True:
menu()
yn = input("Do you want to continue? (y/n): ").lower()
if yn != 'y': break
if __name__ == '__main__':
THmain()
|
board = [
["_", "_", "_"],
["_", "_", "_"],
["_", "_", "_"]
]
is_x_turn = True
is_valid_move = False
is_still_playing = True
def if_raw(board):
x_won = False
o_won = False
for i in range(len(board)):
x_counter = ''
o_counter = ''
for n in range(len(board)):
if board[i][n] == 'x':
x_counter += 'x'
elif board[i][n] == 'o':
o_counter += 'o'
if x_counter == 'xxx':
x_won = True
elif o_counter == 'ooo':
o_won = True
return o_won, x_won
def if_column(board):
x_won = False
o_won = False
for i in range(len(board)):
x_counter = ''
o_counter = ''
for n in range(len(board)):
if board[n][i] == 'x':
x_counter += 'x'
elif board[n][i] == 'o':
o_counter += 'o'
if x_counter == 'xxx':
x_won = True
print("2")
elif o_counter == 'ooo':
o_won = True
return o_won, x_won
def if_diagonal(board):
x_won = False
o_won = False
if (board[0][0] and board[1][1] and board[2][2] == 'x') or (board[0][2] and board[1][1] and board[2][0] == 'x'):
x_won = True
elif(board[0][0] and board[1][1] and board[2][2] == 'x') or (board[0][2] and board[1][1] and board[2][0] == 'o'):
o_won = True
return o_won, x_won
def print_board(board):
for raw in board:
blank_str = ""
for item in raw:
blank_str += item
print(blank_str)
print("enter x and y coordinates (1 - 3)")
while is_still_playing:
print_board(board)
if is_x_turn:
print("it's x's turn")
else:
print("it's o's turn")
while not is_valid_move:
move_x = int(input("x coordinate: >")) - 1
move_y = int(input("y coordinate: >")) - 1
if board[move_y][move_x] != "_":
print("spot already taken")
is_valid_move = False
else:
is_valid_move = True
if is_x_turn:
board[move_y][move_x] = "x"
is_x_turn = False
else:
board[move_y][move_x] = "o"
is_x_turn = True
o_won_row, x_won_row = if_raw(board)
o_won_column, x_won_column = if_column(board)
o_won_diagonal, x_won_diagonal = if_diagonal(board)
if o_won_column or o_won_row or o_won_diagonal:
print("o won")
print_board(board)
break
elif x_won_row or x_won_column or x_won_diagonal:
print("x won")
print_board(board)
break
is_valid_move = False
|
from utils import database
USER_CHOICE = """
Your Choices are the following :
- "a" to add a new book
- "l" to list all books
- "r" to mark a book as read
- "d" to delete the book
- "q" to exit
Enter Your Choice:"""
#Defining Function for providing options to theuser
def menu():
database.create_books_table()
user_input = input(USER_CHOICE).strip()
while user_input != "q":
if user_input == "a":
add_book()
elif user_input == "l":
books_list()
elif user_input == "r":
read_book()
elif user_input == "d":
delete_book()
else:
print("Wrong Input , please try again!!!")
user_input = input(USER_CHOICE)
# Adds the book you entered in the Database
def add_book():
book_name = input("Enter the name of the book: ").strip()
author_name = input("Enter the name of the Author: ").strip()
database.add_books(book_name, author_name)
#Print the list of books present in the database
def books_list():
books = database.get_all_books()
for book in books:
read = "YES" if book["read"] == 1 else "NO"
print(f"{book['book_name']} is written by {book['author_name']}, read: {read}")
#If the the has been read already then it will be marked as read
def read_book():
book_name = input("Enter the name of the book you have read already: ").strip()
database.mark_as_read(book_name)
#Delete the book you want to delete from the database
def delete_book():
book_name = input("Enter the name of the book you want to delete: ").strip()
books = database.get_all_books()
for book in books:
database.delete_the_book(book_name)
#Driver Function
if __name__ == "__main__":
menu()
|
import random, sys
print ('ROCK, PAPER,SCISSORS')
#these variable to keep track of the wins
wins = 0
losses = 0
ties = 0
#The main game loop
while True:
print('%s Wins, %s Losses, %s Ties' % (wins,losses,ties))
while True:
print('Enter you move:(r)ock,(p)aper, (s)cissors or (q)uit')
playerMove = input()
if playerMove == 'q':
print('Bye!')
sys.exit()
if playerMove == 'r' or playerMove == 'p' or playerMove == 's':
break
print('Type one of q, r, s or q.')
#diplay what the person has chosen
if playerMove == 'r':
print('Rock versus...')
elif playerMove == 'p':
print('Paper versus...')
elif playerMove == 's':
print('Scissors versus...')
#display what the computer chosen
ranNum = random.randint(1,3)
if ranNum == 1:
comMove = 'r'
print('ROCK')
if ranNum == 2:
comMove = 'p'
print('PAPER')
if ranNum == 3:
comMove = 's'
print('SCISSORS')
#display win loss record
if playerMove == comMove:
print("it's a tie")
ties = ties + 1
elif playerMove == 'r' and comMove == 's':
print('you win!')
wins = wins + 1
elif playerMove == 'p' and comMove == 'r':
print('you win')
wins = wins + 1
elif playerMove == 's' and comMove == 'p':
print('you win')
wins = wins + 1
elif playerMove == 'r' and comMove == 'p':
print('you lose!')
losses = losses + 1
elif playerMove == 'p' and comMove == 's':
print('you lose!')
losses = losses + 1
elif playerMove == 's' and comMove == 'r':
print('you lose!')
losses = losses + 1
|
#fortune ball
import random
def getA(AnswerN):
if AnswerN == 1:
print('you will marry a hottie')
elif AnswerN == 2:
print('you will have a sad life')
elif AnswerN == 3:
print('you will be cool, but your friends won\'t like you')
elif AnswerN == 4:
print('you will die very old')
elif AnswerN == 5:
print('you will die young')
elif AnswerN == 6:
print('you will be rich out of your mind')
elif AnswerN == 7:
print('you will poor out of your mind')
r = random.randint(1,7)
fortune = getA(r)
print(fortune)
|
import sqlite3
class Connect(object):
def __init__(self,db_name):
try:
self.connection = sqlite3.connect(db_name)
self.c = self.connection.cursor()
except sqlite3.Error:
print("Erro ao abrir o banco.")
def commit_db(self):
if self.c:
self.connection.commit()
def close_db(self):
if self.c:
self.connection.close()
print("conexão fechada.")
class Organizador(object):
tb_name = 'organizador'
def __init__(self):
self.db = Connect('organizador.db')
self.tb_name
def cadastra_game(self):
self.nome = input("Nome do jogo: ")
self.genero = input("Genero do jogo: ")
self.horas = input("horas para terminar o jogo: ")
self.data = input("Data de lançamento: ")
try:
self.db.c.execute("""
INSERT INTO organizador(nome,genero,horas,data)
VALUES(?,?,?,?)
""",(self.nome,self.genero,self.horas,self.data))
self.db.commit_db()
except sqlite3.IntegrityError:
return False
def ler_games(self):
sql = 'SELECT id,nome,genero,horas,data FROM organizador ORDER BY nome'
r = self.db.c.execute(sql)
return r.fetchall()
def imprimir_games(self):
lstGames = self.ler_games()
print('{:>3s} {:5} {:3s} {:3s} {:3s} ' .format(
'id', 'nome','genero', 'horas', 'lancado',))
for d in lstGames:
print(d)
def localizar_genero(self):
while True:
self.genero = input("Digite o genero do jogo: ")
if self.genero:
r = self.db.c.execute('SELECT * FROM organizador WHERE genero =?',(self.genero,))
self.db.commit_db()
return r.fetchall()
def imprimir_genero(self):
self.localizar_genero()
lstDeGenero = self.localizar_genero()
for d in lstDeGenero:
print(d)
def localizar_acima(self):
sql = 'SELECT * FROM organizador WHERE horas >=30 '
r = self.db.c.execute(sql)
return r.fetchall()
def imprimir_acima(self):
self.localizar_acima()
lstAcima = self.localizar_acima()
for a in lstAcima:
print(a)
def localizar_abaixo(self):
sql = 'SELECT * FROM organizador WHERE horas <30'
r = self.db.c.execute(sql)
return r.fetchall()
def imprimir_abaixo(self):
self.localizar_abaixo()
lstAbaixo = self.localizar_abaixo()
for c in lstAbaixo:
print(c)
O = Organizador()
#
#
#O.localizar_genero()
#O.imprimir_genero()
def menu():
print("1- Cadastrar jogo \n2- Listar todos os jogos \n3- Buscar jogo por genero \n4- Buscar jogos com mais de 30 horas"
" \n5- Buscar jogos com menos de 30 horas \n"
"0- Sair")
return int(input("Entre com a opção: "))
if __name__ == '__main__':
O = Organizador()
op = -1
while op != 0:
op = menu()
if op==1:
O.cadastra_game()
elif op==2:
O.imprimir_games()
elif op==3:
O.imprimir_genero()
elif op == 4:
O.imprimir_acima()
elif op == 5:
O.imprimir_abaixo()
|
import unittest
class NumberTest(unittest.TestCase):
"""
Uses subtest to display all tests within a test method
"""
def test_even_numbers(self):
"""
with subtest, all failures are shown
"""
for i in range(10):
with self.subTest(i=i):
self.assertEqual(i % 2,0)
def test_even_numbers_again(self):
"""
without subtest, only first failure is shown
"""
for i in range(10):
self.assertEqual(i % 2,0) |
# 链表机制不明!
from typing import *
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 此段代码只能在leetcode下通过
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
res_num = Solution.ln_to_int(l1) + Solution.ln_to_int(l2)
return [ int(num) for num in str(res_num)[::-1] ]
@staticmethod
def ln_to_int(ln):
cur_str = ''
cur_node = ln
while 1:
cur_str = str(cur_node.val) + cur_str
cur_node = cur_node.next
if cur_node is None:break
return int(cur_str)
if __name__ == '__main__':
s = Solution()
|
# Importing the module – tkinter, time
# Create the main window (container)
# Add number of widgets to the main window:Button, Entry
# Apply the event Trigger on the widgets.
import time #Python time module provides many ways of representing time in code
from tkinter import * #tkinter module is used for graphical representation in output
from tkinter import messagebox #MessageBox module is used to display message boxes in your applications
root = Tk() #The root window is created. The root window is a main application window in our programs.
root.geometry("400x250") #set the geometry to window
root.title("Countdown Timer") #set title to window
hour = StringVar() # Declaration of variables
minute = StringVar()
second = StringVar()
hour.set("00") # setting the default value as 0
minute.set("00")
second.set("00")
# Use of Entry class to take input from the user
hourEntry = Entry(root, width=3, font=("Arial", 18, ""),textvariable=hour,borderwidth="10")
hourEntry.place(x=80, y=20)
minuteEntry = Entry(root, width=3, font=("Arial", 18, ""),textvariable=minute,borderwidth="10")
minuteEntry.place(x=180, y=20)
secondEntry = Entry(root, width=3, font=("Arial", 18, ""),textvariable=second,borderwidth="10")
secondEntry.place(x=280, y=20)
def submit():
try: # the input provided by the user is stored in here :temp
temp = int(hour.get()) * 3600 + int(minute.get()) * 60 + int(second.get()) # total secods calculate
except:
print("Please input the right value")
while temp > -1:
# divmod(firstvalue = temp//60, secondvalue = temp%60)
mins, secs = divmod(temp, 60)
# Converting the input entered in mins or secs to hours,
# mins ,secs(input = 110 min --> 120*60 = 6600 => 1hr :
# 50min: 0sec)
hours = 0
if mins > 60: hours, mins = divmod(mins, 60)
# divmod(firstvalue = temp//60, secondvalue = temp%60)
# using format () method to store the value up to
# two decimal places
hour.set("{0:2d}".format(hours))
minute.set("{0:2d}".format(mins))
second.set("{0:2d}".format(secs))
# updating the GUI window after decrementing the
# temp value every time
root.update()
time.sleep(1)
# when temp value = 0; then a messagebox pop's up
# with a message:"Time's up"
if (temp == 0):
messagebox.showinfo("Time Countdown", "Time's up ")
# after every one sec the value of temp will be decremented
# by one
temp -= 1
btn = Button(root, text='Start Countdown', bd='5',command=submit, fg="black",bg="white", font=("Helvetica 26 bold", 10 ),relief=GROOVE, padx=40,pady=20,borderwidth="20")
btn.place(x=70, y=120)
root.configure(background="black")
# infinite loop which is required to
# run tkinter program infinitely
# until an interrupt occurs
root.mainloop() |
# PROBLEM DESCRIPTION
#
# An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.
# is_isogram("Dermatoglyphics" ) == true
# is_isogram("aba" ) == false
# is_isogram("moOse" ) == false # -- ignore letter case
# My naive solution
def is_isogram(string):
charstring = [char for char in string]
checked = []
for char in charstring:
if char not in checked:
checked.append(char)
checked.append(char.upper())
elif char in checked:
return False
return True
# Thoughtful approach
def is_isogram(string):
return len(string) == len(set(string.lower()))
# What is set() method: https://www.geeksforgeeks.org/python-set-method/
# Kata link: https://www.codewars.com/kata/54ba84be607a92aa900000f1
|
class Stack():
"""堆栈"""
def __init__(self, max_size):
self.max_size = max_size
self.arr = []
def counts(self):
return len(self.arr)
def push(self, item):
if len(self.arr) == self.max_size:
print('数据已满,不能存入')
return None
self.arr.insert(0, item)
print('%s存入成功'%item)
def pull(self):
return self.arr.pop()
def full(self):
if len(self.arr) == self.max_size:
print('Is Full!!')
else:
print('Not Full!!')
def index_of(self, index):
return self.arr[index]
def replace(self, index, item):
self.arr[index] = item
print('Done!!')
def delete(self, index):
del self.arr[index]
s = Stack(5)
s.counts()
class Node():
"""地址"""
def __init__(self, value):
self.value = value
self.next = None
self.head = False
self.end = False
class LinlkedList():
"""链表"""
def __init__(self):
self.arr = []
def initlist(self, item):
node = Node(item[0])
self.arr.append(node)
next = node.next
node.head = True
for x in range(1,len(item)):
node = Node(item[x])
self.arr.append(node)
node.next = next
next = node.next
if x == len(item) - 1:
node.end = True
print('创建链表成功!')
def counts(self):
print('长度为%s' % len(self.arr))
def add(self, item):
node = Node(item)
node.end = True
self.arr.append(node)
self.arr[-2].end = False
self.arr[-2].next = node
print('添加成功')
def index_of(self, index):
print(self.arr[index].value)
def remove_item(self, item):
remove_list = []
for x in range(len(self.arr)):
if item == self.arr[x].value:
self.arr[x-1].next = self.arr[x+1]
remove_list.append(x)
for y in remove_list:
del self.arr[y]
print('%s删除成功!' % item)
def remove_all(self):
self.arr = []
print('删除全部,成功!')
def remove_index(self, index):
if index == 0:
self.arr[1].head = True
print('删除成功')
return None
elif index == len(self.arr) - 1:
self.arr[-2].end = True
print('删除成功')
return None
del self.arr[index]
self.arr[index-1].next = self.arr[index]
print('删除成功')
return None
def update_item(self, item1, item2):
for x in range(len(self.arr)):
if item1 == self.arr[x].value:
self.arr[x].value = item2
print('修改成功!')
break
def look(self):
total = [x.value for x in self.arr]
print(total)
l = LinlkedList()
l.initlist([1,2,3,4,5,6])
class Location():
def __init__(self, value):
self.value = value
self.next = None
class LinkTable():
"""链表没有列表"""
def __init__(self):
self.head = Location('head')
self.end = Location('end')
self.head.next = self.end
# def add(self, item):
# obj = Location(item)
# loc = self.head
# while loc.next != self.end:
# loc = loc.next
# loc.next = obj
# obj.next = self.end
# print('添加成功')
def add(self, item):
self.insert(self.counts(), item)
def insert(self, index, item):
obj = Location(item)
loc = self.head
count = 0
while count != index:
loc = loc.next
count += 1
obj.next = loc.next
loc.next = obj
print('添加成功')
def counts(self):
count = 0
obj = self.head
while obj.next.value != 'end':
obj = obj.next
count += 1
# print('长度为%d'%count)
return count
def update(self, item1, item2):
loc = self.head
while loc.value != item1:
loc = loc.next
loc.value = item2
print('修改成功')
def index_of(self, index):
loc = self.head
count = 0
while count != index:
loc = loc.next
print(loc.value)
def remove_by_index(self, index):
loc = self.head
count = 0
while count != index:
loc = loc.next
count += 1
a = loc.next
loc.next = loc.next.next
print('删除成功')
def remove_by_item(self, item):
loc = self.head
count = 0
while loc.next.value != item:
loc = loc.next
count += 1
loc.next = loc.next.next
print('删除成功')
def look(self):
loc = self.head.next
while loc.value != 'end':
print(loc.value, end=' ')
loc = loc.next
li = LinkTable()
li.add(100)
li.add(999)
li.add(666)
li.add(222)
li.remove_by_index(0)
li.look()
li.counts()
def func1():
print('func1')
def func2():
print('func2')
def func3():
print('func3')
d = {'a': func1, 'b': func2, 'c': func3}
d.get('a')()
|
class Stack:
def __init__(self, max_size):
self.max_size = max_size
self.top = None
def push(self, item):
if self.size() != self.max_size:
node = Node(item)
node.next_node = self.top
self.top = node
def pop(self):
if self.top is None:
return None
else:
tmp = self.top.value
self.top = self.top.next_node
return tmp
def index(self, item):
top = self.top
index = self.size() - 1
while top:
if top.value == item:
return index
index -= 1
top = top.next_node
return None
def empty(self):
self.top = None
def full(self):
for i in range(self.max_size):
self.push(i)
def size(self):
top = self.top
count = 0
while top:
count += 1
top = top.next_node
return count
def get(self, index):
top = self.top
num = self.size()
for i in range(num):
if index == num-1-i:
return top.value
top = top.next_node
class Query:
def __init__(self):
self.right = None
def push(self, item):
right = self.right
if right:
while right.next_node:
right = right.next_node
right.next_node = Node(item)
else:
self.right = Node(item)
def pop(self):
if self.right is None:
return None
else:
right = self.right
self.right = right.next_node
return right
def size(self):
count = 0
right = self.right
while right:
count += 1
right = right.next_node
return count
class Node:
def __init__(self, value):
self.value = value
self.next_node = None
#链表
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
if self.head:
head = self.head
while head.next_node:
head = head.next_node
head.next_node = Node(value)
else:
self.head = Node(value)
def insert(self, value, index):
head = self.head
if index <= 0:
self.head = Node(value)
self.head.next_node = head
elif index >= self.size():
if head:
while head.next_node:
head = head.next_node
head.next_node = Node(value)
else:
self.append(value)
else:
next_node = head.next_node
for i in range(index - 1):
head = head.next_node
next_node = next_node.next_node
head.next_node = Node(value)
head.next_node.next_node = next_node
def delete(self, index):
head = self.head
if head:
if index == 0:
self.head = head.next_node
if 0 < index < self.size() - 1:
next_node = head.next_node
for i in range(index - 1):
head = head.next_node
next_node = next_node.next_node
head.next_node = next_node.next_node
if index == self.size() - 1:
while head.next_node.next_node:
head = head.next_node
head.next_node = None
def size(self):
count = 0
head = self.head
while head:
count += 1
head = head.next_node
return count
def remove(self, value):
head = self.head
if head:
if head.value == value:
self.head = head.next_node
else:
while head.next_node:
if head.next_node.value == value:
head.next_node = head.next_node.next_node
break
head = head.next_node
def index(self, value):
head = self.head
index = 0
index_list = []
while head:
if head.value == value:
index_list.append(index)
index += 1
head = head.next_node
return index_list
def __repr__(self):
str_link = ''
head = self.head
if head:
while True:
str_link += str(head.value)
if head.next_node:
head = head.next_node
str_link += '→'
else:
break
return str_link
else:
return 'There is nothing'
if __name__ == "__main__":
pass |
#Simple neural network with backpropagation learning
#Created by Mark Palenik
#I created this mainly as an exercise in learning python
#it's not necessarily the most efficient python code, as it is
#my first project, but it works.
import random
import math
class Node:
def __init__(self):
self.weights = [] #weights connecting to next layer
self.invalue = 0 #input from previous layer
self.outvalue = 0 #output to next layer
self.olddws = [] #for momentum
class Layer:
def __init__(self):
self.Nodes = []
self.nnodes = 0
class Network:
def __init__(self):
self.alpha = 0.1 #momentum
self.eta = 10.0 #scale factor on gradient
self.Nlayers = 0
self.Layers = []
def ActivationFunction(self,x):
#activation function, bound between 0 and 1
return 1.0/(1.0+math.exp(-x))
def ActivationDeriv(self,x):
#derivative of activation function
denom = (1.0+math.exp(-x))
return math.exp(-x)/(denom*denom)
def AddLayers(self,nNodes):
#Add layers to neural network. nNodes is a list
#containing the number of nodes in each layer
nAdd = len(nNodes)
for i in range(nAdd):
L = Layer()
L.nnodes=nNodes[i]
for j in range(nNodes[i]): L.Nodes.append(Node())
self.Layers.append(L)
if (self.Nlayers>0):
for node in self.Layers[self.Nlayers-1].Nodes:
for j in range(nNodes[i]): node.weights.append(2.0*(random.random()-0.5))
node.olddws = [0]*nNodes[i]
self.Nlayers = self.Nlayers+1
def AddLayer(self,nNodes):
#wrapper for AddLayers to add a single layer with nNodes nodes
AddLayers(1,[nNodes])
def RunNetwork(self,input):
#forward propagate the network. input is a list containing the
#input. Returns a list with the output from each node in the output layer
currLayer = self.Layers[0]
for i in range(currLayer.nnodes): currLayer.Nodes[i].outvalue = input[i]
LastLayer = currLayer
for i in range(1,self.Nlayers):
currLayer = self.Layers[i]
for j in range(currLayer.nnodes):
node = currLayer.Nodes[j]
node.invalue = 0
for k in range(LastLayer.nnodes):
node.invalue = node.invalue + LastLayer.Nodes[k].outvalue*LastLayer.Nodes[k].weights[j]
node.outvalue = self.ActivationFunction(node.invalue)
LastLayer = currLayer
return [node.outvalue for node in currLayer.Nodes]
def BackProp(self,input,desiredOut):
#Run one iteration of backwards propagation
#Although typically described as a gradient descent, another interpretation of this
#agorithm is as the pullback of a one-form of the difference between the desired and
#actual output from the space of outputs to the space of weights.
derivo = [] #derivative of error function with respect to the output of a given layer
#start with the derivative of the error function with respect to the output layer
netout = self.RunNetwork(input) #run the error network
for i in range(len(input)): derivo.append(desiredOut[i] - netout[i]) #take difference between desired and actual output
for i in range(self.Nlayers-2,-1,-1):
currLayer = self.Layers[i]
derivCurr = [0]*currLayer.nnodes #to build derivative of output with respect to current layer
for k in range(self.Layers[i+1].nnodes):
node = self.Layers[i+1].Nodes[k]
dodx = self.ActivationDeriv(node.invalue) #derivative of node output with respect to input
for j in range(currLayer.nnodes):
node2 = currLayer.Nodes[j]
#derivative of error with respect to node j
derivCurr[j] = derivCurr[j]+derivo[k]*dodx*node2.weights[k]
dEdwj = derivo[k]*dodx*node2.outvalue #derivative of error with respect to weight
dw = (1.0-self.alpha)*self.eta*dEdwj + self.alpha*node2.olddws[k]
node2.weights[k] = node2.weights[k] + dw #adjust weight
node2.olddws[k] = dw #set momentum derivative
derivo = derivCurr
|
import re
def find_repeated_word(text):
"""
Function finds the first repeated word in a string and returns this word.
"""
if not isinstance(text, str):
raise TypeError
word_list = []
text_list = re.findall(r'[A-Za-z]+', text.lower())
for word in text_list:
if word in word_list:
return word
word_list.append(word)
return('There is no repeated word!')
def count_words(text):
"""
Function takes a string and returns a count of each of the words in the provided string.
"""
if not isinstance(text, str):
raise TypeError
word_list = {}
text_list = re.findall(r'[A-Za-z]+', text.lower())
for word in text_list:
if word in word_list:
word_list[word] += 1
else:
word_list[word] = 1
return word_list
|
class Node:
"""
Node class initilizing
"""
def __init__(self, value, next=None):
"""
Init node instance with value and next element
"""
self.value = value
self.next = next
def __str__(self):
""" Return an object instance
"""
return f'{self.value} -> {self.next}'
def __repr__(self):
"""
Return an object instance
"""
return f'{self.value}'
class Stack:
def __init__(self):
self.top = None
def __str__(self):
return f'{self.top}'
def __repr__(self):
return f'{self.top}'
def push(self, value):
self.top = Node(value, self.top)
def pop(self):
if self.top:
stored_top = self.top
self.top = self.top.next
stored_top.next = None
return stored_top.value
else:
raise Exception('Stack is empty')
def peek(self):
if self.top:
return self.top.value
else:
raise Exception('There is no top!')
def is_empty(self):
if self.top is None:
return True
else:
return False
class Queue:
"""class Queue"""
def __init__(self, next=None):
"""Initiate class"""
self.front = None
self.rear = None
def __str__(self) -> str:
"""Informal string representation
"""
output = []
curr = self.front
while curr is not None:
output.append(curr.value)
curr = curr.next
return " -> ".join(output)
def is_empty(self):
"""method to check if Queue is empty"""
if self.front == None:
return True
return False
def enqueue(self, val):
"""Method that adds an element to the end of the queue"""
if self.is_empty():
self.front = self.rear = Node(val)
else:
new_node = Node(val)
self.rear.next, self.rear = new_node, new_node
def dequeue(self):
"""Method that removes the node from the front of the queue, and returns its value."""
if not self.is_empty():
temp = self.front
self.front = self.front.next
temp.next = None
return temp
else:
raise Exception('Queue is empty!')
def peek(self):
"""Method returns the value of the front node"""
if not self.is_empty():
return self.front.value
return None |
class Node:
"""
This is the Node Class
"""
def __init__(self, value):
"""
This is my initialize of the Node
"""
self.value = value
self.next = None
def __str__(self):
"""
return string with the the object instance
"""
return f'{self.value} : {self.next}'
def __repr__(self):
"""
return string with the the object instance
"""
return self.value
class LinkedList:
"""
This is my Class LinkedList with methods __init__ and __insert__
"""
def __init__(self, nodes=None):
"""
This is my initialization of LinkedList
"""
self.head = None
if nodes is not None:
node = Node(value=nodes.pop(0))
self.head = node
for elem in nodes:
node.next = Node(value=elem)
node = node.next
def __repr__(self):
"""
Return an object instance
"""
node = self.head
nodes = []
while node is not None:
nodes.append(node.value)
node = node.next
nodes.append("None")
return " -> ".join(nodes)
def __iter__(self):
"""
To traverse a linked list
"""
node = self.head
while node is not None:
yield node
node = node.next
def insert(self, value):
"""
Inserts a value in the beginning of the list
"""
node = Node(value)
if self.head is not None:
node.next = self.head
self.head = node
def includes(self, data):
"""
This func returns True if data is in linked list or False if it is not
"""
current = self.head
found = False
while current and found is False:
if current.value == data:
found = True
else:
current = current.next
return found
def append(self, value):
"""
Insert a new element at the end of the list.
"""
node = Node(value)
current = self.head
if not self.head:
self.head = node
return
while current.next:
current = current.next
current.next = node
def insert_after(self, val, new_val):
"""
Insert a new element after the given value
"""
current = self.head
if not current:
raise Exception('List is empty')
while current:
if current.value == val:
break
current = current.next
if current:
node = Node(new_val)
node.next = current.next
current.next = node
else:
raise Exception(f'Node with value {val} not found!')
def insert_before(self, val, new_val):
"""
Insert a new element before the given value
"""
prev = self.head
new_node = Node(new_val)
if not self.head:
raise Exception("List is empty")
if prev.value == val:
return self.insert(new_val)
for node in self:
if node.value == val:
prev.next = new_node
new_node.next = node
return
prev = node
raise Exception(f'Node with value {val} not found!')
def remove_node(self, val):
if not self.head:
raise Exception("List is empty")
if self.head.value == val:
self.head = self.head.next
return
prev = self.head
for node in self:
if node.value == val:
prev.next = node.next
return
prev = node
raise Exception(f'Node with value {val} not found')
def get_at_end_index(self, n):
prev = None
current = self.head
follow = current.next
while current:
current.next = prev
prev = current
current = follow
if follow:
follow = follow.next
self.head = prev
count = 0
for el in self:
if count == n:
return el.value
count += 1
raise Exception(f'Node at index {n} is out of range!')
def eeney_meeney_miney_moe(self, k: int) -> str:
current = self.head
while current.next:
current = current.next
current.next = self.head
current = prev = self.head
count = 0
while current.next != current:
count += 1
if not count % k:
prev.next = current.next
prev, current = current, current.next
return current.value
|
def multiply(a, b):
return sum([a for _ in range(b)])
def expo_sum(x, y):
if x < 0 or y < 0:
return "Please enter non-negative numbers for both x and y"
result = 1
for _ in range(y):
result = multiply(result, x)
return result
|
string1='a(b(x)d)efghijkl'
string2='(123).)(qw(e)'
def match(str):
count = 0
for i in str:
if i == "(":
count += 1
elif i == ")":
count -= 1
if count < 0:
return False
return count == 0
def match2(input_string):
s = []
balanced = True
index = 0
while index < len(input_string) and balanced:
token = input_string[index]
if token == "(":
s.append(token)
elif token == ")":
if len(s) == 0:
balanced = False
else:
s.pop()
index += 1
return balanced and len(s) == 0
# Prima functie verifica daca numarul de paranteze deschise si inchise este egal
print(match(string1))
# A doua functie verifica daca parantezele daca parantezele au corespondent unele cu altele
print(match2(string2)) |
#!/usr/bin/python
import sys
import re
# check that a filename argument was provided, otherwise
if len(sys.argv) < 2:
raise Exception("Filename must be first argument provided")
filename = sys.argv[1]
lines = []
# open file in read mode, assuming file is in same directory as script
try:
file = open(filename, 'r')
# read Fibbonacci indexes from file into list
lines = file.readlines()
file.close()
except IOError:
print "File '%s' was not found in current directory" % filename
# strip out newline characters
lines = [line.replace('\n', '') for line in lines]
# ignore empty lines
try:
lines.remove("")
except:
pass
for line in lines:
numbers = line.split(" ")
a = int(numbers[0])
b = int(numbers[1])
num = int(numbers[2])
current = 1
digits = []
while current <= num:
digits.append(current)
current += 1
#print digits
for digit in digits:
new_value = ""
index = digits.index(digit)
divisible_by_a = digit % a == 0
divisible_by_b = digit % b == 0
divisible_by_both = divisible_by_a and divisible_by_b
if divisible_by_a:
new_value = "F"
if divisible_by_b:
new_value = "B"
if divisible_by_both:
new_value = "FB"
if new_value:
digits[index] = new_value
digits = [str(d) for d in digits]
print " ".join(digits)
|
#!/usr/bin/python
'''Gathering acutal housing expenses from person and save results
in variables to be called later'''
print('We are going to go over some of your monthly expenses, please answer in all lowercase')
mortgage_rent = input('Do you have a mortgage or rent?')
if mortgage_rent == 'mortgage':
mortgage_1 = input('How much is your mortgage?')
mortgage_2 = input('Do you have a second mortage payment; if so, how much is your payment?')
rent = '0'
else:
rent = input('How much is your rent?')
mortgage_1 = '0'
mortgage_2 = '0'
electric = input('How much is your electric bill?')
gas = input('How much is your home gas bill?')
phone = input('Are your phone, internet and cable all together?')
if phone == 'yes':
phone_cable_internet = input('How much is your phone/internet/cable bill?')
home_phone = '0'
cell_phone = '0'
cable = '0'
internet = '0'
else:
home_phone = input('How much is your home phone bill?')
cell_phone = input('How much is your cell phone bill?')
cable = input('How much is your cable bill?')
internet = input('How much is your internet bill?')
phone_cable_internet = '0'
water_sewer = input('How much is your water and sewer bill?')
trash = input('How much is your trash bill?')
home_insurance = input('How much is your home or renters insurance bill?')
property_taxes = input('How much is are your property taxes?')
total_actual_housing = int(mortgage_1) + int(mortgage_2) + int(rent) + int(electric) + int(gas) + int(phone_cable_internet) + int(home_phone) + int(cell_phone) + int(cable) + int(internet) + int(water_sewer) + int(trash) + int(home_insurance) + int(property_taxes)
print('Total actual housing expenses' + ' ' + total_actual_housing) |
#!/usr/bin/python
import sys
# check that a filename argument was provided, otherwise
if len(sys.argv) < 2:
raise Exception("Filename must be first argument provided")
filename = sys.argv[1]
lines = []
# open file in read mode, assuming file is in same directory as script
try:
file = open(filename, 'r')
# read Fibbonacci indexes from file into list
lines = file.readlines()
file.close()
except IOError:
print "File '%s' was not found in current directory" % filename
# strip out newline characters
lines = [line.replace('\n', '') for line in lines]
# ignore empty lines
try:
lines.remove("")
except:
pass
for line in lines:
pairs = []
digits, value = line.split(";")
value = int(value)
numbers = [int(d) for d in digits.split(",")]
# remove any numbers greater than target value
too_high = [x for x in numbers if x > value]
[numbers.remove(x) for x in too_high]
# if sum of all digits is less than value, there are no pairs
if sum(numbers) < value:
print "NULL"
break
for number in numbers:
compliment = value - number
if compliment in numbers:
# we have a pair, add to list
pairs.append([str(number), str(compliment)])
# remove compliment from numbers to remove duplicates
numbers.remove(compliment)
if pairs:
pairs = ";".join([",".join(pair) for pair in pairs])
print pairs
else:
print "NULL"
|
"""
1. Идем по списку вниз
2. Открываем форму нажатием enter
3. Ставим мышь в определенную координату экрана
4. Кликаем левой кнопкой
5. Закрываем форму комбинацией ctrl+enter
"""
import pyautogui as pg
import time as t
i = 1
while i <= 100:
t.sleep(5)
pg.hotkey('down')
pg.press('enter')
t.sleep(7)
pg.moveTo(1145, 696)
pg.click(button='left')
t.sleep(2)
pg.hotkey('ctrlright','enter')
i = i + 1
|
# -*- coding: utf-8 -*-
import numpy as np
def frontera(rf, r, P, T, M, L):
"""
Magnitudes en la prontera radiativo-convectiva.
Intermpolación lineal para calcular los valores de la temperatura,
presión, masa y luminosidad a un valor específico del radio ('rf').
Los objetos 'r', 'P', 'T', 'M', 'L' han de contener al menos dos elementos
(un valor en la zona radiatva y otro en la convectiva).
El valor del radio en la frontera, rf, viene como input y output para una
mejor visualización.
Input:
rf: radio en la frontera radiativo-convectiva
r: array_like
radio
P: array_like
presión
T: array_like
temperatura
M: array_like
masa
L: array_like
luminosidad
Output:
Frontera: narray
valores de los parámetros físicos en la frontera
"""
Pf = np.interp(rf, r, P)
Tf = np.interp(rf, r, T)
Mf = np.interp(rf, r, M)
Lf = np.interp(rf, r, L)
Frontera = np.array([rf, Pf, Tf, Mf, Lf])
return(Frontera)
|
#One common use of dictionaries is counting how often we "see" something
'''
ccc = dict()
ccc['csev'] = 1
ccc['cwen'] = 1
print(ccc)
ccc['cwen'] = ccc['cwen'] + 1
print(ccc)
'''
counts = dict()
print(counts)
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names:
if name not in counts:
counts[name] = 1
else:
counts[name] = counts[name] + 1
print(counts) |
'''
Dictionaries are like lists except that they use KEYS
instead of numbers to look up values.
'''
#######LIST#########
print('LIST')
lst = list()
lst.append(12)
lst.append(183)
print(lst)
lst[0] = 23
print(lst)
'''
####LIST=lst####
Key Value
[0] 21
[1] 183
'''
######DICTIONARIES############
print('Dictionaries')
ddd = dict()
ddd['age'] = 21
ddd['course'] = 182
print(ddd)
ddd['age'] = 23
print(ddd)
####Dictionary = ddd#####
'''
Key Value
['course'] 182
['age'] 21
''' |
#Time Stamp 3:48:56
#Lists
'''
Collections
A list is a kind of a collection
friends = ['Joseph', 'Glenn', 'Sally']
'''
print([1,23,76]) #List
'''
>Lists are surrounded by Square brackets
and the elements in the lists are separated by commas
>A list element can be any Python object-even another list
'''
print(['Red', 'Yellow', 'Blue'])
print(type(['Red', 'Yellow', 'Blue']))
print([1, [5, 6], 7])
print(type([1, [5, 6], 7]))
print([])
print(type([]))
#Using list in for loops
for i in [5, 4, 3, 2, 1]:
print(i)
print('Fineshed') |
#Definite loops
#for i in [5,4,3,2,1]:
# print(i)
#print('BlastOFF!!!!')
friends = ['Joseph','Glean','Sally']
for friend in friends:
print("Happy New Year: ",friend)
print("BlastOFF!!!!") |
#counting lines in file
fhand = open('mbox.txt')
count = 0
for eachline in fhand:
count = count + 1
print("Total number of lines: ",count) |
# Name: Monty Hall Game and Monte Carlo Simulation
# Version: 0.2a3
# Summary: A simple game that replicates the Monty Hall problem, and a Monte Carlo simulator to determine probabilities
# Keywords: Monty Hall, Monte Carlo
# Author: Jacob J. Walker
#
# Header comments based on meta-data specs at https://packaging.python.org/specifications/core-metadata/
import random
car_location = random.randint(1,3)
# print(car_location)
# Initialize doors
door = {}
for i in (1,2,3):
door[i] = "Goat"
# print(str(i) + ": " + door[i])
door[car_location] = "Car"
# Get guess and tell player whether they won or not
guess = input("Which door do you choose? ")
if door[int(guess)] == "Goat":
print("Sorry, you got a goat. If you chose door number " + str(car_location) + " you would have won the car...")
elif door[int(guess)] == "Car":
print("You won a car!!!")
else:
print("Sorry, I did not understand.")
|
import pandas as pd
import json
with open('COUNTRY.json') as f:
data = json.load(f)
# Output: {'name': 'Bob', 'languages': ['English', 'Fench']}
x=pd.DataFrame(data)
print(x) |
import turtle
from typing import List, Tuple, Optional
import math
class Label(turtle.Turtle):
def __init__(self, x, y):
super().__init__(shape='blank')
self.up()
self.goto(x, y)
def msg(self, text):
self.clear()
self.write(text, align="left")
class Checker(turtle.Turtle):
is_lady: bool = False
def __init__(self, i: int, j: int, size: float, color: Tuple[float, float, float]):
super().__init__(shape='circle')
self.up()
self._color = color
self.fillcolor(color)
self.pencolor('grey')
self.goto(i * size, j * size)
self.shapesize(1.6, 1.6, 2)
def set_lady(self):
self.is_lady = True
self.shapesize(1.6, 1.6, 6)
self.pencolor('green')
def select_checker(self):
self.pencolor('red')
def unselect_checker(self):
self.pencolor('grey')
def is_black(self):
"""Проверяет шашка чёрная или нет"""
if self._color == 'black':
return False
else:
return True
def __str__(self):
if self.is_black():
return '0 '
else:
return '1 '
def __repr__(self):
return self.__str__()
class Square(turtle.Turtle):
def __init__(self, i, j, size, color):
super().__init__(shape='square')
self.size = size
self.up()
self.fillcolor(color)
self.goto(i * size, j * size)
self.shapesize(2, 2)
class Board(turtle.Turtle):
board: List[List[Square]] = []
size = 800
count = 8
checkers: List[List[Checker]] = []
take_checker: Optional[Tuple[int, int]] = None
status: Label = Label(-100, -150)
error: Label = Label(-200, -250)
step_white: bool = True
def __init__(self, size=800, count=8):
super().__init__()
self.size = size
self.count = count
self.create_board()
self.create_checkers()
def create_board(self):
turtle.tracer(False)
for i in range(self.count):
board_line = []
for j in range(self.count):
color = (i + j) % 2
color = 'SaddleBrown' if color == 1 else 'lightyellow'
board_line.append(Square(i, j, 40, color=color))
self.board.append(board_line)
turtle.tracer(True)
def create_checkers(self):
turtle.tracer(False)
for i in range(self.count):
chess_line = []
for j in range(self.count):
is_set = (i + j) % 2
if is_set:
if i < 3:
checker = Checker(i, j, 40, 'black')
chess_line.append(checker)
continue
if i >= 5:
checker = Checker(i, j, 40, 'white')
chess_line.append(checker)
continue
chess_line.append(None)
self.checkers.append(chess_line)
turtle.tracer(True)
def move(self, i1: int, j1: int, i2: int, j2: int):
distance_i = i2 - i1
distance_j = j2 - j1
i: int = int(i1)
j: int = int(j1)
count_steps = abs(distance_i)
trace_step = []
# 1 Ходить можно только шашкой пустым местом не ходим
f: Checker = self.checkers[i1][j1]
if f is None:
self.error.msg('Не можем ходить пустым местом')
return
for k in range(count_steps + 1):
trace_step.append((i, j, str(self.checkers[i][j])))
i += int(math.copysign(1, distance_i))
j += int(math.copysign(1, distance_j))
victim_list = []
if len(trace_step) >= 3:
checker_attack = trace_step[0][2]
attack_is_black = checker_attack.is_black()
for kill_checker_tuple in trace_step:
victim = kill_checker_tuple[2]
if victim is None:
continue
victim_is_black = victim_is_black()
if attack_is_black != victim_is_black:
victim_list.append(kill_checker_tuple)
# 2 Ходить только в пустое место
f1: Checker = self.checkers[i2][j2]
if f1 is not None:
self.error.msg('Нельзя ходить на другую шашку')
return
f: Checker = self.checkers[i1][j1]
# --> Троссировка шашки <-
# 12 Шашка не может ходить назад
if f.is_lady:
if f.is_black():
if i2 < i1:
self.error.msg('Нельзя ходить назад')
return
else:
if i2 == i1 or j2 == j1:
self.error.msg('Неверный ход!')
return
else:
if i2 > i1:
self.error.msg('Нельзя ходить назад')
return
else:
if i2 == i1 or j2 == j1:
self.error.msg('Неверный ход!')
return
# Нельзя ходить через две клетки
if f.is_lady:
if f.is_black():
if trace_step[1][2] is not None:
print('Верный ход')
else:
if len(trace_step) >= 3:
self.error.msg('Нельзя ходить через две пустые клетки')
return
else:
if trace_step[1][2] is not None:
print('Верный ход')
else:
if len(trace_step) >= 3:
self.error.msg('Нельзя ходить через две пустые клетки')
return
# 7. Шашка превращается в дамку на противоположной стороне
if f.is_black():
if i2 == board.count - 1:
f.set_lady()
else:
if i2 == 0:
f.set_lady()
# 4. дамка может ходить по диагонали в любое место
first_step = trace_step[0]
last_step = trace_step[-1]
first_eq = first_step[0] == i1 and first_step[1] == j1
last_eq = last_step[0] == i2 and last_step[1] == j2
if not (first_eq and last_eq):
self.error.msg('Ходить можно только по диагонали')
return
# 10. Дамка может бить по диагонали только чужих
for color_is_black in trace_step[1:]:
if first_step[2] is not None and first_step[2].is_black() == color_is_black[2].is_black():
self.error.msg('Своих рубить нельзя!')
return
f.goto(i2 * 40, j2 * 40)
for next_victim in victim_list
if self.step_white:
self.status.msg('Ход белых')
else:
self.status.msg('Ход черных')
self.step_white = not self.step_white
self.checkers[i2][j2] = f
self.checkers[i1][j1] = None
turtle.tracer(False)
board = Board()
turtle.tracer(True)
def on_click_screen(x, y):
print('клик в точку (', x, y, ')')
size = 40
x1, y1 = -size // 2, -size // 2
if x < x1 or y < y1 or y > 8 * size or x > 8 * size:
print('мимо')
return
cx, cy = x - x1, y - y1
i, j = int(cx // size), int(cy // size)
check = board.checkers[i][j]
print('норм координаты', i, j)
print(check)
if board.take_checker is None:
board.take_checker = (i, j)
active_checker = board.checkers[i][j]
if active_checker is not None:
active_checker.select_checker()
else:
active_i = board.take_checker[0]
active_j = board.take_checker[1]
board.move(
active_i, active_j,
i, j
)
act_checker = board.checkers[active_i][active_j]
if act_checker is not None:
act_checker.unselect_checker()
board.take_checker = None
turtle.onscreenclick(on_click_screen)
turtle.done()
|
import turtle
from random import random
car = turtle.Turtle()
car.shape('turtle')
button = turtle.Turtle()
button.goto(x, y)
def create_car(x, y):
turtle.tracer(False)
car_xy = turtle.Turtle()
car_xy.up()
car_xy.goto(x, y)
car_xy.fillcolor((random(), random(), random()))
turtle.tracer(True)
def drive():
create_car.goto(create_car, 1000)
turtle.onscreenclick(create_car)
turtle.ontimer(create_car, 100)
#cars = cars[]
#def drive():
#turtle.tracer(False)
#cars.goto(0, 10)
#cars.clear()
#cars.forward(1000)
#turtle.tracer(True)
#turtle.ontimer(drive, 100)
turtle.done() |
import datetime
import turtle
turtle.tracer(False)
pen = turtle.Turtle()
pen.hideturtle()
pen.goto(0, 100)
t = datetime.datetime.today()
pen.write('Сегодня:', align="center", font=("Arial", 14, "bold"))
pen.forward(65)
pen.goto(0, 70)
pen.write(t, align="center", font=("Arial", 14, "normal"))
pen.goto(0, 50)
p = turtle.textinput("Name", "Введите Ваше имя: ")
turtle.write(p, False, align="left", font=("Arial", 16, "bold"))
def get_user_birthday():
year = int(turtle.numinput('Вводим дату рождения', 'Введите год'))
month = int(turtle.numinput('Вводим дату рождения', 'Введите месяц'))
day = int(turtle.numinput('Вводим дату рождения', 'Введите день'))
birthday = datetime.datetime(year, month, day)
return birthday
def calc(original_date, now):
delta1 = datetime.datetime(now.year, original_date.month, original_date.day)
delta2 = datetime.datetime(now.year + 1, original_date.month, original_date.day)
return ((delta1 if delta1 > now else delta2) - now).days
bd = get_user_birthday()
now = datetime.datetime.now()
c = calc(bd, now)
pen.goto(0, -30)
pen.write('До Вашего дня рождения осталось дней: ', align="center", font=("Arial", 14, "normal"))
pen.goto(0, -60)
pen.write(c, align="center", font=("Arial", 16, "bold"))
#f"{t.hour}:{minute}:{t.second}"
#turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal"))
turtle.done()
|
import turtle
player = turtle.Turtle()
def checker(x, y, size, color):
"""
Нарисуем фигуру в нужном месте
:param x: координата Х фигуры
:param y: координата У фигуры
:param color: цвет фигуры
:return: в нужном положении рисуется фигура
"""
player.speed(0)
player.up()
player.goto(x, y)
player.down()
player.fillcolor(color)
iterations = 30
player.begin_fill()
for i in range(iterations+1):
player.fd(size/iterations)
player.left(360/iterations)
player.end_fill()
checker(0, 0, 360,'darkgrey')
checker(11, 10, 300, 'white')
checker(15, 20, 240, 'darkgrey')
#player.circle(100)
#player.circle(800)
#player.circle(600)
player.hideturtle()
turtle.done() |
# Assuming input graph is represented by adjacency list
g1 = {"a": ["b"],
"b": ["c", "d"],
"c": [],
"d": ["c"],
"e": ["c"]
}
g2 = {"a": ["b"],
"b": ["c", "d"],
"c": ["e"],
"d": ["c"],
"e": ["c"]
}
#print(g1)
def isPath(n1, n2, g):
queue = []
seen = {}
queue.insert(0, n1)
seen[n1] = 1
while len(queue) > 0:
n = queue.pop(0)
for nbr in g[n]:
if nbr == n2:
return True
if nbr not in seen:
seen[nbr] = 1
queue.insert(0, nbr)
return False
print(isPath("a", "e", g2))
"""
Can just do BFS and check if each new node is the one we want to find
Time: O(V + E) where V is the number of nodes and E is the number of edges
- this is because we go through all the nodes and explore all the edges
out of them so we touch each node and edge once
Space: Adjacency Matrix O(V + E) storing all the nodes and edges in the
representation
""" |
import logging
import typing
def logger_config(
prefix: str = 'NULL',
file_level: str = 'INFO',
console_level: str = 'INFO',
log_file: str = 'test.log') -> typing.NoReturn:
"""Set up the log to print to both the log file and the console
:param prefix: Sets the log prefix, which is the content in []
:param file_level: The log level output to the log file
:param console_level: The level of log output to the console
:param log_file: The log level log file path to output to the console
:return: No return value
"""
# Get an instance of Logger
logger = logging.getLogger()
logger.setLevel('NOTSET') # Set the minimum log level. Only logs above this level will be output
# log format
BASIC_FORMAT = f'[{prefix}]%(asctime)s - %(levelname)s: %(message)s'
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT)
# Sets the handler to output to the console
chlr = logging.StreamHandler()
chlr.setFormatter(formatter)
chlr.setLevel(console_level) # Set the console logging level
# Sets the handler to output to the file
fhlr = logging.FileHandler(filename=log_file, encoding='utf-8') # Note that the encoding of the log file is set here
fhlr.setFormatter(formatter)
fhlr.setLevel(file_level) # Sets the log file log level
# Add two handlers to the logger
logger.addHandler(chlr)
logger.addHandler(fhlr) |
"""Grammar."""
from rule import Rule
# -- coding: utf-8 --
__author__ = 'stepan'
__license__ = 'MIT'
__version__ = '1.0'
class Grammar:
"""Represents grammar with all components."""
def __init__(self):
"""Initialization."""
self.rules = []
self.terminals = []
self.nonterminals = []
self.start = False
def addNonTerminal(self, name):
"""Add non-terminal."""
if name == '':
raise ValueError("Invalid terminal symbol '" + name +
"'", 3)
if name in self.terminals:
raise ValueError("Symbol '" + name +
"' is already in terminals", 3)
if name in self.nonterminals:
raise ValueError("Duplicate symbol '" + name +
"' in nonterminals", 3)
self.nonterminals.append(name)
def addTerminal(self, name):
"""Add terminal symbol."""
if name == '':
raise ValueError("Invalid non-terminal symbol'" + name +
"'", 3)
if name in self.nonterminals:
raise ValueError("Symbol '" + name +
"' is already in non-terminals", 3)
if name in self.terminals:
raise ValueError("Duplicate symbol '" + name +
"' in terminals", 3)
self.terminals.append(name)
def addRule(self, leftSide, rightSide):
"""Add rule to symbol."""
if self.isTerm(leftSide):
# left side must be non-terminal
raise ValueError("Left side of rule can't be terminal", 3)
for symbol in rightSide:
# checks if symbol is in grammar
self.isTerm(symbol)
# include rule to grammar
r = Rule(leftSide, rightSide)
self.rules.append(r)
def setStartSymbol(self, name):
"""Set start symbol."""
if not self.isTerm(name):
self.start = name
else:
raise ValueError("Start symbol '" + name +
"' can't be terminal.", 3)
def isTerm(self, name):
"""Decide if symbol is terminal or not."""
if name in self.terminals:
return True
elif name in self.nonterminals:
return False
else:
raise ValueError("Symbol '" + name +
"' is not in grammar alphabet", 3)
def __str__(self):
"""To string."""
s = "(\n {"
s += ", ".join([nonterm for nonterm in self.nonterminals])
s += "},\n {"
s += ", ".join(["'" + term + "'" for term in self.terminals])
s += "},\n {\n"
for rule in self.rules:
s += " " + rule.toStringDiff(self.isTerm) + ";\n"
s += " },\n"
s += " " + str(self.start) + "\n)"
return s
|
#Using pandas data reader this program will print a table of close values for a list of stocks from a year from today up until today's date
#Note that I am retrieving the stock data using Yahoo Finance
import pandas as pd
import pandas_datareader.data as pdr
import datetime as dt
#this list may be modified as desired and can include as many company ticker symbols as desired
tickers = ["AMZN", "RYCE", "DAL", "BNED", "NCBS", "C", "FAST", "WFC", "JPM"]
stock_df = pd.DataFrame() #initialize the data frame for which we will put the data of each stock
completed = []
attempt = 0
while len(tickers) != 0 and attempt <=5: #the attempts counter is a safety net in case the data isn't able to be received due to connection issues
tickers = [j for j in tickers if j not in completed] #add everything that isn't in the completed list to the list tickers
for i in range(len(tickers)):
try:
temp = pdr.get_data_yahoo(tickers[i], dt.date.today()-dt.timedelta(365), dt.date.today()) #retrieve the data from Yahoo finance
temp.dropna(inplace = True)
stock_df[tickers[i]] = temp["Adj Close"] #store the data in the stock data frame
completed.append(tickers[i])
except: #in case we aren't able to receive the data
print(tickers[i], ": Failed to fetch data...retrying")
continue
attempt += 1
print(stock_df)
|
#!/home/sahil/anaconda2/bin/python
import sys
import numpy as np
from sklearn import tree
from sklearn.preprocessing import LabelEncoder
from matplotlib import pyplot as plt
from sklearn.utils import shuffle
import math
import optparse
print 'Let\'s do decision tree!!'
#function to create new Table and add the rows as arrays in the table
table=[]
def processText(table,data):
data = data.strip()
fields = data.split(',')
table.append(fields)
for line in sys.stdin.readlines():
processText(table,line)
#totalrows in the table
tr= len(table)
print 'Total Rows in the data are-', tr
#Now we have to do the main task for ENCODING
#Encoding is the process of converting Catergorical to Numerical
#We have a total of 7 cols (excluding the 'ID', 'Age', ) to be converted to Numerical
#STEPS FOR ENCODING-
# 1. SPLIT THE COLUMNS IN INDIVIDUAL ARRAYS
# 2. ENCODE EACH COLUMN USING LABLE_ENCODER
# 3. COMBINE THE ENCODED LABEL TO FORM THE ORIGINAL TABLE
# STEP 1:SPLIT THE COLUMNS IN INDIVIDUAL ARRAYS
n = 7
lists = [[] for _ in range(n)]
#for 1st column
for l in range(0,tr):
lists[0].append(table[l][1])
#for rest of the columns
k=3
for i in range(1,7):
for j in range(0,tr):
lists[i].append(table[j][k])
k=k+1
if k>10:
break
lists=np.array(lists)
# STEP 2: ENCODE EACH COLUMN USING LABLE_ENCODER
label_encoder=LabelEncoder()
for i in range(0,7):
lists[i]=label_encoder.fit_transform(lists[i].ravel()).reshape(*lists[i].shape)
#to check whether the encoder works-
#print lists[0]
#print lists[6]
# STEP 3: COMBINE THE ENCODED LABEL TO FORM THE ORIGINAL TABLE
for i in range(0,tr):
table[i][1]=lists[0][i]
k=3
for i in range(1,7):
for j in range(0,tr):
table[j][k]=lists[i][j]
k=k+1
if k>10:
break
#Now split the encoded data in Training and Test sets
#'X' set will contain the features
#'Y' set will contain the targets
trainingX = []
trainingY = []
testX = []
testY = []
#Split the data in 90:10 for Training:Test
#TO NOTE- Also remove the column ID from the data set as it is not a feature, and it useless
#So we start with index 1 and not 0 as it is the ID
for i in range(0, tr):
newrow=[ table[i][1], table[i][2], table[i][3], table[i][4], table[i][5], table[i][6], table[i][7], table[i][8] ]
if i%10==0:
testX.append(newrow)
testY.append(table[i][9])
else:
trainingX.append(newrow)
trainingY.append(table[i][9])
print 'Total Rows are', tr
print 'Training Set has',len(trainingX),'rows, which is about',round( len(trainingX)*100/ float( (len(trainingX)+len(testX))) ),'% of the total rows'
print 'Test Set has',len(testX),'rows, which is about',float(len(testX)*100/(len(trainingX)+len(testX))),'% of the total rows'
#Replace 'Very Late Adopter' as 1 and the rest as 0
#First for Training
string='Very Late'
for i in range(0,len(trainingY)):
if str(trainingY[i]) == string:
trainingY[i]=1
else:
trainingY[i]=0
#Next for Test
for i in range(0,len(testY)):
if str(testY[i]) == string:
testY[i]=1
else:
testY[i]=0
#Convert training and test sets to numpy arrays
#This is done for efficient processing by scikit
trainingX = np.array(trainingX)
trainingY = np.array(trainingY)
testX = np.array(testX)
testY = np.array(testY)
#Check the training set
#print trainingX
#print trainingY
#NOW we VARY the max_depth
max_leaf_nodes = [2, 4, 8, 16, 32, 64, 128, 256]
max_depth = [None, 2, 4, 8, 16]
for i in range(0, len(max_depth)):
dicaccuracies = {}
accuracies = []
for j in range(0, len(max_leaf_nodes)):
clf = tree.DecisionTreeClassifier(max_leaf_nodes=max_leaf_nodes[j], max_depth = max_depth[i])
clf.fit(trainingX, trainingY)
correct = 0
incorrect = 0
#feed the test features through the model, to see how well the model
#predicts the class from the samples in the test set it has never seen
predictions = clf.predict(testX)
for k in range(0, predictions.shape[0]):
if(predictions[k] == testY[k]):
correct += 1
else:
incorrect += 1
#print "correct predictions: ", correct, " incorrect predictions: ", incorrect
#compute accuracy
accuracy = float(correct) / (correct + incorrect)
accuracies.append(accuracy)
dicaccuracies[max_leaf_nodes[i]] = accuracies
plt.plot(max_leaf_nodes,accuracies)
plt.xticks(max_leaf_nodes)
plt.xlabel('Max_Leaf_Nodes')
plt.ylabel('Accuracy')
plt.title('Accuracy at Max Depth of '+ str(max_depth[i]))
plt.show()
#print 'For max_depth=', max_depth[i]
#print 'Accuracies-',dicaccuracies
#PART B BEGINS HERE
#Count the number of Very Late Adopters vs Not very late in the original dataset
countlate=0
for i in range(0,tr):
if str(table[i][9]) == string:
countlate+=1
else:
countlate+=0
print 'Total Values of Very Late Adopters-',countlate
print 'Total Values of Other Adopters-',tr-countlate
#Create table with 50:50 and shuffle the table in the end
i=0
j=0
table50=[]
while(i<tr and j<=countlate):
newrow=[ table[i][1], table[i][2], table[i][3], table[i][4], table[i][5], table[i][6], table[i][7], table[i][8], table[i][9]]
if table[i][9] != string:
table50.append(newrow)
j+=1
i+=1
i=0
j=0
while(i<tr and j<=countlate):
newrow=[ table[i][1], table[i][2], table[i][3], table[i][4], table[i][5], table[i][6], table[i][7], table[i][8], table[i][9]]
if table[i][9] == string:
table50.append(newrow)
j+=1
i+=1
#SHUFFLE THE TABLE
table50=shuffle(table50, random_state=0)
#print table50
#CHECK WHETHER THE NEW TABLE CREATED IS UPTO STANDARD
print 'Total Rows in the new created table are-', len(table50)
countlate=0
for i in range(0,len(table50)):
if str(table50[i][8]) == string:
countlate+=1
else:
countlate+=0
print 'IN WHICH'
print 'Very Late Adopters are',countlate,'which is about',float( countlate*100/len(table50) ),'% of the total rows'
countlate=0
for i in range(0,len(table50)):
if str(table50[i][8]) == string:
countlate+=1
else:
countlate+=0
print 'Others\' are',countlate,'which is about',( countlate*100/len(table50) ),'% of the total rows'
#PART TWO OF THE QUESTION
#Create Test and Training out of the 50:50, with ration 90:10
trainingX = []
trainingY = []
testX = []
testY = []
for i in range(0, len(table50)):
newrow=[ table50[i][0],table50[i][1], table50[i][2], table50[i][3], table50[i][4], table50[i][5], table50[i][6], table50[i][7]]
if i%10==0:
testX.append(newrow)
testY.append(table50[i][8])
else:
trainingX.append(newrow)
trainingY.append(table50[i][8])
print 'Training Set has',len(trainingX),'rows, which is about', math.ceil( len(trainingX)*100/ float( (len(trainingX)+len(testX))) ),'% of the total rows'
print 'Test Set has',len(testX),'rows, which is about', math.ceil(len(testX)*100/(len(trainingX)+len(testX))),'% of the total rows'
#Replace 'Very Late Adopter' as 1 and the rest as 0
#First for Training
string='Very Late'
for i in range(0,len(trainingY)):
if str(trainingY[i]) == string:
trainingY[i]=1
else:
trainingY[i]=0
#Next for Test
for i in range(0,len(testY)):
if str(testY[i]) == string:
testY[i]=1
else:
testY[i]=0
#Convert training and test sets to numpy arrays
#This is done for efficient processing by scikit
trainingX = np.array(trainingX)
trainingY = np.array(trainingY)
testX = np.array(testX)
testY = np.array(testY)
#Check the training set
#print trainingX
#print trainingY
#NOW we VARY the max_depth
max_leaf_nodes = [2, 4, 8, 16, 32, 64, 128, 256]
max_depth = [None, 2, 4, 8, 16]
for i in range(0, len(max_depth)):
dicaccuracies = {}
accuracies = []
for j in range(0, len(max_leaf_nodes)):
clf = tree.DecisionTreeClassifier(max_leaf_nodes=max_leaf_nodes[j], max_depth = max_depth[i])
clf.fit(trainingX, trainingY)
correct = 0
incorrect = 0
#feed the test features through the model, to see how well the model
#predicts the class from the samples in the test set it has never seen
predictions = clf.predict(testX)
for k in range(0, predictions.shape[0]):
if(predictions[k] == testY[k]):
correct += 1
else:
incorrect += 1
#print "correct predictions: ", correct, " incorrect predictions: ", incorrect
#compute accuracy
accuracy = float(correct) / (correct + incorrect)
accuracies.append(accuracy)
dicaccuracies[max_leaf_nodes[i]] = accuracies
plt.plot(max_leaf_nodes,accuracies)
plt.xticks(max_leaf_nodes)
plt.xlabel('Max_Leaf_Nodes')
plt.ylabel('Accuracy')
plt.title('Accuracy at Max Depth of '+ str(max_depth[i]))
plt.show()
#print 'For max_depth=', max_depth[i]
#print 'Accuracies-',dicaccuracies
print 'Hope you Enjoyed the graphs!!!!!'
print 'Goodbye World!!!'
|
import numpy as np
def outer_product(F, G):
b = np.size(F)
r = np.size(G)
W= np.zeros((b,r))
for i in range(b):
for j in range(r):
W[i, j] = F[i] * G[j]
return W
|
#!/usr/bin/python3
import re
import os
class Parser:
"""The parser class is used to parse the episodes and the file for converting the names"""
# hardcoded patterns list to search for
patterns = [
'(?P<Season>S[0-9]{1,2}).*(?P<Episode>E[0-9]{1,3})' # 'S[0-9]{1,2}.*E[0-9]{1,3}'
]
fileTypePattern = "\.[a-zA-z]{1,}$"
def __init__(self):
self.ignore_list = list()
self.episode_guide_file = ""
self.episodes_folder = ""
self.delimiter = ""
self.num_chunks = 0
# TODO make this more robust, in a more systematic way not so brute force
# TODO wrap this stuff in try-catch blocks for safety
def find_pattern(self, episode_folder):
num_files = len(os.listdir(episode_folder))
num_matches = 0
for pattern in self.patterns:
for fileName in os.listdir(episode_folder):
if re.search(pattern, fileName):
num_matches += 1
else:
print("Found a file that does not conform to the pattern: " + fileName)
print("Is is safe to ignore this file when renaming ? [y n]")
choice = input()
if choice.lower().strip() == "y":
self.ignore_list.append(fileName)
else:
print("File will not be ignored, continuing search for proper pattern")
continue
if num_matches == (num_files - len(self.ignore_list)):
print("Pattern '" + pattern + "' matches all files in directory")
return pattern
# TODO don't just give up like this...
print("Unable to find a pattern that suits all files... sorry")
# TODO what if not all the files are the same file type???
# grab the file type for the episodes
def find_file_type(self, episode_folder):
regex = re.compile(self.fileTypePattern)
file_type = ""
for fileName in os.listdir(episode_folder):
print(fileName)
result = regex.search(fileName)
if not result:
print("A file caused the regex to fail: " + fileName)
# TODO lets make this not a fatal error
return None
if file_type == "":
file_type = result.group(0)
elif file_type == result.group(0) or self.ignore_list.__contains__(fileName):
continue
else:
print("There is a file that has a different extension then all the others " + fileName)
# TODO lets make this not a fatal error
return None
return file_type
def parse_episode_names(self, episode_name_file):
file = open(episode_name_file, "r")
episode_names = file.readlines()
for name in episode_names:
print(name)
# TODO want to make this process automatic
def get_delimiter_from_user(self):
print("\nIn order to make this work we need some more information from you, the user")
while True:
print("\nPlease insert the delimiter used in the episode names: ")
delimiter = input()
if delimiter.__len__() > 1 or delimiter.isalpha() or delimiter.isnumeric():
print("ERROR: delimiter cannot be numeric, alpha, or larger than 1 character")
# TODO the automated version of the demlimeter problem
# delimiters should be non-numeric, non-alpha symbls
# ie: . _
def find_delimiter(self, episodes_folder):
for fileName in os.listdir(episodes_folder):
print("fileName: "+fileName)
for char in fileName:
print("char: "+char)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.