text stringlengths 37 1.41M |
|---|
student = {
"name": input("Insert name: "),
"modules": [
{
"subject" : input("Subject: "),
"grade": input("Grade: ")
},
{
"subject" : input("Subject: "),
"grade": input("Grade: ")
}
]
}
print("Student: {}".format(student["name"]))
for module in student["modules"]:
print("\t {} \t: {}".format(module["subject"], module["grade"])) |
age = int (input("what is your age"))
height = int (input("Height?"))
result = age * height
if result == 4:
print(result, "is normal")
elif result >4:
print(result, "is huge")
elif result <4:
print(result, "is tiny")
|
#program will strip any leading or trailing spaces, and will also convert the string to lowercase
string = input("please enter a string: ")
normalised = string.strip().lower()
stringlength = len(string)
normalisedlength = len(normalised)
print("Normalised string is: {}". format (normalised))
print("The original string is {}". format (stringlength))
print("The normalised string is {}". format (normalisedlength))
print("The string has been reduced from {} to {}". format (stringlength, normalisedlength)) |
#!/usr/bin/env python
"""
Copyright (c) 2005 Dustin Sallings <dustin@spy.net>
"""
import sys
def tail(f, n=100, est_line_len=175):
while True:
try:
f.seek(-1 * est_line_len * n, 2)
except IOError:
f.seek(0)
atstart = (f.tell() == 0)
lines = f.read().split("\n")
if atstart or len(lines) > (n+1):
break
est_line_len *= 1.3
if len(lines) > n:
start = len(lines) - n - 1
else:
start = 0
return lines[start:len(lines)-1]
if __name__ == '__main__':
f=open(sys.argv[1])
print '\n'.join(tail(f))
f.close()
|
#SET: set used to store multiple items in single variable
_set = { "abhi","sai","kiran","charan"}
print(_set)
_set.add("subba")
print(_set)
thisset ={"bala","shashi"}
_set.update(thisset)
print(_set)
print(len(_set)) |
def odd():
s = 1
while True:
s = s + 2
yield s
def cj(m):
return lambda x: x % m > 0
def primes():
yield 2
it = odd()
while True:
a = next(it)
yield a
it = filter(cj(a), it)
for n in primes():
if n < 1000:
print(n)
else:
break
|
numerator = 1
denominator = 1
for y in range(10,100):
for x in range(10,100):
if x >= y:
break
x_str = str(x)
y_str = str(y)
for i in x_str:
if i == '0':
continue
elif x % 11 == 0 or y % 11 == 0:
continue
elif i in y_str:
y_divs = y_str.replace(i,'')
x_divs = x_str.replace(i,'')
if x_divs == '0' or y_divs == '0':
continue
elif x/y == int(x_divs)/int(y_divs):
numerator *= x
denominator *= y
print(numerator,denominator)
div = 2
while div <= numerator:
if numerator % div == 0 and denominator % div == 0:
numerator /= div
denominator /= div
div = 2
else:
div += 1
print(numerator,denominator) |
power = 1
for ind in range(0,1000):
power *= 2
power_str = str(power)
sumo = 0
for digit in power_str:
sumo += int(digit)
print(sumo) |
'''
Build Min Heap
'''
class MinHeap:
def __init__(self, capacity):
self.size = 0
self.capacity = capacity
self.arr = [None] * capacity
def left_child(self, i):
return (2 * i) + 1
def right_child(self, i):
return (2 * i) + 2
def parent(self, i):
return (i - 1)/2
def getmin(self):
return self.arr[0]
def insert(self, item):
self.size += 1
self.arr[self.size - 1] = item
i = self.size -1
while i > 0:
par = self.parent(i)
if self.arr[par] > self.arr[i]:
# swap parent & child
tmp = self.arr[i]
self.arr[i] = self.arr[par]
self.arr[par] = tmp
i = self.parent(i)
else:
break
def heapify(self, idx):
i = idx
small = i
lc = self.left_child(i)
rc = self.right_child(i)
if lc < self.size and self.arr[small] > self.arr[lc]:
small = lc
if rc < self.size and self.arr[small] > self.arr[rc]:
small = rc
# Swap i and small
if small != i :
tmp = self.arr[i]
self.arr[i] = self.arr[small]
self.arr[small] = tmp
self.heapify(small)
def extractmin(self):
item = self.arr[0]
last_idx = self.size -1
cur_idx = 0
# Swap last and current(0th) idx
tmp = self.arr[last_idx]
self.arr[last_idx] = self.arr[cur_idx]
self.arr[cur_idx] = tmp
self.size -= 1
self.heapify(cur_idx)
return item
def delidx(self, idx):
ele = self.arr[idx]
self.arr[idx] = -float("inf")
i = idx
while i > 0:
par = self.parent(i)
if self.arr[par] > self.arr[i]:
# swap parent & child
tmp = self.arr[i]
self.arr[i] = self.arr[par]
self.arr[par] = tmp
i = self.parent(i)
self.extractmin()
return ele
def main():
min_heap = MinHeap(7)
min_heap.insert(20)
min_heap.insert(40)
min_heap.insert(50)
min_heap.insert(5)
min_heap.insert(60)
min_heap.insert(3)
min_heap.insert(1)
print (min_heap.arr)
print(min_heap.delidx(3))
print(min_heap.arr[0:min_heap.size])
# print(min_heap.extractmin())
# print(min_heap.arr[0:min_heap.size])
# print(min_heap.extractmin())
# print(min_heap.arr[0:min_heap.size])
# min_heap.insert(4)
# print(min_heap.arr[0:min_heap.size])
if __name__ == "__main__":
main() |
'''
Find the number of islands:
Given a boolean 2D matrix, find the number of islands.
A group of connected 1s forms an island. For example,
the below matrix contains 5 islands
Input : mat[][] = {{1, 1, 0, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 0, 1, 1},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 1}
Output : 5
'''
class Solution:
def __init__(self):
# print("hello")
self.matrix = [[1, 1, 0, 0, 0],
[0, 1, 0, 0, 1],
[1, 0, 1, 1, 1],
[1, 0, 1, 0, 1],
[1, 0, 1, 0, 1]
]
# self.visited = [[0] * len(self.matrix)] * len(self.matrix)
self.visited = [[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]
self.counter = 0
def count_islands(self):
for i in range (len(self.matrix)):
for j in range(len(self.matrix[0])):
# print("CI method i={}, j={} visited {} matrix {} ".format(i, j, self.visited[i][j], self.matrix[i][j]))
# if (((self.matrix[i][j] == 1 and self.visited[i][j] == 0)):
if self.matrix[i][j] == 1:
if self.visited[i][j] == 0:
# print("Calling from main")
self.dfsutil(i, j)
self.counter = self.counter + 1
return self.counter
def issafe(self, row, col):
if row < 0 or row >= len(self.matrix):
return False
if col < 0 or col >= len(self.matrix[0]):
return False
if self.visited[row][col] == 1 or self.matrix[row][col] == 0:
return False
return True
def dfsutil(self, r, c):
# print("dfsutil")
self.visited[r][c] = 1
# N NE E SE S SW W NW
directions = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]
for i in directions:
row = i[0]
col = i[1]
if self.issafe(row +r , col +c):
# if self.matrix[row + r][col + c] == 1 and self.visited[row + r][col + c] == 0:
self.dfsutil(row + r, col + c)
def main():
obj = Solution()
print("Number of islands are {}".format(obj.count_islands()))
if __name__ == "__main__":
main()
|
# https://leetcode.com/problems/binary-tree-postorder-traversal/
# Approach: Iterative approach.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Stack:
def __init__(self):
self.items = []
# self.top = -1
def push(self,ele):
self.items.append(ele)
def pop(self):
if self.isempty() == False:
return self.items.pop()
def size(self):
return len(self.items)
def isempty(self):
if self.items == []:
return True
else:
return False
def top(self):
return self.items[-1]
class Solution(object):
def __init__(self):
self.result = []
def postorderRecurUtil(self, root):
if root == None:
return
self.postorderRecurUtil(root.left)
self.postorderRecurUtil(root.right)
self.result.append(root.val)
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
prev = None
cur = root
mystk = Stack()
while True:
while cur != None:
mystk.push(cur)
cur = cur.left
if mystk.isempty() == True:
return self.result
cur = mystk.top()
if (cur.right == None or cur.right == prev):
prev = cur
self.result.append(cur.val)
mystk.pop()
cur = None
else:
prev = cur
cur = cur.right
return self.result
|
'''
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
path1 = []
path2 = []
def findPath(root, key, path):
if root == None:
return False
path.append(root)
if root == key:
return True
left = findPath(root.left, key, path)
right = findPath(root.right, key, path)
if left == True or right == True:
return True
path.pop()
return False
l1 = findPath(root, p, path1)
l2 = findPath(root, q, path2)
if l1 == False or l2 == False:
return None
i = 0
while True:
try:
if path1[i] != path2[i]:
return path1[i-1]
except IndexError:
return path1[i-1]
i += 1
for i in path1:
if i != None:
print i.val
print("Q is: ")
for i in path2:
if i != None:
print i.val
# print path1
|
from argparse import ArgumentParser
from re import match
import shlex
import sys
class ArgsParser(ArgumentParser):
'''ArgumentParser that adds an "--args" flag that takes extra arguments as a single Bash string.
The value passed to "--args" will be split with `shlex`, and converted into potentially multiple arguments.
Note that the value typically needs to be passed as "--args=<value>" (as opposed to as two Bash arguments: "--args", "<value>").
Useful for e.g. specifying arguments across multiple YAML files that lack the ability to concatenate lists.
'''
ARGS_HELP = '''Additional arguments, passed as one bash-token string (e.g. "-f -x").
If the string being passed begins with a "-" character (as it typically will), then this argument should be expressed as one bash token like "--args=-f -x" (as opposed to two tokens: "--args", "-f -x"), so that argparse doesn\'t get confused.
Useful for e.g. specifying arguments across multiple YAML files that lack the ability to concatenate lists.
'''
def __init__(self, *args, log=None, **kwargs):
super(ArgsParser, self).__init__(*args, **kwargs)
self.add_argument('--args', help=self.ARGS_HELP)
if log is True:
self._log = print
elif log:
if hasattr(log, 'write'):
def _print(msg):
log.write(msg + '\n')
self._log = _print
else:
self._log = log
else:
self._log = None
def log(self, *args):
if self._log:
self._log(*args)
def parse_args(self, *args, **kwargs):
extra_args, _ = self.parse_known_args()
self.log(f'extra_args: {extra_args}')
extra_args = extra_args.args
if extra_args:
extra_args = shlex.split(extra_args)
self.log(f'post-shlex --args: {extra_args}')
[(idx, args_arg)] = [
(idx, arg)
for idx, arg in enumerate(sys.argv)
if arg.startswith('--args')
]
args_arg_span_size = 1 if args_arg.startswith('--args=') else 2
args = sys.argv
# Strip 'python' executable from front of sys.argv, if present:
if match('python3?', args[0]):
args = args[1:]
# Strip called python file from sys.argv; ArgumentParser.parse_args() does this on its own
# when called with no arguments, but we are passing explicit arguments here, so need to
# mimic it.
args = args[1:]
# Strip "--args=<value>" or ["--args","<value>"] args:
args = sys.argv[1:idx] + extra_args + sys.argv[(idx+args_arg_span_size):]
args = super(ArgsParser, self).parse_args(args)
else:
args = super(ArgsParser, self).parse_args()
return args
def exit(self, status=0, message=None):
if status:
args_msg = 'error: argument --args: expected one argument'
if args_msg in message:
raise Exception(f'argparse is exiting with message "{args_msg}". Most likely, you are passing a value to the "--args" flag as a separate Bash argument, and that value begins with a dash ("-"), confusing argparse. Pass "--args=<value>" as one bash token instead.')
else:
raise Exception(f'argparse error: {message}')
exit(status)
|
"""
Exercise 1.
A company is organized hierarchically in departments.
Each department has one person in charge and exactly two subdepartments, or else is a single person.
We have a structure that records the productivity of every person in it, as a numerical value.
We are asked to tell the (sub)department that has highest average productivity.
For example, the structure could look like this in Ptyhon:
[3, [-1, [4, [2], [0]], [1]],[5, [2], [-4]]]
This represents 9 employees.
The top employee has productivity 3 and heads two subdepartments.
The first of them is headed by an employee with productivity -1, etc.
At the bottom there there are 5 departments formed by single employees with no further responsibilities, with productivities 2, 0, 1, 2, and -4.
The average productivity of the last employee is -4.
The department to which s/he belongs is [5,[2],[-4]], with an average productivity of (5+2-4)/3 = 1.
The whole organization has average productivity (3-1+4+2+...-4)/9=12/9.
Write a function (and subfunctions, if needed) that gets a structure like this one and returns the substructure corresponding to the department with the highest average productivity.
Make it efficient meaning avoid redundant computations.
You can assume that the structure given is syntactically correct and encodes a set of hierarchical departments as described above - you don't need to check correctness.
Python is prefered but if you use another language, say how the structure is represented.
Give also the tests cases that you use.
"""
"""
This is an aplication for The Maximum Average Subtree of a Binary Tree
The time and space complexity is O(N).
The N is the number of the nodes in the tree, number of employees in the organization.
"""
"""
Output on my machine:
$ python3 Exercise1.py
test_failure
F
test_left_branch
.
test_provided_case
.
test_right_branch
.
test_simple_negative
.
test_simple_positive
.
test_tie_depatments
.
test_tie_zeros_depatments
.
======================================================================
FAIL: test_failure (__main__.TestSum)
----------------------------------------------------------------------
Traceback (most recent call last):
File "Exercise1.py", line 196, in test_failure
self.assertEqual (get_dep_hap(emp_prod), (22.0, [[4, [2], [0]]]), "FAIL")
AssertionError: Tuples differ: (2.0, [[4, [2], [0]]]) != (22.0, [[4, [2], [0]]])
First differing element 0:
2.0
22.0
- (2.0, [[4, [2], [0]]])
+ (22.0, [[4, [2], [0]]])
? +
: FAIL
----------------------------------------------------------------------
Ran 8 tests in 0.002s
FAILED (failures=1)
"""
import unittest
def get_dep_hap_helper(emp_prod, cnt, max_avg, res):
"""
helper function
"""
#base case of recursion
if (len(emp_prod) == 1):
#return leaf node and count 1
return emp_prod[0],1
#call it recursively on left subtree
left_dep, cnt[0] = get_dep_hap_helper(emp_prod[1], list(cnt), max_avg, res)
#call it recursively on righh subtree
right_dep, cnt[1] = get_dep_hap_helper(emp_prod[2], list(cnt), max_avg, res)
#computer the sum
sum_dep = left_dep + right_dep + emp_prod[0]
#compute the number of nodes
cnt = cnt[0] + cnt[1] + 1
#update the highest average
if(sum_dep/cnt > max_avg[0]):
max_avg[0] = sum_dep/cnt
res.clear()
res.append(emp_prod)
#check for tie deparments
elif(sum_dep/cnt == max_avg[0]) :
res.append(emp_prod)
#return sum and nr of nodes
return sum_dep,cnt
def get_dep_hap(emp_prod):
"""
function to get the department with the highest average productivity
input: the employee productivity list
output: highest average of department(s) and the substructure(s) coreponding to this average
"""
#number of nodes in left subtree
left_cnt = 0
#number of nodes in right subtree
right_cnt = 0
#highest average
max_avg = [float('-inf')]
#substrucure(s) with highest average
res = []
#I am coming from C++ and I want to pass by refrence, I am not sure this is the best way to do it
cnt = [left_cnt, right_cnt]
#helper function called recursively to get the results using a Depth First Search Algorithm
get_dep_hap_helper(emp_prod, cnt, max_avg, res)
#return highest average and the list with department havig that average
return max_avg[0], res
class TestSum(unittest.TestCase):
"""
Testing the function using unittest
Test1: test_provided_case
Test2: test_simple_negative
Test3: test_simple_positive
Test4: test_tie_depatments
Test5: test_tie_zeros_depatments
Test6: test_left_branch
Test7: test_right_branch
Test8: test_failure
"""
def test_provided_case(self):
emp_prod = [3, [-1, [4, [2], [0]], [1]],[5, [2], [-4]]]
print('\n')
print(self._testMethodName)
self.assertEqual(get_dep_hap(emp_prod), (2.0, [[4, [2], [0]]]), "FAIL")
def test_simple_negative(self):
emp_prod = [-1, [-2], [-3]]
print('\n')
print(self._testMethodName)
self.assertEqual(get_dep_hap(emp_prod), (-2.0, [[-1, [-2], [-3]]]), "FAIL")
def test_simple_positive(self):
emp_prod = [1, [2], [3]]
print('\n')
print(self._testMethodName)
self.assertEqual (get_dep_hap(emp_prod), (2.0, [[1, [2], [3]]]), "FAIL")
def test_tie_depatments(self):
emp_prod = [-11, [3, [-1, [4, [2], [0]], [1]],[5, [2], [-4]]], [3, [-1, [4, [2], [0]], [1]],[5, [2], [-4]]]]
print('\n')
print(self._testMethodName)
self.assertEqual (get_dep_hap(emp_prod), (2.0, [[4, [2], [0]], [4, [2], [0]]]), "FAIL")
def test_tie_zeros_depatments(self):
emp_prod = [0, [0, [0, [0], [0]], [0]],[0, [0], [0]]]
print('\n')
print(self._testMethodName)
self.assertEqual (get_dep_hap(emp_prod), (0.0,[[0, [0], [0]],[0, [0, [0], [0]], [0]],[0, [0], [0]],[0, [0, [0, [0], [0]], [0]], [0, [0], [0]]]]), "FAIL")
def test_left_branch(self):
emp_prod = [3, [100, [4, [2], [0]], [1]],[5, [2], [-4]]]
print('\n')
print(self._testMethodName)
self.assertEqual (get_dep_hap(emp_prod), (21.4, [[100, [4, [2], [0]], [1]]]), "FAIL")
def test_right_branch(self):
emp_prod = [3, [5, [2], [-4]], [100, [4, [2], [0]], [1]]]
print('\n')
print(self._testMethodName)
self.assertEqual (get_dep_hap(emp_prod), (21.4, [[100, [4, [2], [0]], [1]]]), "FAIL")
def test_failure(self):
emp_prod = [3, [-1, [4, [2], [0]], [1]],[5, [2], [-4]]]
print('\n')
print(self._testMethodName)
self.assertEqual (get_dep_hap(emp_prod), (22.0, [[4, [2], [0]]]), "FAIL")
if __name__ == "__main__":
unittest.main()
|
def abreMochila(mochila) :
if len(mochila) == 0:
print('Bolso Vazio!')
return False
if len(mochila)!= 0:
print("Itens no bolso:\nDigite o numero correspondente dele para escolher")
for item in mochila:
print(mochila.index(item)+1,"-",item)
i=input("Escolha:",)
escolha=mochila[int(i)-1]
return(escolha) |
from tkinter import *
class Main(Frame):
def __init__(self, master=None):
if(master != None):
master = Tk()
master.title("学习")
super().__init__(master)
self.button = {
'bg': "#f5f5f5",
'fg': "#333333",
}
self.pack()
self.start()
self.mainloop()
pass
def start(self):
leftLabel = Label(self)
leftLabel["bg"] = "#eeeeee"
leftTitle = Label(leftLabel)
leftTitle["text"] = "Test"
leftTitle["width"] = 30
leftTitle.pack()
item = StringVar()
leftList = Listbox(leftLabel, listvariable=item)
item.set(["aaa", "bbb", "ccc", "ddd", "eee"])
leftList["width"] = 26
leftList.bind('<Button-1>', self.list_click)
leftList.pack()
rightLabel = Label(self)
rightLabel["width"] = 90
rightLabel["bg"] = "#aaa"
self.rightNote = Label(rightLabel)
self.rightNote["text"] = "空"
self.rightNote.pack()
leftLabel.pack(side="left")
rightLabel.pack(side="right", fill=Y)
pass
def list_click(self, e):
pass |
#!python
from __future__ import print_function
import unittest
######################################################################
# this problem is from
# https://www.interviewcake.com/question/python/reverse-linked-list
#
# Hooray! It's opposite day. Linked lists go the opposite way today.
# Write a function for reversing a linked list. Do it in-place.
# Your function will have one input: the head of the list.
# Your function should return the new head of the list.
# Here's a sample linked list node class:
class LinkedListNode:
def __init__(self, value):
self.value = value
self.next = None
#
######################################################################
# Now my turn
def reverse_linked_list(head):
"""reverse a singly linked list in place"""
if head:
onebehind = None
twobehind = None
while head.next:
twobehind = onebehind
onebehind = head
head = head.next
onebehind.next = twobehind
head.next = onebehind
return head
def ll2list(head):
"""converts our linked list to a python list"""
if head:
list = [head.value]
while head.next:
head = head.next
list.append(head.value)
return list
else:
return None
# Now Test
class TestReverseLinkedList(unittest.TestCase):
def setUp(self):
self.a = LinkedListNode('A')
self.b = LinkedListNode('B')
self.c = LinkedListNode('C')
self.d = LinkedListNode('D')
self.a.next = self.b
self.b.next = self.c
self.c.next = self.d
def test_0empty(self):
"""No linked list just None"""
head = reverse_linked_list(None)
self.assertEquals(None, head)
def test_1node(self):
"""a linked list of one element"""
self.a.next = None
head = reverse_linked_list(self.a)
self.assertEqual(self.a, head)
def test_4banger(self):
"""no cycles"""
l1 = ll2list(self.a)
head = reverse_linked_list(self.a)
l2 = ll2list(head)
l2.reverse()
self.assertEquals(l1, l2)
if __name__ == "__main__":
# unittest.main()
suite = unittest.TestLoader().loadTestsFromTestCase(TestReverseLinkedList)
unittest.TextTestRunner(verbosity=2).run(suite)
|
#!python
from __future__ import print_function
from operator import itemgetter
import unittest
######################################################################
# this problem is from
# https://www.interviewcake.com/question/highest-product-of-3
# interviewcake 4
# https://www.interviewcake.com/question/python/merging-ranges
# Your company built an in-house calendar tool called HiCal. You want to
# add a feature to see the times in a day when everyone is available.
#
# To do this, you'll need to know when any team is having a meeting. In
# HiCal, a meeting is stored as tuples of integers (start_time,
# end_time). These integers represent the number of 30-minute blocks
# past 9:00am.
#
# For example:
#
# (2, 3) # meeting from 10:00 - 10:30 am
# (6, 9) # meeting from 12:00 - 1:30 pm
#
# Write a function merge_ranges() that takes a list of meeting time
# ranges and returns a list of condensed ranges.
#
# For example, given:
#
test1 = [(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)]
#
# your function would return:
soln1 = [(0, 1), (3, 8), (9, 12)]
# Do not assume the meetings are in order. The meeting times are coming
# from multiple teams.
#
# Write a solution that's efficient even when we can't put a nice upper
# bound on the numbers representing our time ranges. Here we've
# simplified our times down to the number of 30-minute slots past 9:00
# am. But we want the function to work even for very large numbers, like
# Unix timestamps. In any case, the spirit of the challenge is to merge
# meetings where start_time and end_time don't have an upper bound.
######################################################################
# Now my turn
# I seem to recall seeing this before solved by a first pass sort of
# the ranges then a second pass merging ranges using a push down list
# to push and pop new ranges, so let's try that...
def merge_ranges(meetings):
if len(meetings) <= 1:
return meetings
meetings = sorted(meetings, key=itemgetter(0))
pdl = [meetings[0]]
meetings = meetings[1:]
for (nstart, nend) in meetings:
(start, end) = pdl[-1]
if nstart <= end:
if end <= nend:
end = nend
pdl[-1] = (start, end)
else:
pdl.append((nstart, nend))
return pdl
class TestMergingRanges(unittest.TestCase):
def test_givenexample(self):
"""test any examples from the problem"""
print("")
for soln, test in [
[[(0, 1), (3, 8), (9, 12)],
[(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)]]]:
print("merge_ranges %s" % test)
print(" is %s (should be %s)" % (merge_ranges(test), soln))
self.assertEqual(soln, merge_ranges(test))
def test_others(self):
"""test other trials"""
print("")
for soln, test in [
[[(-4, 8), (9, 12)],
[(3, 5), (-4, 8), (10, 12), (9, 10)]],
[[(0, 3)],
[(0, 3), (1, 2)]]]:
print("merge_ranges %s" % test)
print(" is %s (should be %s)" % (merge_ranges(test), soln))
self.assertEqual(soln, merge_ranges(test))
if __name__ == "__main__":
# # unittest.main()
suite = unittest.TestLoader().loadTestsFromTestCase(TestMergingRanges)
unittest.TextTestRunner(verbosity=2).run(suite)
|
#!python
from __future__ import print_function
import unittest
######################################################################
# this problem is from
# https://www.interviewcake.com/question/highest-product-of-3
# Given a list_of_ints, find the highest_product you can get from three of
# the integers.
# The input list_of_ints will always have at least three integers.
def highest_product0(list_of_ints):
"""two neg nums may be bigger than three pos nums. do both products. return max"""
# I think this is the correct approach for this problem, it reduces
# logic complexity by trying both of the possible answers, determining
# the actual max in its last comparison
# it is presumably o(n log n) with one sort that could go to o(n^2)
# there is an o(n) sol'n but logic is more complex, and requires many many
# more mults
list_of_ints.sort()
min0 = list_of_ints[0]
min1 = list_of_ints[1]
max0 = list_of_ints[-1]
max1 = list_of_ints[-2]
max2 = list_of_ints[-3]
poss1 = min0 * min1 * max0
poss2 = max0 * max1 * max2
return poss1 if poss1 > poss2 else poss2 # such an ugly ternary conditional
def highest_productordern(list_of_ints):
"""a greedy order n approach taken off web (with a critical bug fix!)"""
# from
# https://knaidu.gitbooks.io/problem-solving/content/primitive_types/highest_product_of_3.html
# Maintain the following values as we traverse the array
# lowest_number
# highest_number
# lowest_product_of_2
# highest_product_of_2
# highest_product_of_3
low = min(list_of_ints[0], list_of_ints[1])
high = max(list_of_ints[0], list_of_ints[1])
low_prod2 = high_prod2 = list_of_ints[0] * list_of_ints[1]
high_prod3 = high_prod2 * list_of_ints[2]
i = 2
while i < len(list_of_ints):
curr = list_of_ints[i]
high_prod3 = max(
high_prod2 * curr,
low_prod2 * curr,
high_prod3)
low_prod2 = min(low * curr, low_prod2)
high_prod2 = max(high * curr, high_prod2)
high = max(high, curr)
low = min(low, curr)
i += 1 # heh, knaidu web book never incrs i, and so oo loop
return high_prod3
# first approach, correct and better than brute force, but way too
# many comparisons (ie complex logic)
def highest_product1(list_of_ints):
"""return the highest product, use logic to figure out which three operands to use"""
# this has two sorts, both are of sublists
# this works, is correct, but logic is a bit complex
# probably simpler mainteance with highest_product0
neg = []
pos = []
for int in list_of_ints:
if int < 0:
neg.append(int)
else:
pos.append(int)
neg.sort()
pos.sort()
if len(pos) == 0:
# no pos ints, so highest number are three "small" negs
return(neg[-3] * neg[-2] * neg[-1])
elif len(pos) == 1:
# 1 pos int, so return that * prod of two "large" negs
return(neg[0] * neg[1] * pos[-1])
elif len(neg) >= 2:
maxneg = neg[0] * neg[1]
if maxneg > pos[-3] * pos[-2]:
return maxneg * pos[-1]
elif len(pos) == 2:
return neg[-1] * pos[-2] * pos[-1]
else:
return pos[-3] * pos[-2] * pos[-1]
class TestHighestProduct(unittest.TestCase):
def test_givenexample(self):
"""test the example from the problem"""
for soln, test in [
[300, [-10, -10, 1, 3, 2]],
]:
self.assertEqual(soln, highest_product0(test))
def test_givenexampleordern(self):
"""test the example from the problem using order n soln"""
for soln, test in [
[300, [-10, -10, 1, 3, 2]],
]:
self.assertEqual(soln, highest_productordern(test))
def test_highestproduct(self):
"""test all 3 highest_product strategies, make sure they are equal to each other"""
print("")
for t in [
[1, 2, 3],
[-1, 0, 1],
[-3, -4, 2],
[0, 1, 2, 3, 4, 5],
[-1, 0, 1, 2, 3, 4],
[-3, -4, 0, 1, 2, 3, 4],
[1, 2, 3, -3, -4, 0, 4],
[-1, -2, -3, 0, 1, 2, 30, 1, 2, -4, -5, 3],
[-10, -10, 1, 3, 2]]:
print("highest product of %s is %s" % (t, highest_product0(t)))
self.assertEqual(highest_productordern(t), highest_product0(t))
self.assertEqual(highest_product0(t), highest_product1(t))
if __name__ == "__main__":
# # unittest.main()
suite = unittest.TestLoader().loadTestsFromTestCase(TestHighestProduct)
unittest.TextTestRunner(verbosity=2).run(suite)
|
#!python
from __future__ import print_function
import unittest
######################################################################
# this problem is from
# https://www.interviewcake.com/question/python/which-appears-twice
#
# I have a list where every number in the range 1...n appears once
# except for one number which appears twice.
# Write a function for finding the number that appears twice.
#
######################################################################
# Now my turn
# 1. first try, not seen, 1/2 a binary search until I realized list of
# ints is not necessarily sorted.
# 2. 2nd try, in my head, can I xor them? Nah.
# 3. 3rd try, I recall the gaussian formula to add n consecutive
# integers, and then realize I can quickly determine this number
# as well as sum my entire list
# and the difference will be the duplicated number
def which_twice(ints):
"""find the number in ints that appears twice"""
n = len(ints)
# n ints, so the list is
# 1..(n-1) + some duplicated number
# = ((n-1) * (1 + n - 1) / 2)
# = ((n-1) * (n) / 2)
# = ((n-1) * (n / 2.0)
gauss = int((n - 1) * (n / 2.0))
total = sum(ints)
dupe = total - gauss
return dupe
class TestTwice(unittest.TestCase):
def test_examples(self):
"""test some examples"""
tests = [
[1, [1, 1, 2, 3]],
[2, [1, 2, 2, 3]],
[2, [1, 2, 2, 3]],
[2, [1, 2, 2, 3]],
[2, [1, 2, 2, 3]],
[3, [3, 1, 2, 3]],
]
for soln, ints in tests:
print("")
print("%s <- %s" % (soln, ints))
ans = which_twice(ints)
print("%s <= %s" % (ans, ints))
self.assertEqual(soln, ans)
if __name__ == "__main__":
# unittest.main()
suite = unittest.TestLoader().loadTestsFromTestCase(TestTwice)
unittest.TextTestRunner(verbosity=2).run(suite)
|
def max_list_iter(int_list): # must use iteration not recursion
"""finds the max of a list of numbers and returns the value (not the index)
If int_list is empty, returns None. If list is None, raises ValueError"""
pass
if int_list == None: #error for None value
raise ValueError
elif len(int_list) == 0: #empty list return
return None
maxi = int_list[0] #the first num is the first max as only current element checked
for num in int_list:
if num > maxi:
maxi = num
return maxi
def reverse_rec(int_list): # must use recursion
"""recursively reverses a list of numbers and returns the reversed list
If list is None, raises ValueError"""
if int_list == None: #error for None value
raise ValueError
if len(int_list) == 1 or len(int_list) == 0: #base case; only one element in list, have reached the end
return int_list
var = reverse_rec(int_list[1:]) #recursive call, slices list until one element in list
var.append(int_list[0])
return var
def bin_search(target, low, high, int_list): # must use recursion
"""searches for target in int_list[low..high] and returns index if found
If target is not found returns None. If list is None, raises ValueError """
if int_list == None:
raise ValueError
if len(int_list) == 0:
return None
mid = (high + low) // 2
if target == int_list[mid]:
return mid
if high == low:
return None
if target > int_list[mid]:
return bin_search(target, mid + 1, high, int_list)
if target < int_list[mid]:
return bin_search(target, low, mid - 1, int_list)
|
#!/usr/bin/env python3
import csv
def read_csv_file(filename, delimiter=' '):
labs = []
feats = []
with open(filename, 'r') as f:
reader = csv.reader(f, delimiter=delimiter)
for row in reader:
labs.append(row[0])
feats.append(list(map(float, row[1:])))
return feats, labs
def build_dic(filename):
dic = {}
rev_dic = {}
with open(filename,'r') as f:
for line in f:
word, ID= line.rstrip().split(' ')
dic[word] = int(ID)
rev_dic[int(ID)] = word
return dic, rev_dic
def build_targets(filename, dic):
targets = []
with open(filename,'r') as f:
for line in f:
targets.append(dic[line.rstrip()])
return targets
def build_label_color_list(target_list, color_list):
''' assume the targets are in pairs
'''
word_color_dict = {}
for i, target in enumerate(target_list):
word_color_dict[target] = color_list[i%len(color_list)]
return word_color_dict
def write_feat_lab(filename, feats, labs, delimiter=' '):
''' write a csv like file with feature list and label list
args:
filename: The output filename
feats: the feature list with (num_occur, feat_dim)
labs: the label list with length = num_occur
delimiter: the delimiter in csv file
'''
with open(filename,'w') as f:
for i, feat_list in enumerate(feats):
for j in feat_list:
f.write(str(j)+ delimiter)
f.write(str(labs[i])+'\n')
return
def write_feat_in_lab_name(feat_dic, out_dir, delimiter=' '):
''' write a label file with features
args:
feat_dic: The dictionary with dic[lab]=shape(num_occur,feat_dim)
out_dir : The output directory of the generated features
delimiter:The csv file delimiter, default=' '
'''
for i in feat_dic:
with open(out_dir+'/'+str(i),'a') as f:
for j in feat_dic[i]:
for k in range(len(j)-1):
f.write(str(j[k])+delimiter)
f.write(str(j[len(j)-1])+ '\n')
return
def build_lexicon(fn, word_dic):
''' build the lexicon map
args:
fn: the lexicon file name
return:
lexicon_dic: the lexicon dictionary
with lexicon_dic[word_id] = list of phonemes
'''
lexicon_dic = {}
with open(fn,'r') as f:
for line in f:
line_sp = line.rstrip().split(' ')
lexicon_dic[word_dic[line_sp[0]]] = []
for i in range(1,len(line_sp)):
lexicon_dic[word_dic[line_sp[0]]].append(line_sp[i])
return lexicon_dic
|
'''
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
What is the total of all the name scores in the file?
i personally removed all quotation marks to name list.
'''
with open('unordered.txt') as f:
names = [i.split(",") for i in f.readlines()]
names = sorted(names[0])
names = [x.lower() for x in names]
def score(index_value, name):
alphabet_value = 0
for letter in name:
letter_value = 0
letter_value = ord(letter) - 96
alphabet_value = alphabet_value + letter_value
return (index_value * alphabet_value)
counter = 1
total_val = 0
for name in names:
total_val = total_val + score(counter, name)
counter = counter + 1
print(total_val) |
"""
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
"""
def length_collatz(subject):
og_subject = subject
counter = 1
while subject != 1:
if subject % 2 == 0:
counter += 1
subject = subject / 2
else:
counter += 1
subject = (3*subject) + 1
subject_counter = (og_subject, counter)
return subject_counter
def is_it_longest(tuple_val, max_so_far):
if tuple_val[1] > max_so_far:
return True
max_so_far = 0
longest_number = 0
for x in range(1, 1000000):
print(x)
current_it = length_collatz(x)
if is_it_longest(current_it, max_so_far):
max_so_far = current_it[1]
longest_number = current_it[0]
print(longest_number)
|
'''
Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
digits: https://projecteuler.net/problem=13
'''
with open('numbers.txt') as f:
numbers = [i.split() for i in f.readlines()]
working_value = 0
for rows in numbers:
working_value = working_value + int(rows[0])
print(str(working_value)[:10])
|
# -*- coding: utf-8 -*-
## @package cliask
#
# A module for getting validated user input via the console.
import re
## Ask for input until a valid response is given and return the
# response.
# @param question A string containing a question asking for
# input.
# @param default A default answer if the user gives no
# answer (default: None).
# @param validator A regex, function, tuple or list to
# validate the question (default: None). If
# it is a regex the input must match it to be
# validated. If it is a function the function
# must take the input as a parameter and
# return true if the input is valid. If it is
# a tuple or a list the input must be an
# element in it to valid.
# @param invalid_response A string containing the response to print
# when invalid input is entered (default:
# None).
# @return The validated input.
def ask(question, default='', validator='',
invalid_response=''):
if default:
question = '{} |{}| '.format(question.strip(), default)
while True:
answer = input(question)
# If there is no input and a default is given, return the
# default.
if not answer and default:
answer = default
break
# If there is input but no validator, return the input.
if not validator:
break
# If there is a validator, return the input if it is valid.
if _validate(validator, answer):
break
print(invalid_response)
return answer
## Ask for yes or no until a valid response is given and return True
# if the answer is yes.
#
# @param question A string containing a question asking for
# input.
# @param default A default answer if the user gives no
# answer (default: None).
# @param validator A regex, function, tuple or list to
# validate the question (default: a regex for
# yes and no). If it is a regex the input
# must match it to be validated. If it is a
# function the function must take the input
# as a parameter and return true if the input
# is valid. If it is a tuple or a list the
# input must be an element in it to valid.
# @param invalid_response A string containing the response to print
# when invalid input is entered (default:
# Please enter "yes" or "no").
# @return The validated input.
def agree(question, default='', validator=r'(?i)\Ay(?:es)?|no?\Z',
invalid_response='Please enter "yes" or "no"'):
if ask(question,
default=default,
validator=validator,
invalid_response=invalid_response)[0].lower() == 'y':
return True
else:
return False
## Returns true if the given validator validates the given input.
# @param validator See ask().
# @param s Input string to validate.
# @return True if the given validator validates the given input.
def _validate(validator, s):
valid = False
# If the validator is a function.
if (hasattr(validator, '__call__')):
if validator(s):
return True
elif type(validator) is list or type(validator) is tuple:
if s in validator:
return True
elif re.search(validator, s):
return True
return False
## Unit test by an example of usage.
def _test():
## Checks if input is within a range.
# @param input Input string to check.
# @return True if input is within range.
def in_range(s):
number = ''
try:
number = int(s)
except ValueError:
pass
return number in range(1, 11)
print('Please answer the following questions:')
# If you use cliask from another module you have to prefix it with
# its module name, i.e. call cliask.ask and cliask.agree.
ynq = ask('Yes or no or quit? ',
validator=r'(?i)[ynq]',
invalid_response='Answer y or n for yes or no',
default='y')
number = ask('A number between 1 and 10: ',
validator=in_range,
invalid_response='You must specify a number between 1 and 10')
animal = ask('Cow or cat? ',
validator=('cow', 'cat'),
invalid_response='You must say cow or cat')
yn = agree('Yes or no? ')
q = ask('Why? ')
print('You answered:')
print(ynq)
print(number)
print(animal)
print(q)
print(yn)
if __name__ == '__main__':
_test()
|
# Creare un decoratore di classe per far si che la classe di partenza sia modificata in modo
# da creare un dizionario interno contenente tutti gli attributi e i valori della classe.
def decoratorDictionary(cls):
def decorator(*args, **kwargs):
diz= dict()
for i in range(len(args)):
diz[i] = args[i]
setattr(cls, "diz", diz)
return cls(*args, **kwargs)
return decorator
@decoratorDictionary
class Test:
def __init__(self, *args, **kwargs):
self._a = args[0]
self._b = args[1]
self._c = args[2]
# Creare un decoratore di funzione che per ogni elemento passato come dizionario alla funzione stampa la
# coppia chiave valore singolarmente
import functools
def decoratorPrint(funz):
@functools.wraps(funz)
def wrapper(*args, **kwargs):
for el in args:
for key in el:
print(key, el[key])
funz(*args, **kwargs)
return wrapper
@decoratorPrint
def func(diz = {}):
print(f"stampa effettuata di {diz}")
print()
print("-------------------- Decoratore di classe: -----------------------")
a= Test(1, "ciao", [1, 2, "ciao", ["fanculo"]])
print(a.diz)
print("-------------------- Decoratore di funzione: ---------------------")
func(a.diz) |
#Scrivere la classe MyDictionary che implementa gli operatori di dict riportati di seguito.
# MyDictionary deve avere solo una variabile di istanza e questa deve essere di tipo lista.
# Per rappresentare le coppie, dovete usare la classe MyPair che ha due variabili di istanza
# (key e value) e i metodi getKey, getValue,setKey, setValue.
class MyPair:
def __init__(self, k, v):
self._key= k
self._value= v
def getKey(self):
return self._key
def setKey(self, k):
self._key= k
def getValue(self):
return self._value
def setValue(self, v):
self._value= v
class MyDictionary:
def __init__(self):
self._dic= list()
def getDic(self):
return self._dic
def insert(self, k, v):
for e in self._dic:
if e.getKey() == k:
assert("The key already exists")
return
self._dic.append(MyPair(k, v))
def getFromKey(self, k):
if len(self._dic) == 0:
assert("There is no value in the dictionary")
else:
for e in self._dic:
if e.getKey() == k:
return e
def setFromKey(self, k, v):
if len(self._dic) == 0:
assert("There is no value in the dictionary")
else:
for e in self._dic:
if e.getKey() == k:
e.setValue(v)
def delFromKey(self, k):
if len(self._dic) == 0:
assert("There is no value in the dictionary")
return
else:
for i in range(0, len(self._dic)):
if self._dic[i].getKey() == k:
c= i
self._dic.pop(i)
def isKeyInside(self, k):
for e in self._dic:
if e.getKey() == k:
return True
return False
def isNotKeyInside(self, k):
for e in self._dic:
if e.getKey() == k:
return False
return True
def isEquivalent(self, obj):
if not isinstance(obj, MyDictionary):
assert("The object passed isn't a dictionary")
else:
x= obj.getDic()
if len(self._dic) == len(x):
c= 0
for e in self._dic:
for i in range(0, len(self._dic)):
if e.getValue() == x[i].getValue():
c+= 1
if c == len(self._dic):
return True
return False
def isNotEquivalent(self, obj):
if not isinstance(obj, MyDictionary):
assert ("The object passed isn't a dictionary")
else:
x = obj.getDic()
if len(self._dic) == len(x):
c = 0
for e in self._dic:
for i in range(0, len(self._dic)):
if e.getValue() == x[i].getValue():
c += 1
if c == len(self._dic):
return False
return True
c= MyDictionary()
c.insert("chiave", 6)
print(c.getFromKey("chiave")) |
#Scrivere una funzione che prende in input un intero positivo
#ne restituisce e produce un generatore degli interi
#0, 1, 3, 6, 10, .. In altre parole, l’i-esimo elemento
#e`(0 + 1 + 2 + ... + i-1)
def gen(n):
x= 0
for k in range (0, n):
x+= k
yield x
for k in gen(5):
print(k) |
import random
class Treasure:
def __init__(self):
type=random.randint(1,2)
self.creat_treasure(type)
def creat_treasure(self,type):
if type==1:
self.name="木剑"
self.attack_max=5
self.attack_min=1
self.level=2
self.belonging=0
if type==2:
self.name="铜剑"
self.attack_max=10
self.attack_min=5
self.level=5
self.belonging=0
if __name__ == '__main__':
Treasure=Treasure()
print(Treasure.name)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@course: Python is Easy
@assignment: Homework #2
@description: functiona and how to call them
Created on Thu Feb 11 21:36:13 2021
@author: Claus Derlien
"""
# defines name of artist/group/band
#Artist = "Pink Floyd"
# defines music style/genre
#Genre = "Progressive Rock"
# defines Album name
#Album = "The Dark Side of the Moon"
def Artist():
return "Pink Floyd"
def Genre():
return "Progressive Rock"
def Album():
return "The Dark Side of the Moon"
# for the extra credit, a function that will return true if artist and genre is equal
def valid():
if Artist() == Genre():
return True
else:
return False
print(Artist())
print(Genre())
print(Album())
print(valid())
|
# # chant = print("We Will Rock You")
# # print(chant)
# print("Let's test your programming knowledge.")
# print("""Why do we use methods?
# 1. To repeat a statement multiple times.
# 2. To decompose a program into several small subroutines.
# 3. To determine the execution time of a program.
# 4. To interrupt the execution of a program.""")
# print("This is a number:", 125 + 125)
text = "Nobody expects the Spanish inquisition!"
text = text.replace("!", "")
text = text.lower()
print(text)
|
num = 9
# def evaluate_num(num):
# return
if num > 10:
print('greater')
elif num == 10:
print('equal')
else:
print('less')
# pass
|
'''
I came across this problem in code war and I had fun and productive time coding this. And learned the importance of order of operation and how it effects the result you want to get.
Just enter a numer and it will return an array with all of the integer's divisors(except for 1 and itself) from smallest to largest. Try entering a prime number too.
'''
user_input = int(input("➡➡➡➡➡➡: Enter a number below. \n➡➡➡➡➡➡: "))
def divisor(num):
div = []
if num > 1:
for i in range(2,num):
if num % i == 0:
div.append(i)
return div
def prime(num):
flag = False
if num > 1:
for i in range(2,num):
if num % i == 0:
flag = True
break
if num < 0:
return "➡➡➡➡➡➡: Please enter a positive number."
elif num == 0:
return f"➡➡➡➡➡➡: {num} is rational, whole, integer and real number. Some say it's natural number too but it's debatable ¯\_(ツ)_/¯"
elif num == 1:
return f"➡➡➡➡➡➡: {num} is a number, a single entity. Remember {num} is not a whole number since it has only one divisor"
else:
if num == 69:
return f"( ͡° ͜ʖ ͡°): {num} eh?? ( ͡° ͜ʖ ͡°) Well the divisors are: {sorted(divisor(num))}" # added this special case for the number 69. huehuehue
elif flag:
return f"➡➡➡➡➡➡: The divisor of {num}: {sorted(divisor(num))}"
else:
return f"➡➡➡➡➡➡: {num} is a prime number. A prime number is a whole number with exactly two integral divisors, 1 and itself i.e. {num}"
print(prime(user_input))
|
#Even-tual Reduction Problem Code: EVENTUAL
#You are given a string S with length N. You may perform the following operation any number of times: choose a non-empty substring of S (possibly the whole string S) such that each character occurs an even number of times in this substring and erase this substring from S. (The parts of S before and after the erased substring are concatenated and the next operation is performed on this shorter string.)
# For example, from the string "acabbad", we can erase the highlighted substring "abba", since each character occurs an even number of times in this substring. After this operation, the remaining string is "acd".
# Is it possible to erase the whole string using one or more operations?
# Note: A string B is a substring of a string A if B can be obtained from A by deleting several (possibly none or all) characters from the beginning and several (possibly none or all) characters from the end.
# Input
# The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
# The first line of each test case contains a single integer N.
# The second line contains a single string S with length N.
# Output
# For each test case, print a single line containing the string "YES" if it is possible to erase the whole string or "NO" otherwise (without quotes).
# Constraints
# 1≤T≤200
# 1≤N≤1,000
# S contains only lowercase English letters
# Example Input
# 4
# 6
# cabbac
# 7
# acabbad
# 18
# fbedfcbdaebaaceeba
# 21
# yourcrushlovesyouback
# Example Output
# YES
# NO
# YES
# NO
# Explanation
# Example case 1: We can perform two operations: erase the substring "abba", which leaves us with the string "cc", and then erase "cc"
#Solution:-
# cook your dish here
try:
t=int(input())
for _ in range(t):
n=input()
s=input()
flag='YES'
freq =[0]*26
n = len(s)
for i in range(n):
freq[ord(s[i])-97]+= 1
for i in range(26):
if (freq[i]% 2 == 1):
flag='NO'
break
print(flag)
except:
pass
|
"""
输入非负整数n计算n!
Version: 0.1
Author: 骆昊
Date: 2018-03-01
"""
#calculate the factorial
def factorial1(n):
result = 1
# for x in range(1, n + 1):
# result *= x
# print('%d! = %d' % (n, result))
for y in range(n,0,-1):
result *= y
print('%d!=%d'%(n, result))
return result
factorial1(3)
|
"""
检查变量的类型
Version: 0.1
Author: 骆昊
Date: 2018-02-27
"""
a = 100
b = 1000000000000000000
c = 12.345
d = 1 + 5j
e = 'A'
f = 'hello, world'
g = True
h = {"age":"18"}
i = [1,2,3]
print(type(a))#<class 'int'>
print(type(b))#<class 'int'>
print(type(c))#<class 'float'>
print(type(d))#<class 'complex'>
print(type(e))#<class 'str'>
print(type(f))#<class 'str'>
print(type(g))#<class 'bool'>
print(type(h))#<class 'dict'>
print(type(i))#<class 'list'>
|
"""
类型转换
Version: 0.1
Author: tester
Date: 2019-11-25
"""
#use the function type() to get the variable's type
a = 100
print(a)#100
print(type(a))#<class 'int'>
b = str(a)
print('the value of b is:',b)#the value of b is: 100
print(type(b))#<class 'str'>
c = 12.345
print('the value of c is:',c)
print('the type of c is:',type(c))
"""
the value of c is: 12.345
the type of c is: <class 'float'>
"""
d = str(c)
print('the value of d is:',d)
print('the type of d is:',type(d))
'''
the value of d is: 12.345
the type of d is: <class 'str'>
'''
e = '123'
print('the value of e is:',e)
print('the type of e is:',type(e))
'''
the value of e is: 123
the type of e is: <class 'str'>
'''
f = int(e)
print('the value of f is:',f)
print('the type of f is:',type(f))
'''
the value of f is: 123
the type of f is: <class 'int'>
'''
g = '123.456'
print('the value of g is:',g)
print('the type of g is:',type(g))
'''
the value of g is: 123.456
the type of g is: <class 'str'>
'''
h = float(g)
print('the value of h is:',h)
print('the type of h is:',type(h))
'''
the value of h is: 123.456
the type of h is: <class 'float'>
'''
i = False
print('the value of i is:',i)
print('the type of i is:',type(i))
'''
the value of i is: False
the type of i is: <class 'bool'>
'''
j = str(i)
print('the value of j is:',j)
print('the type of j is:',type(j))
'''
the value of j is: False
the type of j is: <class 'str'>
'''
k = 'hello'
print('the value of k is:',k)
print('the type of k is:',type(k))
'''
the value of k is: hello
the type of k is: <class 'str'>
'''
m = bool(k)
print('the value of m is:',m)
print('the type of m is:',type(m))
'''
the value of m is: True
the type of m is: <class 'bool'>
'''
print(a)
print(type(a))
print(b)
print(type(b))
print(c)
print(type(c))
print(d)
print(type(d))
print(e)
print(type(e))
print(f)
print(type(f))
print(g)
print(type(g))
print(h)
print(type(h))
print(i)
print(type(i))
print(j)
print(type(j))
print(k)
print(type(k))
print(m)
print(type(m))
'''
100
<class 'int'>
100
<class 'str'>
12.345
<class 'float'>
12.345
<class 'str'>
123
<class 'str'>
123
<class 'int'>
123.456
<class 'str'>
123.456
<class 'float'>
False
<class 'bool'>
False
<class 'str'>
hello
<class 'str'>
True
<class 'bool'>
'''
complex_number = 34 + 56j #This is a complex number.
print(complex_number)
print(type(complex_number))
'''
(34+56j)
<class 'complex'>
'''
test_string = "hello,world" #This is a string.
print(test_string)
print(type(test_string))
'''
hello,world
<class 'str'>
''' |
"""
用while循环实现1~100之间的奇数求和
"""
sum,num = 0,1
while num <= 100:
sum += num
num += 2
print("1到100的奇数之和为:",sum)
#1到100的奇数之和为: 2500 |
# encoding: utf-8
'''
@author: developer
@software: python
@file: word_count.py
@time: 2019/12/25 21:30
@desc:
'''
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
with open(filename, 'rb') as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " do not exist."
print(msg)
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
#
# filename = 'alice.txt'
# count_words(filename)
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
count_words(filename)
'''
The file alice.txt has about 17842 words.
Sorry, the file siddhartha.txt do not exist.
The file moby_dick.txt has about 215829 words.
The file little_women.txt has about 189079 words.
''' |
class Arvore:
def __init__(self, raiz = None):
self.__raiz = raiz
@property
def raiz(self):
return self.__raiz
def inserir_elemento(self, no):
no.no_direito = None
no.no_esquerdo = None
if self.__raiz is None:
self.__raiz = no
else:
self.__inserir(self.raiz, no)
def __inserir(self, referencia, novo_no):
if referencia.peso() < novo_no.peso():
if referencia.no_direito is None:
referencia.no_direito = novo_no
else:
self.__inserir(referencia.no_direito, novo_no)
else:
if referencia.no_esquerdo is None:
referencia.no_esquerdo = novo_no
else:
self.__inserir(referencia.no_esquerdo, novo_no)
def buscar(self, no_busca):
self.__buscar(self.__raiz, no_busca)
def __buscar(self, referencia, no_busca):
if referencia.valor == no_busca.valor:
return referencia
else:
# Direita do nó
if referencia.peso() < no_busca.peso():
if referencia.no_direito is None:
raise ValueError("Elemento não encontrado")
else:
print("Navegando pela direita do nó", referencia.valor.__str__())
return self.__buscar(referencia.no_direito, no_busca)
else:
# Esquerda do nó
if referencia.no_esquerdo is None:
raise ValueError("Elemento não encontrado")
else:
print("Navegando pela esquerda do nó", referencia.valor.__str__())
return self.__buscar(referencia.no_esquerdo, no_busca)
def __str__(self):
return "[(X)]" if self.__raiz is None else self.__raiz.__str__()
|
#!/usr/bin/env python3
# Activity7
# Vahini Madipalli
# Course: ISQA3900-850: Web Application Development
# Date: 11-12-2020
# Creating python program which reads from the csv files, display the list, search based on cust_id
from Customer import Customer
import csv
FILENAME = "customers.csv"
customer_details = []
def read_csv():
# Exception handling to handle invalid values and read from csv
try:
with open(FILENAME, newline="") as file:
read = csv.reader(file)
next(read)
for row in read:
customer_details.append([row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7]])
return customer_details
# file not found exception handler
except OSError:
print("File cannot be opened or read" + FILENAME)
# function to read customer list
def read_customerlist():
for data in customer_details:
customer_id_name = Customer(data[0],data[1],data[2])
print('{0} : {1}'.format(customer_id_name.cust_num(),customer_id_name.cust_name()))
#print(str(customer_id_name.cust_num()))
# function to search based on customer_id
def search_id(customer_id):
for data in customer_details:
customer_id_name = Customer(data[0],data[1],data[2],data[3],data[4],data[5],data[6],data[7])
if(customer_id == customer_id_name.cust_num()):
return customer_id_name
break
return None
def main():
customer_details = read_csv()
print("CUSTOMER VIEWER")
print()
print("ALL CUSTOMERS")
print("----------------------------")
read_customerlist()
print()
choice = "y"
# repetitive structure to prompt and look up
while choice.lower() == "y":
try:
customer_id = input("Enter Customer Id: ")
customer_object = search_id(customer_id)
if(customer_object == None):
print()
print("Customer a does not exist")
print()
else:
print()
print(customer_object)
print()
choice = input("Would you like to continue? y/n: ")
print()
# exception to handle invalid customer id entries
except ValueError:
print("Customer a does not exist")
choice = input("Would you like to continue? y/n: ")
print()
print("Bye!")
if __name__ == "__main__":
main() |
groceries = ['candy', 'hot pockets', 'kung fu movie', 'peanut butter', 'bread', 'cat food', 'wine']
for index, item in enumerate(groceries, 1):
print(f'{index}. {item}')
|
import time
from timeit import default_timer as Timer
def fib(number):
if number <= 1: return 1
return fib(number - 2) + fib(number - 1)
start = time.clock()
for _ in xrange(4):
fib(30)
end = time.clock()
print('\nserial time', end - start)
|
from abc import ABC, abstractmethod
from enum import Enum, unique
@unique
class VEHICLE_TYPE(Enum):
CAR = 'car'
TRUCK = 'truck'
class IVehicle(ABC):
@abstractmethod
def get_wheels(self):
pass
@abstractmethod
def get_type(self):
pass
@abstractmethod
def max_speed(self):
pass
@abstractmethod #'''Return True if self vehicle is faster than given vehicle.'''
def is_faster(self, vehicle):
pass
|
a = [
{"name": 2,
"age": 3},
{"name": 3,
"age": 4},
]
def f():
for x in a:
yield x["name"]
for x in f():
print x |
# coding:utf-8
import os
def mkdir(path, dir_list):
for x in dir_list:
os.mkdir(os.path.join(path, x))
def a_z():
return [chr(x) for x in range(97, 97+26)]
def A_Z():
return [chr(x) for x in range(65, 91)]
if __name__ == '__main__':
dir_list = [str(x) for x in range(12)]
path = r'C:\Users\cooper\Desktop\opp\chongqing\p'
# a_z
# dir_list.extend(a_z())
# A_Z
# dir_list.extend(A_Z())
# print '\n'.join(dir_list)
# print dir_list
# 开始创建目录
mkdir(path, dir_list)
|
def hourglassSum(arr):
listSum=[]
for i in range(len(arr)-2):
sum=0
for j in range(len(arr)-2):
sum=arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2]
listSum.append(sum)
return max(listSum)
# arr=[[1, 1, 1, 0, 0, 0],
# [0, 1, 0, 0, 0, 0],
# [1, 1, 1, 0, 0, 0],
# [0, 0, 2, 4, 4, 0],
# [0, 0, 0, 2, 0, 0],
# [0, 0, 1, 2, 4, 0]]
# print(hourglassSum(arr))
if __name__ == '__main__':
arr = []
for _ in range(6):
arr.append(list(map(int, input().rstrip().split())))
result = hourglassSum(arr)
print(result) |
from collections import Counter
def reverse(split):
return split[::-1]
def shufflestr(rev):
def splitstr(s):
count=Counter(s)
str=""
for i in count:
str=str+i
return str
def reverseShuffleMerge(s):
split=splitstr(s)
rev=reverse(split)
shuffle=shufflestr(rev)
s="abcdefgabcdefg"
print(reverseShuffleMerge(s))
|
def jumpingOnClouds(c):
num_of_jumps=0
i=0
while i<len(c)-1:
num_of_jumps+=1
if i==len(c)-2:
break
if c[i+2]==1:
i+=1
else:
i+=2
return num_of_jumps
c=[0,0,0,1,0,0]
print(jumpingOnClouds(c))
|
# -*- coding: Latin-1 -*-
"""
# -*- coding: Latin-1 -*-
rien d'assez complexe le code source écrit en vue d'une relation pour une formation
#la suite directaffiche une table de mutiplication
nbr = input("\t veillez saisir un nombre")
nbr = int(nbr)
i = 0
while i <= 20:
print("\t", nbr, "*" , i ,"=", nbr * i )
i +=1
enter = input("Q pour quiter le programme 5 pour voir le tableau de conversion de l'euro en dollars canadien")
j = 1
dol = 1.65
while enter== "5" :
while j <= 38 :
print(j,"euro(s)","=", j * dol, "dollar(s)" )
j +=1
break
while enter == "Q" or "q":
break
#la suite direct du progamme affiche une suite de nombre chaque nombre triple du précedent
w = input("Un nombre svp")
w = int(w)
g =1
while g <= 12 :
print(w*3)
w *= 3
g +=1
"""
import os
nom = os.getlogin()
print(nom)
print("lol")
|
"""ceci est mon programme en ligne de commande de calcul de base"""
#fonction de calcul
def Addition():
resultat =nbr0 + nbr1
print("\t {} + {} ={}".format(nbr0,nbr1,resultat))
""" ceci est ma fonction d'addition
"""
def Soustration():
resultat = nbr0 - nbr1
print("{} - {} = {}".format(nbr0,nbr1,resultat))
def Multiplication():
resultat= nbr0* nbr1
print("{} * {} = {}".format(nbr0,nbr1,resultat))
def Division():
resultat= nbr0 / nbr1
reste = nbr0 % nbr1
print("\t {}/{} = {} avec {} comme reste.......".format(nbr0, nbr1, resultat, reste) |
"""
while chaine.lower() != "q":
print("Tapez 'Q' pour quiter...")
chaine= input()
print("merci tchao.....!")
"""
|
santa= 8
print(santa)
nouritures = ['pomme de terre','riz au gras','ayimolou']
loisires = ['dormir','gaming sur android','la programation web en html']
favoris = loisires + nouritures
print(favoris)
n1 = "Kokou Amétépé joseph"
n2 ="HOMAWOO"
texte_blague = '''bonjour %s %s.
bonjour comment vas tu Mr luck'''
print(texte_blague %(n2,n1))
age = input('tapez svp votre age:')
age = int(age)
if age >18:
print("majeur")
else :
print("jeune")
annee = input("saisissez une année:")
annee = int (annee)
#je verifie que les restes son nuls prealablement conversion d variable et input
if annee % 400 ==0 or ( annee % 4 == 0 and annee % 100 !=0):
print("l'année que vous avez saisi est bisextile")
else:
print("elle n'est pas bisextile")
#la ligne qui suit celle-ci est unr fonction qui demande à l'utisateur de saisir un nombre
nombre = input("saisissez un nombre:")
nombre = int (nombre)
i = 0
while i < 10:
print(i + 1,"*",nombre,"=",( i + 1)* nombre)
i +=1
while 1:
lettre = input("Tapez 'Q' pour quitter : ")
if lettre == "Q":
print("Fin de la boucle")
break
|
# The following programe provides the user with an output that varies upon
# whether the program is run during the week or at the weekend
import datetime # "The datetime module supplies classes for manipulating dates and times." - docs.python.org - /module-datetime
x = datetime.datetime.now() # This Command is used to provide information on the datetime values attached to "today"
# datetime.weekday values range from 0-6, monday being 0, sunday being 6
if x.weekday() < 5: # if the output is within the range of values attached to the week days
print("Yes, unfortunately today is a weekday.") # Then print this statement
elif x.weekday() > 4: # If the output is within the range of values attached to the weekend
print("It is the weekend, yay!") # Then print this statement
#References
# https://docs.python.org/3/library/datetime.html#module-datetime
# https://kite.com/python/docs/datetime.datetime.weekday
|
# Print sum of all even numbers from 1 to 10 numbers ?
sum=0
for x in range(1,11):
if x%2==0:
sum=sum+x
print("Sum of even numbers:",sum) |
class Person(object):
def __init__(self):
self.__age = 0
# 装饰器方式的property, 把age方法当做属性使用, 表示当获取属性时会执行下面修饰的方法
@property
def age(self):
return self.__age
# 把age方法当做属性使用, 表示当设置属性时会执行下面修饰的方法
@age.setter
def age(self, new_age):
if new_age >= 150:
print("成精了")
else:
self.__age = new_age
# 创建person
p = Person()
print(p.age)
p.age = 100
print(p.age)
p.age = 1000 |
import threading
import time
# 唱歌任务
def sing():
# 扩展: 获取当前线程
# print("sing当前执行的线程为:", threading.current_thread())
for i in range(3):
print("sing %d" % i)
time.sleep(1)
# 跳舞任务
def dance():
# 扩展: 获取当前线程
# print("dance当前执行的线程为:", threading.current_thread())
for i in range(3):
print("dangcing %d" % i)
time.sleep(1)
if __name__ == '__main__':
# 扩展: 获取当前线程
# print("当前执行的线程为:", threading.current_thread())
# 创建唱歌的线程
# target: 线程执行的函数名
sing_thread = threading.Thread(target=sing)
# 创建跳舞的线程
dance_thread = threading.Thread(target=dance)
# 开启线程
sing_thread.start()
dance_thread.start() |
'''
进程
1.进程是系统分配资源的最小单位,一个进程一旦创立就会需要分配资源.比较耗资源.
2.各个进程之间无法通信,也无法共享任何资源,哪怕是全局变量的数据,进程间也无法共享
线程
1.线程是程序执行的最小单位,进程负责分配资源,线程负责执行程序
2.可以认为,进程是线程的容器,一个进程里至少需要有一个线程
3.线程本身不拥有系统资源,
4.属于同一个进程的多个线程之间可以共享资源.
'''
import threading
import time
# 唱歌任务
def sing(num):
# 扩展: 获取当前线程
# print("sing当前执行的线程为:", threading.current_thread())
for i in range(num):
print("sing %d" % i)
time.sleep(1)
# 跳舞任务
def dance(count):
# 扩展: 获取当前线程
# print("dance当前执行的线程为:", threading.current_thread())
for i in range(count):
print("dangcing %d" % i)
time.sleep(1)
if __name__ == '__main__':
# 扩展: 获取当前线程
# print("当前执行的线程为:", threading.current_thread())
# 创建唱歌的线程
# target: 线程执行的函数名
sing_thread = threading.Thread(target=sing, args = (5,))
# 创建跳舞的线程
dance_thread = threading.Thread(target=dance, kwargs={'count':4})
# 开启线程
sing_thread.start()
dance_thread.start() |
import copy # 使用深拷贝需要导入copy模块
# 可变类型有: 列表、字典、集合
'''
可变类型进行深拷贝会对该对象到最后一个可变类型的每一层对象就行拷贝, 对每一层拷贝的对象都会开辟新的内存空间进行存储。
'''
a1 = [1, 2]
b1 = copy.deepcopy(a1) # 使用copy模块里的deepcopy()函数就是深拷贝了
# 查看内存地址
print(id(a1))
print(id(b1))
print("-" * 10)
a2 = {"name": "张三"}
b2 = copy.deepcopy(a2)
# 查看内存地址
print(id(a2))
print(id(b2))
print("-" * 10)
a3 = {1, 2}
b3 = copy.deepcopy(a3)
# 查看内存地址
print(id(a3))
print(id(b3))
print("-" * 10)
a4 = [1, 2, ["李四", "王五"]]
b4 = copy.deepcopy(a4) # 使用copy模块里的deepcopy()函数就是深拷贝了
# 查看内存地址
print(id(a4))
print(id(b4))
# 查看内存地址
print(id(a4[2]))
print(id(b4[2]))
a4[2][0] = "王五"
# 因为列表的内存地址不同,所以数据不会收到影响
print(a4)
print(b4) |
# defining a function; giving it a name and telling what arguments we need.
def cheese_and_crackers (cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses!")
print(f"You have {boxes_of_crackers} boxes of crackers!")
print("Man that's enough for a party!")
print("Get a blanket.\n")
# printing a string.
print("We can just give the function numbers directly:")
# passin arguments to the function.
cheese_and_crackers(20, 30)
print("OR, we can use variables from our script:")
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
print("We can even do math inside too:")
cheese_and_crackers(10 + 20, 5 + 6)
print("And we can combine the two, variables and math:")
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
'''Study Drills
1. Ok.
2. Ok.
3. Ok. Didn't do 10, but I got it working with `input()` which was cool.
'''
|
# printing a string
print("Mary had a little lamb.")
# printing a string with formated string of snow
print("Its fleece was white as {}.".format('snow'))
# printing a string
print("And everywhere that Mary went.")
#printing a string "." and multiplying it by 10
print("." * 10) # what'd that do? it printed string '.' 10 times.
# assigning strings to variables in line 10 through 21
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
# watch that comma at the end. Try removing it to see what happens.
# concatenating strings. After end6 we are ending with an empty string.
print(end1 + end2 + end3 + end4 + end5 + end6, end=" ")
# concatenating strings and priting them in the same line as in line 25. If end=" " is removed then the new strings are printed on separate lines.
print(end7 + end8 + end9 + end10 + end11 + end12)
# Study drills
# 1. Ok
|
'''
def swoop(stuff, increment):
i = 0
numbers = []
while i < stuff:
print(f"At the top i is {i}")
numbers.append(i)
i = i + increment
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}")
print("The numbers: ")
for num in numbers:
print(num)
crazy = 15
increment = 2
super = swoop(crazy, increment)
'''
"""
Study Drills
1. Ok
2. Ok
3. Ok
4. Ok
5.
"""
def swoop(stuff, increment):
i = []
numbers = []
for i in range(0,7):
print(f"At the top i is {i}")
numbers.append(i)
print("The numbers: ")
for x in numbers:
print(x)
stuff = 6
increment = 2
swoop(stuff, increment) |
"""
This defines a class for a tic-tac-toe game.
"""
from itertools import cycle
from random import choice
class tic_tac_toe:
"""A game of tic-tac-toe between two players, human or computer."""
def __init__(self, n_humans = 2):
self.board = [['-' for i in range(3)] for i in range(3)]
self.n_humans = n_humans
self.symbols = ['X', 'O']
self.symbols_cycle = cycle([self.symbols[0], self.symbols[1]])
self.current_symbol = next(self.symbols_cycle)
self.player_type_dict = {2: ['human', 'human'], 1: ['human', 'computer'], 0: ['computer', 'computer']}
self.player_types = cycle(self.player_type_dict[n_humans])
self.current_player_type = next(self.player_types)
self.move_lookup = move_lookup = {1: (0,0), 2: (0,1), 3: (0,2), 4: (1,0), 5: (1,1), 6: (1,2), 7: (2,0), 8: (2,1), 9: (2,2)}
self.winning_move_sets = [{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {1, 4, 7}, {2, 5, 8}, {3, 6, 9}, {1, 5, 9}, {3, 5, 7}]
self.player_moves = {self.symbols[0]: set(), self.symbols[1]: set()}
self.has_winner = False
def print_board_definition(self):
"""Prints what spaces correspond to what move on the board."""
for i in range(3):
row = []
for j in range(3):
row.append(str(3*i + j+1))
print('|'.join(row))
print('')
def print_board(self):
"""Prints the current state of the board."""
for row in self.board:
print('|'.join(row))
print('')
def winning_player(self, symbol):
"""Determine if someone has won."""
if symbol not in self.symbols:
raise Exception('Invalid player symbol provided.')
return any([len(winning_move_set.intersection(self.player_moves[symbol])) == 3 for winning_move_set in self.winning_move_sets])
def board_full(self):
"""Returns a boolean for whether or not the board is full."""
full = True
for row in self.board:
if '-' in row:
full = False
break
return full
def validate_move(self, move):
"""Return boolean for whether provided move is valid."""
return move in range(1, 10)
def use_move(self, move, symbol):
"""Add the move to the set of moves the player has used."""
if symbol not in self.symbols:
raise Exception('Invalid player symbol provided.')
self.player_moves[symbol] = self.player_moves[symbol].union([move])
def add_token(self, move, symbol):
"""Accepts a move and an arbitrary symbol."""
if not self.validate_move(move):
raise Exception('Invalid move provided.')
if self.board_full():
raise Exception('There are no remaining moves.')
elif self.board[self.move_lookup[move][0]][self.move_lookup[move][1]] != '-':
raise Exception('That move is already taken.')
else:
self.use_move(move, symbol)
self.board[self.move_lookup[move][0]][self.move_lookup[move][1]] = symbol
def computer_move(self, symbol):
"""Make a random move for the computer."""
if self.board_full():
raise Exception('There are no remaining moves.')
else:
used_moves = [move for moves in self.player_moves.values() for move in moves]
available_moves = [move for move in range(1, 10) if move not in used_moves]
move = choice(available_moves)
self.add_token(move, symbol)
def human_move(self, move, symbol):
"""Allow a human player to make a move."""
self.add_token(move, symbol)
def alternate_player(self):
"""Change whose turn it is."""
self.current_symbol = next(self.symbols_cycle)
self.current_player_type = next(self.player_types)
def play_game(self):
"""Play a game!"""
print('Welcome to tic-tac-toe! Below is your board definition. Enter the number corresponding to the spot you want when asked.\n')
self.print_board_definition()
while not self.board_full():
print('Player %s\'s turn.' % self.current_symbol)
if self.current_player_type == 'human':
move = int(input('Please enter your move: '))
self.human_move(move, self.current_symbol)
else:
self.computer_move(self.current_symbol)
self.print_board()
if self.winning_player(self.current_symbol):
self.has_winner = True
print('Player %s wins!' % self.current_symbol)
break
self.alternate_player()
if not self.has_winner:
print('It\'s a tie!')
def play_ttt_vs_computer():
"""Automatically play human vs. computer when this script is run."""
ttt = tic_tac_toe(n_humans=1)
ttt.play_game()
if __name__ == '__main__':
play_ttt_vs_computer()
|
def search(nums,target):
for i in range(len(nums)):
if nums[i]==target:
return (i)
if target not in nums:
return -1
nums = [10,20,30,40]
target = 3
k = search(nums,target)
print(k)
|
def search(nums,target):
if target not in nums:
return -1
l = 0
r = len(nums)-1
while l<=r:
mid = (l+r)//2
if nums[mid]<target:
l = mid+1
elif nums[mid]>target:
r = mid-1
else:
return mid
nums = [10,20,30,40]
target = 40
k = search(nums,target)
print(k)
|
#this prepares to turn the words from arrays into strings
def listToString(s):
str1 = ""
for ele in s:
str1 += ele
return str1
message = (input("enter your message (3 words max): "))
#this splits the sentence into individual words
s = message.split(" ")
start = s [0:1]
middle = s [1:2]
end = s [2:3]
#this turns the words from arrays to strings
start = listToString(start)
middle = listToString(middle)
end = listToString(end)
fword = len(start)
sword = len(middle)
tword = len(end)
#this seperates each word into 2 parts: the first letter and the rest
sstart = start [0:1]
estart = start [1:fword]
smiddle = middle [0:1]
emiddle = middle [1:sword]
send = end [0:1]
eend = end [1:tword]
#this transforms the words into pig latin
if sstart == "a":
first = estart + "way"
elif sstart == "e":
first = estart + "way"
elif sstart == "i":
first = estart + "way"
elif sstart == "o":
first = estart + "way"
elif sstart == "u":
first = estart + "way"
else:
first = estart + sstart + ("ay")
if smiddle == "a":
second = emiddle + ("way")
elif smiddle == "e":
second = emiddle + ("way")
elif smiddle == "i":
second = emiddle + ("way")
elif smiddle == "o":
second = emiddle + ("way")
elif smiddle == "u":
second = emiddle + ("way")
else:
second = emiddle + smiddle + ("ay")
if send == "a":
third = eend + ("way")
elif send == "e":
third = eend + ("way")
elif send == "i":
third = eend + ("way")
elif send == "o":
third = eend + ("way")
elif send == "u":
third = eend + ("way")
else:
third = eend + send + ("ay")
#this puts the transformed letters together and make them lower case
newsentence = first + (" ") + second + (" ") + third
newsentence = newsentence.lower()
print (newsentence)
|
def removeDuplicates(nums):
if len(nums) <= 2: return
i = 0
j = 2
while True:
if len(nums) <= j: break
if nums[i] == nums[j]: nums.pop(j)
else:
i += 1
j += 1
if __name__ == "__main__":
nums = [1,1,1,2,2,3]
removeDuplicates(nums)
print(nums)
|
def lengOfLastWord(str):
LastWord = str.split(" ")
temp = []
for i in LastWord:
if len(i) > 0:
temp.append(len(i))
return int(temp[-1])
if __name__ == "__main__":
strings = "hello world "
print(lengOfLastWord(strings))
|
def PlusOne(digits):
carry = 0
result = []
temp = 1
for i in reversed(digits):
value = (i + carry + temp) % 10
carry = (i + carry + temp) // 10
result.insert(0, value)
temp = 0
if carry == 1: result.insert(0, carry)
return result
if __name__ == "__main__":
digits = [9, 0, 9]
print(PlusOne(digits))
|
# 在数组中找x + y = target,输出x, y的下标
# 遍历数组通过字典记录x, 同时查询hash值查找字典中有无target - x
def twoSum(nums, target):
hashtable = dict()
for i, num in enumerate(nums):
if target - num in hashtable:
return [hashtable[target - num], i]
hashtable[num] = i
return []
if __name__ == '__main__':
nums = [10, 1, 2, 3, 5, 6, 7, 11, 15]
# target = 16
# print(twoSum(nums, target))
newNums = nums.insert(0, -1000)
print(nums, "\n", newNums)
|
import numpy as np
def detect_growth_events(areas, threshold=-350):
"""Given a list of bacterial growth areas, detect growth events.
A growth event is defined as when the bacterial area changed by a certain
threshold value.
:param areas: list of areas
:type areas: list
:param threshold: the bacterial area change threshold used to detect
growth events, defaults to -350
:type threshold: int
:return: list containing growth events
:rtype: list
"""
event_id = 0
events = [event_id]
for ele in np.diff(areas) < threshold:
if ele:
event_id += 1
events.append(event_id)
return events
def normalize_times(times, events):
"""Given a list of times and event ids, normalize the times (i.e. calculate
the time since the start of each event).
:param times: list of times
:type times: list
:param events: list of event ids
:type events: list
:return: list of normalized times
:rtype: list
"""
normalized_times = []
for event in sorted(np.unique(events)):
event_times = times[events == event]
normalized_times.extend(list(event_times - min(event_times)))
return normalized_times
|
# Faça um programa que tenha uma função chamada área(),
# que receba as dimensões de um terreno retangular (largura e comprimento)
# e mostre a área do terreno:
def area(comprimento,largura):
r=comprimento*largura
print(f'A area é de {r:.2f}')
c=float(input('Digite o comprimento:\n'))
l=float(input('Digite a largura:\n'))
area(c,l)
|
salario_inicial=float(input('Informe o seu salario atual \nR$'))
aumento = 0
percentual = 0
reajuste1 = 20
reajuste2 = 15
reajuste3 = 10
reajuste4 = 5
if salario_inicial <= 280:
aumento = salario_inicial*(reajuste1/100)
percentual = reajuste1
print(f'Salario inicial R${salario_inicial}')
print(f'{percentual}%')
print(f'R${salario_inicial-aumento}')
print(f'R${salario_inicial+aumento}')
elif salario_inicial < 700:
aumento = salario_inicial*(reajuste2/100)
percentual = reajuste2
print(f'Salario inicial R${salario_inicial}')
print(f'{percentual}%')
print(f'R${salario_inicial-aumento}')
print(f'R${salario_inicial+aumento}')
elif salario_inicial < 1500:
aumento = salario_inicial*(reajuste3/100)
percentual = reajuste3
print(f'Salario inicial R${salario_inicial}')
print(f'{percentual}%')
print(f'R${salario_inicial-aumento}')
print(f'R${salario_inicial+aumento}')
elif salario_inicial > 1500:
aumento = salario_inicial*(reajuste4/100)
percentual = reajuste4
print(f'Salario inicial R${salario_inicial}')
print(f'{percentual}%')
print(f'R${salario_inicial-aumento}')
print(f'R${salario_inicial+aumento}')
|
#Escreva um programa que pede a senha uma senha ao usuário, e
# só sai do loop quando digitarem
#corretamente a senha. A senha é “Blue123”
#2b - Exiba quantas vezes o usuário errou a digitação.
#senha = 'Blue123'
#usuario = input('Digite a senha:\n')
#while usuario != senha:
# usuario = input('Digite a senha:\n')
# if usuario == senha:
# print('Senha correta.')'
senha = 'Blue123'
usuario = input('Digite a sua senha:\n')
erros = 0
while senha != usuario:
usuario = input('Senha incorreta!\nDigite novamente: ')
if usuario==senha:
print('Acesso liberado!')
elif erros == 5:
print('Acesso Bloqueado!')
break
erros += 1
print(f'Você errou {erros} vezes')
|
#Crie um dicionário em que suas chaves serão os números 1, 4, 5, 6, 7, e 9 (que podem ser armazenados em uma lista) e seus valores correspondentes aos quadrados desses números.
lista = [1,4,5,6,7,9]
quadrados = dict()
for i in lista:
quadrados [i] = i**2
print(quadrados)
# Crie um dicionário em que suas chaves correspondem a números inteiros entre [1, 10] e cada valor associado é o número ao quadrado.
dicionario = {} #outra forma de criar um dicionario
numero = int(input('Digite quantos numeros voce quer.'))
for i in range(1,numero+1):
dicionario[i] = i**2
print(dicionario)
|
# 9.Faça um Programa que leia um vetor A com 10 números inteiros, calcule e mostre a soma dos quadrados dos
# elementos do vetor.
lista=[]
vezes =0
while vezes != 10:
num = int(input('Digite um valor:\n'))
num2 = num*num
lista.append(num2)
vezes +=1
resultado=sum(lista)
print(resultado) |
#Reading Files --ex15.py
from sys import argv
#how to unpack argv
script, filename = argv
#open the file
txt = open(filename)
#display the file name and read it
print "Here is your file %r:" % filename
print txt.read()
#Be courteous, clean up after yourself!
txt.close()
#Ask for file name again with a prompt
print "Type the filename again:"
file_again = raw_input("> ")
#open the file again
txt_again = open(file_again)
#read and display contents of the file again.
print txt_again.read()
txt_again.close()
|
# Doing things to Lists - ex38.py
ten_things = "Apples Oranges Crows Telephone Light Sugar"
#print "The list 'ten_things:", ten_things # unnecessary - this list is parsed and printed on lines 7,8
# print "Number of items in list 'ten_things", len(ten_things) # This will count every single character including spaces
print "Wait there are not 10 things in that list. Let's fix that."
stuff = ten_things.split(' ')
print "Printing the list 'stuff':", stuff # debug only
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) <> 10:
next_one = more_stuff.pop()
print "Adding: ", next_one
stuff.append(next_one)
print "There are %d items now." % len(stuff)
print "There we go: ", stuff
print "Let's do some things with stuff."
print "stuff[1]:\t", stuff[1]
print "stuff[-1]:\t", stuff[-1] # Whoa! fancy
print "stuff.pop():\t ", stuff.pop()
print "' '.join(stuff):\t", ' '.join(stuff) # What? cool!
print "'~'.join(stuff[3:6]):\t", '~'.join(stuff[3:6]) # super stellar!
|
from random import randint
import sys
sys.path.append(".")
from Card import *
class Deck:
def __init__(self, empty = False):
self.contents = []
if not empty:
self.construct_deck().shuffle_deck()
def construct_deck(self):
suits = ["Diamonds", "Hearts", "Spades", "Clubs"]
for suit in suits:
for value in range(1, 14):
rank = ""
if value == 1:
rank = "Ace"
elif value > 1 and value < 11:
rank = str(value)
elif value == 11:
rank = "Jack"
elif value == 12:
rank = "Queen"
else:
rank = "King"
self.contents.append(Card(suit, rank, value))
return self
def printMe(self):
for card in self.contents:
print(card)
return self
def shuffle_deck(self):
for i in range(len(self.contents)):
rand = randint(0, 51)
self.contents[i], self.contents[rand] = self.contents[rand], self.contents[i]
return self
def draw_card(self, amount = 1):
if len(self.contents) <= 0:
return None
return self.contents.pop()
def count_cards(self):
return len(self.contents)
def add_card(self, card):
self.contents.append(card)
return self
game = True
main_deck = Deck()
main_deck.shuffle_deck().shuffle_deck()
while(game):
currentCard = main_deck.draw_card()
print(f"Your card is {currentCard}")
nextCard = main_deck.draw_card()
user_input = input("next card higher or lower(or same)?: ")
if user_input == "quit":
game = False
elif user_input == "higher":
if nextCard.value > currentCard.value:
print(nextCard)
print("you win!")
else:
print(nextCard)
print("you lose!")
game = False
elif user_input == "lower":
if nextCard.value < currentCard.value:
print(nextCard)
print("you win!")
else:
print(nextCard)
print("you lose!")
game = False
elif user_input == "same":
if nextCard.value == currentCard.value:
print(nextCard)
print("damn how'd you guess that!?")
else:
print(nextCard)
print("you lose!")
game = False
else:
print(f"your command was: {user_input}") |
# Facade pattern hides the complexities of the system and provides an interface
# to the client using which the client can access the system. This pattern involves a single class
# which provides simplified methods required by client and delegates calls to methods of existing system classes
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def draw(self):
pass
class Rectangle(Shape):
def draw(self):
print("Rectangle:draw()")
class Square(Shape):
def draw(self):
print("Square:draw()")
class ShapeMaker:
def __init__(self):
self._shapeMap = {
'rectangle': Rectangle(),
'square': Square()
}
def drawRectangle(self):
self._shapeMap['rectangle'].draw()
def drawSquare(self):
self._shapeMap['square'].draw()
# Client Code
shapeMaker = ShapeMaker()
shapeMaker.drawRectangle()
shapeMaker.drawSquare()
|
# Adapter pattern works as a bridge between two incompatible interfaces.
# This pattern involves a single class which is responsible to join functionalities
# of independent or incompatible interfaces.
#
from abc import ABC, abstractmethod
# Target interface
class Target(ABC):
def __init__(self):
self._adaptee = Adaptee()
@abstractmethod
def request(self):
pass
class Adapter(Target):
def request(self):
self._adaptee.adaptee_request()
class Adaptee:
def adaptee_request(self):
print("Adaptee function called.")
## Client code
print("Adapter 1")
adapter = Adapter()
adapter.request()
class MediaPlayer(ABC):
@abstractmethod
def play(self, audioType, fileName ):
pass
class AdvancedMediaPlayer(ABC):
@abstractmethod
def playVlc(self, filename):
pass
@abstractmethod
def playMp4(self, filename):
pass
class VlcPlayer(AdvancedMediaPlayer):
def playVlc(self, filename):
print("Playing vlc file:", filename)
def playMp4(self, filename):
print("not supported")
class Mp4Player(AdvancedMediaPlayer):
def playVlc(self, filename):
print("not supported")
def playMp4(self, filename):
print("Playing mp4 file: ", filename)
class MediaAdapter(MediaPlayer):
def __init__(self, audiotype):
if audiotype == 'vlc':
self._advancedMediaPlayer = VlcPlayer()
elif audiotype == 'mp4':
self._advancedMediaPlayer = Mp4Player()
def play(self, audioType, fileName):
if audioType == 'vlc':
self._advancedMediaPlayer.playVlc(fileName)
elif(audioType == 'mp4'):
self._advancedMediaPlayer.playMp4(fileName)
class AudioPlayer(MediaPlayer):
def __init__(self):
self._mediaPlayerVlc = MediaAdapter('vlc')
self._mediaPlayerMp4 = MediaAdapter('mp4')
def play(self, audioType, fileName):
if audioType == 'mp3':
print("internal MP3 feature fileName:", fileName)
elif audioType == 'vlc':
self._mediaPlayerVlc.play(audioType, fileName)
elif audioType == 'mp4':
self._mediaPlayerMp4.play(audioType, fileName)
else:
print("not supported: " + audioType)
#Cleint Code
print("Adapter 2")
adapter = AudioPlayer()
adapter.play("mp3", "some mp3")
adapter.play("vlc", "some mp4") |
"""Realizar una funcion que devuelva un valor booleano indicando si un numero que se le pasa por argumento es o no un
numero perfecto. Un numero perfecto es aquel que es igual a la suma de sus divisores incluyendo el uno y excluyendo al un
numero mismo.
Utilizando esta funcion realizar un programa que escriba a lista de los numeros "perfectos" hasta uno dado, introducido
como dato del programa"""
import argparse
import pprint
# funcion que devuelve los divisores de un numero que se le pasa como parametro
def divisores(n):
lista_divisores = [e for e in range(1, n) if n % e == 0]
return lista_divisores
# funcion que utilizando la funcion "divisores", determina si un numero es perfecto o no
def esPerfecto(n):
suma_divisores = 0
for e in divisores(n):
suma_divisores += e
return suma_divisores == n
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="introducir numero")
parser.add_argument(dest="target", help="target number", required=True, type=int)
params = parser.parse_args()
lista_perfectos = [e for e in range(params.target) if esPerfecto(e)]
pprint.pprint(lista_perfectos)
|
def buildMemo(): # Memo matrix builder
m = [-1] * (items + 1)
for i in range(items):
m[i] = [-1] * (capacity + 1)
return m
def backpack(i, cc):
if memo[i][cc] != -1:
return memo[i][cc] # Return if this operation has already been processed
if i == (items - 1) or cc == 0: # All items have already been visited or backpack is full
memo[i][cc] = 0
elif weight[i] > cc: # Item does not fit in backpack
memo[i][cc] = backpack(i + 1, cc)
else:
memo[i][cc] = max(price[i] + backpack(i + 1, cc - weight[i]), backpack(i + 1, cc))
return memo[i][cc]
items, capacity = [int(x) for x in input().split()]
price = [int(x) for x in input().split()] # Item price
weight = [int(x) for x in input().split()] # Item weight
memo = buildMemo() # Memo matrix for DP
print(backpack(0, capacity))
|
# https://leetcode.com/problems/game-of-life/
class Solution(object):
def getOriValue(self, board, i, j):
if i < 0 or j < 0 or i >= self.row_num or j >= self.col_num:
return None
if self.change_status[i][j]:
ori_value = 1 - board[i][j]
else:
ori_value = board[i][j]
return ori_value
def computeNextState(self, board, i, j):
current_value = self.getOriValue(board, i, j)
count_lives = 0
for sur_x, sur_y in ((-1, -1), (-1, 0), (-1, 1),
( 0, -1), ( 0, 1),
( 1, -1), ( 1, 0), ( 1, 1)):
surround_value = self.getOriValue(board, i + sur_x, j + sur_y)
if surround_value is not None and surround_value == 1:
count_lives += 1
new_value, is_changed = current_value, False
if current_value == 1:
if count_lives < 2:
new_value, is_changed = 0, True
if count_lives > 3:
new_value, is_changed = 0, True
else:
if count_lives == 3:
new_value, is_changed = 1, True
return new_value, is_changed
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
self.row_num = len(board)
self.col_num = len(board[0])
# ATTENTION! In Python, initialize 2D list should be careful
self.change_status = [[False for i in range(self.col_num)] for j in range(self.row_num)]
for i in range(self.row_num):
for j in range(self.col_num):
new_value, is_changed = self.computeNextState(board, i, j)
board[i][j] = new_value
self.change_status[i][j] = is_changed
# test
board = [[0, 1, 1],
[1, 0, 1],
[1, 0, 1]]
s = Solution()
s.gameOfLife(board)
print(board) |
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
use_dp = True
if use_dp:
return self.isMatch_v2(s, p, 0, 0)
# if len(p) == 0:
# return len(s) == 0
#
# first_match = len(s) > 0 and p[0] in [s[0], "."]
# if len(p) >= 2 and p[1] == "*":
# # 1. We keep the first match and continue to the next char in s, using current p
# # Note that, if first_match is False, python will short cut and directly assign False to the following
# # match_result_ignore_first_match = first_match and self.isMatch(s[1:], p)
#
# # 2. Or we ignore the wildcard regex in p, and we start matching the same string using next regex in p
# # match_result_keep_first_match = self.isMatch(s, p[2:])
# return (first_match and self.isMatch(s[1:], p)) or self.isMatch(s, p[2:])
# else:
# return first_match and self.isMatch(s[1:], p[1:])
def isMatch_v2(self, s, p, i, j, memo={}):
# check if s[i:] can be matched with p[j:]
i_j_pair = (i, j)
if i_j_pair not in memo:
if j == len(p):
match_result = i == len(s)
else:
first_match = i < len(s) and p[j] in [s[i], "."]
if j < len(p) - 1 and p[j + 1] == "*":
match_result = (first_match and self.isMatch_v2(s, p, i + 1, j, memo)) or self.isMatch_v2(s, p, i, j + 2, memo)
else:
match_result = first_match and self.isMatch_v2(s, p, i + 1, j + 1, memo)
memo[i_j_pair] = match_result
return memo[i_j_pair]
s1 = Solution()
s = "ab"
p = ".*c"
print(s1.isMatch(s, p))
|
# https://leetcode.com/problems/maximal-rectangle/
class Solution(object):
def maximalRectangle(self, matrix):
"""
:param matrix: List[List[str]]
:return: int
"""
if len(matrix) == 0: return 0
cur_height_list = []
max_area = 0
for each_row in matrix:
if len(cur_height_list) == 0:
# For the first row
cur_height_list = each_row
else:
for i in range(len(each_row)):
if each_row[i] == 1:
cur_height_list[i] += 1 # It can be just 1, or the height with above consequent 1s
else:
cur_height_list[i] = 0 # reset to 0
max_area = max(max_area, self.largestRectangleArea(cur_height_list))
return max_area
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
if len(heights) == 0:
return 0
elif len(heights) == 1:
return heights[0]
heights.append(0) # Add 0 as the end item to ensure we end in Line 19
visit_stack = []
sum = 0
i = 0
while i < len(heights):
if len(visit_stack) == 0 or heights[visit_stack[-1]] < heights[i]:
visit_stack.append(i)
i += 1
else:
j = visit_stack.pop() # The height
if len(visit_stack) > 0:
length = i - visit_stack[-1] - 1
else:
length = i
sum = max(sum, heights[j] * length)
return sum |
#!/usr/bin/env python
# https://leetcode.com/problems/reorder-list/
# Definition for singly-linked list.
def print_list(head):
cur = head
list_str = ""
while cur is not None:
list_str += str(cur.val) + "->"
cur = cur.next
print(list_str[:-2])
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
len = 0
cur = head
while cur is not None:
cur = cur.next
len += 1
if len < 3: return
second_half_ptr = head
tmp_len = 1
pass_mid_len = len / 2 + 2
# if len is odd, like 5, last should be len / 2 + 1 = 3, second_half should be len / 2 + 2 = 4
# if len is even, like 6, last should be len / 2 + 1 = 4, second_half should be len / 2 + 2 = 5
while tmp_len < pass_mid_len:
last = second_half_ptr
second_half_ptr = second_half_ptr.next
tmp_len += 1
last.next = None
# print_list(second_half_ptr)
# Reverse
last = None
while second_half_ptr is not None:
tmp = second_half_ptr.next
second_half_ptr.next = last
last = second_half_ptr
second_half_ptr = tmp
second_half_ptr = last
# print_list(second_half_ptr)
first_half_ptr = head
while second_half_ptr is not None:
first_half_last = first_half_ptr
first_half_ptr = first_half_last.next
second_half_last = second_half_ptr
second_half_ptr = second_half_last.next
first_half_last.next = second_half_last
second_half_last.next = first_half_ptr
if __name__ == "__main__":
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
Solution().reorderList(head)
print_list(head)
|
import numpy
from math import *
boundaries_x = list(map(float, input("Enter boundaries x (using space): ").split()))
step_x = float(input("Enter step x: "))
boundaries_y = list(map(float, input("Enter boundaries y (using space): ").split()))
step_y = float(input("Enter step y: "))
function = eval("lambda x, y: " + input("Enter function in python format (using x, y as args): "))
filename = input("Enter filename: ")
with open("../data/" + filename, "w") as f:
print((boundaries_x[1] - boundaries_x[0]) % step_x == 0)
f.write(f"{int((boundaries_x[1] - boundaries_x[0]) % step_x != 0) + int((boundaries_x[1] - boundaries_x[0] + step_x) / step_x)} ")
f.write(f"{int((boundaries_y[1] - boundaries_y[0]) % step_y != 0) + int((boundaries_y[1] - boundaries_y[0] + step_y) / step_y)}\n")
for x in numpy.arange(boundaries_x[0], step_x + boundaries_x[1], step_x):
for y in numpy.arange(boundaries_y[0], step_y + boundaries_y[1], step_y):
f.write("{:.2f} {:.2f} {:.3f} ".format(x, y, function(x, y)))
f.write("\n")
print("Done! Check file in \"data\" folder!")
|
import tkinter as tk
from tkinter import *
import os
#attach things to this to effect the app as a whole
root = tk.Tk()
root.geometry('400x200')
root.configure(background="teal")
def button_command():
eg = e.get()
fg = f.get()
gg = g.get()
hg = eg.replace(fg,gg)
e.delete(0, END)
f.delete(0, END)
g.delete(0, END)
root.clipboard_clear()
root.clipboard_append(hg)
print(hg)
e.insert(0, "Result Is")
f.insert(0, "In Your")
g.insert(0, "Clipboard")
return None
#title
root.title("DROmie Tools 1")
Label(root, text="List Demessifier", bg="#add8e6", font="none 35 bold").pack()
#text box
e = Entry(root)
e.place(width=150,height=150)
e.insert(END,"Enter List Here")
e.pack()
#text box2
f = Entry(root, width = 20)
f.insert(END,"What Do U Want Replaced?")
f.pack()
#text box2
g = Entry(root, width = 20)
g.insert(END,"Replace with...")
g.pack()
#button
b = Button(root, text = "Submit", command = button_command,)
b.pack()
root.mainloop()
|
#A complete classification of the English Language, by BCPI
#Yes it's inefficient but it works.
#Copyright me 2/8/2020 AD
opening = '''
English words list
A python code that classifies all words by letter, length, and letter and length.
To use:
You need to have the python library nltk installed
To do this in your terminal/command prompt type
"pip install nltk"
then in the python shell enter "import nltk"
Once you've imported nltk type "nltk.download()" and select the words package under corpus or alternatively install all.
+ The are 698 lists to choose from. You can search for words that are a certain length, words that start with a certain letter, or words that start with a certain letter and are a certain length long.
+ If you want a list of all words that start with 'A', you'd type "letterA" into the python shell after running the code. This works for "letterA", "letterB", "letterC", ETC
+ If you want a list of all words that are three letters long, you'd type "letter3" into the python shell after running the code. This works for "letter1 - letter24"
+ If you want a list of all words that are three letters long and start with 'A', you'd type "letterA3" into the python shell after running the code. This works for all 26 letters and up to 24 letter words.
+ If you want a list of all words type "word_list" into the python shell after running the code.
+ If you want a list of all words that contains the letter 'A' you can enter "conatins_letterA" this works for all 26 letters
+ So "letterT" gives all words that start with 'T', "letter5" gives all five letter words, and "letterT5" gives all five letter words that start with 'T'
+ If you want the length of a list do "len(list-name)" for example "len(letterT5)" out puts the length of "letterT5"(695)
'''
from nltk.corpus import words
word_list = words.words()
letter1 = []
letter2 = []
letter3 = []
letter4 = []
letter5 = []
letter6 = []
letter7 = []
letter8 = []
letter9 = []
letter10 = []
letter11 = []
letter12 = []
letter13 = []
letter14 = []
letter15 = []
letter16 = []
letter17 = []
letter18 = []
letter19 = []
letter20 = []
letter21 = []
letter22 = []
letter23 = []
letter24 = []
# ---------------
letterA = []
letterB = []
letterC = []
letterD = []
letterE = []
letterF = []
letterG = []
letterH = []
letterI = []
letterJ = []
letterK = []
letterL = []
letterM = []
letterN = []
letterO = []
letterP = []
letterQ = []
letterR = []
letterS = []
letterT = []
letterU = []
letterV = []
letterW = []
letterX = []
letterY = []
letterZ = []
# ----------------
contains_letterA = []
contains_letterB = []
contains_letterC = []
contains_letterD = []
contains_letterE = []
contains_letterF = []
contains_letterG = []
contains_letterH = []
contains_letterI = []
contains_letterJ = []
contains_letterK = []
contains_letterL = []
contains_letterM = []
contains_letterN = []
contains_letterO = []
contains_letterP = []
contains_letterQ = []
contains_letterR = []
contains_letterS = []
contains_letterT = []
contains_letterU = []
contains_letterV = []
contains_letterW = []
contains_letterX = []
contains_letterY = []
contains_letterZ = []
#----------------------------
# a
letterA1 = []
letterA2 = []
letterA3 = []
letterA4 = []
letterA5 = []
letterA6 = []
letterA7 = []
letterA8 = []
letterA9 = []
letterA10 = []
letterA11 = []
letterA12 = []
letterA13 = []
letterA14 = []
letterA15 = []
letterA16 = []
letterA17 = []
letterA18 = []
letterA19 = []
letterA20 = []
letterA21 = []
letterA22 = []
letterA23 = []
letterA24 = []
# b
letterB1 = []
letterB2 = []
letterB3 = []
letterB4 = []
letterB5 = []
letterB6 = []
letterB7 = []
letterB8 = []
letterB9 = []
letterB10 = []
letterB11 = []
letterB12 = []
letterB13 = []
letterB14 = []
letterB15 = []
letterB16 = []
letterB17 = []
letterB18 = []
letterB19 = []
letterB20 = []
letterB21 = []
letterB22 = []
letterB23 = []
letterB24 = []
# c
letterC1 = []
letterC2 = []
letterC3 = []
letterC4 = []
letterC5 = []
letterC6 = []
letterC7 = []
letterC8 = []
letterC9 = []
letterC10 = []
letterC11 = []
letterC12 = []
letterC13 = []
letterC14 = []
letterC15 = []
letterC16 = []
letterC17 = []
letterC18 = []
letterC19 = []
letterC20 = []
letterC21 = []
letterC22 = []
letterC23 = []
letterC24 = []
# d
letterD1 = []
letterD2 = []
letterD3 = []
letterD4 = []
letterD5 = []
letterD6 = []
letterD7 = []
letterD8 = []
letterD9 = []
letterD10 = []
letterD11 = []
letterD12 = []
letterD13 = []
letterD14 = []
letterD15 = []
letterD16 = []
letterD17 = []
letterD18 = []
letterD19 = []
letterD20 = []
letterD21 = []
letterD22 = []
letterD23 = []
letterD24 = []
# e
letterE1 = []
letterE2 = []
letterE3 = []
letterE4 = []
letterE5 = []
letterE6 = []
letterE7 = []
letterE8 = []
letterE9 = []
letterE10 = []
letterE11 = []
letterE12 = []
letterE13 = []
letterE14 = []
letterE15 = []
letterE16 = []
letterE17 = []
letterE18 = []
letterE19 = []
letterE20 = []
letterE21 = []
letterE22 = []
letterE23 = []
letterE24 = []
# f
letterF1 = []
letterF2 = []
letterF3 = []
letterF4 = []
letterF5 = []
letterF6 = []
letterF7 = []
letterF8 = []
letterF9 = []
letterF10 = []
letterF11 = []
letterF12 = []
letterF13 = []
letterF14 = []
letterF15 = []
letterF16 = []
letterF17 = []
letterF18 = []
letterF19 = []
letterF20 = []
letterF21 = []
letterF22 = []
letterF23 = []
letterF24 = []
# g
letterG1 = []
letterG2 = []
letterG3 = []
letterG4 = []
letterG5 = []
letterG6 = []
letterG7 = []
letterG8 = []
letterG9 = []
letterG10 = []
letterG11 = []
letterG12 = []
letterG13 = []
letterG14 = []
letterG15 = []
letterG16 = []
letterG17 = []
letterG18 = []
letterG19 = []
letterG20 = []
letterG21 = []
letterG22 = []
letterG23 = []
letterG24 = []
# h
letterH1 = []
letterH2 = []
letterH3 = []
letterH4 = []
letterH5 = []
letterH6 = []
letterH7 = []
letterH8 = []
letterH9 = []
letterH10 = []
letterH11 = []
letterH12 = []
letterH13 = []
letterH14 = []
letterH15 = []
letterH16 = []
letterH17 = []
letterH18 = []
letterH19 = []
letterH20 = []
letterH21 = []
letterH22 = []
letterH23 = []
letterH24 = []
# i
letterI1 = []
letterI2 = []
letterI3 = []
letterI4 = []
letterI5 = []
letterI6 = []
letterI7 = []
letterI8 = []
letterI9 = []
letterI10 = []
letterI11 = []
letterI12 = []
letterI13 = []
letterI14 = []
letterI15 = []
letterI16 = []
letterI17 = []
letterI18 = []
letterI19 = []
letterI20 = []
letterI21 = []
letterI22 = []
letterI23 = []
letterI24 = []
# j
letterJ1 = []
letterJ2 = []
letterJ3 = []
letterJ4 = []
letterJ5 = []
letterJ6 = []
letterJ7 = []
letterJ8 = []
letterJ9 = []
letterJ10 = []
letterJ11 = []
letterJ12 = []
letterJ13 = []
letterJ14 = []
letterJ15 = []
letterJ16 = []
letterJ17 = []
letterJ18 = []
letterJ19 = []
letterJ20 = []
letterJ21 = []
letterJ22 = []
letterJ23 = []
letterJ24 = []
# k
letterK1 = []
letterK2 = []
letterK3 = []
letterK4 = []
letterK5 = []
letterK6 = []
letterK7 = []
letterK8 = []
letterK9 = []
letterK10 = []
letterK11 = []
letterK12 = []
letterK13 = []
letterK14 = []
letterK15 = []
letterK16 = []
letterK17 = []
letterK18 = []
letterK19 = []
letterK20 = []
letterK21 = []
letterK22 = []
letterK23 = []
letterK24 = []
# l
letterL1 = []
letterL2 = []
letterL3 = []
letterL4 = []
letterL5 = []
letterL6 = []
letterL7 = []
letterL8 = []
letterL9 = []
letterL10 = []
letterL11 = []
letterL12 = []
letterL13 = []
letterL14 = []
letterL15 = []
letterL16 = []
letterL17 = []
letterL18 = []
letterL19 = []
letterL20 = []
letterL21 = []
letterL22 = []
letterL23 = []
letterL24 = []
# m
letterM1 = []
letterM2 = []
letterM3 = []
letterM4 = []
letterM5 = []
letterM6 = []
letterM7 = []
letterM8 = []
letterM9 = []
letterM10 = []
letterM11 = []
letterM12 = []
letterM13 = []
letterM14 = []
letterM15 = []
letterM16 = []
letterM17 = []
letterM18 = []
letterM19 = []
letterM20 = []
letterM21 = []
letterM22 = []
letterM23 = []
letterM24 = []
# n
letterN1 = []
letterN2 = []
letterN3 = []
letterN4 = []
letterN5 = []
letterN6 = []
letterN7 = []
letterN8 = []
letterN9 = []
letterN10 = []
letterN11 = []
letterN12 = []
letterN13 = []
letterN14 = []
letterN15 = []
letterN16 = []
letterN17 = []
letterN18 = []
letterN19 = []
letterN20 = []
letterN21 = []
letterN22 = []
letterN23 = []
letterN24 = []
# o
letterO1 = []
letterO2 = []
letterO3 = []
letterO4 = []
letterO5 = []
letterO6 = []
letterO7 = []
letterO8 = []
letterO9 = []
letterO10 = []
letterO11 = []
letterO12 = []
letterO13 = []
letterO14 = []
letterO15 = []
letterO16 = []
letterO17 = []
letterO18 = []
letterO19 = []
letterO20 = []
letterO21 = []
letterO22 = []
letterO23 = []
letterO24 = []
# p
letterP1 = []
letterP2 = []
letterP3 = []
letterP4 = []
letterP5 = []
letterP6 = []
letterP7 = []
letterP8 = []
letterP9 = []
letterP10 = []
letterP11 = []
letterP12 = []
letterP13 = []
letterP14 = []
letterP15 = []
letterP16 = []
letterP17 = []
letterP18 = []
letterP19 = []
letterP20 = []
letterP21 = []
letterP22 = []
letterP23 = []
letterP24 = []
# q
letterQ1 = []
letterQ2 = []
letterQ3 = []
letterQ4 = []
letterQ5 = []
letterQ6 = []
letterQ7 = []
letterQ8 = []
letterQ9 = []
letterQ10 = []
letterQ11 = []
letterQ12 = []
letterQ13 = []
letterQ14 = []
letterQ15 = []
letterQ16 = []
letterQ17 = []
letterQ18 = []
letterQ19 = []
letterQ20 = []
letterQ21 = []
letterQ22 = []
letterQ23 = []
letterQ24 = []
# r
letterR1 = []
letterR2 = []
letterR3 = []
letterR4 = []
letterR5 = []
letterR6 = []
letterR7 = []
letterR8 = []
letterR9 = []
letterR10 = []
letterR11 = []
letterR12 = []
letterR13 = []
letterR14 = []
letterR15 = []
letterR16 = []
letterR17 = []
letterR18 = []
letterR19 = []
letterR20 = []
letterR21 = []
letterR22 = []
letterR23 = []
letterR24 = []
# s
letterS1 = []
letterS2 = []
letterS3 = []
letterS4 = []
letterS5 = []
letterS6 = []
letterS7 = []
letterS8 = []
letterS9 = []
letterS10 = []
letterS11 = []
letterS12 = []
letterS13 = []
letterS14 = []
letterS15 = []
letterS16 = []
letterS17 = []
letterS18 = []
letterS19 = []
letterS20 = []
letterS21 = []
letterS22 = []
letterS23 = []
letterS24 = []
# t
letterT1 = []
letterT2 = []
letterT3 = []
letterT4 = []
letterT5 = []
letterT6 = []
letterT7 = []
letterT8 = []
letterT9 = []
letterT10 = []
letterT11 = []
letterT12 = []
letterT13 = []
letterT14 = []
letterT15 = []
letterT16 = []
letterT17 = []
letterT18 = []
letterT19 = []
letterT20 = []
letterT21 = []
letterT22 = []
letterT23 = []
letterT24 = []
# u
letterU1 = []
letterU2 = []
letterU3 = []
letterU4 = []
letterU5 = []
letterU6 = []
letterU7 = []
letterU8 = []
letterU9 = []
letterU10 = []
letterU11 = []
letterU12 = []
letterU13 = []
letterU14 = []
letterU15 = []
letterU16 = []
letterU17 = []
letterU18 = []
letterU19 = []
letterU20 = []
letterU21 = []
letterU22 = []
letterU23 = []
letterU24 = []
# v
letterV1 = []
letterV2 = []
letterV3 = []
letterV4 = []
letterV5 = []
letterV6 = []
letterV7 = []
letterV8 = []
letterV9 = []
letterV10 = []
letterV11 = []
letterV12 = []
letterV13 = []
letterV14 = []
letterV15 = []
letterV16 = []
letterV17 = []
letterV18 = []
letterV19 = []
letterV20 = []
letterV21 = []
letterV22 = []
letterV23 = []
letterV24 = []
# w
letterW1 = []
letterW2 = []
letterW3 = []
letterW4 = []
letterW5 = []
letterW6 = []
letterW7 = []
letterW8 = []
letterW9 = []
letterW10 = []
letterW11 = []
letterW12 = []
letterW13 = []
letterW14 = []
letterW15 = []
letterW16 = []
letterW17 = []
letterW18 = []
letterW19 = []
letterW20 = []
letterW21 = []
letterW22 = []
letterW23 = []
letterW24 = []
# x
letterX1 = []
letterX2 = []
letterX3 = []
letterX4 = []
letterX5 = []
letterX6 = []
letterX7 = []
letterX8 = []
letterX9 = []
letterX10 = []
letterX11 = []
letterX12 = []
letterX13 = []
letterX14 = []
letterX15 = []
letterX16 = []
letterX17 = []
letterX18 = []
letterX19 = []
letterX20 = []
letterX21 = []
letterX22 = []
letterX23 = []
letterX24 = []
# y
letterY1 = []
letterY2 = []
letterY3 = []
letterY4 = []
letterY5 = []
letterY6 = []
letterY7 = []
letterY8 = []
letterY9 = []
letterY10 = []
letterY11 = []
letterY12 = []
letterY13 = []
letterY14 = []
letterY15 = []
letterY16 = []
letterY17 = []
letterY18 = []
letterY19 = []
letterY20 = []
letterY21 = []
letterY22 = []
letterY23 = []
letterY24 = []
# z
letterZ1 = []
letterZ2 = []
letterZ3 = []
letterZ4 = []
letterZ5 = []
letterZ6 = []
letterZ7 = []
letterZ8 = []
letterZ9 = []
letterZ10 = []
letterZ11 = []
letterZ12 = []
letterZ13 = []
letterZ14 = []
letterZ15 = []
letterZ16 = []
letterZ17 = []
letterZ18 = []
letterZ19 = []
letterZ20 = []
letterZ21 = []
letterZ22 = []
letterZ23 = []
letterZ24 = []
# -----------------
for i in range(len(word_list)):
x = word_list[i]
x = x.lower()
x = x[0]
if len(word_list[i]) == 1:
list.append(letter1, word_list[i])
if x == 'a':
list.append(letterA1, word_list[i])
if x == 'b':
list.append(letterB1, word_list[i])
if x == 'c':
list.append(letterC1, word_list[i])
if x == 'd':
list.append(letterD1, word_list[i])
if x == 'e':
list.append(letterE1, word_list[i])
if x == 'f':
list.append(letterF1, word_list[i])
if x == 'g':
list.append(letterG1, word_list[i])
if x == 'h':
list.append(letterH1, word_list[i])
if x == 'i':
list.append(letterI1, word_list[i])
if x == 'j':
list.append(letterJ1, word_list[i])
if x == 'k':
list.append(letterK1, word_list[i])
if x == 'l':
list.append(letterL1, word_list[i])
if x == 'm':
list.append(letterM1, word_list[i])
if x == 'n':
list.append(letterN1, word_list[i])
if x == 'o':
list.append(letterO1, word_list[i])
if x == 'p':
list.append(letterP1, word_list[i])
if x == 'q':
list.append(letterQ1, word_list[i])
if x == 'r':
list.append(letterR1, word_list[i])
if x == 's':
list.append(letterS1, word_list[i])
if x == 't':
list.append(letterT1, word_list[i])
if x == 'u':
list.append(letterU1, word_list[i])
if x == 'v':
list.append(letterV1, word_list[i])
if x == 'w':
list.append(letterW1, word_list[i])
if x == 'x':
list.append(letterX1, word_list[i])
if x == 'y':
list.append(letterY1, word_list[i])
if x == 'z':
list.append(letterZ1, word_list[i])
if len(word_list[i]) == 2:
list.append(letter2, word_list[i])
if x == 'a':
list.append(letterA2, word_list[i])
if x == 'b':
list.append(letterB2, word_list[i])
if x == 'c':
list.append(letterC2, word_list[i])
if x == 'd':
list.append(letterD2, word_list[i])
if x == 'e':
list.append(letterE2, word_list[i])
if x == 'f':
list.append(letterF2, word_list[i])
if x == 'g':
list.append(letterG2, word_list[i])
if x == 'h':
list.append(letterH2, word_list[i])
if x == 'i':
list.append(letterI2, word_list[i])
if x == 'j':
list.append(letterJ2, word_list[i])
if x == 'k':
list.append(letterK2, word_list[i])
if x == 'l':
list.append(letterL2, word_list[i])
if x == 'm':
list.append(letterM2, word_list[i])
if x == 'n':
list.append(letterN2, word_list[i])
if x == 'o':
list.append(letterO2, word_list[i])
if x == 'p':
list.append(letterP2, word_list[i])
if x == 'q':
list.append(letterQ2, word_list[i])
if x == 'r':
list.append(letterR2, word_list[i])
if x == 's':
list.append(letterS2, word_list[i])
if x == 't':
list.append(letterT2, word_list[i])
if x == 'u':
list.append(letterU2, word_list[i])
if x == 'v':
list.append(letterV2, word_list[i])
if x == 'w':
list.append(letterW2, word_list[i])
if x == 'x':
list.append(letterX2, word_list[i])
if x == 'y':
list.append(letterY2, word_list[i])
if x == 'z':
list.append(letterZ2, word_list[i])
if len(word_list[i]) == 3:
list.append(letter3, word_list[i])
if x == 'a':
list.append(letterA3, word_list[i])
if x == 'b':
list.append(letterB3, word_list[i])
if x == 'c':
list.append(letterC3, word_list[i])
if x == 'd':
list.append(letterD3, word_list[i])
if x == 'e':
list.append(letterE3, word_list[i])
if x == 'f':
list.append(letterF3, word_list[i])
if x == 'g':
list.append(letterG3, word_list[i])
if x == 'h':
list.append(letterH3, word_list[i])
if x == 'i':
list.append(letterI3, word_list[i])
if x == 'j':
list.append(letterJ3, word_list[i])
if x == 'k':
list.append(letterK3, word_list[i])
if x == 'l':
list.append(letterL3, word_list[i])
if x == 'm':
list.append(letterM3, word_list[i])
if x == 'n':
list.append(letterN3, word_list[i])
if x == 'o':
list.append(letterO3, word_list[i])
if x == 'p':
list.append(letterP3, word_list[i])
if x == 'q':
list.append(letterQ3, word_list[i])
if x == 'r':
list.append(letterR3, word_list[i])
if x == 's':
list.append(letterS3, word_list[i])
if x == 't':
list.append(letterT3, word_list[i])
if x == 'u':
list.append(letterU3, word_list[i])
if x == 'v':
list.append(letterV3, word_list[i])
if x == 'w':
list.append(letterW3, word_list[i])
if x == 'x':
list.append(letterX3, word_list[i])
if x == 'y':
list.append(letterY3, word_list[i])
if x == 'z':
list.append(letterZ3, word_list[i])
if len(word_list[i]) == 4:
list.append(letter4, word_list[i])
if x == 'a':
list.append(letterA4, word_list[i])
if x == 'b':
list.append(letterB4, word_list[i])
if x == 'c':
list.append(letterC4, word_list[i])
if x == 'd':
list.append(letterD4, word_list[i])
if x == 'e':
list.append(letterE4, word_list[i])
if x == 'f':
list.append(letterF4, word_list[i])
if x == 'g':
list.append(letterG4, word_list[i])
if x == 'h':
list.append(letterH4, word_list[i])
if x == 'i':
list.append(letterI4, word_list[i])
if x == 'j':
list.append(letterJ4, word_list[i])
if x == 'k':
list.append(letterK4, word_list[i])
if x == 'l':
list.append(letterL4, word_list[i])
if x == 'm':
list.append(letterM4, word_list[i])
if x == 'n':
list.append(letterN4, word_list[i])
if x == 'o':
list.append(letterO4, word_list[i])
if x == 'p':
list.append(letterP4, word_list[i])
if x == 'q':
list.append(letterQ4, word_list[i])
if x == 'r':
list.append(letterR4, word_list[i])
if x == 's':
list.append(letterS4, word_list[i])
if x == 't':
list.append(letterT4, word_list[i])
if x == 'u':
list.append(letterU4, word_list[i])
if x == 'v':
list.append(letterV4, word_list[i])
if x == 'w':
list.append(letterW4, word_list[i])
if x == 'x':
list.append(letterX4, word_list[i])
if x == 'y':
list.append(letterY4, word_list[i])
if x == 'z':
list.append(letterZ4, word_list[i])
if len(word_list[i]) == 5:
list.append(letter5, word_list[i])
if x == 'a':
list.append(letterA5, word_list[i])
if x == 'b':
list.append(letterB5, word_list[i])
if x == 'c':
list.append(letterC5, word_list[i])
if x == 'd':
list.append(letterD5, word_list[i])
if x == 'e':
list.append(letterE5, word_list[i])
if x == 'f':
list.append(letterF5, word_list[i])
if x == 'g':
list.append(letterG5, word_list[i])
if x == 'h':
list.append(letterH5, word_list[i])
if x == 'i':
list.append(letterI5, word_list[i])
if x == 'j':
list.append(letterJ5, word_list[i])
if x == 'k':
list.append(letterK5, word_list[i])
if x == 'l':
list.append(letterL5, word_list[i])
if x == 'm':
list.append(letterM5, word_list[i])
if x == 'n':
list.append(letterN5, word_list[i])
if x == 'o':
list.append(letterO5, word_list[i])
if x == 'p':
list.append(letterP5, word_list[i])
if x == 'q':
list.append(letterQ5, word_list[i])
if x == 'r':
list.append(letterR5, word_list[i])
if x == 's':
list.append(letterS5, word_list[i])
if x == 't':
list.append(letterT5, word_list[i])
if x == 'u':
list.append(letterU5, word_list[i])
if x == 'v':
list.append(letterV5, word_list[i])
if x == 'w':
list.append(letterW5, word_list[i])
if x == 'x':
list.append(letterX5, word_list[i])
if x == 'y':
list.append(letterY5, word_list[i])
if x == 'z':
list.append(letterZ5, word_list[i])
if len(word_list[i]) == 6:
list.append(letter6, word_list[i])
if x == 'a':
list.append(letterA6, word_list[i])
if x == 'b':
list.append(letterB6, word_list[i])
if x == 'c':
list.append(letterC6, word_list[i])
if x == 'd':
list.append(letterD6, word_list[i])
if x == 'e':
list.append(letterE6, word_list[i])
if x == 'f':
list.append(letterF6, word_list[i])
if x == 'g':
list.append(letterG6, word_list[i])
if x == 'h':
list.append(letterH6, word_list[i])
if x == 'i':
list.append(letterI6, word_list[i])
if x == 'j':
list.append(letterJ6, word_list[i])
if x == 'k':
list.append(letterK6, word_list[i])
if x == 'l':
list.append(letterL6, word_list[i])
if x == 'm':
list.append(letterM6, word_list[i])
if x == 'n':
list.append(letterN6, word_list[i])
if x == 'o':
list.append(letterO6, word_list[i])
if x == 'p':
list.append(letterP6, word_list[i])
if x == 'q':
list.append(letterQ6, word_list[i])
if x == 'r':
list.append(letterR6, word_list[i])
if x == 's':
list.append(letterS6, word_list[i])
if x == 't':
list.append(letterT6, word_list[i])
if x == 'u':
list.append(letterU6, word_list[i])
if x == 'v':
list.append(letterV6, word_list[i])
if x == 'w':
list.append(letterW6, word_list[i])
if x == 'x':
list.append(letterX6, word_list[i])
if x == 'y':
list.append(letterY6, word_list[i])
if x == 'z':
list.append(letterZ6, word_list[i])
if len(word_list[i]) == 7:
list.append(letter7, word_list[i])
if x == 'a':
list.append(letterA7, word_list[i])
if x == 'b':
list.append(letterB7, word_list[i])
if x == 'c':
list.append(letterC7, word_list[i])
if x == 'd':
list.append(letterD7, word_list[i])
if x == 'e':
list.append(letterE7, word_list[i])
if x == 'f':
list.append(letterF7, word_list[i])
if x == 'g':
list.append(letterG7, word_list[i])
if x == 'h':
list.append(letterH7, word_list[i])
if x == 'i':
list.append(letterI7, word_list[i])
if x == 'j':
list.append(letterJ7, word_list[i])
if x == 'k':
list.append(letterK7, word_list[i])
if x == 'l':
list.append(letterL7, word_list[i])
if x == 'm':
list.append(letterM7, word_list[i])
if x == 'n':
list.append(letterN7, word_list[i])
if x == 'o':
list.append(letterO7, word_list[i])
if x == 'p':
list.append(letterP7, word_list[i])
if x == 'q':
list.append(letterQ7, word_list[i])
if x == 'r':
list.append(letterR7, word_list[i])
if x == 's':
list.append(letterS7, word_list[i])
if x == 't':
list.append(letterT7, word_list[i])
if x == 'u':
list.append(letterU7, word_list[i])
if x == 'v':
list.append(letterV7, word_list[i])
if x == 'w':
list.append(letterW7, word_list[i])
if x == 'x':
list.append(letterX7, word_list[i])
if x == 'y':
list.append(letterY7, word_list[i])
if x == 'z':
list.append(letterZ7, word_list[i])
if len(word_list[i]) == 8:
list.append(letter8, word_list[i])
if x == 'a':
list.append(letterA8, word_list[i])
if x == 'b':
list.append(letterB8, word_list[i])
if x == 'c':
list.append(letterC8, word_list[i])
if x == 'd':
list.append(letterD8, word_list[i])
if x == 'e':
list.append(letterE8, word_list[i])
if x == 'f':
list.append(letterF8, word_list[i])
if x == 'g':
list.append(letterG8, word_list[i])
if x == 'h':
list.append(letterH8, word_list[i])
if x == 'i':
list.append(letterI8, word_list[i])
if x == 'j':
list.append(letterJ8, word_list[i])
if x == 'k':
list.append(letterK8, word_list[i])
if x == 'l':
list.append(letterL8, word_list[i])
if x == 'm':
list.append(letterM8, word_list[i])
if x == 'n':
list.append(letterN8, word_list[i])
if x == 'o':
list.append(letterO8, word_list[i])
if x == 'p':
list.append(letterP8, word_list[i])
if x == 'q':
list.append(letterQ8, word_list[i])
if x == 'r':
list.append(letterR8, word_list[i])
if x == 's':
list.append(letterS8, word_list[i])
if x == 't':
list.append(letterT8, word_list[i])
if x == 'u':
list.append(letterU8, word_list[i])
if x == 'v':
list.append(letterV8, word_list[i])
if x == 'w':
list.append(letterW8, word_list[i])
if x == 'x':
list.append(letterX8, word_list[i])
if x == 'y':
list.append(letterY8, word_list[i])
if x == 'z':
list.append(letterZ8, word_list[i])
if len(word_list[i]) == 9:
list.append(letter9, word_list[i])
if x == 'a':
list.append(letterA9, word_list[i])
if x == 'b':
list.append(letterB9, word_list[i])
if x == 'c':
list.append(letterC9, word_list[i])
if x == 'd':
list.append(letterD9, word_list[i])
if x == 'e':
list.append(letterE9, word_list[i])
if x == 'f':
list.append(letterF9, word_list[i])
if x == 'g':
list.append(letterG9, word_list[i])
if x == 'h':
list.append(letterH9, word_list[i])
if x == 'i':
list.append(letterI9, word_list[i])
if x == 'j':
list.append(letterJ9, word_list[i])
if x == 'k':
list.append(letterK9, word_list[i])
if x == 'l':
list.append(letterL9, word_list[i])
if x == 'm':
list.append(letterM9, word_list[i])
if x == 'n':
list.append(letterN9, word_list[i])
if x == 'o':
list.append(letterO9, word_list[i])
if x == 'p':
list.append(letterP9, word_list[i])
if x == 'q':
list.append(letterQ9, word_list[i])
if x == 'r':
list.append(letterR9, word_list[i])
if x == 's':
list.append(letterS9, word_list[i])
if x == 't':
list.append(letterT9, word_list[i])
if x == 'u':
list.append(letterU9, word_list[i])
if x == 'v':
list.append(letterV9, word_list[i])
if x == 'w':
list.append(letterW9, word_list[i])
if x == 'x':
list.append(letterX9, word_list[i])
if x == 'y':
list.append(letterY9, word_list[i])
if x == 'z':
list.append(letterZ9, word_list[i])
if len(word_list[i]) == 10:
list.append(letter10, word_list[i])
if x == 'a':
list.append(letterA10, word_list[i])
if x == 'b':
list.append(letterB10, word_list[i])
if x == 'c':
list.append(letterC10, word_list[i])
if x == 'd':
list.append(letterD10, word_list[i])
if x == 'e':
list.append(letterE10, word_list[i])
if x == 'f':
list.append(letterF10, word_list[i])
if x == 'g':
list.append(letterG10, word_list[i])
if x == 'h':
list.append(letterH10, word_list[i])
if x == 'i':
list.append(letterI10, word_list[i])
if x == 'j':
list.append(letterJ10, word_list[i])
if x == 'k':
list.append(letterK10, word_list[i])
if x == 'l':
list.append(letterL10, word_list[i])
if x == 'm':
list.append(letterM10, word_list[i])
if x == 'n':
list.append(letterN10, word_list[i])
if x == 'o':
list.append(letterO10, word_list[i])
if x == 'p':
list.append(letterP10, word_list[i])
if x == 'q':
list.append(letterQ10, word_list[i])
if x == 'r':
list.append(letterR10, word_list[i])
if x == 's':
list.append(letterS10, word_list[i])
if x == 't':
list.append(letterT10, word_list[i])
if x == 'u':
list.append(letterU10, word_list[i])
if x == 'v':
list.append(letterV10, word_list[i])
if x == 'w':
list.append(letterW10, word_list[i])
if x == 'x':
list.append(letterX10, word_list[i])
if x == 'y':
list.append(letterY10, word_list[i])
if x == 'z':
list.append(letterZ10, word_list[i])
if len(word_list[i]) == 11:
list.append(letter11, word_list[i])
if x == 'a':
list.append(letterA11, word_list[i])
if x == 'b':
list.append(letterB11, word_list[i])
if x == 'c':
list.append(letterC11, word_list[i])
if x == 'd':
list.append(letterD11, word_list[i])
if x == 'e':
list.append(letterE11, word_list[i])
if x == 'f':
list.append(letterF11, word_list[i])
if x == 'g':
list.append(letterG11, word_list[i])
if x == 'h':
list.append(letterH11, word_list[i])
if x == 'i':
list.append(letterI11, word_list[i])
if x == 'j':
list.append(letterJ11, word_list[i])
if x == 'k':
list.append(letterK11, word_list[i])
if x == 'l':
list.append(letterL11, word_list[i])
if x == 'm':
list.append(letterM11, word_list[i])
if x == 'n':
list.append(letterN11, word_list[i])
if x == 'o':
list.append(letterO11, word_list[i])
if x == 'p':
list.append(letterP11, word_list[i])
if x == 'q':
list.append(letterQ11, word_list[i])
if x == 'r':
list.append(letterR11, word_list[i])
if x == 's':
list.append(letterS11, word_list[i])
if x == 't':
list.append(letterT11, word_list[i])
if x == 'u':
list.append(letterU11, word_list[i])
if x == 'v':
list.append(letterV11, word_list[i])
if x == 'w':
list.append(letterW11, word_list[i])
if x == 'x':
list.append(letterX11, word_list[i])
if x == 'y':
list.append(letterY11, word_list[i])
if x == 'z':
list.append(letterZ11, word_list[i])
if len(word_list[i]) == 12:
list.append(letter12, word_list[i])
if x == 'a':
list.append(letterA12, word_list[i])
if x == 'b':
list.append(letterB12, word_list[i])
if x == 'c':
list.append(letterC12, word_list[i])
if x == 'd':
list.append(letterD12, word_list[i])
if x == 'e':
list.append(letterE12, word_list[i])
if x == 'f':
list.append(letterF12, word_list[i])
if x == 'g':
list.append(letterG12, word_list[i])
if x == 'h':
list.append(letterH12, word_list[i])
if x == 'i':
list.append(letterI12, word_list[i])
if x == 'j':
list.append(letterJ12, word_list[i])
if x == 'k':
list.append(letterK12, word_list[i])
if x == 'l':
list.append(letterL12, word_list[i])
if x == 'm':
list.append(letterM12, word_list[i])
if x == 'n':
list.append(letterN12, word_list[i])
if x == 'o':
list.append(letterO12, word_list[i])
if x == 'p':
list.append(letterP12, word_list[i])
if x == 'q':
list.append(letterQ12, word_list[i])
if x == 'r':
list.append(letterR12, word_list[i])
if x == 's':
list.append(letterS12, word_list[i])
if x == 't':
list.append(letterT12, word_list[i])
if x == 'u':
list.append(letterU12, word_list[i])
if x == 'v':
list.append(letterV12, word_list[i])
if x == 'w':
list.append(letterW12, word_list[i])
if x == 'x':
list.append(letterX12, word_list[i])
if x == 'y':
list.append(letterY12, word_list[i])
if x == 'z':
list.append(letterZ12, word_list[i])
if len(word_list[i]) == 13:
list.append(letter13, word_list[i])
if x == 'a':
list.append(letterA13, word_list[i])
if x == 'b':
list.append(letterB13, word_list[i])
if x == 'c':
list.append(letterC13, word_list[i])
if x == 'd':
list.append(letterD13, word_list[i])
if x == 'e':
list.append(letterE13, word_list[i])
if x == 'f':
list.append(letterF13, word_list[i])
if x == 'g':
list.append(letterG13, word_list[i])
if x == 'h':
list.append(letterH13, word_list[i])
if x == 'i':
list.append(letterI13, word_list[i])
if x == 'j':
list.append(letterJ13, word_list[i])
if x == 'k':
list.append(letterK13, word_list[i])
if x == 'l':
list.append(letterL13, word_list[i])
if x == 'm':
list.append(letterM13, word_list[i])
if x == 'n':
list.append(letterN13, word_list[i])
if x == 'o':
list.append(letterO13, word_list[i])
if x == 'p':
list.append(letterP13, word_list[i])
if x == 'q':
list.append(letterQ13, word_list[i])
if x == 'r':
list.append(letterR13, word_list[i])
if x == 's':
list.append(letterS13, word_list[i])
if x == 't':
list.append(letterT13, word_list[i])
if x == 'u':
list.append(letterU13, word_list[i])
if x == 'v':
list.append(letterV13, word_list[i])
if x == 'w':
list.append(letterW13, word_list[i])
if x == 'x':
list.append(letterX13, word_list[i])
if x == 'y':
list.append(letterY13, word_list[i])
if x == 'z':
list.append(letterZ13, word_list[i])
if len(word_list[i]) == 14:
list.append(letter14, word_list[i])
if x == 'a':
list.append(letterA14, word_list[i])
if x == 'b':
list.append(letterB14, word_list[i])
if x == 'c':
list.append(letterC14, word_list[i])
if x == 'd':
list.append(letterD14, word_list[i])
if x == 'e':
list.append(letterE14, word_list[i])
if x == 'f':
list.append(letterF14, word_list[i])
if x == 'g':
list.append(letterG14, word_list[i])
if x == 'h':
list.append(letterH14, word_list[i])
if x == 'i':
list.append(letterI14, word_list[i])
if x == 'j':
list.append(letterJ14, word_list[i])
if x == 'k':
list.append(letterK14, word_list[i])
if x == 'l':
list.append(letterL14, word_list[i])
if x == 'm':
list.append(letterM14, word_list[i])
if x == 'n':
list.append(letterN14, word_list[i])
if x == 'o':
list.append(letterO14, word_list[i])
if x == 'p':
list.append(letterP14, word_list[i])
if x == 'q':
list.append(letterQ14, word_list[i])
if x == 'r':
list.append(letterR14, word_list[i])
if x == 's':
list.append(letterS14, word_list[i])
if x == 't':
list.append(letterT14, word_list[i])
if x == 'u':
list.append(letterU14, word_list[i])
if x == 'v':
list.append(letterV14, word_list[i])
if x == 'w':
list.append(letterW14, word_list[i])
if x == 'x':
list.append(letterX14, word_list[i])
if x == 'y':
list.append(letterY14, word_list[i])
if x == 'z':
list.append(letterZ14, word_list[i])
if len(word_list[i]) == 15:
list.append(letter15, word_list[i])
if x == 'a':
list.append(letterA15, word_list[i])
if x == 'b':
list.append(letterB15, word_list[i])
if x == 'c':
list.append(letterC15, word_list[i])
if x == 'd':
list.append(letterD15, word_list[i])
if x == 'e':
list.append(letterE15, word_list[i])
if x == 'f':
list.append(letterF15, word_list[i])
if x == 'g':
list.append(letterG15, word_list[i])
if x == 'h':
list.append(letterH15, word_list[i])
if x == 'i':
list.append(letterI15, word_list[i])
if x == 'j':
list.append(letterJ15, word_list[i])
if x == 'k':
list.append(letterK15, word_list[i])
if x == 'l':
list.append(letterL15, word_list[i])
if x == 'm':
list.append(letterM15, word_list[i])
if x == 'n':
list.append(letterN15, word_list[i])
if x == 'o':
list.append(letterO15, word_list[i])
if x == 'p':
list.append(letterP15, word_list[i])
if x == 'q':
list.append(letterQ15, word_list[i])
if x == 'r':
list.append(letterR15, word_list[i])
if x == 's':
list.append(letterS15, word_list[i])
if x == 't':
list.append(letterT15, word_list[i])
if x == 'u':
list.append(letterU15, word_list[i])
if x == 'v':
list.append(letterV15, word_list[i])
if x == 'w':
list.append(letterW15, word_list[i])
if x == 'x':
list.append(letterX15, word_list[i])
if x == 'y':
list.append(letterY15, word_list[i])
if x == 'z':
list.append(letterZ15, word_list[i])
if len(word_list[i]) == 16:
list.append(letter16, word_list[i])
if x == 'a':
list.append(letterA16, word_list[i])
if x == 'b':
list.append(letterB16, word_list[i])
if x == 'c':
list.append(letterC16, word_list[i])
if x == 'd':
list.append(letterD16, word_list[i])
if x == 'e':
list.append(letterE16, word_list[i])
if x == 'f':
list.append(letterF16, word_list[i])
if x == 'g':
list.append(letterG16, word_list[i])
if x == 'h':
list.append(letterH16, word_list[i])
if x == 'i':
list.append(letterI16, word_list[i])
if x == 'j':
list.append(letterJ16, word_list[i])
if x == 'k':
list.append(letterK16, word_list[i])
if x == 'l':
list.append(letterL16, word_list[i])
if x == 'm':
list.append(letterM16, word_list[i])
if x == 'n':
list.append(letterN16, word_list[i])
if x == 'o':
list.append(letterO16, word_list[i])
if x == 'p':
list.append(letterP16, word_list[i])
if x == 'q':
list.append(letterQ16, word_list[i])
if x == 'r':
list.append(letterR16, word_list[i])
if x == 's':
list.append(letterS16, word_list[i])
if x == 't':
list.append(letterT16, word_list[i])
if x == 'u':
list.append(letterU16, word_list[i])
if x == 'v':
list.append(letterV16, word_list[i])
if x == 'w':
list.append(letterW16, word_list[i])
if x == 'x':
list.append(letterX16, word_list[i])
if x == 'y':
list.append(letterY16, word_list[i])
if x == 'z':
list.append(letterZ16, word_list[i])
if len(word_list[i]) == 17:
list.append(letter17, word_list[i])
if x == 'a':
list.append(letterA17, word_list[i])
if x == 'b':
list.append(letterB17, word_list[i])
if x == 'c':
list.append(letterC17, word_list[i])
if x == 'd':
list.append(letterD17, word_list[i])
if x == 'e':
list.append(letterE17, word_list[i])
if x == 'f':
list.append(letterF17, word_list[i])
if x == 'g':
list.append(letterG17, word_list[i])
if x == 'h':
list.append(letterH17, word_list[i])
if x == 'i':
list.append(letterI17, word_list[i])
if x == 'j':
list.append(letterJ17, word_list[i])
if x == 'k':
list.append(letterK17, word_list[i])
if x == 'l':
list.append(letterL17, word_list[i])
if x == 'm':
list.append(letterM17, word_list[i])
if x == 'n':
list.append(letterN17, word_list[i])
if x == 'o':
list.append(letterO17, word_list[i])
if x == 'p':
list.append(letterP17, word_list[i])
if x == 'q':
list.append(letterQ17, word_list[i])
if x == 'r':
list.append(letterR17, word_list[i])
if x == 's':
list.append(letterS17, word_list[i])
if x == 't':
list.append(letterT17, word_list[i])
if x == 'u':
list.append(letterU17, word_list[i])
if x == 'v':
list.append(letterV17, word_list[i])
if x == 'w':
list.append(letterW17, word_list[i])
if x == 'x':
list.append(letterX17, word_list[i])
if x == 'y':
list.append(letterY17, word_list[i])
if x == 'z':
list.append(letterZ17, word_list[i])
if len(word_list[i]) == 18:
list.append(letter18, word_list[i])
if x == 'a':
list.append(letterA18, word_list[i])
if x == 'b':
list.append(letterB18, word_list[i])
if x == 'c':
list.append(letterC18, word_list[i])
if x == 'd':
list.append(letterD18, word_list[i])
if x == 'e':
list.append(letterE18, word_list[i])
if x == 'f':
list.append(letterF18, word_list[i])
if x == 'g':
list.append(letterG18, word_list[i])
if x == 'h':
list.append(letterH18, word_list[i])
if x == 'i':
list.append(letterI18, word_list[i])
if x == 'j':
list.append(letterJ18, word_list[i])
if x == 'k':
list.append(letterK18, word_list[i])
if x == 'l':
list.append(letterL18, word_list[i])
if x == 'm':
list.append(letterM18, word_list[i])
if x == 'n':
list.append(letterN18, word_list[i])
if x == 'o':
list.append(letterO18, word_list[i])
if x == 'p':
list.append(letterP18, word_list[i])
if x == 'q':
list.append(letterQ18, word_list[i])
if x == 'r':
list.append(letterR18, word_list[i])
if x == 's':
list.append(letterS18, word_list[i])
if x == 't':
list.append(letterT18, word_list[i])
if x == 'u':
list.append(letterU18, word_list[i])
if x == 'v':
list.append(letterV18, word_list[i])
if x == 'w':
list.append(letterW18, word_list[i])
if x == 'x':
list.append(letterX18, word_list[i])
if x == 'y':
list.append(letterY18, word_list[i])
if x == 'z':
list.append(letterZ18, word_list[i])
if len(word_list[i]) == 19:
list.append(letter19, word_list[i])
if x == 'a':
list.append(letterA19, word_list[i])
if x == 'b':
list.append(letterB19, word_list[i])
if x == 'c':
list.append(letterC19, word_list[i])
if x == 'd':
list.append(letterD19, word_list[i])
if x == 'e':
list.append(letterE19, word_list[i])
if x == 'f':
list.append(letterF19, word_list[i])
if x == 'g':
list.append(letterG19, word_list[i])
if x == 'h':
list.append(letterH19, word_list[i])
if x == 'i':
list.append(letterI19, word_list[i])
if x == 'j':
list.append(letterJ19, word_list[i])
if x == 'k':
list.append(letterK19, word_list[i])
if x == 'l':
list.append(letterL19, word_list[i])
if x == 'm':
list.append(letterM19, word_list[i])
if x == 'n':
list.append(letterN19, word_list[i])
if x == 'o':
list.append(letterO19, word_list[i])
if x == 'p':
list.append(letterP19, word_list[i])
if x == 'q':
list.append(letterQ19, word_list[i])
if x == 'r':
list.append(letterR19, word_list[i])
if x == 's':
list.append(letterS19, word_list[i])
if x == 't':
list.append(letterT19, word_list[i])
if x == 'u':
list.append(letterU19, word_list[i])
if x == 'v':
list.append(letterV19, word_list[i])
if x == 'w':
list.append(letterW19, word_list[i])
if x == 'x':
list.append(letterX19, word_list[i])
if x == 'y':
list.append(letterY19, word_list[i])
if x == 'z':
list.append(letterZ19, word_list[i])
if len(word_list[i]) == 20:
list.append(letter20, word_list[i])
if x == 'a':
list.append(letterA20, word_list[i])
if x == 'b':
list.append(letterB20, word_list[i])
if x == 'c':
list.append(letterC20, word_list[i])
if x == 'd':
list.append(letterD20, word_list[i])
if x == 'e':
list.append(letterE20, word_list[i])
if x == 'f':
list.append(letterF20, word_list[i])
if x == 'g':
list.append(letterG20, word_list[i])
if x == 'h':
list.append(letterH20, word_list[i])
if x == 'i':
list.append(letterI20, word_list[i])
if x == 'j':
list.append(letterJ20, word_list[i])
if x == 'k':
list.append(letterK20, word_list[i])
if x == 'l':
list.append(letterL20, word_list[i])
if x == 'm':
list.append(letterM20, word_list[i])
if x == 'n':
list.append(letterN20, word_list[i])
if x == 'o':
list.append(letterO20, word_list[i])
if x == 'p':
list.append(letterP20, word_list[i])
if x == 'q':
list.append(letterQ20, word_list[i])
if x == 'r':
list.append(letterR20, word_list[i])
if x == 's':
list.append(letterS20, word_list[i])
if x == 't':
list.append(letterT20, word_list[i])
if x == 'u':
list.append(letterU20, word_list[i])
if x == 'v':
list.append(letterV20, word_list[i])
if x == 'w':
list.append(letterW20, word_list[i])
if x == 'x':
list.append(letterX20, word_list[i])
if x == 'y':
list.append(letterY20, word_list[i])
if x == 'z':
list.append(letterZ20, word_list[i])
if len(word_list[i]) == 21:
list.append(letter21, word_list[i])
if x == 'a':
list.append(letterA21, word_list[i])
if x == 'b':
list.append(letterB21, word_list[i])
if x == 'c':
list.append(letterC21, word_list[i])
if x == 'd':
list.append(letterD21, word_list[i])
if x == 'e':
list.append(letterE21, word_list[i])
if x == 'f':
list.append(letterF21, word_list[i])
if x == 'g':
list.append(letterG21, word_list[i])
if x == 'h':
list.append(letterH21, word_list[i])
if x == 'i':
list.append(letterI21, word_list[i])
if x == 'j':
list.append(letterJ21, word_list[i])
if x == 'k':
list.append(letterK21, word_list[i])
if x == 'l':
list.append(letterL21, word_list[i])
if x == 'm':
list.append(letterM21, word_list[i])
if x == 'n':
list.append(letterN21, word_list[i])
if x == 'o':
list.append(letterO21, word_list[i])
if x == 'p':
list.append(letterP21, word_list[i])
if x == 'q':
list.append(letterQ21, word_list[i])
if x == 'r':
list.append(letterR21, word_list[i])
if x == 's':
list.append(letterS21, word_list[i])
if x == 't':
list.append(letterT21, word_list[i])
if x == 'u':
list.append(letterU21, word_list[i])
if x == 'v':
list.append(letterV21, word_list[i])
if x == 'w':
list.append(letterW21, word_list[i])
if x == 'x':
list.append(letterX21, word_list[i])
if x == 'y':
list.append(letterY21, word_list[i])
if x == 'z':
list.append(letterZ21, word_list[i])
if len(word_list[i]) == 22:
list.append(letter22, word_list[i])
if x == 'a':
list.append(letterA22, word_list[i])
if x == 'b':
list.append(letterB22, word_list[i])
if x == 'c':
list.append(letterC22, word_list[i])
if x == 'd':
list.append(letterD22, word_list[i])
if x == 'e':
list.append(letterE22, word_list[i])
if x == 'f':
list.append(letterF22, word_list[i])
if x == 'g':
list.append(letterG22, word_list[i])
if x == 'h':
list.append(letterH22, word_list[i])
if x == 'i':
list.append(letterI22, word_list[i])
if x == 'j':
list.append(letterJ22, word_list[i])
if x == 'k':
list.append(letterK22, word_list[i])
if x == 'l':
list.append(letterL22, word_list[i])
if x == 'm':
list.append(letterM22, word_list[i])
if x == 'n':
list.append(letterN22, word_list[i])
if x == 'o':
list.append(letterO22, word_list[i])
if x == 'p':
list.append(letterP22, word_list[i])
if x == 'q':
list.append(letterQ22, word_list[i])
if x == 'r':
list.append(letterR22, word_list[i])
if x == 's':
list.append(letterS22, word_list[i])
if x == 't':
list.append(letterT22, word_list[i])
if x == 'u':
list.append(letterU22, word_list[i])
if x == 'v':
list.append(letterV22, word_list[i])
if x == 'w':
list.append(letterW22, word_list[i])
if x == 'x':
list.append(letterX22, word_list[i])
if x == 'y':
list.append(letterY22, word_list[i])
if x == 'z':
list.append(letterZ22, word_list[i])
if len(word_list[i]) == 23:
list.append(letter23, word_list[i])
if x == 'a':
list.append(letterA23, word_list[i])
if x == 'b':
list.append(letterB23, word_list[i])
if x == 'c':
list.append(letterC23, word_list[i])
if x == 'd':
list.append(letterD23, word_list[i])
if x == 'e':
list.append(letterE23, word_list[i])
if x == 'f':
list.append(letterF23, word_list[i])
if x == 'g':
list.append(letterG23, word_list[i])
if x == 'h':
list.append(letterH23, word_list[i])
if x == 'i':
list.append(letterI23, word_list[i])
if x == 'j':
list.append(letterJ23, word_list[i])
if x == 'k':
list.append(letterK23, word_list[i])
if x == 'l':
list.append(letterL23, word_list[i])
if x == 'm':
list.append(letterM23, word_list[i])
if x == 'n':
list.append(letterN23, word_list[i])
if x == 'o':
list.append(letterO23, word_list[i])
if x == 'p':
list.append(letterP23, word_list[i])
if x == 'q':
list.append(letterQ23, word_list[i])
if x == 'r':
list.append(letterR23, word_list[i])
if x == 's':
list.append(letterS23, word_list[i])
if x == 't':
list.append(letterT23, word_list[i])
if x == 'u':
list.append(letterU23, word_list[i])
if x == 'v':
list.append(letterV23, word_list[i])
if x == 'w':
list.append(letterW23, word_list[i])
if x == 'x':
list.append(letterX23, word_list[i])
if x == 'y':
list.append(letterY23, word_list[i])
if x == 'z':
list.append(letterZ23, word_list[i])
if len(word_list[i]) == 24:
list.append(letter24, word_list[i])
if x == 'a':
list.append(letterA24, word_list[i])
if x == 'b':
list.append(letterB24, word_list[i])
if x == 'c':
list.append(letterC24, word_list[i])
if x == 'd':
list.append(letterD24, word_list[i])
if x == 'e':
list.append(letterE24, word_list[i])
if x == 'f':
list.append(letterF24, word_list[i])
if x == 'g':
list.append(letterG24, word_list[i])
if x == 'h':
list.append(letterH24, word_list[i])
if x == 'i':
list.append(letterI24, word_list[i])
if x == 'j':
list.append(letterJ24, word_list[i])
if x == 'k':
list.append(letterK24, word_list[i])
if x == 'l':
list.append(letterL24, word_list[i])
if x == 'm':
list.append(letterM24, word_list[i])
if x == 'n':
list.append(letterN24, word_list[i])
if x == 'o':
list.append(letterO24, word_list[i])
if x == 'p':
list.append(letterP24, word_list[i])
if x == 'q':
list.append(letterQ24, word_list[i])
if x == 'r':
list.append(letterR24, word_list[i])
if x == 's':
list.append(letterS24, word_list[i])
if x == 't':
list.append(letterT24, word_list[i])
if x == 'u':
list.append(letterU24, word_list[i])
if x == 'v':
list.append(letterV24, word_list[i])
if x == 'w':
list.append(letterW24, word_list[i])
if x == 'x':
list.append(letterX24, word_list[i])
if x == 'y':
list.append(letterY24, word_list[i])
if x == 'z':
list.append(letterZ24, word_list[i])
for i in range(len(word_list)):
x = word_list[i]
x = x.lower()
x = x[0]
if x == 'a':
list.append(letterA, word_list[i])
if x == 'b':
list.append(letterB, word_list[i])
if x == 'c':
list.append(letterC, word_list[i])
if x == 'd':
list.append(letterD, word_list[i])
if x == 'e':
list.append(letterE, word_list[i])
if x == 'f':
list.append(letterF, word_list[i])
if x == 'g':
list.append(letterG, word_list[i])
if x == 'h':
list.append(letterH, word_list[i])
if x == 'i':
list.append(letterI, word_list[i])
if x == 'j':
list.append(letterJ, word_list[i])
if x == 'k':
list.append(letterK, word_list[i])
if x == 'l':
list.append(letterL, word_list[i])
if x == 'm':
list.append(letterM, word_list[i])
if x == 'n':
list.append(letterN, word_list[i])
if x == 'o':
list.append(letterO, word_list[i])
if x == 'p':
list.append(letterP, word_list[i])
if x == 'q':
list.append(letterQ, word_list[i])
if x == 'r':
list.append(letterR, word_list[i])
if x == 's':
list.append(letterS, word_list[i])
if x == 't':
list.append(letterT, word_list[i])
if x == 'u':
list.append(letterU, word_list[i])
if x == 'v':
list.append(letterV, word_list[i])
if x == 'w':
list.append(letterW, word_list[i])
if x == 'x':
list.append(letterX, word_list[i])
if x == 'y':
list.append(letterY, word_list[i])
if x == 'z':
list.append(letterZ, word_list[i])
for i in range(len(word_list)):
x = word_list[i]
if 'a' in x.lower():
list.append(contains_letterA, word_list[i])
if 'b' in x.lower():
list.append(contains_letterB, word_list[i])
if 'c' in x.lower():
list.append(contains_letterC, word_list[i])
if 'd' in x.lower():
list.append(contains_letterD, word_list[i])
if 'e' in x.lower():
list.append(contains_letterE, word_list[i])
if 'f' in x.lower():
list.append(contains_letterF, word_list[i])
if 'g' in x.lower():
list.append(contains_letterG, word_list[i])
if 'h' in x.lower():
list.append(contains_letterH, word_list[i])
if 'i' in x.lower():
list.append(contains_letterI, word_list[i])
if 'j' in x.lower():
list.append(contains_letterJ, word_list[i])
if 'k' in x.lower():
list.append(contains_letterK, word_list[i])
if 'l' in x.lower():
list.append(contains_letterL, word_list[i])
if 'm' in x.lower():
list.append(contains_letterM, word_list[i])
if 'n' in x.lower():
list.append(contains_letterN, word_list[i])
if 'o' in x.lower():
list.append(contains_letterO, word_list[i])
if 'p' in x.lower():
list.append(contains_letterP, word_list[i])
if 'q' in x.lower():
list.append(contains_letterQ, word_list[i])
if 'r' in x.lower():
list.append(contains_letterR, word_list[i])
if 's' in x.lower():
list.append(contains_letterS, word_list[i])
if 't' in x.lower():
list.append(contains_letterT, word_list[i])
if 'u' in x.lower():
list.append(contains_letterU, word_list[i])
if 'v' in x.lower():
list.append(contains_letterV, word_list[i])
if 'w' in x.lower():
list.append(contains_letterW, word_list[i])
if 'x' in x.lower():
list.append(contains_letterX, word_list[i])
if 'y' in x.lower():
list.append(contains_letterY, word_list[i])
if 'z' in x.lower():
list.append(contains_letterZ, word_list[i])
print(opening)
|
import numpy as np
"""
创建Numpy数组
"""
print('使用普通一维数组生成NumPy一维数组')
data = [1, 2, 3.2, 4, 7]
arr = np.array(data)
print(arr)
print('元素类型:',arr.dtype)
print()
print('使用普通二维数组生成NumPy二维数组')
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arr = np.array(data)
print(arr)
print('数组维度:',arr.shape)
print()
"""
zeros(),zeros_like(),ones(),ones_like(),empty(),empty_like(),
"""
print('使用zeros/empty')
# 语法格式numpy.zeros(shape, dtype=float, order='C')
print(np.zeros(6)) # 生成包含6个0的一维数组
print(np.zeros((3, 6))) # 生成3*6的二维数组
print(np.zeros_like(arr)) # 根据arr数组形状与类型创建数据全为0的数组
print(np.empty((2, 3, 2))) # 生成2*3*2的三维数组,所有元素未初始化。注意与zeros区分。
print(np.eye(5,5,1)) # 生成N*M(默认N=M)对角线矩阵,第三个参数指定对角线位置。
print(np.identity(5)) # 生成N*N对角线矩阵
print()
print('使用arrange生成连续元素')
print(np.arange(15)) # [0, 1, 2, ..., 14]
# 打印结果
"""
使用普通一维数组生成NumPy一维数组
[1. 2. 3.2 4. 7. ]
元素类型: float64
使用普通二维数组生成NumPy二维数组
[[1 2 3 4]
[5 6 7 8]]
数组维度: (2, 4)
使用zeros/empty
[0. 0. 0. 0. 0. 0.]
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
[[0 0 0 0]
[0 0 0 0]]
[[[1.81064342e-295 2.13945865e+161]
[4.59220660e-072 5.98129763e-154]
[1.06758000e+224 4.46811730e-091]]
[[5.98149672e-154 7.50187034e+247]
[1.96097649e+243 3.03736202e+180]
[3.55455412e+180 6.01347002e-154]]]
[[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]
[0. 0. 0. 0. 0.]]
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]
使用arrange生成连续元素
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
请按任意键继续. . .
""" |
def get_images_and_labels(img_dict):
"""
Given an img_dict, creates two lists img_labels and img_list
Generally img_dict is modelled as to contain label as key
and the key's value contains a list which has all the
images present in the category.
Parameters:
img_dict - dictionary with keys containing label category
and corresponding values containing images
in that category.
Returns:
(img_list, img_labels)
img_labels: contains labels of all the images.
img_list: contains list of all images.
"""
img_labels = []
img_list = []
for key in img_dict.keys():
for img in img_dict[key]:
img_labels.append(key)
img_list.append(img)
return (img_list, img_labels)
# TODO: Changes for imporovement:
# Do something instead of 2 loops.
|
'''
Exemplo de aplicação das fórmulas de predador-presa com o método de Runge-Kutta de 4 ordem
importando os métodos do módulo que está nessa mesma pasta.
Exemplo aplicado:
problema 27.22 do livro Chapra Canale Métodos Numéricos para engenharia
'''
from RK4predadorpresa import *
x = 2
y = 1
t = 0
tStop = 30
h = 0.1
a = 1.5
b = 0.7
c = 0.9
d = 0.4
t, x, y = integrationPredadorPresa(predador, presa, t, x, y, h, tStop, a, b, c, d)
plt.plot(t, x, '-', t, y, '--')
plt.grid(True)
plt.xlabel('tempo'); plt.ylabel('presador/presa');
plt.legend(('presa', 'predador'), loc=0)
plt.show()
|
'''
Nesse código, uma funcao que calcula o K1 do metodo
RungeKutta de 2 ordem para que o próximo y seja calculado:
yi+1 = y + K1
No final tem um comentário com um exemplo de aplicação
com a equação =>
y' = sen(y)
y(0) = 1
Exemplo 7.3 livro Kiusalaas Numerical python
'''
import numpy as np
import math
def integrateRK2(F, xi, yi, h, xStop):
def RK2(F, xi, yi, h):
K0 = h*F(xi, yi)
K1 = h*F(xi + h/2, yi + (1/2)*K0)
return K1
X = []
Y = []
K = []
X.append(xi)
Y.append(yi)
while xi < xStop:
h = min(h, xStop - xi)
K.append(RK2(F, xi, yi, h))
yi = yi + RK2(F, xi, yi, h)
xi = xi + h
X.append(xi)
Y.append(yi)
return np.array(X), np.array(Y), np.array(K)
'''
h = 0.1
x = 0
xStop = 0.5
y = 1
def F(x, y):
return math.sin(y)
X,Y,K = integrateRK2(F, x, y, h, xStop)
print(X, Y, K)
'''
|
"""
Author: Vivek Rana
Usage : Just run the script in a Python enabled computer.
Date : 12-Aug-2016
"""
def findPrime(N):
while( N%2 == 0):
N = N//2
if N == 1:
return 2
i = 3
sqrtN = int(N**0.5)
while(i<=sqrtN and i<N):
if (N%i == 0):
N = N//i
i = 3
else:
i += 2
if N > 2:
return N
else:
return i
def main():
for T in range(int(input("Test cases : "))):
N = int(input("Number "+str(T+1)+" : "))
print(findPrime(N))
return
if __name__ == '__main__': #IF the script is called from cmd or directly executed
main()
input('Press any key to exit.')
|
#This program tells if a number is pallindrome or not
#This program is made by Saksham Gupta
#This function makes sure input is a positive integer
def IntegerGetter(str):
while True:
try:
num = int(input(str))
except ValueError:
print("That's not an Integer. Please Enter Details again.")
else:
if num>=0:
return num
else:
print("Please enter a correct number.")
#Input
num = IntegerGetter("Enter a number you want to check is pallindrome or not: ")
#process
y = num
z=0
while y>0:
z =z*10+ (y%10)
y //=10
#Output
if z==num:
print(f"The number {num} is a Pallindrome number.")
else:
print(f"The number {num} is not a Pallindrome number.") |
#This program makes a pascal triangle
#This program is made by Saksham Gupta
#This function makes sure input is a positive integer
def IntegerGetter(str):
while True:
try:
num = int(input(str))
except ValueError:
print("That's not an Integer. Please Enter Details again.")
else:
if num>=0:
return num
else:
print("Please enter a correct number.")
def pascalrow(int):
if int==1:
return [1]
row=[1,1]
for i in range(0,len(pascalrow(int-1))):
try:
n=pascalrow(int-1)[i]+pascalrow(int-1)[i+1]
except:
pass
else:
n = pascalrow(int - 1)[i] + pascalrow(int - 1)[i + 1]
row.insert(i+1,n)
return row
#Input
num = IntegerGetter("Enter a number till which you want the patterns: ")
#Output
for i in range(1,num+1):
leng= len(pascalrow(num))
print(((leng-len(pascalrow(i))))*" ",end="")
for k in pascalrow(i):
print(k,end=" ")
print() |
import random
def guess_number(number):
while True:
input_number = int(raw_input('Input your number:\n'))
if input_number > number:
print "Your number is bigger"
elif input_number < number:
print "Your number is smaller"
else:
print "Bingo"
break
def main():
print "--------Begin Game--------"
while True:
number = random.randint(0, 99)
guess_number(number)
ans = ''
while True:
ans = raw_input('Do you want to continue? [yes/no]\n')
if ans in ['yes', 'no']:
break
else:
print 'Invaild input'
if ans == 'no':
print '--------Game over--------'
break
if __name__ == '__main__':
main()
|
from data_structures import Queue
from factories import stack_factory
def interleave_stack(stack):
'''
This problem was asked by Google.
Given a stack of N elements, interleave the first half of the stack with the second half reversed using only one other queue. This should be done in-place.
Recall that you can only push or pop from a stack, and enqueue or dequeue from a queue.
For example, if the stack is [1, 2, 3, 4, 5], it should become [1, 5, 2, 4, 3]. If the stack is [1, 2, 3, 4], it should become [1, 4, 2, 3].
'''
stack_size = 0
queue = Queue()
while True:
try:
queue.enqueue(stack.pop())
stack_size += 1
except IndexError:
break
while True:
try:
stack.push(queue.dequeue())
except IndexError:
break
while True:
try:
queue.enqueue(stack.pop())
except IndexError:
break
while True:
try:
stack.push(queue.dequeue())
except IndexError:
break
for regurgitation_size in range(stack_size - 1, 0, -1):
for _ in range(regurgitation_size):
queue.enqueue(stack.pop())
for _ in range(regurgitation_size):
stack.push(queue.dequeue())
return stack
if __name__ == "__main__":
assert interleave_stack(stack_factory([])) == stack_factory([])
assert interleave_stack(stack_factory([1, 2, 3, 4, 5])) == stack_factory([1, 5, 2, 4, 3])
assert interleave_stack(stack_factory([1])) == stack_factory([1])
assert interleave_stack(stack_factory([1, 2, 3, 4])) == stack_factory([1, 4, 2, 3])
assert interleave_stack(stack_factory([1, 2])) == stack_factory([1, 2])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.