text stringlengths 37 1.41M |
|---|
# A heap is a complete binary tree
# A complete binary tree's leaf level is all left skewed with no gaps in between and all nodes in previous level should have two children always
# Heap is also a priority queue
# it's queue except every nodes has a priority and the node with the highest priority is the one that is first to be extracted
# Key functions:
# insertions - log(n) because of shifting down
# max/min lookup - O(1) because max/min is always at the root
# deletion/extraction - log(n) ; you can only delete the root and then shifting up
# Max heap - the key at each node is at least as great as the keys stored at its children
# Min heap - the key at each node is at most as the keys stored at its children
import itertools
import heapq
def top_k(k, stream): # stream is an iterable object
# itertools.islice(iterable, stop) / itertools.islice(iterable, start, stop)
# ref -> https://docs.python.org/2/library/itertools.html#itertools.islice
# Why itertools.islice over normal slicing?
# ref -> https://stackoverflow.com/questions/32172612/why-would-i-want-to-use-itertools-islice-instead-of-normal-list-slicing
min_heap = [(len(s), s) for s in itertools.islice(stream, k)] # an list of tuples
heapq.heapify(min_heap) # it seems it will heapify using value at the idx 0 if each element is an iterable themselves
# heapq always creates a min heap. If max heap is needed, then flip the signs of the values
for next_string in stream: # because stream is an iterable object, the iteration for this loop will start after where line 23 left off
heapq.heappushpop(min_heap, (len(next_string), next_string))
return [p[1] for p in heapq.nsmallest(k, min_heap)]
# heapq library:
# ref -> https://docs.python.org/3/library/heapq.html
# -> heapq.heapify(L) - transforms the elements in L into a heap in-place
# -> heapq.nlargest(k, L) / heapq.nsmallest(k, L) - returns k largest / smallest list of elements in the iterable L which can be a heap
# -> heapq.heappush(h, e) - pushes a new element, e on the heap, h
# -> heapq.heappop(h) - pops the smallest element from the heap
# -> heapq.heapushpop(h, a) - pushes on the heap and then pops and returns the smallest element
# -> e = h[0] - returns smallest element on the heap without popping it
class Heap:
def __init__(self, iterable, type="min"):
self.iterable = []
self.type = type
for idx, element in iterable:
self.push(element, idx)
def peek(self):
return self.iterable[0]
def push_pop(self, element, idx=None):
self.push(element)
return self.pop()
def push(self, element, idx=None):
if not idx:
idx = len(self.iterable) - 1
self.iterable.append(element)
self.shift_up(idx)
def shift_up(self, idx):
if idx <= 0:
return
parent_idx = (idx - 2)/2 if idx % 2 == 0 else (idx-1)/2
if self.iterable[idx] < self.iterable[parent_idx] and self.type == "min":
self.iterable[idx], self.iterable[parent_idx] = self.iterable[parent_idx], self.iterable[idx]
if self.iterable[idx] > self.iterable[parent_idx] and self.type == "max":
self.iterable[idx], self.iterable[parent_idx] = self.iterable[parent_idx], self.iterable[idx]
self.shift_up(parent_idx)
def pop(self):
self.iterable[0], self.iterable[-1] = self.iterable[-1], self.iterable[0]
popped = self.iterable.pop()
self.shift_down(0)
return popped
def shift_down(self, idx):
if idx >= len(self.iterable):
return
left_child = self.iterable[2*idx+1]
right_child = self.iterable[2*idx+2]
if left_child and right_child:
if self.type == "min":
if left_child < right_child and left_child < self.iterable[idx]:
self.iterable[2*idx+1], self.iterable[idx] = self.iterable[idx], self.iterable[2*idx+1]
self.shift_down(2*idx+1)
elif right_child < left_child and right_child < self.iterable[idx]:
self.iterable[2*idx+2], self.iterable[idx] = self.iterable[idx], self.iterable[2*idx+2]
self.shift_down(2*idx+2)
elif self.type == "max":
if left_child > right_child and left_child > self.iterable[idx]:
self.iterable[2*idx+1], self.iterable[idx] = self.iterable[idx], self.iterable[2*idx+1]
self.shift_down(2*idx+1)
elif right_child > left_child and right_child > self.iterable[idx]:
self.iterable[2*idx+2], self.iterable[idx] = self.iterable[idx], self.iterable[2*idx+2]
self.shift_down(2*idx+2)
elif left_child:
if left_child < right_child and left_child < self.iterable[idx] and self.type == "min":
self.iterable[2*idx+1], self.iterable[idx] = self.iterable[idx], self.iterable[2*idx+1]
self.shift_down(2*idx+1)
elif left_child > right_child and left_child > self.iterable[idx] and self.type == "max":
self.iterable[2*idx+1], self.iterable[idx] = self.iterable[idx], self.iterable[2*idx+1]
self.shift_down(2*idx+1)
|
# Remove and replace
# Prompt:
# 1) Replace each "a" by two "d"s
# 2) Delete each entry containing a "b"
# Input:
# -> an array of characters
# -> an integer that denotes the number of entries of the array that the operation
# is to be applied to
# Note: One can assume there is enough space in the array to hold the final result
# Example:
# ["a", "c", "d", "b", "b", "c", "a"] , 7 => ["d", "d", "c", "d", "c", "d", "d"]
# ["a", "b", "a", "c", "o"] , 4 => ["d", "d", "d", "d", "c"]
# ["a", "c", "a", "a", "v", "z", "p"] , 4 => ["d", "d", "c", "d", "d", "d", "d"]
def replace_and_remove(size, s):
# below is essentially a filter in place
write_idx, a_count = 0, 0
for i in range(size):
if s[i] != "b":
s[write_idx] = s[i]
write_idx += 1
if s[i] == "a":
a_count += 1
# below handles the replace from the back
curr_idx = write_idx - 1
# 1 less because of the trailing incrementation of write_idx from the
# previous loop
write_idx += a_count - 1
# -> the write_idx for this loop will start from the back which is why the
# a_count is added in anticipation of the extra indices needed for replacing
# elements
# -> 1 less again because of the trailing incrementation of write_idx
while curr_idx >= 0:
if s[curr_idx] == "a":
s[write_idx-1:write_idx+1] = "dd"
write_idx -= 2
else:
s[write_idx] = s[curr_idx]
write_idx -= 1
curr_idx -= 1
final_size = write_idx + 1
return s[-final_size:]
print(replace_and_remove(7, ["a", "c", "d", "b", "b", "c", "a"]))
print(replace_and_remove(4, ["a", "b", "a", "c", "o"]))
print(replace_and_remove(4, ["a", "c", "a", "a", "v", "z", "p"]))
# losing infomation due to clash or over lap between curr_idx and write_idx
# is not expected because of the assumption given to us from the prompt that is
# there will be always enough space in the given array to have the final array.
# Therefore, proper inputs to make sure that happens are expected with respect
# to that assumption. |
#!/usr/bin/python
#Solution for printing groups of similar words
import re
import collections
import Trie
import makegroups
import fileutils
#getting dictionary containing word vs list of words similar to key
#internally used trie
similarWords = fileutils.getSimilarWordDictionary()
groupingUtils = makegroups.GroupingUtil()
groups = []
for w in similarWords.keys():
#getting set containing groups(list) of words all similar to each other
set = groupingUtils.findgroup(similarWords,w)
if set:
for list in set:
if list not in groups:
groups.append(list)
print(list)
|
print(" *** WELCOME TO KM->MI OR MI->KM CONVERTOR *** ")
method=0
km=0
mi=0
ratio= 0.621371 #1Km = 0.621371 miles
while (method!=1 and method !=2):
print("Enter 1 to convert Kilometers to Miles")
print("Enter 2 to convert Miles to Kilometers")
try:
method = int(input("Your choice : "))
except:
print("Please enter a valid number! ")
if (method==1):
while km==0:
try:
km = int(input("Enter the value in kilometers to convert : "))
except:
print("Please enter a valid number! ")
mi = km*ratio
format_mi = "{:.2f}".format(mi) # format our value to only have 2 decimals
print(km, "km in miles : ", format_mi, "mile")
if (method==2):
while mi==0:
try:
mi = int(input("Enter the value in miles to convert : "))
except:
print("Please enter a valid number! ")
km = mi/ratio
format_km = "{:.2f}".format(km)
print(mi, "mile in kilometers : ", format_km, "km") |
print(" *** WELCOME TO LEAP YEAR PROGRAM *** ")
year=0
leap=False
while year<500:
try:
year = int(input("Enter the year : "))
except:
print("Please enter a valid year! ")
if (year%4)==0:
if (year%100)==0:
if (year%400)==0:
leap=True
else:
leap=True
if leap==True:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year)) |
# the function anagram will identify if words contain the same letter
def anagram(word, word_list):
# the variable sorted_word holds the function sorted() which sorts the word whose anagrams we need
sorted_word = sorted(word)
# ana_gram is a container that holds words with identical letters
ana_gram = []
# 'words' represent words in word_list
# this loop ensures all the words in word_list are checked to know if they are anagrams to sorted_word
for words in word_list:
if sorted_word == sorted(words):
# to add anagrams to the container(list) created
ana_gram.append(words)
return ana_gram
print(anagram('abba', ['aabb', 'abcd', 'bbaa', 'dada']))
print(anagram('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']))
print(anagram('laser', ['lazing', 'lazy', 'lacer']))
|
#!/usr/bin/env pythonw
import argparse
import json
import monte2
import matplotlib.pyplot as plt
# These should be private. Will cover later
# For numeric parameters, these are lower and upper bounds if there are bounds.
# For strings, these are constraints on values if there are any.
trading_days_lbound = 10
trading_days_ubound = 252
trading_years_lbound = 0
trading_years_ubound = 1000
bins_ubound = 20
bins_lbound = 10
valid_y_n = ["Y", "N", "y", "n"]
valid_tickers = ["AAPL", "GOOG", "AMZN"]
general_patience = 2
# Determines if the program is interactive or is running inside something
# like a Jupyter notebook.
def is_interactive():
import __main__ as main
return not hasattr(main, '__file__')
# Default is that the program is not interactive.
# Change from the prompt or a Jupyter cell if is interactive.
interactive = True
interactive = is_interactive()
# Inputs are a prompt string, the upper and lower bounds on the value and the
# number of failed attempts to tolerate.
def safe_get_int(prompt, lbound, ubound, patience):
done = False
result = None
temp = None
tries = 0
# Loop until successful input or have exhausted all the tries.
while (not done) and (tries <= patience):
# The try ... except implements toleration for non-integer inputs.
try:
tries += 1
temp = input(prompt + ":")
temp = int(temp)
if (temp < lbound) or (temp > ubound):
print("Valid range is " + str(lbound) + " to " + str(ubound) + " Try again.")
else:
done = True
result = temp
except TypeError as ve:
# Not an integer. Will try again.
# Will print a specific error message.
print("Input must be an integer.")
except Exception as e:
# Not sure what happened but will try again.
print("Got an expected exception. Trying again.")
# Did the function fail in getting a valid input?
if not done:
# Not my finest error message.
print("Prepare to die fool!")
raise ValueError
return result
# Prompts for a string input. The inputs are:
# - prompt message
# - An optional list of valid inputs.
# - The number of base inputs to tolerate.
def safe_get_string(prompt, valid_values, patience):
done = False
result = None
temp = None
tries = 0
# Loop until valid input or too many failed attempts.
while (not done) and (tries <= patience):
try:
tries += 1
temp = input(prompt + ":")
if not temp in valid_values:
print("Valid values are ", valid_values)
else:
done = True
result = temp
# Should narrow this exception to something more specific
except Exception as e:
print("Got exception. Trying again.")
# Raise input value failure.
if not done:
print("Prepare to die fool!")
raise ValueError
return result
# Double checks all of the input parameters to ensure correctness.
# Input is a dictionary of parameter names and values.
def validate_args(args):
result = True
try:
if args['trading_years'] is None or \
args['trading_days'] is None or \
args['bins'] is None or \
args['ticker'] is None or \
args['plot_to_file'] is None:
result = False
return result
if args['trading_years'] > trading_years_ubound or args['trading_years'] < trading_years_lbound:
result = False
# This and the following error messages should be more complete, e.g. shows bounds.
print("Trading years invalid.")
elif args['trading_days'] > trading_days_ubound or args['trading_days'] < trading_days_lbound:
result = False
print("Trading days invalid.")
elif args['bins'] > bins_ubound or args['bins'] < bins_lbound:
result = False
print("Bins invalid.")
elif args['ticker'] not in valid_tickers:
result = False
print("Ticker invalid.")
elif args['plot_to_file'] not in valid_y_n:
result = False
print("Plot to file invalid.")
except Exception as e:
print("Print something awful happened.",e)
raise ValueError
return result
# Gets and validates the input parameters that define the simulation.
def get_args():
result = None
# If the program is not interactive, parse the arguments.
# The help messages should be more descriptive.
if not interactive:
parser = argparse.ArgumentParser(
description='Monte Carlo GBM simulation of stock price evolution..')
parser.add_argument('--ticker', default=None, type=str, metavar='str',
help='Ticker to simulate')
parser.add_argument('--trading_days', default=None, type=int, metavar='int',
help='Number of trading days per year.')
parser.add_argument('--trading_years', default=None, type=int, metavar='int',
help='Number of random years to simulate.')
parser.add_argument('--bins', default=20, type=int, metavar='int',
help='Number of bins for return histogram')
parser.add_argument('--plot_to_file', default="N", type=str, metavar='str',
help='Write charts to file?')
parser.add_argument('--simulation_label', default="default", type=str, metavar='str',
help='Label for simulation.')
args = parser.parse_args()
result = vars(args)
else:
# The program is interactive. Will use prompts.
result = {}
# Notice that the code below is very highly patterned. I could simply into a parameterized procedures
# that incorporates the two steps, which would be less error prone.
temp = safe_get_string("Enter ticker:", valid_tickers, general_patience)
result = {"ticker": temp}
temp = safe_get_int("Enter no. of trading days", trading_days_lbound, trading_days_ubound, general_patience)
result['trading_days'] = temp
temp = safe_get_int("Number of years to simulate", trading_years_lbound, \
trading_years_ubound, general_patience)
result['trading_years'] = temp
temp = safe_get_int("Enter no. of histogram bins", bins_lbound, bins_ubound,general_patience)
result['bins'] = temp
temp = input("Plot to file (Y/N):")
result['plot_to_file'] = temp
temp = input("Simulation label:")
result['simulation_label'] = temp
return result
# Plots the yearly returns
# If n is not none, this is the file to plot to.
def year_plot(yy,n):
plt.figure(figsize=(20, 10))
for i in range(0, len(yy)):
plt.plot(yy[i])
if n is not None:
plt.savefig(n)
else:
plt.show()
plt.close()
# Plots the histogram of returns
# If n is not none, this is the file to plot to.
def histo_return(yy, b, n):
r = []
for i in range(0,len(yy)):
t = yy[i]
t = t[-1]
r.append(t)
# print(r)
plt.figure(figsize=(20, 10))
plt.hist(r,b)
if n is not None:
plt.savefig(n)
else:
plt.show()
plt.close()
def run_simulation(args):
print("Running simulations with parameters:\n")
print(json.dumps(args,indent=2))
result = monte2.run_simulations(args['ticker'], args['trading_days'], args['trading_years'])
if args['plot_to_file'] == 'Y':
fy = args['simulation_label'] + "_years.png"
fh = args['simulation_label'] + "_histo.png"
else:
fy = None
fh = None
# print("Years = ", result)
year_plot(result, fy)
histo_return(result, args['bins'], fh)
return result
# This module should/could be callable from other main programs. The other main programs may pass in parameters.
def configure_and_run_simulation(args):
if validate_args(args):
run_simulation(args)
else:
raise ValueError("Invalid input parameters.")
# The main program if the simulation is running standalone.
def run_it():
args = get_args()
if validate_args(args):
print("On the way.")
run_simulation(args)
else:
print("Got an error.")
#interactive = True
#run_it()
if not interactive:
run_it() |
import BInaryTree
import queue
class PaperFolding:
def __init__(self, N):
self.N = N
self.tree = BInaryTree.BinaryTree()
def main(self):
#创造二叉树
self.folding_process()
#遍历二叉树
self.midErgodic()
print(self.ls)
def folding_process(self):
if self.tree.root.value == None:
self.tree.root.value = "down"
self.N -= 1
while self.N != 0:
self.__layerEgrodic(self.tree.root)
self.N -= 1
def __insert_node(self, curr):
left_node = BInaryTree.BinaryTree.Node(None, "down", None, None)
right_node = BInaryTree.BinaryTree.Node(None, "up", None, None)
curr.left = left_node
curr.right = right_node
def __layerEgrodic(self, curr):
self.queue = queue.Queue()
self.queue.enqueue(self.tree.root)
#遍历循环队列
while self.queue.size() != 0:
#从队列中弹出一个节点
temp = self.queue.dequeue()
#如果有左子节点,就把左子节点放入队列中
if temp.left != None:
self.queue.enqueue(temp.left)
#如果有右子节点,就把右子节点放入队列中
if temp.right != None:
self.queue.enqueue(temp.right)
#如果啥都没有,向当前节点添加结点
if temp.left == None and temp.right == None:
self.__insert_node(temp)
# 中序遍历
def midErgodic(self):
self.ls = []
self.add_keys_midErgodic(self.tree.root)
return self.ls
# 使用中序遍历,把指定的子树中所有键放到ls中
def add_keys_midErgodic(self, curr_root):
if curr_root.left != None:
self.add_keys_midErgodic(curr_root.left)
self.ls.append(curr_root.value)
if curr_root.right != None:
self.add_keys_midErgodic(curr_root.right)
if __name__ == '__main__':
test = PaperFolding(2)
test.main()
|
#!/usr/bin/python3
#One Dimensional Cellular Automata
#Author: Cristhian Eduardo Fuertes Daza
#Class managing logic and computation of lattice's cells
class CellularAutomata():
#Constructor
#params:
#numCells: the number of cells in each generation
#rule_name: string representing the name of the rule to apply
def __init__(self, numCells, rule_name):
#List of rules
self.__rules = [self.__rule30, self.__rule54, self.__rule60,
self.__rule62, self.__rule90, self.__rule94,
self.__rule102, self.__rule110, self.__rule122,
self.__rule126,self.__rule150, self.__rule158,
self.__rule182, self.__rule188, self.__rule190,
self.__rule220, self.__rule222, self.__rule250]
self.__numCells = numCells
self.__rule_ind = self.__determinate_rule_ind(rule_name)
#Uses the name of the rule to determinate the location in the
#rule's list
def __determinate_rule_ind(self, rule_name):
if rule_name == "Rule 30":
return 0
elif rule_name == "Rule 54":
return 1
elif rule_name == "Rule 60":
return 2
elif rule_name == "Rule 62":
return 3
elif rule_name == "Rule 90":
return 4
elif rule_name == "Rule 94":
return 5
elif rule_name == "Rule 102":
return 6
elif rule_name == "Rule 110":
return 7
elif rule_name == "Rule 122":
return 8
elif rule_name == "Rule 126":
return 9
elif rule_name == "Rule 150":
return 10
elif rule_name == "Rule 158":
return 11
elif rule_name == "Rule 182":
return 12
elif rule_name == "Rule 188":
return 13
elif rule_name == "Rule 190":
return 14
elif rule_name == "Rule 220":
return 15
elif rule_name == "Rule 222":
return 16
elif rule_name == "Rule 250":
return 17
#Applies corresponding rule to the cells
#param:
#cell_list -> list of cells to apply rule
#matrix -> 2-dimensional array representing the lattice
#lattice -> lattice of button cells
#generation -> the current generation
def apply_rule(self, cell_list, matrix, lattice, generation):
rule = self.__rules[self.__rule_ind]
for k in range(0, len(cell_list)):
cellpos = cell_list[k]
rule(matrix, lattice, cellpos, generation)
def __rule250(self, matrix, lattice, cellPos, generation):
if matrix[generation][cellPos] == 1:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
elif matrix[generation][cellPos] == 0:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
def __rule122(self, matrix, lattice, cellPos, generation):
if matrix[generation][cellPos] == 1:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(1)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(2)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
# print(3)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(4)
elif matrix[generation][cellPos] == 0:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(5)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(6)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(7)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
def __rule222(self, matrix, lattice, cellPos, generation):
if matrix[generation][cellPos] == 1:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(1)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(2)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
# print(3)
else:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(4)
elif matrix[generation][cellPos] == 0:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(5)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(6)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(7)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
def __rule110(self, matrix, lattice, cellPos, generation):
if matrix[generation][cellPos] == 1:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(1)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(2)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
# print(3)
else:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(4)
elif matrix[generation][cellPos] == 0:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(5)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(6)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(7)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
def __rule220(self, matrix, lattice, cellPos, generation):
if matrix[generation][cellPos] == 1:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(1)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(2)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
# print(3)
else:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(4)
elif matrix[generation][cellPos] == 0:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(5)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(6)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(7)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
def __rule102(self, matrix, lattice, cellPos, generation):
if matrix[generation][cellPos] == 1:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(1)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(2)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
# print(3)
else:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(4)
elif matrix[generation][cellPos] == 0:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(5)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(6)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(7)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
def __rule190(self, matrix, lattice, cellPos, generation):
if matrix[generation][cellPos] == 1:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(1)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(2)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
# print(3)
else:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(4)
elif matrix[generation][cellPos] == 0:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(5)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(6)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(7)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
def __rule94(self, matrix, lattice, cellPos, generation):
if matrix[generation][cellPos] == 1:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
else:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
elif matrix[generation][cellPos] == 0:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
def __rule188(self, matrix, lattice, cellPos, generation):
if matrix[generation][cellPos] == 1:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(1)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(2)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
# print(3)
else:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(4)
elif matrix[generation][cellPos] == 0:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(5)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(6)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(7)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
def __rule90(self, matrix, lattice, cellPos, generation):
if matrix[generation][cellPos] == 1:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
elif matrix[generation][cellPos] == 0:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
def __rule182(self, matrix, lattice, cellPos, generation):
if matrix[generation][cellPos] == 1:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(1)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(2)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
# print(3)
else:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(4)
elif matrix[generation][cellPos] == 0:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(5)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(6)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(7)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
def __rule62(self, matrix, lattice, cellPos, generation):
if matrix[generation][cellPos] == 1:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(1)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(2)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
# print(3)
else:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(4)
elif matrix[generation][cellPos] == 0:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(5)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(6)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(7)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
def __rule158(self, matrix, lattice, cellPos, generation):
if matrix[generation][cellPos] == 1:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(1)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(2)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
# print(3)
else:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(4)
elif matrix[generation][cellPos] == 0:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(5)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(6)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(7)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
def __rule60(self, matrix, lattice, cellPos, generation):
if matrix[generation][cellPos] == 1:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(1)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(2)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
# print(3)
else:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(4)
elif matrix[generation][cellPos] == 0:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(5)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(6)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(7)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
def __rule150(self, matrix, lattice, cellPos, generation):
if matrix[generation][cellPos] == 1:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(1)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(2)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
# print(3)
else:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(4)
elif matrix[generation][cellPos] == 0:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(5)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(6)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(7)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
def __rule54(self, matrix, lattice, cellPos, generation):
if matrix[generation][cellPos] == 1:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(1)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(2)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
# print(3)
else:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(4)
elif matrix[generation][cellPos] == 0:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(5)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(6)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(7)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
def __rule126(self, matrix, lattice, cellPos, generation):
if matrix[generation][cellPos] == 1:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
#print(1)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(2)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
# print(3)
else:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(4)
elif matrix[generation][cellPos] == 0:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(5)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(6)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
#print(7)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
def __rule30(self, matrix, lattice, cellPos, generation):
if matrix[generation][cellPos] == 1:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
else:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
elif matrix[generation][cellPos] == 0:
if matrix[generation][cellPos - 1] == 1 and matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
elif matrix[generation][cellPos - 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
elif matrix[generation][cellPos + 1] == 1:
matrix[generation + 1][cellPos] = 1
lattice.get_child_at(cellPos, generation + 1).set_opacity(0.0)
else:
matrix[generation + 1][cellPos] = 0
lattice.get_child_at(cellPos, generation + 1).set_opacity(1.0)
|
# Document at least 3 use cases of static methods
"""
Static methods do not take the 'self' or 'cls' parameters although they can take any number of arguments.
They cannot modify object or class state except when called by class or instance methods. In this wise,
they can be called helper functions which is one way to use them. However, they are primarily a way to
namespace methods
"""
# A class of circles
class Cirlce:
def __init__(self, radius, circumference = 0, area = 0):
self.radius = radius
self.area = area
self.circumference = circumference
def calculate_area(self):
self.area = (2 * math.pi) * (self.radius ** 2)
return self.area
def calculate_circumference(self):
self.circumference = (2 * math.pi) * self.calculate_diameter(self.radius)
return self.circumference
@staticmethod
def calculate_diameter(radius):
return 2 * radius |
class Quick_sort():
def __init__(self, array):
self.quick_sort(array)
def quick_sort(self, array):
tamanho = len(array)
self.quick_recursivo(array,0,tamanho-1)
def quick_recursivo(self, array,primeiro_elemento,ultimo_elemento):
if primeiro_elemento<ultimo_elemento:
splitpoint = self.partition(array,primeiro_elemento,ultimo_elemento)
self.quick_recursivo(array,primeiro_elemento,splitpoint-1)
self.quick_recursivo(array,splitpoint+1,ultimo_elemento)
def partition(self, array,primeiro_elemento,ultimo_elemento):
pivot = array[primeiro_elemento]
done = False
marador_esquerdo = primeiro_elemento+1
marador_direito = ultimo_elemento
while not done:
while ((marador_esquerdo <= marador_direito) and (array[marador_esquerdo] <= pivot)): marador_esquerdo = marador_esquerdo + 1
while ((array[marador_direito] >= pivot) and (marador_direito >= marador_esquerdo)):marador_direito = marador_direito -1
if (marador_direito < marador_esquerdo): done = True
else:
array[marador_esquerdo], array[marador_direito] = array[marador_direito], array[marador_esquerdo]
array[primeiro_elemento], array[marador_direito] = array[marador_direito], array[primeiro_elemento]
return marador_direito
pass |
# TODO: Add arithmetic operations
# TODO: Add string/print operations
class PositionBase(object):
def __init__(self, x=0, y=0):
self._x = x
self._y = y
def x(self):
return self._x
def y(self):
return self._y
class Position(PositionBase):
def __init__(self, x=0, y=0, parent=None):
self.parent = parent if parent else PositionBase(x, y)
super(Position, self).__init__(x, y)
def absX(self):
return self._x + self.parent.x()
def absY(self):
return self._y + self.parent.y()
def asTuple(self):
return (self.absX(), self.absY())
|
def maximum_path_sumI(triangle):
if len(triangle) == 1:
return triangle[0][0]
else:
max_item = max_items(triangle[-1]) # => 1 # return max num between every two number in the last arr in triangle
added_item = add_items(max_item, triangle[-2]) # => 2 # add all items in the last arr in triangle to the arr before it
triangle = triangle[0:-2] # pop the last two arrays in triangle because we don't want them anymore
triangle.append(added_item) # add the new array from steps one and two to be the last array in triangle
return maximum_path_sumI(triangle) # pass triangle again to the function # pass triangle again to the function
def max_items(arr):
return [max(arr[i], arr[i+1]) for i in range(len(arr)-1)] # return an array of max num between every two items in an array
def add_items(arr1, arr2):
return [arr1[i]+ arr2[i] for i in range(len(arr1))] # add two arrays to each other
triangle = [ [75, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0],
[95, 64, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0],
[17, 47, 82, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0],
[18, 35, 87, 10, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0],
[20, 4, 82, 47, 65, 0, 0, 0,0, 0, 0, 0, 0, 0, 0],
[19, 1, 23, 75, 3, 34, 0, 0,0, 0, 0, 0, 0, 0, 0],
[88, 2, 77, 73, 7, 63, 67,0,0, 0, 0, 0, 0, 0, 0],
[99, 65, 4, 28, 6, 16, 70, 92, 0, 0, 0, 0, 0, 0, 0],
[41, 41, 26, 56, 83, 40, 80, 70, 33, 0, 0, 0, 0, 0, 0 ],
[41, 48, 72, 33, 47, 32, 37, 16, 94, 29, 0, 0, 0, 0, 0],
[53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14, 0, 0, 0, 0],
[70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57, 0, 0, 0],
[91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48, 0, 0],
[63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31, 0],
[4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23]]
|
from datetime import date
def counting_sundays(first_year, last_year):
sundays = 0
for year in range(first_year, last_year+1):
for month in range(1, 13):
if date(year, month, day=1).weekday() == 6:
sundays += 1
return sundays
|
# this is not the efficient solution for large numbers
def prime_summation(num):
list_of_primes = []
for i in range(2, num):
if is_prime(i):
list_of_primes.append(i)
return sum(list_of_primes)
def is_prime(num):
prime = True
for i in range(2, int(num/2)+1):
if num % i == 0:
prime = False
return prime
'''
Sieve of Eratosthenes Algorithm => the efficient algorithm to find prime numbers below n
def sieve(n):
primes = 2*[False] + [True] * (n -1)
for i in range(2, int(n**0.5+1.5)):
for j in range(i*i, n+1, i):
primes[j] = False
return [prime for prime, checked in enumerate(primes) if checked]
'''
|
#creating a tuple
tup=("mango",66,58.0,"hello world")
# print(tup)
#accessing a tuple
# print(tup[1:])
# print(tup[::-3])
# print(tup[1:2])
# print(tup[0:3])
# print(tup[::-1])
#updation of a tuple ### tuple updation is not possible throws an error coz tuple is immutable
# tup[0]="good morning"
#adding a tuple
# b=("popular","learn python ",55,86.5)
# c=tup+b
# print(c)
#replicating a tuple
# print(tup*5)
#slicing a tuple
# print(tup[1:])
# print(tup[::-3])
# print(tup[1:2])
# print(tup[0:3])
# print(tup[::-1])
# deleting a tuples certain value is not possible ### A complete tuple can be deleted
# del(tup)
###FUNCTIONS OF TUPLE
# print(len(tup))
# converting a list into a tuple
# a=[10,20,30]
# # tuple(a)
# # b=tuple(a)
# # print(b)
var1=("mango ","metro ")
print(min(var1))
var2=(5558,5696965,2255.22,000.258,0.2,6666666666.3)
print(max(var2))
|
# #aceesing a string
# dt="hacker"
# b="software"
# print(dt[0:])
# print(dt[::-1])
# print(dt[:-2])
#concatinating
# data=dt[0:]+"software"
# print(data)
# data=dt+b
# print(data)
# data=dt+"micro"
# print(data)
#replication
# data=dt*5
# print(data)
#slicing
# print(dt[0:4])
# print(dt[-6:-1])
# membership operator
str1="hello python"
str2="my world"
str3="hello python"
print(str1 in str3)
|
#reverse of a string
# str=input("enter a string to reverse:")
# a=len(str)
# for i in reversed(str):
# print(i)
#slicing a string
# s=input("enter a string:")
# print(s[2:5])
#finding the maxium length of a string
# s1,s2=input("string 1:"),input("string2:")
# a,b=len(s1),len(s2)
# if (a>b)&(a!=b):
# print(s1,"is the biggest string and the length is:",a)
# elif(b>a)&(b!=a):
# print(s2,"is the biggest string and the length is:",b)
# else:
# print("Both string1 and string are equal in length")
#Boolean expression
# 1
# a=True and not False
# print(a)
# 2
# b= True and not false
# print(b)
# 3
# c= True or True and False
# print(c)
# 4
# d= not True or not False
# print(d)
# e = True and not 0
# print(e)
# f =52.3 < 52
# print(f)
# 7
# g = 1+52<52.3
# print(g)
# 8
# print(4!=4.0)
# Boolean expressions :
#1
# a,b=4,4
# print(a==b)
# 2
# Operations on a list
#multiplying a list
# lis1=[1,2,3,4,5,6,7,8,9]
# count=1
# for i in lis1:
# a=i*count
# count=a
# print(a)
# num=int(input("Enter the number your want to find the divisiblity:"))
# b=[]
# for i in range(1,100):
# if (i%num==0):
# print("These are numbers divisiblity:",i)
# a=[5445,5646,8,8,9,5,6,7,5,8,88,888,44,5,5,65,1,4,5]
# # b=[4,5,8,4,2,5,8,5,56,5,8,8,8,4,5,5,]
# print(max(a))
# print(min(a))
# dicts={"India":"IN","united states of america":"USA","china":"chn","srilanka":"sl"}
# print(dicts.values())
# print(dicts.keys())
# import os
# f=open("abc.txt","w")
# f.write("Take it easy")
# f.close()
# f=open("abc.txt","r")
# x=f.read()
# print(x)
# f.close()
# class traingle:
# def __init__(self,angle1,angle2,angle3):
# self.angle1=angle1
# self.angle2=angle2
# self.angle3=angle3
# number_of_sides=3
# def check_angles(self):
# if self.angle1+self.angle2+self.angle3==180:
# print(True)
# a=[[1,2],[3,4],[5,6]]
# b=[]
# c=[]
# for i in a:
# c.append(i[0])
# b.append(i[1])
# print(b)
# print(c)
# print(a[0][0]
# dict1={"ram":80,"raj":"shop","rock":90,"fly":"high"}
# b= dict([(value, key)for key,value in dict1.items()])
# print(b)
# Adding a list
# lis1=[1,2,3,"hello"]
# lis2=["good","bad","sing"]
# lis3=["morning","afte"]
# for i in lis2:
# lis1.append(i)
# print(lis1)
# for j in lis3:
# # lis1.append(j)
# lis1.extend(lis2)
# lis1.extend(lis3)
# print(lis1)
x1=int(input('enter the factor'))
def add(a,b):
return a+b
def sub(c,d):
return c-d
def mul(e,f):
return e*f
def div(g,h):
f=float(g)/float(h)
return float(f)
def ADD(A,B,C):
return A+B+C
def SUB(D,E,F):
return D-E-F
def MUL(G,H,I):
return G*H*I
def DIV(J,K,L):
F=float(J)/float(K)/float(L)
return float(F)
if(x1==2):
p2=int(input('enter the value '))
q2=int(input('enter the value'))
n2=int(input('enter 1.add or 2.sub or 3.mul or 4.div'))
if(n2==1):
print (add(p2,q2))
elif(n2==2):
sub(p2,q2)
elif(n2==3):
mul(p2,q2)
elif(n2==4):
div(p2,q2)
else:
'Please enter the proper operation'
elif(x1==3):
p3=int(input('enter the value'))
q3=int(input('enter the value'))
r3=int(input('enter the value'))
n3=int(input('enter 1.add or 2.sub or 3.mul or 4.div'))
if(n3==1):
print (ADD(p3,q3,r3))
elif(n3==2):
print (SUB(p3,q3,r3))
elif(n3==3):
print (MUL(p3,q3,r3))
elif(n3==4):
print (DIV(p3,q3,r3))
else:
print ('Please enter the proper operation')
else:
print('enter the proper factor')
|
#is operator
# a=[2,5,1,2,9,9,6,3]
# y=[9]
# y==9
# print(y is a)
# not is
a=[5,8]
b=[5,8]
print(a is not b) |
# this project is done in collaboration with Jorge Henriquez (https://github.com/penguingovernor)
# this program takes an image and pixelates it!
from PIL import Image
import argparse
import sys
# Get the photo from the command line
parser = argparse.ArgumentParser(description="turns a photo into a ppm file")
parser.add_argument('--photo', dest="photo", metavar='p', type=str)
parser.add_argument('--output', dest="output", metavar='o', type=str)
args = parser.parse_args()
photoStr = args.photo
ppmFile = args.output
# Check if a photo was a passed in.
if photoStr == None:
print("Give me a photo please.")
# In UNIX, exiting with a
# non zero status means that an error occurred.
error = 1
exit(error)
else:
# open the image.
image = Image.open(photoStr)
# gets the ppm header ready
# bytearray is an array of binary values
# encode utf 8 makes sure that the string gets converted correctly from decimal to binary
# They need to be in str
p6 = bytearray("P6\n", "utf-8")
w_h = bytearray("32 32\n", "utf-8")
max_color_brightness = bytearray("255\n", "utf-8")
# New file_file contains the ppmFile
# ppmFile is the ppm file passed in from arguments in the command line
# open the ppmFile and write to it in binary (hence the "wb")
new_file = open(ppmFile, "wb")
# writes to ppmFile to new_file
new_file.write(p6)
new_file.write(w_h)
new_file.write(max_color_brightness)
new_file.flush()
# resize it
image_resized = image.resize((32, 32))
# image_resized.save("whatever.ppm")
# tPixel gets the pixel values of the 32x32 photo
# tPixel is a list of lists, where each sublist contains the [r,g,b] value
# of each individual pixel
tPixel = list(image_resized.getdata())
# iterating through the list of lists in tPixel
# so each pix will contain a sublist i.e. [r,g,b]
for pix in tPixel:
# bytearray turns a decimal sublist into a binary sublist
byt = bytearray(pix)
# and writes it to the new_file
new_file.write(byt)
|
# Creating Files in Python:
# first make a file with txt toward make a text file
# Read a text file by open commands.
# syntax
#r = open('file location','mode')
r = open('c:\myfile.txt', 'r') # r mode is for reading
print(r.read())
# to reprint from start
r.seek(0) # type '0' ZERO which goes first line of the file
print(r.read())
# Writing to Files in Python:~
# first create a blank txt file in drive & save it where you want.
r = open('c:\mynewfile.txt', 'w') # w mode is for writing
r.write('Hello Everyone ,How are you\nHow was the day today') # '\n' is for the new line or next line
r.close()
r = open('c:\mynewfile.txt', 'r')
print(r.read()) |
from langdetect import detect
from langdetect import DetectorFactory
import sys
def getLang(text, set_lang):
try:
DetectorFactory.seed = 0
lang = detect(text)
if lang in ["hi"]:
return lang
elif lang in ["ko", "zh-tw", "zh-cn"]:
return "zh-tw" # default locale - traditional chinese
return "en" # default language - english
except:
print("Exception:", sys.exc_info()[0])
if set_lang == "":
return "en" # revert to default language - en
else:
return set_lang # revert to previous language
if __name__ == "__main__":
inp = input("Enter text:")
l = getLang(inp, "")
print("Detected language:", l) |
#!/usr/bin/env python3
nums = set()
a = 2
while a <= 100:
b = 2
while b <= 100:
nums.add(a**b)
b += 1
a += 1
print(len(nums))
|
#!/usr/bin/env python3
def prime_factors(n):
factors = []
lastresult = n
c = 2
while lastresult != 1:
if lastresult % c == 0 and c % 2 > 0:
factors.append(c)
lastresult /= c
c = c + 1
else:
c = c + 1
return factors
# print prime_factors(13195)
print(max(prime_factors(600851475143)))
|
# Uses python3
import sys
def fibonacci_partial_sum_naive(m, n):
f=[]
m = m % 60
n = n % 60
if n < m:
n = n + m + 1
sum = 0
if n == 1:
return 1
for i in range(n):
if i == 0 or i == 1:
f.append(1)
else:
f.append( (f[i-1] + f[i-2]) % 10)
# if m == 0:
# if i in range (0, n):
# sum = sum + f[i]
if i in range((m - 1) , (n + 1)):
sum = sum + f[i]
return sum % 10
if __name__ == '__main__':
input = sys.stdin.readline();
from_, to = map(int, input.split())
print(fibonacci_partial_sum_naive(from_, to))
|
# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
print("Hello world")
"""
Write a NumPy program to find the number of elements
of an array, length of one array element in bytes and total
bytes consumed by the elements.
"""
import numpy as np
array = np.array([2, 1, 1, 0, 9, 7, 3, 6, 9, 4, 2])
print(f"Number of elements in the array: {array.size}")
print(f"Length of one array element: {array.itemsize} bytes")
print(f"Total Bytes conusmed: {array.nbytes} bytes")
import numpy as np
a = np.array([1,2,3,4,5])
print(a.size)
print(a.itemsize)
print(a.size * a.itemsize)
"""
Write a NumPy program to find the set difference of two
arrays. The set difference will return the sorted, unique
values in array1 that are not in array2.
"""
import numpy as np
array1 = np.array([1, 2, 3, 4, 5, 2, 1, 1, 0, 9, 7, 3, 6, 9, 4, 2])
array2 = np.array([8, 5, 4, 2, 3, 6, 7, 8, 2])
set_difference = np.setdiff1d(array1, array2)
print(set_difference)
a = np.array([5,4,3,2,1])
b = np.array([2,3,4,6])
print(np.setdiff1d(a,b))
"""
Write a NumPy program to compute the cross product
of two given vectors.
"""
import numpy as np
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[2, 3, 4], [4, 5, 6]])
cross_product = np.cross(arr1, arr2)
print(cross_product)
A = np.array([5,6,7])
B = np.array([1,2,3])
output = np.cross(A,B)
print(output)
"""
Write a NumPy program to compute the determinant of
a given square array
"""
import numpy as np
sq_arr = np.array(
[
[
[1, 2, 3],
[2, 3, 4],
[5, 6, 7]
],
[
[1, 2, 3],
[4, 5, 6],
[8, 4, 0]
],
[
[8, 9, 1],
[5, 6, 3],
[6, 2, 7]
]
]
)
det = np.linalg.det(sq_arr)
print(det)
arr = np.array([[6,1,1],[4,-2,5],[2,8,7]])
output_det = np.linalg.det(arr)
print(output_det)
"""
Write a NumPy program to compute the eigenvalues and
right eigenvectors of a given square array.
"""
import numpy as np
sq_arr = np.array([[1, 2], [6, 9]])
eigen_vals, eigen_vectors = np.linalg.eig(sq_arr)
print(f"Eigen Values: {eigen_vals}")
print(f"Eigen Vectors: {eigen_vectors}")
arr = np.array([[6,1,1],[4,-2,5],[2,8,7]])
w,v = np.linalg.eig(arr)
print("eigenvalue",w)
print("eigenvector",v)
"""
Write a NumPy program to multiple three matrices each
of 3*3 dimensions.
"""
import numpy as np
A = np.array([
[1, 2, 3],
[2, 3, 4],
[5, 6, 7]
])
B = np.array([
[5, 6, 7],
[9, 8, 2],
[6, 6, 6]
])
C = np.array([
[5, 3, 2],
[0, 0, 0],
[6, 3, 4]
])
ABC = np.matmul(np.matmul(A, B), C) # (A x B) x C
print(ABC)
arr = np.random.randint(0,10,size=(3,3))
a2 = np.random.randint(0,10,size=(3,3))
a3 = np.random.randint(0,10,size=(3,3))
print(np.matmul(np.matmul(a3,a2),arr))
print(np.dot(np.dot(a3,a2),arr))
|
"""
Name : AbdElrahman Ibrahim Zaki
Email : abdelrahmanzaki.aez@gmail.com
Project : C - Number Guess Game - main file
"""
from function import play
winning_trial = 0
losing_trial = 0
trials = 0
print(" --------- Welcome to Number Guess Game! --------- \n")
winning_trial, losing_trial, trials = play(winning_trial, losing_trial, trials)
print("You played %d game\n\tYour number of wins %d\n\tYour number of losses %d\n" % (trials, winning_trial, losing_trial))
reply = str(input("Play again!! Yes: y No: n "))
while reply == 'y':
winning_trial, losing_trial, trials = play(winning_trial, losing_trial, trials)
print("You played %d game\n\tYour number of wins %d\n\tYour number of losses %d\n" % (trials, winning_trial, losing_trial))
reply = str(input("Play again!! Yes: y No: n "))
print("Thank u, see u later ...")
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
fin = open('words.txt')
def uses_all(words, letters):
for letter in words:
if letter not in letters:
return False
return True
if __name__ == "__main__":
print uses_all('abcdefg', 'acd') |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
def is_power(a,b):
#this function is a power of b
if b == 0:
print 'anynumber is not divisable by 0'
return None
elif a == b:
return True
elif a % b == 0:
return is_power(a/b,b)
else:
return False
def is_power_custom():
a = int(raw_input('Please enter a: '))
b = int(raw_input('Please enter b: '))
print is_power(a,b)
if __name__ == "__main__":
print is_power(8,2)
is_power_custom() |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
def letter_backward(str):
#this function takes a string as an argument and displays the letters backward, one per line.
if len(str) == 0:
print 'Over'
else:
for i in range(len(str)):
print str[-i-1]
if __name__ == "__main__":
print 'backward("apple")'
letter_backward('apple')
print'\n','backward('')'
letter_backward('')
print'\n','backward("a")'
letter_backward('a')
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
def invert_dict(d):
"""Inverts a dictionary, returning a map from val to a list of keys.
If the mapping key->val appears in d, then in the new dictionary
val maps to a list that includes key.
d: dict
Returns: dict
"""
inverse = dict()
for key in d:
val = d[key]
if val not in inverse:
inverse[val] = [key]
else:
inverse[val].append(key)
return inverse
def invert_dict_modify(d):
inverse = {}
for key, val in d.iteritems():
inverse.setdefault(val, []).append(key)
return inverse
if __name__ == '__main__':
d = {'a': 1, 'o': 1, 'p': 1, 'r': 2, 't': 1}
print invert_dict(d)
print invert_dict_modify(d) |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
def is_palindrome(word):
#this function is a palindrome
#A palindrome is a word that is spelled the same backward and forward, like “noon” and “redivider”.
if len(word) <= 1:
return True
if word[::1]== word[::-1]:
return True
return False
if __name__ == "__main__":
print is_palindrome(' ')
print is_palindrome('pop')
print is_palindrome('moom')
print is_palindrome('redivider') |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
def chop(list):
#this function takes a list, modifies it by removing the first and last elements, and returns None.
del list[0]
del list[-1]
if __name__ == "__main__":
list = [1,2,3,4,5,6,7,8,9]
print chop(list) |
def main():
numbers = get_numbers()
print_number_facts(numbers)
usernames = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45', 'BaseInterpreterInterface',
'BaseStdIn', 'Command', 'ExecState', 'InteractiveConsole', 'InterpreterInterface', 'StartServer',
'bob']
username = input("Enter username: ")
determine_access(username, usernames)
def determine_access(username, usernames):
if username in usernames:
print("Access granted")
else:
print("Access denied")
def print_number_facts(numbers):
print(f"The first number is {numbers[0]}")
print(f"The last number is {numbers[-1]}")
print(f"The smallest number is {min(numbers)}")
print(f"The largest number is {max(numbers)}")
print(f"The largest number is {sum(numbers) / len(numbers)}")
def get_numbers():
numbers = []
for i in range(5):
numbers.append(float(input("Number: ")))
return numbers
main()
|
"""
Code to simulate using taxis.
"""
from prac_08.taxi import Taxi
from prac_08.silver_service_taxi import SilverServiceTaxi
def main():
total_fare = 0
current_taxi = None
taxis = [Taxi("Prius", 100), SilverServiceTaxi("Limo", 100, 2), SilverServiceTaxi("Hummer", 200, 4)]
print("Let's Drive")
print("q)uit, c)hoose taxi, d)rive)")
menu_input = input('>>> ')
while menu_input.lower() != 'q':
if menu_input.lower() == 'c':
print('Taxis available: ')
for i, taxi in enumerate(taxis):
print(f'{i} - {taxi}')
try:
taxi_input = int(input('Choose taxi: '))
current_taxi = taxis[taxi_input]
except ValueError:
print('Invalid taxi choice')
except IndexError:
print('Invalid taxi choice')
elif menu_input.lower() == 'd':
if current_taxi:
current_taxi.start_fare()
distance = float(input('Drive how far? '))
current_taxi.drive(distance)
print(f'Your {current_taxi.name} trip cost you ${current_taxi.get_fare():.2f}')
total_fare += current_taxi.get_fare()
else:
print('You need to choose a taxi before you can drive')
else:
print('Invalid option')
print(f'Bill to date: ${total_fare:.2f}')
print("q)uit, c)hoose taxi, d)rive)")
menu_input = input('>>> ')
print(f'Total trip cost: ${total_fare:.2f}')
print("Taxis are now:")
for i, taxi in enumerate(taxis):
print(f'{i} - {taxi}')
main()
|
# Exercise 3:
# Create a loop that quits with ‘q’
#
# Extra Credit: Make the loop quit with a user defined input
def main():
input1= input("Press q to quit")
iQuit= input("Enter your Quit phrase")
while(input1 != iQuit): #"q"):
input1=input("Press q to quit")
if __name__ == '__main__':
main() |
def sumOfMultiples(upto):
# sum = 0
# for x in range(upto):
# if x % 3 == 0 or x % 5 == 0:
# sum += x
# return sum
return sum([x for x in range(upto) if x % 3 == 0 or x % 5 == 0 ])
print(sumOfMultiples(10))
|
def move_zeros(array):
b,c = [],[]
for i in range(len(array)):
if array[i] == (0 or 0.0) and not(array[i] is False) :
b.append(int(array[i]))
else:
c.append(array[i])
return (c+b) |
def iq_test(numbers):
odd =[]
even=[]
for i in [int(i) for i in numbers.split()] :
odd.append(i) if i%2 else even.append(i)
return 1 + [int(i) for i in numbers.split()].index(odd[0]) if len(odd) < 2 else 1 +[int(i) for i in numbers.split()].index(even[0]) |
import re
regex = input('Enter Regular Expression: ')
fhandle = open("mbox-short.txt")
count = 0
for line in fhandle:
x = re.findall(regex, line)
if len(x) > 0:
count = count + 1
print('The expression was found', count, 'times')
|
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# We use the TF helper function to pull down the data from the MNIST site
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# x is placeholder for the 28 X 28 image data
x = tf.placeholder(tf.float32, shape=[None, 784])
# y_ is called "y bar" and is a 10 element vector, containing the predicted
# probability of each digit(0-9) class.
y_ = tf.placeholder(tf.float32, [None, 10])
# define weights and balances
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# define our inference model
y = tf.nn.softmax(tf.matmul(x, W) + b)
# loss is cross entropy
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
# each training step in gradient decent we want to minimize cross entropy
learning_rate = 0.5
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)
# initialize the global variables
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
# Perform 1000 training steps
for i in range(1000):
# get 100 random data points from the data
# batch_xs = image, batch_ys = digit(0-9) class
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
# Evaluate how well the model did. Do this by comparing the digit
# with the highest probability in actual (y) and predicted (y_).
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
test_accuracy = sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})
print("Test Accuracy: {0}%".format(test_accuracy * 100.0))
sess.close()
|
"""
Python MySQL Drop Table
Delete a Table
You can delete an existing table by using the "DROP TABLE" statement:
"""
#Example
#Delete the table "customers":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "DROP TABLE customers"
mycursor.execute(sql)
"""
Drop Only if Exist
If the the table you want to delete is already deleted, or for any other reason does not exist,
you can use the IF EXISTS keyword to avoid getting an error.
"""
#Example
#Delete the table "customers" if it exists:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "DROP TABLE IF EXISTS customers"
mycursor.execute(sql)
|
"""
Python MySQL Create Database
Creating a Database
To create a database in MySQL, use the "CREATE DATABASE" statement:
"""
#Example
#create a database named "mydatabase":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
"""
If the above code was executed with no errors, you have successfully created a database.
Check if Database Exists
You can check if a database exist by listing all databases in your system by using the "SHOW DATABASES" statement:
"""
#Example
#Return a list of your system's databases:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
"""
Or you can try to access the database when making the connection:
"""
#Example
#Try connecting to the database "mydatabase":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
#If the database does not exist, you will get an error.
|
"""
Smallest Subarray with a given sum
Given an array of positive numbers and a positive number ‘S’, find the length of the smallest subarray whose sum is greater than or equal to ‘S’. Return 0, if no such subarray exists.
Example 1:
Input: [2, 1, 5, 2, 3, 2], S=7
Output: 2
Explanation: The smallest subarray with a sum great than or equal to '7' is [5, 2].
Example 2:
Input: [2, 1, 5, 2, 8], S=7
Output: 1
Explanation: The smallest subarray with a sum greater than or equal to '7' is [8].
Example 3:
Input: [3, 4, 1, 1, 6], S=8
Output: 3
Explanation: Smallest subarrays with a sum greater than or equal to '8' are [3, 4, 1] or [1, 1, 6].
Idea:
- If the subarray sum is < S then increase winsize
- else reduce
"""
import math
def smallest_subarray_with_given_sum(s, arr):
result = math.inf
winStart, sum = 0, 0
for winEnd in range(0,len(arr)):
sum = sum + arr[winEnd]
while sum >= s:
result = min(result, winEnd-winStart+1)
sum = sum - arr[winStart]
winStart += 1
return result
def main():
print("Smallest subarray length: " + str(smallest_subarray_with_given_sum(7, [2, 1, 5, 2, 3, 2])))
print("Smallest subarray length: " + str(smallest_subarray_with_given_sum(7, [2, 1, 5, 2, 8])))
print("Smallest subarray length: " + str(smallest_subarray_with_given_sum(8, [3, 4, 1, 1, 6])))
main() |
#!/usr/bin/python3
import numpy as np
print(' \n REMOVE DUPLICATES \n ')
def remove_dup_in_dict(dct):
lst = []
lst = list(dct)
return lst
def remove_dup_in_list(lst):
lst.sort()
i = len(lst) - 1
while i > 0:
if lst[i] == lst[i-1]:
lst.pop(i)
i -= 1
return lst
def remove_dup_in_array(arr):
lst = arr.tolist()
new_list = []
for i in lst:
if i not in new_list:
new_list.append(i)
return new_list
m_dct = {1,1,1,2,3,3,4}
m_lst = [1,1,1,2,3,3,4]
m_arr = np.array([1,1,1,2,3,3,4])
print(' Original Item : ', m_lst)
print(' Dictionary case : ', remove_dup_in_dict(m_dct))
print(' List case : ', remove_dup_in_list(m_lst))
print(' Ndarray case : ', remove_dup_in_array(m_arr))
|
'''
How do we compute the indices for an array in Python, at which a certain
condition is satisfied
'''
import numpy as np
def first_test(condition, arr):
print('\n *** FIRST TEST *** ')
#true_indexes is a tuple we need to take its first arg.
true_indexes = np.where(condition)
print(' True indexes in array : ', true_indexes[0])
def return_values():
true_values = np.array([])
kk = 0
for i in true_indexes[0]:
true_values = np.append(true_values, arr[i])
kk += 1
return true_values
print(' True values in array : ', return_values())
def second_test(arr):
print('\n *** SECOND TEST *** ')
#This gives us a list type.
true_indexes \
= [index for index,value in enumerate(arr) if value > 2]
#Cast to ndarray.
true_indexes = np.array(true_indexes)
print(' True indexes in array : ', true_indexes)
fh_print = lambda true_indexes : [ arr[i] for i in true_indexes ]
print(' True values in array : ', end = '')
print(fh_print(true_indexes))
def third_test(arr):
print('\n *** THIRD TEST *** ')
true_indexes \
= [index for index in range(len(arr)) if arr[index] > 2]
#Cast to ndarray.
true_indexes = np.array(true_indexes)
print(' True indexes in array : ', true_indexes)
print(' True values in array : [', end = '')
for i in true_indexes:
print(arr[i], " ", end = '')
print(']')
if __name__ == "__main__":
i_array = np.array([i for i in range(-5,6)]);
#This is my condition for founding this items in array
my_condition = i_array > 2
first_test(my_condition, i_array)
second_test(i_array)
third_test(i_array)
|
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.output(11, GPIO.LOW)
GPIO.setup(13, GPIO.OUT)
GPIO.output(13, GPIO.LOW)
GPIO.setup(15, GPIO.OUT)
GPIO.output(15, GPIO.LOW)
while(True):
mode = int(input('Please Input Number : '))
GPIO.output(11, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
GPIO.output(15, GPIO.LOW)
if mode==0:
GPIO.cleanup()
exit()
if mode==1:
GPIO.output(13, GPIO.HIGH)
if mode==2:
GPIO.output(11, GPIO.HIGH)
if mode==3:
GPIO.output(15, GPIO.HIGH)
|
for i in range(1,100):
if i % 3 == 0:
print "fizz"
elif i % 5 == 0:
print "buzz"
elif i % 3 == 0 && i % 5 ==0:
print "fizzbzz"
elif i % 3 != 0 && i % 5 != 0:
print i |
# 为tuple中每个元素命名
## 定义一系列数值常量
NAME,AGE,SEX,EMAIL = range(4)
student = ('Jim',16,'male','jime@gmail.com')
print(student[EMAIL])
## 使用namedtuple代替tuple
from collections import namedtuple
Student = namedtuple('Student',['name','age','sex','email'])
s = Student('Jim',16,'male','jime@gmail.com')
print(s.name) # 可以直接用属性访问tuple
print(isinstance(s,tuple) ) # namedtuple是tuple的子类
|
"""Represents a dataset, linking a unique ID to a set of dataset states."""
from .hash import hash_dictionary
class Dataset:
"""
A dataset, linking a dataset ID to a state and a base dataset.
Parameters
----------
state_id : str
ID of the dataset state of this dataset.
state_type : str
Type of the dataset state of this dataset.
dataset_id : str
(optional) ID (hash) of this dataset. If not supplied, it's generated internally.
base_dataset_id : str or None
ID of the base dataset or `None` if this is a root dataset (default `None`).
is_root : bool
`True`, if this is a root dataset (default `False`).
"""
def __init__(
self, state_id, state_type, dataset_id=None, base_dataset_id=None, is_root=False
):
if not is_root and base_dataset_id is None:
raise ValueError(
"A dataset needs to either have a base dataset or be a root dataset (found neither)."
)
self._state_id = state_id
self._base_dataset_id = base_dataset_id
self._state_type = state_type
self._is_root = is_root
if dataset_id is None:
self._id = hash_dictionary(self.to_dict())
else:
self._id = dataset_id
@classmethod
def from_dict(cls, dict_, dataset_id=None):
"""
Create a `Dataset` object from a dictionary.
Parameters
----------
dict_ : dict
Dictionary containing `state : str` (the ID of the state), `base_dset : str` (ID of the
base dataset, only if this is not a root dataset), `type : str` (type of the state),
`is_root` (`True` if this is a root dataset, default: `False`).
dataset_id : str
(optional) ID (hash) of this dataset. If not supplied, it's generated internally.
Returns
-------
State
A state object.
"""
if not isinstance(dict_, dict):
raise ValueError(
"Expected parameter 'dict_' to be of type 'dict' (found {}).".format(
type(dict_).__name__
)
)
base_ds_id = dict_.get("base_dset", None)
is_root = dict_.get("is_root", False)
try:
state_id = dict_["state"]
state_type = dict_["type"]
except KeyError as e:
raise ValueError(
"Expected key '{}' in state dict (found {}).".format(e, dict_.keys())
)
return cls(state_id, state_type, dataset_id, base_ds_id, is_root)
@property
def id(self):
"""
Get dataset ID.
Returns
-------
str
Dataset ID.
"""
return self._id
@property
def state_id(self):
"""
Get State ID.
Returns
-------
str
State ID.
"""
return self._state_id
@property
def state_type(self):
"""
Get type of state.
Returns
-------
str
State type.
"""
return self._state_type
@property
def is_root(self):
"""
Tell if this is a root dataset.
Returns
-------
bool
`True`, if this is a root dataset.
"""
return self._is_root
@property
def base_dataset_id(self):
"""
Get ID of base dataset.
Returns
-------
str or None
ID of the base dataset or `None` if this is a root dataset.
"""
return self._base_dataset_id
def to_dict(self):
"""
Create dictionary from this Dataset object.
Returns
-------
dict
Dictionary than can be turned back into a Dataset object.
"""
return {
"is_root": self.is_root,
"base_dset": self.base_dataset_id,
"state": self.state_id,
"type": self.state_type,
}
|
#!/usr/bin/python3
"""Iterating in Reverse
Complete!
"""
if __name__ == '__main__':
a = [1, 2, 3, 4]
for x in reversed(a):
print(x)
|
#!/usr/bin/python3
"""Unpacking a Sequence into Separate Variables
Complete!
"""
if __name__ == '__main__':
p = (1, 2, 3)
x, y, z = p
print(x)
print(y)
print(z)
|
#!/usr/bin/python3
"""Transforming and Reducing Data at the Same Time
Complete!
"""
if __name__ == '__main__':
# Output a tuple as CSV
s = ('ACME', 50, 123.45)
print(','.join(str(x) for x in s))
# Data reduction across fields of a data structure
portfolio = [
{'name': 'GOOG', 'shares': 50},
{'name': 'YHOO', 'shares': 75},
{'name': 'AOL', 'shares': 20},
{'name': 'SCOX', 'shares': 65}
]
min_shares = min(s['shares'] for s in portfolio)
print(min_shares)
|
import re
def TRANSCRIPTION():
prompt = input("[1] = DNA to RNA \n[2] = RNA to DNA \n Option: ")
option = int(prompt)
Seq = input("Enter sequence: " )
seq = Seq.upper()
NTS = ''
if option == 1:
for nt in seq:
if nt == 'T':
NTS = NTS + 'U'
else:
NTS = NTS + nt
print(f"\n > {NTS}")
elif option == 2:
for nt in seq:
if nt == 'U':
NTS = NTS + 'T'
else:
NTS = NTS + nt
print(f"\n > {NTS}")
|
#!/usr/bin/env python
import sys
import itertools
import os
from itertools import groupby
from operator import itemgetter
# Function definitions
def pagination(pag, interv, my_dic, sorting_dic, mode, length_dic):
print("\nUsing pagination function...")
# Pagination
if pag:
if int(interv) > int(length_dic):
print("There are only", length_dic, "elements")
print("\nShowing", interv, "elements")
count=0
print("\nOrdering in descending mode...")
for key, value in sorted(sorting_dic.items(), key = itemgetter(1), reverse = True):
if count<=(int(ans4)-1):
count +=1
if mode=="3":
print("Total request of", key, "is", value)
elif mode=="4":
print("Request percentage of", key, "is", value,"%")
elif mode=="5":
print("Total numbers of bits transfered of", key, "is", value, "bits")
else:
break
# No pagination
else:
print("\nShowing all (", length_dic, ") elements")
print("\nOrdering in descending mode...")
for key, value in sorted(sorting_dic.items(), key = itemgetter(1), reverse = True):
if mode=="3":
print("Total request of", key, "is", value)
elif mode=="4":
print("Request percentage of", key, "is", value,"%")
elif mode=="5":
print("Total numbers of bits transfered of", key, "is", value, "bits")
def menu():
print("""Welcome!""")
ans1=input("What would you like to do?\n \
1.Group by IP\n \
2.Group by HTTP status code\n \
q.Exit/Quit\n \
--> ")
if ans1=="1":
print("\nGroup by IP")
elif ans1=="2":
print("\n Group by HTTP status code")
elif ans1=="q":
print("\n Goodbye!")
sys.exit()
else:
print("\n Not Valid Choice")
sys.exit()
ans2=input("What do you want to do for each group?\n \
3.Request count\n \
4.Request count percentage of all logged requests\n \
5.Total number of bytes transferred\n \
--> ")
if ans2=="3":
print("\n Request count")
elif ans2=="4":
print("\n Request count percentage of all logged requests")
elif ans2=="5":
print("\n Total number of bytes transferred")
elif ans2=="q":
print("\n Goodbye!")
sys.exit()
else:
print("\n Not Valid Choice")
sys.exit()
ans3=input("Do you want pagination?\n \
6.Enter pagination\n \
7.Showing all\n \
--> ")
if ans3=="6":
ans4=input("\n Enter pagination:")
elif ans3=="7":
print("\n Showing all")
ans4=0
elif ans3=="q":
print("\n Goodbye!")
sys.exit()
else:
print("\n Not Valid Choice")
sys.exit()
return ans1, ans2, ans3, ans4
def grouping(mode, logfile):
my_list = []
for line in logfile:
x = line.split()
my_list.append(x)
# Remove empty lists from matrix
my_list = [x for x in my_list if x != []]
my_dic = dict()
# Grouping by IP
if mode=="1":
f = lambda x: x[0]
# Grouping by HTTP status code
elif mode=="2":
f = lambda x: x[8]
for key, group in groupby(sorted(my_list, key=f), f):
my_dic[key] = list(group)
return my_dic
def check_file(logfile):
# Check if logfile is empty
log = logfile.read(1)
if not log:
print("\n Log file is EMPTY!")
sys.exit()
'''
Example of using command line arguments
and reading a log file, line by line.
'''
if __name__ == '__main__':
# Checking parameters
if (len(sys.argv) != 2):
print("Incorrect number of parameters, you have to specify log file\n")
sys.exit()
filename = sys.argv[1]
with open(filename, 'r') as logfile:
check_file(logfile)
ans=True
while ans:
ans1, ans2, ans3, ans4 = menu()
ans = False
# Log file is not empty
my_dic = grouping(ans1, logfile)
# Request count
if ans2=="3":
print("Counting request...")
# Create a dictionary to store key and value to descending sorter
sorting_dic = {}
length_dic = 0
for key in my_dic:
length_key = len(my_dic[key])
length_dic += len(my_dic[key])
sorting_dic[key] = length_key
for key in my_dic:
length_key = len(my_dic[key])
# Request count percentage of all logged requests
if ans2=="4":
print("Counting request percentage of all logged requests...")
# Create a dictionary to store key and value to descending sorter
sorting_dic = {}
length_dic = 0
for key in my_dic:
length_key = len(my_dic[key])
length_dic += len(my_dic[key])
print("Total requests", length_dic)
for key in my_dic:
length_key = len(my_dic[key])
sorting_dic[key] = (length_key/length_dic)*100
# Total number of bytes transferred
if ans2=="5":
print("Calculating total number of bytes transferred...")
# Create a dictionary to store key and value to descending sorter
sorting_dic = {}
length_dic = 0
for key in my_dic:
length_dic += len(my_dic[key])
ind_log = my_dic.get(key,"")
data_trans = 0
for line in ind_log:
# To ignore those log with - data transfered
try:
data_trans += int(line[9])
except Exception:
pass
sorting_dic[key] = data_trans
# Pagination
if ans3=="6":
pagination(True, ans4, my_dic, sorting_dic, ans2, length_dic)
if ans3=="7":
pagination(False, 0, my_dic, sorting_dic, ans2, length_dic)
|
import numpy as np
import cv2
def filter_pixels_by_distance(x, y, distance):
filter_mask = np.sqrt(x**2 + y**2) < distance
new_x = x[filter_mask]
new_y = y[filter_mask]
return new_x, new_y
# Identify pixels above the threshold
# Threshold of RGB > 160 does a nice job of identifying ground pixels only
def color_thresh(img, rgb_thresh=(160, 160, 160)):
# Create an array of zeros same xy size as img, but single channel
color_select = np.zeros_like(img[:,:,0])
# Require that each pixel be above all three threshold values in RGB
# above_thresh will now contain a boolean array with "True"
# where threshold was met
above_thresh = (img[:,:,0] > rgb_thresh[0]) \
& (img[:,:,1] > rgb_thresh[1]) \
& (img[:,:,2] > rgb_thresh[2])
# Index the array of zeros with the boolean array and set to 1
color_select[above_thresh] = 1
# Return the binary image
return color_select
def color_below_thresh(img, rgb_thresh=(160, 160, 160)):
# Create an array of zeros same xy size as img, but single channel
color_select = np.zeros_like(img[:,:,0])
# Require that each pixel be below all three threshold values in RGB
# above_thresh will now contain a boolean array with "True"
# where threshold was met
above_thresh = (img[:,:,0] < rgb_thresh[0]) \
& (img[:,:,1] < rgb_thresh[1]) \
& (img[:,:,2] < rgb_thresh[2])
# Index the array of zeros with the boolean array and set to 1
color_select[above_thresh] = 1
# Return the binary image
return color_select
# Identify pixels below the threshold
# Threshold of RGB < 160 does a nice job of identifying obstacles pixels only
#def color_within_thresh(img, rgb_thresh_min=(192, 192, 51), rgb_thresh_max= (255, 255, 114)):
def color_within_thresh(img, rgb_thresh_min=(110, 110, 5), rgb_thresh_max= (255, 255, 90)):
# Create an array of zeros same xy size as img, but single channel
color_select = np.zeros_like(img[:,:,0])
# Require that each pixel be below all three threshold values in RGB
# above_thresh will now contain a boolean array with "True"
# where threshold was met
above_thresh = (img[:,:,0] < rgb_thresh_max[0]) \
& (img[:,:,1] < rgb_thresh_max[1]) \
& (img[:,:,2] < rgb_thresh_max[2]) \
& (img[:,:,0] > rgb_thresh_min[0]) \
& (img[:,:,1] > rgb_thresh_min[1]) \
& (img[:,:,2] > rgb_thresh_min[2])
# Index the array of zeros with the boolean array and set to 1
#print(np.any(above_thresh))
color_select[above_thresh] = 1
# Return the binary image
return color_select
def color_within_thresh_cv(img, rgb_thresh_min=np.array([5, 110, 110]), rgb_thresh_max= np.array([90, 255, 255])):
# rgb_thresh_min=(110, 110, 5), rgb_thresh_max= (255, 255, 90)
# convert to hsv
img_hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
rock = cv2.inRange(img_hsv, rgb_thresh_min, rgb_thresh_max)
return rock
# Define a function to convert to rover-centric coordinates
def rover_coords(binary_img):
# Identify nonzero pixels
ypos, xpos = binary_img.nonzero()
# Calculate pixel positions with reference to the rover position being at the
# center bottom of the image.
x_pixel = np.absolute(ypos - binary_img.shape[0]).astype(np.float)
y_pixel = -(xpos - binary_img.shape[0]).astype(np.float)
return x_pixel, y_pixel
# Define a function to convert to radial coords in rover space
def to_polar_coords(x_pixel, y_pixel):
# Convert (x_pixel, y_pixel) to (distance, angle)
# in polar coordinates in rover space
# Calculate distance to each pixel
dist = np.sqrt(x_pixel**2 + y_pixel**2)
# Calculate angle away from vertical for each pixel
angles = np.arctan2(y_pixel, x_pixel)
return dist, angles
# Define a function to apply a rotation to pixel positions
def rotate_pix(xpix, ypix, yaw):
# TODO:
# Convert yaw to radians
# Apply a rotation
yawrad = yaw * np.pi / 180
xpix_rotated = xpix * np.cos(yawrad) - ypix * np.sin(yawrad)
ypix_rotated = xpix * np.sin(yawrad) + ypix * np.cos(yawrad)
# Return the result
return xpix_rotated, ypix_rotated
# Define a function to perform a translation
def translate_pix(xpix_rot, ypix_rot, xpos, ypos, scale):
# TODO:
# Apply a scaling and a translation
xpix_translated = np.int_(xpos + xpix_rot / scale)
ypix_translated = np.int_(ypos + ypix_rot / scale)
# Return the result
return xpix_translated, ypix_translated
# Define a function to apply rotation and translation (and clipping)
# Once you define the two functions above this function should work
def pix_to_world(xpix, ypix, xpos, ypos, yaw, world_size, scale):
# Apply rotation
xpix_rot, ypix_rot = rotate_pix(xpix, ypix, yaw)
# Apply translation
xpix_tran, ypix_tran = translate_pix(xpix_rot, ypix_rot, xpos, ypos, scale)
# Perform rotation, translation and clipping all at once
x_pix_world = np.clip(np.int_(xpix_tran), 0, world_size - 1)
y_pix_world = np.clip(np.int_(ypix_tran), 0, world_size - 1)
# Return the result
return x_pix_world, y_pix_world
# Define a function to perform a perspective transform
def perspect_transform(img, src, dst):
M = cv2.getPerspectiveTransform(src, dst)
warped = cv2.warpPerspective(img, M, (img.shape[1], img.shape[0]))# keep same size as input image
return warped
# Apply the above functions in succession and update the Rover state accordingly
def perception_step(Rover):
# Perform perception steps to update Rover()
# TODO:
# NOTE: camera image is coming to you in Rover.img
# 1) Define source and destination points for perspective transform
dst_size = 5
# Set a bottom offset to account for the fact that the bottom of the image
# is not the position of the rover but a bit in front of it
# this is just a rough guess, feel free to change it!
bottom_offset = 6
source = np.float32([[14, 140], [301 ,140],[200, 96], [118, 96]])
destination = np.float32([[Rover.img.shape[1]/2 - dst_size, Rover.img.shape[0] - bottom_offset],
[Rover.img.shape[1]/2 + dst_size, Rover.img.shape[0] - bottom_offset],
[Rover.img.shape[1]/2 + dst_size, Rover.img.shape[0] - 2*dst_size - bottom_offset],
[Rover.img.shape[1]/2 - dst_size, Rover.img.shape[0] - 2*dst_size - bottom_offset],
])
# 2) Apply perspective transform
warped = perspect_transform(Rover.img, source, destination)
# 3) Apply color threshold to identify navigable terrain/obstacles/rock samples
terrain_img = color_thresh(warped)
Rover.terrain = terrain_img
obstacle_img = color_below_thresh(warped)
rock_img = color_within_thresh_cv(warped)
# 4) Update Rover.vision_image (this will be displayed on left side of screen)
# Example: Rover.vision_image[:,:,0] = obstacle color-thresholded binary image
# Rover.vision_image[:,:,1] = rock_sample color-thresholded binary image
# Rover.vision_image[:,:,2] = navigable terrain color-thresholded binary image
Rover.vision_image[:,:,0] = obstacle_img * 255
Rover.vision_image[:,:,1] = rock_img * 255
Rover.vision_image[:,:,2] = terrain_img * 255
# 5) Convert map image pixel values to rover-centric coords
### filter near ones and discard far off for world map
obstacle_rovx, obstacle_rovy = rover_coords(obstacle_img)
obstacle_x_filtered, obstacle_y_filtered = filter_pixels_by_distance\
(obstacle_rovx, obstacle_rovy, Rover.nav_vision_thresh)
print("obstacle x len: ", len(obstacle_x_filtered), ", \
obstacle y len: ", len(obstacle_y_filtered))
rock_rovx, rock_rovy = rover_coords(rock_img)
rock_x_filtered, rock_y_filtered = filter_pixels_by_distance\
(rock_rovx, rock_rovy, Rover.rock_vision_thresh)
print("rock rover x len: ", len(rock_x_filtered), ", \
rock rover y len: ", len(rock_y_filtered))
terrain_rovx, terrain_rovy = rover_coords(terrain_img)
terrain_x_filtered, terrain_y_filtered = filter_pixels_by_distance\
(terrain_rovx, terrain_rovy, Rover.nav_vision_thresh)
print("terrain x len: ", len(terrain_x_filtered), ", terrain y len: ", len(terrain_y_filtered))
# 6) Convert rover-centric pixel values to world coordinates
## set init state, last pos and last move
rover_posx, rover_posy = Rover.pos
if Rover.last_pos is not None and len(Rover.last_pos) > 0:
lastx, lasty = Rover.last_pos
Rover.last_move = np.sqrt((rover_posx - lastx) ** 2 + (rover_posy - lasty) ** 2)
Rover.is_init = False
else:
Rover.last_move = 0
Rover.is_init = True
## reset last pos
Rover.last_pos = Rover.pos[:]
rover_yaw = Rover.yaw
world_size = 200
scale = 10
obstacle_dists, obstacle_angles = to_polar_coords(obstacle_x_filtered, obstacle_y_filtered)
print('perception : obstacle angles: ', len(obstacle_angles))
## if there is any obstacle within filtered region
if obstacle_angles is not None and len(obstacle_angles) > 0:
Rover.mean_obstacle_angle = np.mean(obstacle_angles)
Rover.min_obstacle_angle = np.min(obstacle_angles)
Rover.max_obstacle_angle = np.max(obstacle_angles)
Rover.obstacle_angles = obstacle_angles
Rover.len_obstacles = len(obstacle_angles)
Rover.obstacle_dists = obstacle_dists
Rover.mean_obstacle_dist = np.mean(obstacle_dists)
Rover.min_obstacle_dist = np.min(obstacle_dists )
Rover.max_obstacle_dist = np.max(obstacle_dists )
else:
Rover.mean_obstacle_angle = 0
Rover.min_obstacle_angle = 0
Rover.max_obstacle_angle = 0
Rover.obstacle_angles = None
Rover.len_obstacles = 0
Rover.obstacle_dists = None
Rover.mean_obstacle_dist = 0
Rover.min_obstacle_dist = 0
Rover.max_obstacle_dist = 0
obstacle_wx, obstacle_wy = pix_to_world(obstacle_x_filtered, obstacle_y_filtered,\
rover_posx, rover_posy, rover_yaw,\
world_size, scale)
rock_wx, rock_wy = pix_to_world(rock_x_filtered, rock_y_filtered,\
rover_posx, rover_posy, rover_yaw,\
world_size, scale)
terrain_wx, terrain_wy = pix_to_world(terrain_x_filtered, terrain_y_filtered,\
rover_posx, rover_posy, rover_yaw,\
world_size, scale)
# 7) Update Rover worldmap (to be displayed on right side of screen)
# Example: Rover.worldmap[obstacle_y_world, obstacle_x_world, 0] += 1
# Rover.worldmap[rock_y_world, rock_x_world, 1] += 1
# Rover.worldmap[navigable_y_world, navigable_x_world, 2] += 1
Rover.worldmap[obstacle_wy, obstacle_wx, 0] = 255
Rover.worldmap[rock_wy, rock_wx, 1] = 255
Rover.worldmap[terrain_wy, terrain_wx, 2] = 255
# 8) Convert rover-centric pixel positions to polar coordinates
# Update Rover pixel distances and angles
# Rover.nav_dists = rover_centric_pixel_distances
# Rover.nav_angles = rover_centric_angles
rover_dists, rover_angles = to_polar_coords(terrain_x_filtered, terrain_y_filtered)
print('perception : rover angles: ', len(rover_angles))
len_nav = 0
if rover_angles is not None and len(rover_angles) > 0:
len_nav = len(rover_angles)
Rover.nav_dists = rover_dists
Rover.nav_angles = rover_angles
Rover.mean_nav_angle = np.mean(rover_angles)
Rover.min_nav_angle = np.min(rover_angles)
Rover.max_nav_angle = np.max(rover_angles)
Rover.mean_nav_dist = np.mean(rover_dists)
Rover.min_nav_dist = np.min(rover_dists )
Rover.max_nav_dist = np.max(rover_dists )
Rover.len_navs = len_nav
if Rover.len_navs > 0 and Rover.len_obstacles > 0:
Rover.nav_ratio = Rover.len_obstacles / Rover.len_navs
else:
Rover.nav_dists = None
Rover.nav_angles = None
Rover.mean_nav_angle = 0
Rover.min_nav_angle = 0
Rover.max_nav_angle = 0
Rover.mean_nav_dist = 0
Rover.min_nav_dist = 0
Rover.max_nav_dist = 0
Rover.len_navs = 0
if Rover.vel < 0:
Rover.in_backup_mode = True
else:
Rover.in_backup_mode = False
## set sample in vision if there are at least 5 pixels showing a rock. removes noise
## around
Rover.is_sample_in_vision = len(rock_x_filtered) > 5
if Rover.is_sample_in_vision:
rockx = np.mean(rock_x_filtered)
rocky = np.mean(rock_y_filtered)
angle_to_rover = np.arctan2(rocky, rockx) * 180 / np.pi
Rover.steer = np.clip(angle_to_rover, -15, 15)
dist = np.sqrt((rockx - rover_posx)**2 + (rocky - rover_posy)**2)
Rover.mean_rock_angle = angle_to_rover
Rover.mean_rock_dist = dist
Rover.len_rock = len(rock_wx)
else:
Rover.is_sample_in_vision = False
Rover.mean_rock_angle = 0
Rover.mean_rock_dist = 0
Rover.len_rock = 0
#print('from perception: nav_angles: ', len(Rover.nav_angles), ', nav_dists: ', str(len(Rover.nav_dists)))
return Rover |
#This project is about creating a program that can determine the grade and test average of give test scores.
#4/1/2018
#CTI-110 P5HW1 : Test Average and Grade
#Elianna Hunter
def main():
score1 = 0.0
score2 = 0.0
score3 = 0.0
score4 = 0.0
score5 = 0.0
avg = 0.0
score1 = getScore1()
score2 = getScore2()
score3 = getScore3()
score4 = getScore4()
score5 = getScore5()
findAvg = calc_average(score1, score2, score3, score4, score5)
letterGrade = determine_grade(findAvg)
print('Score\t\t Numeric Grade Letter Grade')
print('------------------------------------------------')
print('Score 1:\t', score1, '\t\t', determine_grade(score1))
print('Score 2:\t', score2, '\t\t', determine_grade(score2))
print('Score 3:\t', score3, '\t\t', determine_grade(score3))
print('Score 4:\t', score4, '\t\t', determine_grade(score4))
print('Score 5:\t', score5, '\t\t', determine_grade(score5))
print('Your final average is: ', findAvg, ',', 'This is your letter grade: ', letterGrade)
def getScore1():
score1 = float(input('Please enter test score 1: '))
return score1
def getScore2():
score2 = float(input('Please enter test score 2: '))
return score2
def getScore3():
score3 = float(input('Please enter test score 3: '))
return score3
def getScore4():
score4 = float(input('Please enter test score 4: '))
return score4
def getScore5():
score5 = float(input('Please enter test score 5: '))
return score5
def calc_average(score1, score2, score3, score4, score5):
total = score1 + score2 + score3 + score4 + score5
avg = total / 5
return avg
def determine_grade(findAvg):
if findAvg >= 90 and findAvg <= 100:
grade = 'A'
return grade
elif findAvg >= 80 and findAvg <= 89:
grade = 'B'
return grade
elif findAvg >= 70 and findAvg <= 79:
grade = 'C'
return grade
elif findAvg >= 60 and findAvg <= 69:
grade = 'D'
return grade
else:
grade = 'F'
return grade
main()
|
#CTI-110
#P4LAB: Nested Loops
#Elianna Hunter
#3/22/2018
import turtle
wn = turtle.Screen()
t = turtle.Turtle()
t.pensize(4)
t.pencolor("pink")
t.shape("turtle")
t.left(180)
for i in (1,2,3,4,5):
for j in (1,2,3,4):
t.forward(90)
t.right(90)
t.forward(100)
t.left(73)
|
nombre = input("Ingresa tu nombre: ")
print(f"Tu nombre es: {nombre}") |
import argparse
import os
from lib.string_formatter import format_text
DEFAULT_LINE_SIZE = 40
"""
Configuração dos argumentos de linha de comando:
--line-size: Tamanho máximo permitido para as linhas. O padrão é 40 caracteres.
--justify: Flag opcional que informa se o texto deve ser justificado ou não. Padrão é falso
--input-file: Arquivo de entrada contendo o texto para formatação. Exemplo: input.txt
--output-file: Arquivo de saída para escrita do texto formatado. Opcional. Caso não seja fornecido,
os dados são exibidos no terminal.
"""
argument_parser = argparse.ArgumentParser(
"main.py",
description=
"""
Efetua a formatação do arquivo informado seguindo a parametrização fornecida. Por padrão o script
usa o tamanho máximo da linha de 40 caracteres, não justifica o texto e imprime o resultado
na saída padrão.
"""
)
argument_parser.add_argument("--line-size", help="Tamanho máximo da linha.", type=int,
default=DEFAULT_LINE_SIZE)
argument_parser.add_argument("--justify", help="Aplica a formatação justificada ao texto de entrada.",
action="store_true", default=False)
argument_parser.add_argument("--input-file", required=True, help="Arquivo contendo o texto para formatação.")
argument_parser.add_argument("--output-file", help="Arquivo de saída para o texto formatado.", default=None)
args = argument_parser.parse_args()
if not os.path.exists(args.input_file):
print(f'O arquivo de entrada "{args.input_file}" não foi encontrado. Verifique as informações.')
quit(1)
with open(args.input_file, 'rb') as i_stream:
text = i_stream.read().decode()
formatted_text = format_text(text, args.line_size, args.justify)
if args.output_file:
with open(args.output_file, 'wb') as o_stream:
o_stream.write(formatted_text.encode())
else:
print(formatted_text)
|
data = """o - x
o x x
x o o"""
field = [line.split() for line in data.split('\n')]
def tic_tac_toe(field):
x = False
o = False
y1, y2, y3, di1, di2 = '', '', '', '', ''
count = 0
for elem in field:
elem = ''.join(elem)
count += 1
if elem == 'xxx':
x = True
elif elem == 'ooo':
o = True
y1, y2, y3 = y1 + elem[0], y2 + elem[1], y3 + elem[2]
if count == 1:
di1, di2 = di1 + elem[0], di2 + elem[2]
elif count == 2:
di1, di2 = di1 + elem[1], di2 + elem[1]
else:
di1, di2 = di1 + elem[2], di2 + elem[0]
if y1 == 'xxx' or y2 == 'xxx' or y3 == 'xxx' or di1 == 'xxx' or di2 == 'xxx':
x = True
if y1 == 'ooo' or y2 == 'ooo' or y3 == 'ooo' or di1 == 'ooo' or di2 == 'ooo':
o = True
if (x == False and o == False) or (x == True and o == True):
print('draw')
elif x == True and o == False:
print('x win')
elif x == False and o == True:
print('o win')
tic_tac_toe(field) |
def squared():
st = ' '
st0 = ''
check = False
for i in range(11, 100):
if i % 10 == 0:
pass
else:
if (i + 1) % 10 == 0:
check = True
else:
pass
i = str(i ** 2)
if (len(i) == 3) and (check != True):
i += st * 2
elif (len(i) != 3) and (check != True):
i += st
else:
pass
st0 += i
if check == True:
print(st0)
check = False
st0 = ''
continue
else:
continue
#Довольно громоздко, но, в целом, верно
squared()
|
under_20 = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
big_num = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
def number_in_english(num):
if len(str(num)) == 1:
return under_20[num]
elif len(str(num)) == 2:
if num < 20:
return under_20[num]
if num >= 20:
if num % 10 == 0:
return big_num[num // 10]
else:
return '{} {}'.format(big_num[num // 10], under_20[num % 10])
elif len(str(num)) == 3:
if num % 100 == 0:
return '{} hundred'.format(under_20[num // 100])
elif ((num % 100) < 20) and (num % 100 != 0):
return '{} hundred and {}'.format(under_20[num // 100], under_20[num % 100])
elif (num % 100) >= 20 and str(num)[-1] == '0':
return '{} hundred and {}'.format(under_20[num // 100], big_num[(num % 100) // 10])
elif (num % 100) >= 20 and str(num)[-1] != '0':
return '{} hundred and {} {}'.format(under_20[num // 100], big_num[(num % 100) // 10], under_20[(num % 100) % 10])
print(number_in_english(0).lower()) |
# V27 poo metodo constructor
# ********Muy importante este video******
class Coche():
def __init__(self): #asi es un metodo constructor en python
self.__largoChasis=250 # __ analogo de private
self.__anchoChasis=120
self.__ruedas=4 # __ analogo de private
self.__enmarcha=False
#colocamos self a aquellas propiedades que formen parte del estado inicial
def arracar(self,arrancamos): # es obligatorio colocarlo en python como primer parametro obligatorio
#a diferencia de java que va implicito en el metodo
self.enmarcha=arrancamos
if (self.enmarcha):
return "El coche esta en marcha"
else:
return "El coche esta parado"
def estado(self):
print("El coche tiene ",self.__ruedas," ruedas")
print("El coche tiene un ancho de ",self.anchoChasis)
print("El coche tiene un largo de ",self.largoChasis)
miCoche= Coche() #asi instanciamos una clase
print(miCoche.arracar(True))
miCoche.estado()
miCoche2= Coche()
print(miCoche2.arracar(False))
miCoche2.__ruedas=2
miCoche2.estado()
|
# V8 Tuplas
#se cren con () se leen con []
miTupla=("Lunes","Martes","Miercoles","Jueves","Viernes","Sabado","Domingo")
print(miTupla[2])
print(miTupla[:])
#Convertir una tupla en una lista
miLista=list(miTupla)
#Convertir una list en una tupla
miTupla2=tuple(miLista)
print("Lunes" in miTupla2) # true si existe Lunes
print(miTupla2.count("Lunes")) #cuantas veces esta el elemento
print(len(miTupla2)) #uantos elementos hay
miTupla3=("Enero",) #tupla unitaria (un unico elemento)
miTupla4="Hola","Adios" #tupla sin parentesis otra sintaxys (empaquetado de tupla)
# ******** desempaquetado de tuplas ********
dialunes, diamartes, diaMiercoles, diaJueves, diaViernes, diaSabado, diaDomingo =miTupla2
# python asigna a esas variables en ese orden los valores de la tupla a las variables
print(dialunes)
|
#Funciones con parametros V6
#sin return
# def suma(num1, num2):
# print(num1+num2)
# #
# suma(5,7)
#Funciones con parametros V6
#con return
def suma2(num1, num2):
suma=num1+num2
return suma
#
print(suma2(5,7))
|
import numpy as np
import pandas as pd
X_train_df = pd.read_csv('../data/train_X.csv', header=None)
Y_train_df = pd.read_csv('../data/train_Y.csv', header=None)
"""
Lets say, we take in to account last N days of data. Our first input will be
0 to N-1, 2nd input will be 1 to N and our last set will be len(df)-N to len(df)
"""
N = 60
no_of_records = len(Y_train_df)
X_train = []
Y_train = []
"""
Think of it like a sliding window containing N records.
"""
for i in range(N, no_of_records):
X_train.append(X_train_df.values[i-N:i, :])
Y_train.append(Y_train_df.values[i, :])
# List to np array
X_train, Y_train = np.array(X_train), np.array(Y_train)
"""
X_train.shape: (2717, 60, 8)
Y_train.shape: (2717, 3)
"""
# Build the RNN
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
# Initialise the RNN
regressor = Sequential()
# First LSTM Layer: units = (parameters)^2 parameters=8 (OHLC,V,DV,Ot, VWAP)
regressor.add(LSTM(units = 64, return_sequences = True,
input_shape=(N,8)))
regressor.add(Dropout(0.2))
# 2nd LSTM layer
regressor.add(LSTM(units = 64, return_sequences = True))
regressor.add(Dropout(0.2))
# 3nd LSTM layer
regressor.add(LSTM(units = 64, return_sequences = True))
regressor.add(Dropout(0.2))
# 4th LSTM layer
regressor.add(LSTM(units = 64, return_sequences = False))
regressor.add(Dropout(0.2))
# Add the output layer. We are predicting HLC
regressor.add(Dense(units = 3))
# Compile
regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')
# Fit
regressor.fit(X_train, Y_train, epochs = 100, batch_size = 32)
# Save the model
regressor.save('../data/model.hdf5')
|
import unittest
import main
class TestCalculator(unittest.TestCase):#unittest module provides a set of tools for constructing and running scripts, we will test features of online calculator in this case
def setUp(self):#setUp , when unittest module is used and it enables application to test
main.app.testing = True
self.app = main.app.test_client()
def test_add1(self):
#case 1, A is n integer B is an integer type
solution = self.app.get('/add?A=10&B=2')
self.assertEqual(b'12.0', solution.data)
def test_add2(self):
#case 2, A is rational number and B is rational number p/q form
solution = self.app.get('/add?A=3/2&B=1/2')
self.assertEqual(b'2.0', solution.data)
def test_add3(self):
#case 3, A is a float and B is a float
solution = self.app.get('/add?A=114.22&B=1.002')
self.assertEqual(b'115.222', solution.data)
def test_add4(self):
#case 4, when A is float and B is integer
solution = self.app.get('/add?A=22.222&B=98')
self.assertEqual(b'120.222', solution.data)
def test_add5(self):
#case 5, when A is integer and B is float
solution = self.app.get('/add?A=100&B=95.6')
self.assertEqual(b'195.6', solution.data)
def test_add6(self):
#case 6, when A is fraction p/q and B is an integer
solution = self.app.get('/add?A=1/2&B=89')
self.assertEqual(b'89.5', solution.data)
def test_add7(self):
#case 7, when A is an integer and B is a fraction p/q
solution = self.app.get('/add?A=30&B=2/10')
self.assertEqual(b'30.2', solution.data)
def test_add8(self):
#case 8, when A input is an alphabet(non integer) and B is integer
solution = self.app.get('/add?A=sivani&B=22')
self.assertEqual(b'22.0', solution.data)#non integer type considered as not valid , in this case which is zero
def test_add9(self):
#case 9, when A input is an integer and B input is an alphabet
solution = self.app.get('/add?A=22&B=modali')
self.assertEqual(b'22.0', solution.data)
#when one input is alphabet and other input be any number, whether rational , integer, fraction ultimately the result will be the input which was an integer
def test_add10(self):
#case 10, when A input is of the form p/q where q=0 and B input be any number
solution = self.app.get('add?A=6/0&B=4')
self.assertEqual(b"None", solution.data)
#according to the script if q=0 in p/q form then it should display an error but it is resolved using zerodivision module
def test_add11(self):
#case 11, when A input is any number and B=p/q form where q=0
solution = self.app.get('add?A=19&B=8/0')
self.assertEqual(b"None", solution.data)
def test_sub1(self):
#case 1, A is n integer B is an integer
solution = self.app.get('/sub?A=10&B=3')
self.assertEqual(b'7.0', solution.data)
def test_sub2(self):
#case 2, A is rational number and B is rational number p/q form
solution = self.app.get('/sub?A=8/3&B=2/3')
self.assertEqual(b'2.0', solution.data)
def test_sub3(self):
#case 3, A is a float and B is a float
solution = self.app.get('/sub?A=14.05&B=3.06')
self.assertEqual(b'10.99', solution.data)
def test_sub4(self):
#case 4, when A is float and B is integer
solution = self.app.get('/sub?A=45.55&B=5')
self.assertEqual(b'40.55', solution.data)
def test_sub5(self):
#case 5, when A is integer and B is float
solution = self.app.get('/sub?A=42&B=1.111')
self.assertEqual(b'40.889', solution.data)
def test_sub6(self):
#case 6, when A is fraction p/q and B is an integer
solution = self.app.get('/sub?A=1/2&B=22')
self.assertEqual(b'-21.5', solution.data)
def test_sub7(self):
#case 7, when A is an integer and B is a fraction p/q
solution = self.app.get('/sub?A=4&B=2/10')
self.assertEqual(b'3.8', solution.data)
def test_sub8(self):
#case 8, when A input is an alphabet(non integer) and B is integer
solution = self.app.get('/sub?A=sivani&B=10')
self.assertEqual(b'-10.0', solution.data)#non integer type considered as not valid , in this case which is zero
def test_sub9(self):
#case 9, when A input is an integer and B input is an alphabet
solution = self.app.get('/sub?A=12&B=modali')
self.assertEqual(b'12.0', solution.data)
#when one input is alphabet and other input be any number, whether rational , integer, fraction ultimately the result will be the input which was an integer
def test_sub10(self):
#case 10, when A input is of the form p/q where q=0 and B input be any number
solution = self.app.get('sub?A=3/0&B=5')
self.assertEqual(b"None", solution.data)
#according to the script if q=0 in p/q form then it should display an error
def test_sub11(self):
#case 11, when A input is any number and B=p/q form where q=0
solution = self.app.get('sub?A=92&B=9/0')
self.assertEqual(b"None", solution.data)
def test_mul1(self):
#case 1, A is n integer B is an integer
solution = self.app.get('/mul?A=25&B=2')
self.assertEqual(b'50.0', solution.data)
def test_mul2(self):
#case 2, A is rational number and B is rational number p/q form
solution = self.app.get('/mul?A=5/4&B=12/5')
self.assertEqual(b'3.0', solution.data)
def test_mul3(self):
#case 3, A is a float and B is a float
solution = self.app.get('/mul?A=6.4&B=100.2')
self.assertEqual(b'641.28', solution.data)
def test_mul4(self):
#case 4, when A is float and B is integer
solution = self.app.get('/mul?A=7.6&B=43')
self.assertEqual(b'326.8', solution.data)
def test_mul5(self):
#case 5, when A is integer and B is float
solution = self.app.get('/mul?A=30&B=2.2')
self.assertEqual(b'66.0', solution.data)
def test_mul6(self):
#case 6, when A is fraction p/q and B is an integer
solution = self.app.get('/mul?A=2/3&B=55')
self.assertEqual(b'36.666666666666664', solution.data)
def test_mul7(self):
#case 7, when A is an integer and B is a fraction p/q
solution = self.app.get('/mul?A=19&B=5/14')
self.assertEqual(b'6.785714285714286', solution.data)
def test_mul8(self):
#case 8, when A input is an alphabet(non integer) and B is integer
solution = self.app.get('/mul?A=sivani&B=12')
self.assertEqual(b'0.0', solution.data)#non integer type considered as not valid , in this case which is zero
def test_mul9(self):
#case 9, when A input is an integer and B input is an alphabet
solution = self.app.get('/mul?A=12&B=modali')
self.assertEqual(b'0.0', solution.data)
#when one input is alphabet and other input be any number, whether rational , integer, fraction ultimately the result will be the input which was an integer
def test_mul10(self):
#case 10, when A input is of the form p/q where q=0 and B input be any number
solution = self.app.get('mul?A=8/0&B=2')
self.assertEqual(b"None", solution.data)
#according to the script if q=0 in p/q form then it should display an error but it is resolved using zerodivision module
def test_mul11(self):
#case 11, when A input is any number and B=p/q form where q=0
solution = self.app.get('mul?A=14&B=6/0')
self.assertEqual(b"None", solution.data)
def test_div1(self):
#case 1, A is n integer B is an integer
solution = self.app.get('/div?A=30&B=2')
self.assertEqual(b'15.0', solution.data)
def test_div2(self):
#case 2, A is rational number and B is rational number p/q form
solution = self.app.get('/div?A=3/7&B=61/4')
self.assertEqual(b'0.02810304449648712', solution.data)
def test_div3(self):
#case 3, A is a float and B is a float
solution = self.app.get('/div?A=6.21&B=4.1')
self.assertEqual(b'1.5146341463414634', solution.data)
def test_div4(self):
#case 4, when A is float and B is integer
solution = self.app.get('/div?A=51.33&B=13')
self.assertEqual(b'3.9484615384615385', solution.data)
def test_div5(self):
#case 5, when A is integer and B is float
solution = self.app.get('/div?A=20&B=2.2')
self.assertEqual(b'9.090909090909092', solution.data)
def test_div6(self):
#case 6, when A is fraction p/q and B is an integer
solution = self.app.get('/div?A=1/2&B=100')
self.assertEqual(b'0.005', solution.data)
def test_div7(self):
#case 7, when A is an integer and B is a fraction p/q
solution = self.app.get('/div?A=18&B=2/3')
self.assertEqual(b'27.0', solution.data)
def test_div8(self):
#case 8, when A input is an alphabet(non integer) and B is integer
solution = self.app.get('/div?A=sivani&B=12')
self.assertEqual(b'0.0', solution.data)#non integer type considered as not valid , in this case which is zero
def test_div9(self):
#case 9, when A input is an integer and B input is an alphabet
solution = self.app.get('/div?A=52&B=modali')
self.assertEqual(b'None', solution.data)
#when one input is alphabet and other input be any number, whether rational , integer, fraction ultimately the result will be the input which was an integer
def test_div10(self):
#case 10, when A input is of the form p/q where q=0 and B input be any number
solution = self.app.get('div?A=6/0&B=2')
self.assertEqual(b'None', solution.data)
#according to the script if q=0 in p/q form then it should display an error
def test_div11(self):
#case 11, when A input is any number and B=p/q form where q=0
solution = self.app.get('div?A=17&B=2/0')
self.assertEqual(b'None', solution.data)
if __name__ == '__main__':
unittest.main()
|
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 20 10:04:38 2021
@author: David Stoneking
"""
# Define a function that takes one integer argument and returns logical value true or false depending on if the integer is a prime.
# Per Wikipedia, a prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
# Requirements
# You can assume you will be given an integer input.
# You can not assume that the integer will be only positive. You may be given negative numbers as well (or 0).
# NOTE on performance: There are no fancy optimizations required, but still the most trivial solutions might time out. Numbers go up to 2^31 (or similar, depends on language version). Looping all the way up to n, or n/2, will be too slow.
# Example
# is_prime(1) /* false */
# is_prime(2) /* true */
# is_prime(-1) /* false */
def is_prime(num):
divide_by = range(2,100000)
if num <= 0:
print('False')
return False
else:
pass
for ea in divide_by:
if num % ea == 0:
print('False')
return False
print('True')
return True
is_prime(0)
is_prime(5099) |
# -*- coding: utf-8 -*-
"""
@author: Vivian
"""
from hangman import Hangman
"""
Game() is the entrance and contains different games for users to play(currently only hangman)
Based on user's choice, the Game class will start the game and generate a new round
"""
class Games:
# game ids for hangman
HANGMAN_GAME_ID = 1
OTHER_GAME_ID = 2
def main(self):
# enter the game and start playing
game_id = self.get_game_choice()
self.play_game(game_id)
# leave game
print('Bye!')
def __init__(self):
pass
# return the choice of game the user chooses
def get_game_choice(self):
not_valid_ans = True
while not_valid_ans:
# print game menu
print('Let\'s play games!')
print('--------------------')
print('1. Hangman\n2. Other\n3. Exit')
print('--------------------')
# get user's choice
game_id = input()
if game_id.isdigit():
if 1 <= int(game_id) <= 3:
not_valid_ans = False
else:
print('Invalid input!\n')
else:
print('Invalid input!\n')
return int(game_id)
# play the selected game based on user's choice
def play_game(self, id):
if id == self.HANGMAN_GAME_ID:
print('Play Hangman!\n')
self.hm = Hangman()
self.hm.start_game()
elif id == self.OTHER_GAME_ID:
print('Other games coming soon!')
else:
print('Exiting game')
if __name__=="__main__":
games = Games()
games.main() |
def encrypt_vigenere(plaintext, keyword):
"""
>>> encrypt_vigenere("PYTHON", "A")
'PYTHON'
>>> encrypt_vigenere("python", "a")
'python'
>>> encrypt_vigenere("ATTACKATDAWN", "LEMON")
'LXFOPVEFRNHR'
"""
encrypted = list()
for i in range(0, len(plaintext)):
if plaintext[i].lower() < 'a' or plaintext[i].lower() > 'z':
encrypted.append(plaintext[i])
continue
key = ord(keyword[i % len(keyword)].upper())
encrypted.append(chr(ord('A') + (ord(plaintext[i].upper()) + key) % 26))
if plaintext[i].islower():
encrypted[i] = encrypted[i].lower()
return ''.join(encrypted)
def decrypt_vigenere(ciphertext, keyword):
"""
>>> decrypt_vigenere("PYTHON", "A")
'PYTHON'
>>> decrypt_vigenere("python", "a")
'python'
>>> decrypt_vigenere("LXFOPVEFRNHR", "LEMON")
'ATTACKATDAWN'
"""
decrypted = list()
for i in range(0, len(ciphertext)):
if ciphertext[i].lower() < 'a' or ciphertext[i].lower() > 'z':
decrypted.append(ciphertext[i])
continue
key = ord(keyword[i % len(keyword)].upper())
decrypted.append(chr(ord('A') + (ord(ciphertext[i].upper()) - key) % 26))
if ciphertext[i].islower():
decrypted[i] = decrypted[i].lower()
return ''.join(decrypted)
|
import time
import re
import os
from datetime import datetime
def karma_yesterday():
# Create karma.txt if it doesn't exist
if not os.path.isfile("karma.txt"):
open("karma.txt", "a").close()
# Get all the karma data from the file into a list
with open("karma.txt", "r") as karmafile:
karma = karmafile.readlines()
# Remove all the surrounding whitespace
karma = [line.strip() for line in karma]
# Split all of the strings into tuples on the comma, and remove invalid entries
karma = [tuple(line.split(",")) for line in karma if len(line.split(",")) == 2]
# Convert the karma string to an int and the timestamp to a date
datefmt = "%Y-%m-%d %H:%M:%S.%f"
karma = [(datetime.strptime(d.strip(), datefmt), int(k)) for k, d in karma]
print karma[245][1]
# Sort the karma based on datetime
karma.sort()
# Remove the time information from the datetime, we don't care about it anymore
karma = [(dt.date(), k) for dt, k in karma]
# The `days` will contain the first entry from each day
# We insert the first entry as the base case, since it will always be
# the first we have from that day (we sorted it)
days = [karma[0]]
global averageKarma
for day in karma:
# If this entry is from a new day add it to `days`
if day[0] != days[-1][0]:
days.append(day)
# Get rid of the information about what day it is,
# we only care about start-of-day karma
days = [day[1] for day in days]
# Return the amount of karma gained during the previous day
rawKarma = [line.split(',')[0] for line in open('karma.txt')]
#for i in range(len(rawKarma)):
#print rawKarma[-i]
global soFarKarma
soFarKarma = int(rawKarma[-1]) - days[-1]
print soFarKarma
karma_yesterday()
|
listaObecnosci = [
'iksiński', # 0
'kowalski', # 1
'zimny', # 2
'świtaj' # 3
]
print(listaObecnosci[3])
listaObecnosci.append('aniserowicz')
print(listaObecnosci)
listaObecnosci.insert(0, 'dziekan')
print('z dziekanen:')
print(listaObecnosci)
listaObecnosci.extend(['a', 'b', 'c'])
print(listaObecnosci)
|
# -*- coding: utf-8 -*-
"""
Created on Sun May 30 11:28:13 2021
@author: rafsh
"""
name= ['Rafshan','Bin','Razzak'];
print(name);
name.append('Mahi');
print(name);
name.insert(2, 'habijabi');
print(name);
name.pop(2);
print(name);
print(len(name));
number=[1,51,8,16,7,5];
lst=number[1:4];
print(lst);
lst=number[1:];
print(lst);
i=0
while i<=10:
i=i+1;
if i==6:
continue
print(i);
for item in range(0,100):
print(item);
for item in range(0,100,10):
print(item); |
from globals import *
from math import sqrt
class Game:
"""One game."""
def __init__(self, MOV, isWon, oppName, oppRating, home, day):
"""Initialize the game."""
self.MOV = MOV
self.day = day
self.isWon = isWon
self.home = home
self.oppName = oppName
self.oppRating = oppRating
self.rating, rawRating = self.calculateGameRating()
def calculateGameRating(self):
"""Calculate rating for protagonist team."""
oppR = self.oppRating
if oppR >= 0:
ratingCoef = sqrt(oppR)
if oppR > GOOD_TEAM_CUTOFF:
ratingCoef += GOOD_TEAM_BOOST
else:
ratingCoef = -sqrt(abs(oppR))
if self.isWon:
rating = (ratingCoef * OPP_RATING_WEIGHT) + WIN_BOOST + sqrt(self.MOV)
else:
rating = (ratingCoef * OPP_RATING_WEIGHT) - WIN_BOOST - sqrt(abs(self.MOV))
if self.day > ROAD_GAME_START:
if self.home:
rating -= ROAD_BOOST
else:
rating += ROAD_BOOST
rawRating = rating
recencyCoef = 1
rating *= recencyCoef
return rating, rawRating |
def midpoint(low,high):
return (low+ high)/2
print "Think of a number between 1 and 100"
low = 1
high = 100
while True:
guess = midpoint(low, high)
print "I guess", guess
print "1. Way too low"
print "2. Too low"
print "3. Too high"
print "4. Way too high"
print "5. Correct!"
input = int(raw_input("pick one"))
if input == 1:
# it's way to low
low = guess+15
elif input == 2:
# too low
low = guess
elif input == 3:
# too high
high = guess
elif input == 4:
# way too high
high = guess-15
elif input == 5:
# Correct
print "I won"
break
else:
print "Invalid input"
|
from random import randint
def shuffle():
for i in xrange(100):
first = randint(0,51)
second = randint(0,51)
if first != second:
deck[first], deck[second] = deck[second], deck[first] # python swapping is super easy!
deck = []
# Adds the cards
for card in xrange(1,14): # one for each number (A = 1, J,Q,K = 11, 12, 13)
for suit in xrange(4): # 4 for each suit
deck.append(card)
shuffle()
# let's play!
money = 100
wins = 0
losses = 0
bet = 0
while money > 0:
print "You have", money, "dollars. What would you like to bet? (-1 = quit)"
bet = int(raw_input("$"))
if bet == -1:
break
if bet > money:
print "You don't have that much money!"
continue
elif bet <= 0:
print "You can't bet that"
continue
else:
money = money - bet
hit = True
# draw the first card (haven't taught this so I left it)
hand = deck.pop()
deck.insert(0, hand)
while hit and hand <= 21:
print "Your hand is",hand,"Would you like to hit or stay?"
option = raw_input("(1 = hit, 2 = stay)")
if option == "1":
# draw a new card
new = deck.pop()
hand = hand + new
deck.insert(0, new)
elif option == "2":
hit = False
else:
print "That's not a valid choice"
if hand > 21:
print "WHAHAHAHAHAHAHAHAHAHAHAHHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHHAHAHAHAHAHHAHAHAHAHAHHAHAHAHHAHAHAHAHAHAHAHHAHAHHAHAHAHAHAHAHAHAHAHAHAHHAAHHAHAHAHAHAHHAHAHAHAHAHAHAHHAHAHAHAHAHHAHAHAHAHAHAAHHAHHAHAHAHAHAHAHAHHAHAHHAHHAHAHAHAHAHHHAHAHAHAHAHHAHAHAHHAHAHAHHAHAHHAHAHAHAHAHAHAHAHAHAHHAHAHAHAHAHHAHAHAHAHAHHAHAHAHAHHAHAHAHHAHHAHAHAHAHAHAHAHHAHAHAHAHAHAHAAHAHHAHAHAHHAHA"
if hand <= 21:
dealer = randint(1,22)
print "The dealer has",dealer
if hand > dealer:
print "You won the hand!"
money = money + 2 * bet
wins = wins + 1
else:
print "You lost the hand"
losses = losses + 1
shuffle()
print "Game over"
print "You had",money,"dollars left"
print "You won",wins,"times"
print "You lost",losses,"times" |
""" playgame.py
Contains the Connect 3 game playing application.
This file forms part of the assessment for CP2410 Assignment 2
************** ENTER YOUR NAME HERE ****************************
"""
from connect3board import Connect3Board
from gametree import GameTree
from timeit import default_timer as timer
def main():
print('Welcome to Connect 3 by YOUR NAME HERE')
mode = get_mode()
while mode != 'Q':
if mode == 'A':
run_two_player_mode()
elif mode == 'B':
board_testing()
mode = get_mode()
def run_two_player_mode():
c = get_int("How many columns?")
r = get_int("How many rows?")
start = timer()
game = Connect3Board(c, r)
end = timer()
print(game)
print(end - start)
while True:
print("Turn " + str(game.get_turn_number()))
print(str(game.get_whose_turn()) + "'s Turn")
uinput = get_int("In which column do you want to put?")
if game.can_add_token_to_column(uinput):
game.add_token(uinput)
if game.get_winner():
print(game)
print(game.get_winner() + " Wins")
break
else:
print(game)
else:
print("cannot lah")
return 0
def run_ai_mode():
c = get_int("How many columns?")
r = get_int("How many rows?")
game = Connect3Board(c, r)
print(game)
def get_mode():
mode = input("A. Two-player mode\nB. Play against AI\nQ. Quit\n>>> ")
while mode[0].upper() not in 'ABQ':
mode = input("A. Two-player mode\nB. Play against AI\nQ. Quit\n>>> ")
return mode[0].upper()
def get_int(prompt):
result = 0
finished = False
while not finished:
try:
result = int(input(prompt))
finished = True
except ValueError:
print("Please enter a valid integer.")
return result
def board_testing():
a = [3, 10, 20, 40, 80, 100, 200, 400, 800, 1000]
for i in a:
start = timer()
game = Connect3Board(i, i)
end = timer()
print(end-start)
if __name__ == '__main__':
main()
|
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> #tipos de variables
>>> num1=3
>>> num1
3
>>> print(num1)
3
>>> letras="hola mundo"
>>> letras
'hola mundo'
>>> print(letras)
hola mundo
>>> #imprimir un texto con saltos
>>> palabra="""hola
que
tal
estas"""
>>> print(palabra)
hola
que
tal
estas
>>> palabra
'hola\nque\ntal\nestas'
>>> #hacer saltos de lineas de codigo con black slash
>>> palabra="""dime que tal\
estas en este lugar\
distres"""
>>> print(print)
<built-in function print>
>>> print(palabra)
dime que talestas en este lugardistres
>>> #sacar el tipo a una variable
>>> num1=2
>>> type(num1)
<class 'int'>
>>> num1=2.5
>>> type(num1)
<class 'float'>
>>> type(palabra)
<class 'str'>
>>>
|
#!/usr/bin/python3
class Person:
def __init__(self, first, middle, last, age):
self.first = first
self.middle = middle
self.last = last
self.age = age
def __str__(self):
return self.first + ' ' + self.middle + ' ' + self.last + \
str(self.age)
def initials(self):
return self.first[0] + self.middle[0] + self.last[0]
def changeAge(self,mount):
self.age += mount
aPerson = Person('Jane', 'Q', 'Public', 27)
print(aPerson)
aPerson.changeAge(2)
print(aPerson)
print(aPerson.initials())
|
#!/usr/bin/python3.4
grade = 99
if grade >= 90:
letterGrade = 'A'
elif grade >= 80:
letterGrade = 'B'
elif grade >= 70:
letterGrade = 'C'
elif grade >= 60:
letterGrade = 'D'
else:
letterGrade = 'F'
print(letterGrade)
|
class Circle(object):
"""circle class"""
#--------------- static variables
_all = []
_pi = 3.14159
#--------------- static methods
@staticmethod
def totalArea():
total = 0
for c in Circle._all:
total += c.area()
return total
@staticmethod
def totalCircles():
return len(Circle._all)
#--------------- member methods
def __init__(self,r=1):
self.radius = r
self.__class__._all.append(self)
def area(self):
return self.__class__._pi * self.radius * self.radius
|
import unittest
def safe_int(obj):
try:
return int(obj)
except (ValueError,TypeError):
return "ErrorCast"
def throw_exception(value1,value2,value3):
"""throw tuple as the argument of exception"""
raise Exception(value1,value2,value3)
def not_implemented_method():
raise NotImplementedError("Test")
class ExceptionTest(unittest.TestCase):
class Fool(object):
def __init__(self):
self._finally = False
def run(self,success):
try:
if not success: raise ValueError("just for test")
finally:
self._finally = True
# this method should be called "__bool__" in python3
def __nonzero__(self): return self._finally
def testSample1(self):
self.assertEqual(3,safe_int(3.14))
self.assertEqual("ErrorCast",safe_int("3.14"))
def testErrorMessage(self):
try:
not_implemented_method()
except NotImplementedError as error:
self.assertEqual("Test",str(error))
def testTupleArgs1(self):
filename = "noexist.txt"
try:
fr = open(filename,"rt") # "rt" stands for "read text" ('t' is default mode)
except IOError as error:
self.assertEqual(2,len(error.args))
self.assertEqual(error.args[0],error.errno)
self.assertEqual(error.args[1],error.strerror)
# although IOError will have "filename" attribute, but that attribute will not be included in the tuple
self.assertEqual(filename,error.filename)
else: # When the try block doesn't raise an exception, the else block will run
self.fail("an exception is expected")
def testTupleArgs2(self):
"""test the usage that use tuple as the argument of exception"""
try:
throw_exception(1,"cheka",3.14)
except Exception as error:
arg1,arg2,arg3 = error.args # __getitem__ has been overriden, so can retrieve values directly
self.assertEqual(1,arg1)
self.assertEqual("cheka",arg2)
self.assertAlmostEqual(3.14,arg3)
else:
self.fail("it should throw out an exception")
def testFinally(self):
def fool(success):
f1 = ExceptionTest.Fool()
self.assertFalse(f1)
try:
f1.run(success)
except ValueError:
pass
self.assertTrue(f1)
fool(True)
fool(False)
if __name__ == "__main__":
unittest.main()
|
import unittest
# ------------------------------- Template Pattern
class TemplateBase(object):
def templateMethod(self):
return self.subMethod1() + self.subMethod2()
def subMethod1(self):
raise NotImplementedError("must override in derived class")
def subMethod2(self):
raise NotImplementedError("must override in derived class")
def subMethod3(self):
return 5
class DerivedForInt(TemplateBase):
def subMethod1(self): return 1
def subMethod2(self): return 2
def subMethod3(self):
return 2 * super(DerivedForInt,self).subMethod3()
class DerivedForString(TemplateBase):
def subMethod1(self): return "cheka"
def subMethod2(self): return " stasi"
# ------------------------------- End Template Pattern
class TestPolymorphism(unittest.TestCase):
# =================== helper class definition
class Grandpa(object) : pass
class Father(Grandpa) : pass
class Son(Father) : pass
def testTemplatePattern(self):
int_product = DerivedForInt()
self.assertEqual(3,int_product.templateMethod())
string_product = DerivedForString()
self.assertEqual("cheka stasi",string_product.templateMethod())
def testCallSuperMethod(self):
obj = DerivedForString()
self.assertEqual(5,obj.subMethod3()) # original base method
obj = DerivedForInt()
self.assertEqual(10,obj.subMethod3()) # override base method, but call base version inside it
def testIssubclass(self):
self.assertTrue(issubclass(TestPolymorphism.Son,TestPolymorphism.Father))
self.assertTrue(issubclass(TestPolymorphism.Father,TestPolymorphism.Grandpa))
# can be used to judge not-direct inheritance
self.assertTrue(issubclass(TestPolymorphism.Son,TestPolymorphism.Grandpa))
def testIsinstance(self):
agrandpa = TestPolymorphism.Grandpa()
afather = TestPolymorphism.Father()
ason = TestPolymorphism.Son()
# can be used to test super class
self.assertTrue(isinstance(ason,TestPolymorphism.Father))
self.assertTrue(isinstance(ason,TestPolymorphism.Grandpa))
self.assertTrue(isinstance(afather,TestPolymorphism.Grandpa))
if __name__ == "__main__":
unittest.main() |
import unittest
class MutableImmutableTest(unittest.TestCase):
def testIncrementImmutable(self):
a = 1
b = a
oldid = id(a)
a += 1 # silently create a new object, and point a to that new object
newid = id(a)
# a points to a new object
# b still points to the old object
self.assertEqual(1,b)
self.assertNotEqual(oldid,newid)
self.assertEqual(oldid,id(b))
def testIncrementMutable(self):
a = [0]
b = a
oldid = id(a)
a += [1,2]
newid = id(a)
# a, b still points to the same old object
self.assertEqual(oldid,newid)
self.assertEqual([0,1,2],b)
def testAnExample(self):
def append_seq(oldseq):
oldseq += (9,9)
return oldseq
oldlist = [1,2,3]
oldtuple = (1,2,3)
newlist = append_seq(oldlist)
newtuple = append_seq(oldtuple)
self.assertEqual([1,2,3,9,9],oldlist)
self.assertEqual([1,2,3,9,9],newlist)
self.assertTrue(newlist is oldlist)
self.assertIs(oldlist,newlist)
self.assertEqual((1,2,3),oldtuple)
self.assertEqual((1,2,3,9,9),newtuple) |
class MyTime(object):
def __init__(self,hour,minute):
self._hour = hour
self._minute = minute
def __str__(self):
return "%d:%d"%(self._hour,self._minute)
def __add__(self,other):
return self.__class__(self._hour + other._hour,self._minute + other._minute)
def __iadd__(self,other):
"""in place add"""
self._hour += other._hour
self._minute += other._minute
return self
def __eq__(self,other):
if other is None:
return False
elif self is other:
return True
elif isinstance(other,self.__class__):
return self._hour == other._hour and self._minute == other._minute
else:
return False
def __ne__(self,other):
return not self == other
def __hash__(self):
"""make the class hashable, and can be used as the key"""
return hash((self._hour,self._minute))
def __lt__(self,other):
if self._hour < other._hour : return True
elif self._hour == other._hour and self._minute < other._minute: return True
else: return False
def __le__(self,other):
return (self == other) or (self < other)
def __gt__(self,other):
return not self <= other
def __ge__(self,other):
return not self < other
def __iter__(self):
def generator():
yield self._hour
yield self._minute
return generator()
# in Python 3, this method should be called "__bool__"
def __nonzero__(self):
"""let this object can be used as boolean"""
return bool(self._hour or self._minute)
def __getattr__(self,attr):
"""this method is called only when attr is not found in current instance"""
if attr == "second":
return 0
else:
raise AttributeError("not recognized attribute: %s"%attr)
def __getitem__(self,index):
if index == 0:
return self._hour
elif index == 1:
return self._minute
else:
raise IndexError("Valid Index Only 0 and 1")
def __call__(self):
"""
it can has argument or not, both are OK
because Python doesn't support overload, method with same name but different arguments will still overwrite previous one
"""
return self._hour,self._minute |
class Person(object):
def __init__(self,ssn,name):
self._ssn = ssn
self._name = name
def __eq__(self,rhs):
if self is rhs:
return True
elif isinstance(rhs,Person):
return (self._ssn == rhs._ssn) and (self._name == rhs._name)
else:
return False
def __ne__(self,rhs):
return not self == rhs
def __str__(self):
return "Person<%d,%s>"%(self._ssn,self._name)
|
import unittest
class GroupedArgsTest(unittest.TestCase):
# ---------------------- for test list arguments
def _sum(self,*args):
size = len(args)
sum = args[0]
for index in range(1,size):
sum += args[index]
return sum
def testTupleParameter(self):
self.assertEqual(6,self._sum(1,2,3))
self.assertEqual("chekakgbstasi",self._sum("cheka","kgb","stasi"))
# ---------------------- for test dictionary arguments
def _splitKeysValues(self,keys,values,**kwargs):
del keys[:]
del values[:]
for kv in kwargs.items():
keys.append(kv[0])
values.append(kv[1])
keys.sort()
values.sort()
def testDictParameters(self):
# set some initial values, to test the effect of clearing inside the method
keys = list(range(3))
values = list(range(5))
# chekanote: to pass as "keyword argument", passing as "key=value" format
# and in the method body, all key-word arguments will be grouped into a dictionary
# where the key is like "key"
self._splitKeysValues(keys,values,stasi = 100,cheka=10,kgb=2,cia=3)
self.assertEqual(["cheka","cia","kgb","stasi"],keys)
self.assertEqual([2,3,10,100],values)
def testSplitArguments(self):
"""
when used outside method to invoke function with grouped parameter
"*" or "**" works as spliter, split a collection into individual segments and pass into that method with grouped parameter
"""
# ----------- split list
# ----------- without, (1,2,3) is passed as a single element, then inside method, args is a collection with only one argument
self.assertEqual((1,2,3),self._sum((1,2,3)))
self.assertEqual(18,self._sum(*(5,6,7)))
# ----------- split dictionary
keys = [1]
values = [None]
# chekanote: below codes throw TypeError exception, due to "keyword can only be string"
# self._split_keys_values(keys,values,**{2:"stasi",1:"cheka"})
self._splitKeysValues(keys,values,**{"stasi":2,"cheka":1})
self.assertEqual([1,2],values)
self.assertEqual(["cheka","stasi"],keys)
def testDefaultExtendArgs(self):
"""
test the case that default arguments mixed with tuple arguments
"""
def _method(arg1,defarg="default",*argtuple,**kwargs):
return {"arg1":arg1,"default_arg":defarg,"arg_tuple":argtuple,"arg_dict":kwargs}
self.assertEqual({"arg1":100,"arg_dict":{},"arg_tuple":(),"default_arg":"default"},_method(100))
self.assertEqual({"arg1":101,"arg_dict":{},"arg_tuple":(),"default_arg":"newvalue"},_method(101,"newvalue"))
self.assertEqual({"arg1":1,"arg_dict":{"x":99},"arg_tuple":(3,"cheka"),"default_arg":2},_method(1,2,3,"cheka",x=99))
# only when we have already filled out the two non-tuple argument, left argument will be collected into tuple
self.assertEqual({"arg1":102,"arg_dict":{},"arg_tuple":(1,2),"default_arg":"newvalue2"},_method(102,"newvalue2",1,2))
# keyword arguments are always the last
self.assertEqual({"arg1":103,"arg_dict":{"x":99},"arg_tuple":(),"default_arg":"cheka"},
_method(arg1=103,defarg="cheka",x=99)) |
# name = 'Emre Çat'
# for i in name:
# print(i)
# 62 for döngü uygulama
sayilar=[1,3,5,7,9,12,19,21]
# #1. soru
#
# for i in sayilar:
# if i%3==0:
# print(i)
#2. soru
# toplam=0
# for i in sayilar:
# toplam+=i
# print(toplam)
ürünler=[
{'name':'samsung s6','price': '3000'},
{'name':'samsung s7','price': '4000'},
{'name':'samsung s8','price': '5000'},
{'name':'samsung s9','price': '6000'},
{'name':'samsung s10','price': '7000'},
]
#5 ürünlerin toplam fiyatı
# toplam=0
# for urun in ürünler:
# toplam+=int(urun['price'])
# print(toplam)
#6 5000den az ücretli ürünler
for urun in ürünler:
fiyat=int(urun['price'])
if fiyat<=5000:
print(f'bu ürünün fiyatı 5000den az {urun["name"]}') |
x,y,z=2,5,10
numbers=1,5,7,10,6
sayi1=input("1. sayiyi giriniz")
sayi2=input("2.sayiyi giriniz")
carpim=int(sayi1)*int(sayi2)
print("sonuc:",carpim-(x+y+z))
print(y//x)
toplam=x+y+z
print(toplam%3)
x,*y,z=numbers
z**=2
print(f"z nin değeri : {z}")
ytoplam=y[0]+y[1]+y[2]
print(ytoplam) |
import pandas as pd
import numpy as np
data={
'Column1':[1,2,3,4,5],
'Column2':[10,20,13,45,25],
'Column3':["abc","bca","ade","cba","dea"]
}
df=pd.DataFrame(data)
result=df
result=df['Column2'].unique() # tekrarlamayan bilgileri gösterir
result=df['Column2'].nunique() # kaç tane farklı değer var sayısını verir
result=df['Column2'].value_counts() # hangi elemandan kaç tane var sayısını verir
result=df['Column2']*2 # matematiksel işlemler yapabiliriz
def kareal(x):
return x*x
kareal2=lambda x: x*x
result=df['Column1'].apply(kareal) # bir sütuna fonksiyonu bu şekilde gönderip çıktı alıyoruz apply fonksiyonu ile
result=df['Column1'].apply(kareal2)
result=df['Column1'].apply(lambda x: x*x) # apply fonka direk işlem gönderebiliriz
result=df['Column3'].apply(len) # str değerler için len fonk u direkt gösterebliiriz apply içerisine
df['uzunlukları']=df['Column3'].apply(len) # yeni bir sütun yapmak içinde kullanabiliriz
result=df.columns
result=len(df.columns)
result=len(df.index)
result=df.info
result=df.sort_values("Column2") # Column2 küçükten büyüğe sıralanır
result=df.sort_values("Column2",ascending=False) # Column2 büyükten küçüğe sıralanır
# result=df.sort_values("Column3") #Column3 alfabetik sıralanır
# print(df)
print(result) |
# name=input("lütfen isminizi giriniz.")
# age=int(input("Lütfen yasınızı giriniz"))
# educatelevel=input("lütfen eğitim seviyenizi giriniz.")
# if (age>=18 and (educatelevel=="üni" or educatelevel=="lise")):
# print("Ehliyet alabilirsiniz.")
# else:
# print("ehliyet alma koşulları sağlanamadı.")
#2
# result1=int(input("lütfen 1. sınav notunuzu giriniz. "))
# result2=int(input("lütfen 2. sınav notunuzu giriniz. "))
# ortalama=(result1+result2)/2
# if ortalama>0 and ortalama<25:
# print("not bilginiz : 0")
# elif ortalama>24 and ortalama<45:
# print("not bilginiz : 1")
# elif ortalama>44 and ortalama<55:
# print("not bilginiz : 2")
# elif ortalama>54 and ortalama<70:
# print("not bilginiz : 3")
# elif ortalama>69 and ortalama<85:
# print("not bilginiz : 4")
# elif ortalama>84 and ortalama<101:
# print("not bilginiz : 5")
|
# # class
# class Person:
# #pass # içi bir bir class oluşturup hata almamak için içines pass yazıyoruz
# # class attributes
# address='no information'
# #constructor (yapıcı method)
# def __init__(self, name, year): # self p1,p2 gibi classtan türetilen nesneleri temsil eder
# #object attributes # init fonksiyonu p1,p2 gibi nesneler çalıştırıldığı anda çalışıyor
# self.name=name
# self.birthyear=year
# # instance method
# def intro(self):
# print(f" Hello There. I am "+self.name)
# def calculateAge(self):
# return 2020-self.birthyear
# #objecti (instance)
# p1=Person(name="Emre", year=1997) # bu şekilde yazmamız bile initin çalışması için yeterli
# p2=Person("Enes",2003) # 2 şekilde de nesneyi tanımlayabilirz
# p1.intro()
# p2.intro()
# print(f" yaşım: {p1.calculateAge()}")
# print(f" yaşım: {p2.calculateAge()} adım: {p2.name}")
# #updating
# # p1.name='Ahmet'
# # p1.address='Bursa'
# # # accessing object attributes
# # print(f'name: {p1.name} year: {p1.birthyear} address: {p1.address}')
# # print(f'name: {p2.name} year: {p2.birthyear} address: {p2.address}')
###############################################################################################################
class Circle:
#Class attribute
pi=3.14
def __init__(self,yaricap=1):
self.yaricap=yaricap
#methods
def cevre_hesapla(self):
return 2 * self.pi * self.yaricap
def alan_hesapla(self):
return self.pi * (self.yaricap**2)
c1=Circle() # yaricap=1
c2=Circle(5)
print(f" c1 alan : {c1.alan_hesapla()} c1 cevre:: {c1.cevre_hesapla()} ")
print(f" c2 alan : {c2.alan_hesapla()} c2 cevre: {c2.cevre_hesapla()}") |
import pandas as pd
df=pd.read_csv('imdb.csv')
# 1- Dosya hakkındaki bilgiler
result=df
result=df.info
result=df.columns
# 2- ilk 5 kayıt
result=df.head(5)
# 3- ilk 10 kayıt
result=df.head(10)
# 4- son 5 kayıt
result=df.tail(5)
# 5- son 10 kayıt
result=df.tail(10)
# 6- Sadece Movie_Title column
result=df["Movie_Title"]
# 7- Sadece Movie_Title column ilk 5 kayıt
result=df["Movie_Title"].head(5)
# 8- Sadece Movie_Title ve Rating column ilk 5 kayıt
result=df[["Movie_Title","Rating"]].head(5)
# 9- Sadece Movie_Title ve Rating column son 7 kayıt
result=df[["Movie_Title","Rating"]].head(5)
# 10- Sadece Movie_Title ve Rating column ikinci 5 kayıt
result=df[5:][["Movie_Title","Rating"]].head(5)
# 11- Sadece Movie_Title ve Rating column içeren ve imdb >= 8.0 olan ilk 50 kayıt
result=df[df["Rating"]>=8.0][["Movie_Title","Rating"]].head(50)
# 12- Yayın tarihi 2014 il 2015 arasında olan filmler
result=df[ (df["YR_Released"]>=2014) & (df["YR_Released"]<=2015)][["YR_Released","Movie_Title"]]
# 13- Num_Reviews 100.000 den büyük ya da imdb puanı 8 ile 9 arasında olan filmler
# query ile de aynı şeyleri yapabiliriz
result=df[(df["Num_Reviews"]>100000) | (df["Rating"]>=8) & (df["Rating"]<=9)]
result=df.query("Num_Reviews>100000 | Rating >=8 & Rating <=9")
print(result) |
class Person():
def __init__(self,fname,lname):
self.ad=fname
self.soyad=lname
print("Person Created")
def who_am_i(self):
print('I am a Person')
class Student(Person):
def __init__(self,dene1,dene2,number):
Person.__init__(self,dene1,dene2) ##### Person class ınıın initinni ezmemek için bunu yazıyoruz
self.stuNumber=number
print("Student Created.")
############# override aynı isimli method temel sınıftaki methodu ezer
def who_am_i(self):
print('I am a Student')
p1=Person('Emre','Çat')
p2=Student('Enes','sadfhg',1256)
print(p1.ad,p1.soyad)
print(p2.ad,p2.soyad, p2.stuNumber)
p1.who_am_i()
p2.who_am_i() |
name='Çınar'
surname="deneme"
print("my name is {} {}".format(name,surname)) |
#!/usr/bin/env python3
"""Program that calculates the probability density
function of a Gaussian distribution"""
import numpy as np
def pdf(X, m, S):
"""Function that calculates the probability density
function of a Gaussian distribution"""
if type(X) is not np.ndarray or len(X.shape) != 2:
return None
if type(m) is not np.ndarray or len(m.shape) != 1:
return None
if type(S) is not np.ndarray or len(S.shape) != 2:
return None
n, d = X.shape
if d != m.shape[0] or (d, d) != S.shape:
return None
inv = np.linalg.inv(S)
det = np.linalg.det(S)
a = 1 / np.sqrt((((2 * np.pi) ** (d) * det)))
inv = np.einsum('...k,kl,...l->...', (X - m), inv, (X - m))
b = np.exp(-(1 / 2) * inv)
P = a * b
P = np.where(P >= 1e-300, P, 1e-300)
return P
|
#!/usr/bin/env python3
"""Program that returns the list of school having a specific topic"""
def schools_by_topic(mongo_collection, topic):
"""Function that returns the list of school having a specific topic"""
all_items = mongo_collection.find()
docs = []
doc_filter = []
for elem in all_items:
docs.append(elem)
for elem in docs:
if 'topics' in elem.keys():
if topic in elem['topics']:
doc_filter.append(elem)
return doc_filter
|
#!/usr/bin/env python3
"""Program that calculates the minor matrix of a matrix"""
def determinant(matrix):
"""Function that calculates the determinant of a matrix"""
if type(matrix) is not list or not matrix:
raise TypeError('matrix must be a list of lists')
for data in matrix:
if type(data) is not list:
raise TypeError('matrix must be a list of lists')
if len(matrix) == 1 and len(matrix[0]) == 0:
return 1
for i in range(len(matrix)):
if len(matrix) != len(matrix[i]):
raise ValueError('matrix must be a square matrix')
n = len(matrix)
AM = matrix[:]
for fd in range(n):
for i in range(fd+1, n):
if AM[fd][fd] == 0:
AM[fd][fd] == 1.0e-18
crScaler = AM[i][fd] / AM[fd][fd]
for j in range(n):
AM[i][j] = AM[i][j] - crScaler * AM[fd][j]
product = 1
for i in range(n):
product *= AM[i][i]
return round(product)
def minor(matrix):
"""Function that calculates the minor matrix of a matrix"""
if type(matrix) is not list or not matrix:
raise TypeError("matrix must be a list of lists")
for data in matrix:
if type(data) is not list:
raise TypeError("matrix must be a list of lists")
if len(matrix) != len(data):
raise ValueError("matrix must be a non-empty square matrix")
if len(matrix) == 1:
return [[1]]
minor_matrix = [x[:] for x in matrix]
for i in range(len(matrix)):
sub = matrix[:i] + matrix[i + 1:]
for j in range(len(matrix)):
tmp = sub[:]
for k in range(len(tmp)):
tmp[k] = tmp[k][0:j] + tmp[k][j + 1:]
if len(tmp) > 1:
if len(tmp) > 2:
minor_matrix[i][j] = determinant(tmp)
else:
a = tmp[0][0]
b = tmp[0][1]
c = tmp[1][0]
d = tmp[1][1]
minor_matrix[i][j] = a * d - b * c
else:
minor_matrix[i][j] = tmp[0][0]
return minor_matrix
|
#!/usr/bin/env python3
"""Program that performs matrix multiplication"""
def mat_mul(mat1, mat2):
"""Function that performs matrix multiplication"""
mat1m = len(mat1)
mat1n = len(mat1[0])
mat2m = len(mat2)
mat2n = len(mat2[0])
result = []
if mat1n == mat2m:
for x in range(mat1m):
line = [0] * mat2n
result.append(line)
for y in range(len(result)):
for z in range(len(result[0])):
for i in range(mat1n):
result[y][z] += mat1[y][i] * mat2[i][z]
return result
return None
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.