text
stringlengths 37
1.41M
|
---|
list_of_airlines=["AI","EM","BA"]
print "Iterating the list using keyword in"
for airlines in list_of_airlines:
print airlines
print "Iterating the list using range()"
for index in range(len(list_of_airlines)):
print list_of_airlines[index]
|
list2=[]
i=0
while i<5:
a=input("Enter the items of list2 %d"%i)
list2.append(a)
i+=1
print "List2 is ",list2
|
import sqlite3
con=sqlite3.Connection('hrdb')
cur=con.cursor()
from Tkinter import *
root=Tk()
Label(root,text='Employee Record Keeping System:',font="times 20 bold italic").grid(row=0,column=1)
Label(root,text='Enter Emp Code:').grid(row=1,column=0)
e1=Entry(root)
e1.grid(row=1,column=1)
Label(root,text='Enter First Name:').grid(row=2,column=0)
e2=Entry(root)
e2.grid(row=2,column=1)
Label(root,text='Enter Last Name:').grid(row=3,column=0)
e3=Entry(root)
e3.grid(row=3,column=1)
Label(root,text='Enter Id To Fetch Record:').grid(row=4,column=0)
e4=Entry(root)
e4.grid(row=4,column=1)
def insert():
cur.execute("create table if not exists employee(code number,fname varchar(30),lname varchar(30))")
cur.execute("insert into employee values(e1.get(),e2.get(),e3.get())")
con.commit()
Button(root,text="Insert",command=insert).grid(row=6,column=0)
Button(root,text="Show",command=show).grid(row=6,column=1)
Button(root,text="Show All").grid(row=6,column=2)
root.mainloop()
|
def gcd(a,b):
return a if b==0 else gcd(b,a%b)
print(gcd(16,8)) |
def is_prime(num):
if num<1:return False
if num <=3: return True
if num%2==0 or num%3==0: return False
for i in range(5,num):
if i*i>num:
break
if num%i ==0 or num%(i+2)==0: return False
return True
def are_sexy_primes(a, b):
return is_prime(a) and is_prime(b)
print(are_sexy_primes(5,11)) |
"""Example of an undirected graph."""
from queue import Queue
class PersonNode():
"""Node in a graph representing a person."""
def __init__(self, name, adjacent=None):
"""Create a person node with cohabitants adjacent"""
if adjacent is None:
adjacent = set()
assert isinstance(adjacent, set), \
"adjacent must be a set!"
self.name = name
self.adjacent = adjacent
def __repr__(self):
"""Debugging-friendly representation"""
return f"<PersonNode: {self.name}>"
class CohabitantGraph():
"""Graph holding people and their cohabitant relationships."""
def __init__(self):
"""Create an empty graph"""
self.nodes = set()
def __repr__(self):
return f"<CohabitantGraph: { {n.name for n in self.nodes} }>"
def add_person(self, person):
"""Add a person to our graph"""
self.nodes.add(person)
def cohabitants(self, person1, person2):
"""Set two people as cohabitants"""
person1.adjacent.add(person2)
person2.adjacent.add(person1)
def add_people(self, people_list):
"""Add a list of people to our graph"""
for person in people_list:
self.add_person(person)
def are_connected(self, person1, person2):
"""Are two people connected? Breadth-first search."""
possible_nodes = Queue()
seen = set()
possible_nodes.enqueue(person1)
seen.add(person1)
while not possible_nodes.is_empty():
person = possible_nodes.dequeue()
print("checking", person)
if person is person2:
return True
else:
for cohabitant in person.adjacent - seen:
possible_nodes.enqueue(cohabitant)
seen.add(cohabitant)
print("added to queue:", cohabitant)
return False
def are_connected_recursive(self, person1, person2, seen=None):
"""Were two people cohabitants? Recursive depth-first search."""
if not seen:
seen = set()
if person1 is person2:
return True
seen.add(person1) # Keep track that we've visited here
print("adding", person1)
for person in person1.adjacent:
if person not in seen:
if self.are_connected_recursive(person, person2, seen):
return True
return False
def verbose_are_connected_recursive(self, person1, person2, seen=None):
"""Were two people cohabitants? Recursive depth-first search."""
if not seen:
seen = set()
if person1 is person2:
print("\nreturning True - {} is {}".format(person1.name, person2.name))
return True
seen.add(person1) # Keep track that we've visited here
print("adding", person1)
for person in person1.adjacent:
if person not in seen:
print("calling method on {}'s cohabitant {} with {}".format(person1.name, person.name, person2.name))
if self.verbose_are_connected_recursive(person, person2, seen):
print("\nreturning True from checking {}".format(person.name))
return True
print("returning False from checking {}".format(person1.name))
return False
rachel = PersonNode("Rachel Perkins")
steven = PersonNode("Steven Edouard")
jeff = PersonNode("Jeff Dean")
sara = PersonNode("Sara Ellsworth")
gabe = PersonNode("Gabe")
julie = PersonNode("Julie")
mari = PersonNode("Mari")
troy = PersonNode("Troy")
josh = PersonNode("Josh")
shigs = PersonNode("Jonathan Shigamatsu")
kim = PersonNode("Kim Shores")
sonam = PersonNode("Sonam Gill")
harman = PersonNode("Harman Nagi")
ashley = PersonNode("Ashley Youngblood")
sean = PersonNode("Sean Nichols")
sarah_p = PersonNode("Sarah Pulley")
olivia = PersonNode("Olivia Sorgman")
christie = PersonNode("Christie Bahna")
sarah_r = PersonNode("Sarah Rose")
jay = PersonNode("Jay Snow")
cohabitants = CohabitantGraph()
cohabitants.add_people([rachel, steven, jeff, sara, gabe, julie, mari, troy, josh,
shigs, kim, sonam, harman, ashley, sean, sarah_p, olivia, christie, sarah_r, jay])
cohabitants.set_cohabitants(rachel, steven)
cohabitants.set_cohabitants(rachel, josh)
cohabitants.set_cohabitants(rachel, troy)
cohabitants.set_cohabitants(rachel, jeff)
cohabitants.set_cohabitants(rachel, sara)
cohabitants.set_cohabitants(rachel, gabe)
cohabitants.set_cohabitants(rachel, julie)
cohabitants.set_cohabitants(rachel, sonam)
cohabitants.set_cohabitants(sonam, harman)
cohabitants.set_cohabitants(sonam, julie)
cohabitants.set_cohabitants(sonam, gabe)
cohabitants.set_cohabitants(julie, christie)
cohabitants.set_cohabitants(julie, mari)
cohabitants.set_cohabitants(julie, gabe)
cohabitants.set_cohabitants(julie, steven)
cohabitants.set_cohabitants(julie, olivia)
cohabitants.set_cohabitants(olivia, gabe)
cohabitants.set_cohabitants(sonam, olivia)
cohabitants.set_cohabitants(gabe, steven)
cohabitants.set_cohabitants(gabe, mari)
cohabitants.set_cohabitants(gabe, christie)
cohabitants.set_cohabitants(christie, mari)
cohabitants.set_cohabitants(troy, sean)
cohabitants.set_cohabitants(sean, sarah_p)
cohabitants.set_cohabitants(troy, josh)
cohabitants.set_cohabitants(troy, jeff)
cohabitants.set_cohabitants(troy, sara)
cohabitants.set_cohabitants(josh, jeff)
cohabitants.set_cohabitants(josh, sara)
cohabitants.set_cohabitants(jeff, sara)
cohabitants.set_cohabitants(josh, ashley)
cohabitants.set_cohabitants(ashley, shigs)
cohabitants.set_cohabitants(kim, shigs)
cohabitants.set_cohabitants(troy, mari)
cohabitants.set_cohabitants(sara, sarah_r)
cohabitants.set_cohabitants(sarah_r, jay) |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 26 15:55:34 2016
@author: pcarl_000
"""
num = int(input("Please enter a number: "))
if num % 4 == 0:
numtype = 'evenly divisible by four'
elif num % 2 == 0:
numtype = 'even'
else:
numtype = 'odd'
print('Your number is ' + numtype + '.')
|
from sys import argv # this imports information from the command line
script, filename = argv #this sets the information from the command line to the variables script and filename
txt = open(filename) # this sets the variable txt to "open(filename)" which will open the file named the input from the command line
print(f"Here's your file {filename}:") # this formats the string and inserts the filename variable into it then prints
print(txt.read()) #this reads the txt variable (which was set to open filename) and then prints it
print("Type the filename again:") #this prints the string
file_again = input("> ") #this sets input from the user equal to the variable "file again"
txt_again = open(file_again) # this sets the variable txt_again equal to "open(fuile_again)" which will open the file set equal to the "file_again" variable that the user set
print(txt_again.read()) # this reads the variable "txt_again" and prints it.
|
from sys import argv
baller = argv
filename = input("Want me to empty your file buddy? Go ahead and tell me the filename: ")
print(f"Here, read your file one last time:")
clearjob = open(filename)
print(clearjob.read())
print(f"Now watch it disappear")
clearjob = open(filename, 'w')
clearjob.truncate()
print(f"See, nothing left in your file homes.")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these to the file.")
clearjob.write(line1)
clearjob.write(line2)
clearjob.write(line3)
print(f"Here is the result: ")
clearjob = open(filename)
print(clearjob.read())
|
"""
Another potential option is to create a class "Trivia"
Objects could have attributes of category, question, answer, hint, etc.
"""
trivia_dictionary = {
"What is the capital of California?": "Sacramento",
"How many continents are there?": "7",
"What is the smallest country?": "Vatican City",
"What is the longest river in the world?": "Nile",
"What country has the longest total coastline?": "Canada",
"What year was SJSU founded": "1857",
"What year was the Declaration of Independence signed?": "1776",
"What year did humans first land on the Moon?": "1969",
"What year did the US acquire the Louisiana Purchase?": "1803",
"What year was the Magna Carta signed?": "1215",
"What is the element 'Fe'": "Iron",
"What is the element 'Au'": "Gold",
"What is the element 'Ag'": "Silver",
"What is the element 'He'": "Helium",
"What is the element 'Cu'": "Copper",
"What is the largest organ in the human body?": "Skin",
"What is the longest bone in the human body?": "Femur",
"Which grow faster fingernails or toenails?": "Fingernails",
"What organ produces insulin?": "Pancreas",
"How many blood types are there?": "8",
"Who invented basketball?": "James Naismith",
"Who invented Monopoly?": "Elizabeth Magie",
"Who invented the windshield wiper?": "Mary Anderson",
"Who invented Hot Cheetos?": "Richard Montanez",
"Who invented the ice cream maker?": "Nancy Johnson"
} |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 12 18:45:26 2019
@author: petru
"""
def anti_vowel(text):
vowels = ('aeiouAEIOU')
fl = []
for i in text:
if i not in vowels:
fl.append(i)
return "" .join(fl)
text = "GeeksforGeeks - A Computer Science Portal for Geeks"
print(anti_vowel(text))
|
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 6 20:52:04 2019
@author: petru
"""
from sys import argv
script, filename = argv
def print_all(f):
print(f.read())
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print(line_count, f.readline())
current_file = open(filename)
print("print first all file")
print_all(current_file)
print("Now let's rewind, kind a like of tape")
rewind(current_file)
print("Let's print three lines")
current_line = 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
|
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 15 19:20:37 2019
@author: petru
"""
# censor letter from a text
def censor(text, word):
leeds = '*' * len(word)
variabila = text.split()
count = 0
for item in variabila:
if item == word:
variabila[count] = leeds
count += 1
return ' ' .join(variabila)
print(censor("this is hack is wack hack", "hack"))
|
cart={
'天谕':{'近战':["光刃","圣堂","业刹"],
'远程':["炎天","玉虚","灵珑","流光"]},
'阴阳师':{'SSR':["一目连","荒","茨木童子"],
'SR':["姑获鸟","妖狐","夜叉"],
'R':["椒图","山兔","雨女"]},
'王者荣耀':{'法师':["诸葛亮","貂蝉","妲己"],
'刺客':["兰陵王","荆轲","李白"],
'射手':["李元芳","马可波罗","百里守约"]}
}
count=False
while not count:
for i in cart:
print(i)
choose1=input('请输入:')
if choose1 in cart:
while not count:
for i in cart[choose1]:
print(i)
choose2=input('请输入:')
if choose2 in cart[choose1]:
while not count:
for i in cart[choose1][choose2]:
print(i)
choose3 = input('请输入:')
if choose3=='q':
break
elif choose3=='n':
count=True
elif choose2 == 'q':
break
elif choose2 == 'n':
count = True
elif choose1 == 'q':
break
elif choose1 == 'n':
count = True
|
class Node:
def __init__(self, value, next_node = None):
self.value = value
self.next_node = next_node
def get_node_value(self):
return self.value
def set_next_node(self, next_node):
self.next_node = next_node
def get_next_node(self):
return self.next_node
class LinkedList:
#4 methods: init, get head node, insert beginning, stringify, remove a node
def __init__(self, value = None):
self.head_node = Node(value)
def get_head_node(self):
return self.head_node
def insert_beginning(self, new_head_value):
#1 set a new node
#2 link the new node with the head node
#3 set the new node as the head node
new_node = Node(new_head_value)
new_node.set_next_node(self.head_node)
self.head_node = new_node
def stringify(self):
#1 Create an empty string list
#2 Create a counter: set it at the head node of the linked list
#3 Use the counter to loop through all node: while the counter exists
# if the node the counter is at has a value, append that value to the string list using +=
#4 Update the counter: getting its next node
#5 Return the string list
string_list = ""
counter = self.get_head_node()
while counter:
if counter.get_node_value() != None:
string_list += str(counter.get_node_value())
counter = counter.get_next_node()
return string_list
def remove_node(self, value_to_remove):
#1 Create a counter: set it at the head node of the linked list
#2 Get the value of the counter (head node).
# If this == value to remove -> remove it by setting its next node as the new head node
#3 Else: Use the counter to loop through all node: while the counter exists
# Get the counter's next node. Name it next_node.
# If its next node's value == value to remove, remove it by link the counter(head node)(using set_next_node method)
# to the next node's next node value (using the method get next node)
#4 Break the while loop by setting counter = None
#5 Else: Move the counter to the next node
counter = self.get_head_node()
if counter.get_node_value() == value_to_remove:
self.head_node = counter.get_next_node()
else:
while counter:
next_node = counter.get_next_node()
if next_node.get_node_value() == value_to_remove:
counter.set_next_node(next_node.get_next_node())
counter = None
else:
counter = next_node
|
#!/usr/bin/env python
"""Advent of Code 2020 - Day 08 - Solution by Julian Knorr ([email protected])"""
import re
import sys
from typing import List, Tuple
OPERATION_REGEX = r"^([a-z]{3}) (\+|-)(\d+)$"
def read_puzzle_file(filename: str) -> List[str]:
file = open(filename, 'r')
lines = file.readlines()
return lines
def execute_operation(operation: str) -> Tuple[int, int]:
match_groups = re.compile(OPERATION_REGEX).fullmatch(operation.strip()).groups()
if match_groups is None:
raise ValueError("Invalid Operation Line.")
op = match_groups[0]
if op == "nop":
return 0, 1
diff = int(match_groups[2])
if match_groups[1] == "-":
diff *= -1
if op == "acc":
return diff, 1
if op == "jmp":
return 0, diff
raise ValueError("Invalid Operation.")
def execute_code(program: List[str]) -> Tuple[int, bool]:
executed = [False] * len(program)
acc = 0
pointer = 0
while True:
if pointer == len(program):
return acc, True
if pointer >= len(program):
return acc, False
if executed[pointer]:
return acc, False
acc_diff, pointer_diff = execute_operation(program[pointer])
executed[pointer] = True
acc += acc_diff
pointer += pointer_diff
def task1(puzzle: List[str]) -> int:
return (execute_code(puzzle))[0]
def task2(puzzle: List[str]) -> int:
for i in range(-1, len(puzzle)):
modified_program = puzzle.copy()
if i >= 0:
if modified_program[i].startswith("nop "):
modified_program[i] = "jmp" + modified_program[i][3:]
elif modified_program[i].startswith("jmp "):
modified_program[i] = "nop" + modified_program[i][3:]
else:
continue
acc, success = execute_code(modified_program)
if success:
return acc
raise RuntimeError("Task 2 not solvable.")
if __name__ == '__main__':
if len(sys.argv) == 2:
input_file = sys.argv[1]
puzzle_lines = read_puzzle_file(input_file)
task1_solution = task1(puzzle_lines)
print("Task 1: acc = {:d}".format(task1_solution))
task2_solution = task2(puzzle_lines)
print("Task 2: acc = {:d}".format(task2_solution))
else:
print("Usage: {:s} puzzle file".format(sys.argv[0]))
|
#!/usr/bin/env python
"""Advent of Code 2020 - Day 09 - Solution by Julian Knorr ([email protected])"""
import sys
from typing import List, Optional, Tuple
def find_sum(puzzle: List[int], start: int, end: int, value: int) -> bool:
for i in range(start, end):
for j in range(start, end):
if i == j:
continue
if puzzle[i] + puzzle[j] == value:
return True
return False
def first_error(puzzle: List[int], preamble_length: int) -> Optional[int]:
for i in range(preamble_length, len(puzzle)):
if not find_sum(puzzle, i - preamble_length, i, puzzle[i]):
return puzzle[i]
return None
def read_puzzle_file(filename: str) -> List[int]:
file = open(filename, 'r')
puzzle = []
for line in file.readlines():
puzzle.append(int(line))
return puzzle
def find_sum_set(puzzle: List[int], value: int) -> Tuple[int, int]:
for i in range(0, len(puzzle)):
set_sum = puzzle[i]
for j in range(i + 1, len(puzzle)):
set_sum += puzzle[j]
if set_sum == value:
return i, j
if set_sum > value:
break
raise RuntimeError("No solution.")
def task2(puzzle: List[int], value: int) -> int:
start, end = find_sum_set(puzzle, value)
minimum = min(*(puzzle[start:end + 1]))
maximum = max(*(puzzle[start:end + 1]))
return minimum + maximum
if __name__ == '__main__':
if len(sys.argv) == 2:
input_file = sys.argv[1]
puzzle_lines = read_puzzle_file(input_file)
task1_solution = first_error(puzzle_lines, 25)
print("Task 1: {:d}".format(task1_solution))
task2_solution = task2(puzzle_lines, task1_solution)
print("Task 2: {:d}".format(task2_solution))
else:
print("Usage: {:s} puzzle file".format(sys.argv[0]))
|
__author__ = 'Lei Chen'
'''
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in
the array, and it should return false if every element is distinct.
'''
class Solution:
# @param {integer[]} nums
# @return {boolean}
def containsDuplicate(self, nums):
return len(set(nums)) != len(nums) |
__author__ = 'Lei Chen'
'''
Given a string of numbers and operators, return all possible
results from computing all the different possible ways to group
numbers and operators. The valid operators are +, - and *.
Example 1
Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]
Example 2
Input: "2*3-4*5"
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
Output: [-34, -14, -10, -10, 10]
'''
class Solution(object):
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
ops = set(['+','-','*'])
ret = []
hasOp = False
for i, c in enumerate(input):
if c in ops:
hasOp = True
res1 = self.diffWaysToCompute(input[:i])
res2 = self.diffWaysToCompute(input[i+1:])
if c == '+':ret += [v1+v2 for v1 in res1 for v2 in res2]
elif c == '-':ret += [v1-v2 for v1 in res1 for v2 in res2]
else: ret += [v1*v2 for v1 in res1 for v2 in res2]
if not hasOp:
ret += [int(input)]
return ret
expressions = ['2-1-1', '2*3-4*5']
s = Solution()
for exp in expressions:
print(s.diffWaysToCompute(exp))
|
__author__ = 'Lei Chen'
'''
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
'''
import TreeNode
class Solution:
# @param {TreeNode} root
# @return {boolean}
def isBalanced(self, root):
if not root: return True
leftDepth = self.getDepth(root.left, 1)
rightDepth = self.getDepth(root.right,1)
if abs(leftDepth - rightDepth) > 1: return False
if not self.isBalanced(root.left): return False
if not self.isBalanced(root.right): return False
return True
def getDepth(self, root, preDepth):
if not root:
return preDepth
elif not root.left and not root.right:
return preDepth+1
leftDepth = self.getDepth(root.left,preDepth+1)
rightDepth = self.getDepth(root.right,preDepth+1)
return max(leftDepth, rightDepth)
s = Solution()
n1 = TreeNode.TreeNode(1)
n2 = TreeNode.TreeNode(2)
n3 = TreeNode.TreeNode(3)
n3.left = n1
n1.right = n2
print(s.isBalanced(n3)) |
__author__ = 'Lei Chen'
import TreeNode
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {string[]}
def binaryTreePaths(self, root):
if root == None: return []
if root.left == None and root.right == None: return [str(root.val)]
ret = list()
if root.left: self.helper(root.left, str(root.val), ret)
if root.right: self.helper(root.right, str(root.val), ret)
return ret
def helper(self, root, pre_list, ret):
if root.left == None and root.right == None:
ret.append(pre_list + "->" + str(root.val))
if root.left: self.helper(root.left, pre_list + "->" + str(root.val), ret)
if root.right: self.helper(root.right, pre_list + "->" + str(root.val), ret)
'''
1
/ \
2 3
\
5
'''
n1 = TreeNode.TreeNode(1)
n2 = TreeNode.TreeNode(2)
n3 = TreeNode.TreeNode(3)
n4 = TreeNode.TreeNode(4)
n5 = TreeNode.TreeNode(5)
n1.left = n2
n1.right = n3
n2.right = n5
s = Solution()
print(s.binaryTreePaths(n1)) |
__author__ = 'Lei Chen'
'''
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
'''
class Solution(object):
def removeZeros(self, nums):
if not nums or len(nums) < 1: return None
if len(nums) == 1: return nums[0]
zeros = [i for i,v in enumerate(nums) if v == 0]
if not zeros: return self.removeNegs(nums)
high = self.removeNegs(nums[:zeros[0]])
for i in range(len(zeros)):
segStart = zeros[i] + 1
segStop = zeros[i+1] if i < len(zeros)-1 else len(nums)
prod = self.removeNegs(nums[segStart:segStop])
if (not high and prod) or (high and prod and prod > high):
high = prod
return max(high, 0) if high else 0
def removeNegs(self, nums):
# count the negatives
if not nums or len(nums) < 1: return None
if len(nums) == 1: return nums[0]
negs = [i for i,v in enumerate(nums) if v < 0]
if len(negs)%2 == 0: return self.productOfAllAbs(nums)
if len(negs) == 1:
l = self.productOfAllAbs(nums[:negs[0]])
r = self.productOfAllAbs(nums[negs[0]+1:])
return max(l,r) if l or r else None
# at least 3 negs, find the leftmost and right most negs
return max(self.productOfAllAbs(nums[negs[0]+1:]), self.productOfAllAbs(nums[:negs[-1]]))
def productOfAllAbs(self, nums):
if not nums or len(nums) <= 0: return 0
prod = 1
for n in nums:
prod *= abs(n)
return prod
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return self.removeZeros(nums)
s = Solution()
numss = [[], [0], [2], [0, 2], [-2], [2,-2], [-2,2], [2,2], [-2,-2], [2,-2,2],
[-2,2,-2], [1,2,3,-4,2,2,2], [1,-2,3,-4,2], [2,-2,3,-2,4,-2,5]]
for nums in numss:
print(nums, ':', s.maxProduct(nums))
nums = [0,2]
print(nums, ':', s.removeZeros(nums))
|
__author__ = 'Lei Chen'
'''
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
'''
from ListNode import ListNode
class Solution(object):
def deleteDuplicates(self, head):
cur = head
while cur :
next = cur.next
while next and cur.val == next.val:
next = next.next
cur.next = next
cur = next
return head
input = ListNode.fromArray([1])
s = Solution()
ret = s.deleteDuplicates(input)
ret.printChain()
|
__author__ = 'Lei Chen'
'''
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 2^31 - 1.
For example,
123 -> "One Hundred Twenty Three"
12345 -> "Twelve Thousand Three Hundred Forty Five"
1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
'''
class Solution(object):
def units(self, u):
return ['', " Thousand", " Million", " Billion"][u]
def lessThan100(self,n):
hundredTable=["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
"Nineteen", "Twenty", "Twenty One", "Twenty Two", "Twenty Three", "Twenty Four", "Twenty Five",
"Twenty Six", "Twenty Seven", "Twenty Eight", "Twenty Nine", "Thirty", "Thirty One", "Thirty Two",
"Thirty Three", "Thirty Four", "Thirty Five", "Thirty Six", "Thirty Seven", "Thirty Eight",
"Thirty Nine", "Forty", "Forty One", "Forty Two", "Forty Three", "Forty Four", "Forty Five",
"Forty Six", "Forty Seven", "Forty Eight", "Forty Nine", "Fifty", "Fifty One", "Fifty Two",
"Fifty Three", "Fifty Four", "Fifty Five", "Fifty Six", "Fifty Seven", "Fifty Eight", "Fifty Nine",
"Sixty", "Sixty One", "Sixty Two", "Sixty Three", "Sixty Four", "Sixty Five", "Sixty Six",
"Sixty Seven", "Sixty Eight", "Sixty Nine", "Seventy", "Seventy One", "Seventy Two", "Seventy Three",
"Seventy Four", "Seventy Five", "Seventy Six", "Seventy Seven", "Seventy Eight", "Seventy Nine",
"Eighty", "Eighty One", "Eighty Two", "Eighty Three", "Eighty Four", "Eighty Five", "Eighty Six",
"Eighty Seven", "Eighty Eight", "Eighty Nine", "Ninety", "Ninety One", "Ninety Two", "Ninety Three",
"Ninety Four", "Ninety Five", "Ninety Six", "Ninety Seven", "Ninety Eight", "Ninety Nine"]
return hundredTable[n%100]
def lessThan1000(self,n):
i, r = divmod(n, 100)
ret = ""
ret += "" if i <= 0 else " " + self.lessThan100(i) + " Hundred"
ret += "" if r == 0 else " " + self.lessThan100(n)
return ret
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0: return "Zero"
if num < 100: return self.lessThan1000(num).strip()
ret = ''
for power in range(3, -1, -1):
i, num = divmod(num, 1000**power)
# print(i, num)
if i > 0:
ret += self.lessThan1000(i) + self.units(power)
return ret.strip()
s = Solution()
nums = [0,1,12,123,1234,12345,123456,1234567,12345678,123456789,1234567890]
# nums = [1001]
for n in nums:
print(n, ':', s.numberToWords(n))
|
__author__ = 'Lei Chen'
class Stack:
# initialize your data structure here.
def __init__(self):
self.q1 = []
self.q2 = []
# @param x, an integer
# @return nothing
def push(self, x):
while len(self.q1)>0:
self.q2.append(self.q1.pop(0))
self.q1.append(x)
while len(self.q2)>0:
self.q1.append(self.q2.pop(0))
# @return nothing
def pop(self):
self.q1.pop(0)
# @return an integer
def top(self):
return self.q1[0]
# @return an boolean
def empty(self):
return len(self.q1)==0
s = Stack()
s.push(1)
s.push(2)
print(s.top())
|
# 1. A recursive algorithm must have a base case.
# 2. A recursive algorithm must change its state and move towards the base case.
# 3. A recursive algorithm must call itself, recursively.
# Print every number, starting at 'number', until you reach 0
def recurse(number):
if number <= 0:
return
else:
print(number)
number -= 1
recurse(number)
#recurse(5)
# Fibonacci Sequence [1,1,2,3,5,8,13,21,34]
# Return the Nth Fibonacci Number
def fibonacci(n):
if n < 0:
print("Negative numbers are not valid")
if n == 0:
return 0
elif n == 1:
return 1
else:
# Return (n - 1) + (n - 2)
return fibonacci(n - 1) + fibonacci(n - 2)
print('fib',fibonacci(4))
## Quick Sort ##
# [5 9 3 7 2 8 1 6]
# [3 2 1] [5] [9 7 8 6]
# [2 1] [3] [] [5] [7 8 6] [9] []
# [1] [2] [3] [5] [6] [7] [8] [9]
# Decide on base case
# -base case is []
# Find the pivot point
# Partition data to the left and right of the pivot
# smaller than pivot <- left [pivot] right -> larger than pivot
# what if they are the same size as pivot? pick left or right
# repeat, recurse
my_list = [2,6,3,5,7,8,1,9,4]
def partition(data):
left = []
pivot = data[0]
right = []
for item in data[1:]:
if item < pivot:
left.append(item)
else:
right.append(item)
return left, pivot, right
def quicksort(data):
if data == []:
return data
left, pivot, right = partition(data)
return quicksort(left) + [pivot] + quicksort(right)
print(quicksort(my_list))
|
import pandas
# we need to import part of matplotlib
# because we are no longer in a notebook
import matplotlib.pyplot as plt
import sys
import glob
# load data and transpose so that country names are
# the columns and their gdp data becomes the rows
# read data into a pandas dataframe and transpose
#filename = "gapminder_gdp_oceania.csv"
#filename = sys.argv[1] #first parameter after scriptname
def parse_arguments():
"""Parses the user command line argument and returns file list
Inputs:
------
Nothing
Returns:
--------
file_list: list of file names
"""
if len(sys.argv) == 1:
#no arguments supplied
print("arguments required")
print("Usage: gdp_plot.py <filenames>")
print("Options: -a: plot all data in the current dir.")
exit()
if sys.argv[1] == '-a' :
file_list = glob.glob("*gdp*.csv")
if len(file_list) == 0:
print("No data files found *gdp*.csv in current dir.")
exit()
else:
file_list = sys.argv[1:]
return file_list
def create_plots(filename):
"""Plot data
Inputs:
-------
file name of data
Returns:
--------
Nothing (creates plot on screen)
"""
data = pandas.read_csv(filename, index_col =
'country').T
# create a plot the transposed data
ax = data.plot(title=filename)
# axes labels
ax.set_xlabel('Year')
ax.set_ylabel('GDP Per Capita')
# set axes ticks
ax.set_xticks(range(len(data.index)))
ax.set_xticklabels(data.index,rotation=45)
# display the plot
plt.show()
def main():
file_list = parse_arguments()
for filename in file_list:
create_plots(filename)
main()
|
from Strings import pad_string, unpad_string
def conjugate(sentence: str):
sentence = pad_string(sentence)
# swap conjugations
# This is mine and that is yours -->
# This is yours and that is mine
idx = 0
for key in conjugations.keys():
first_person = key
second_person = conjugations[key]
sentence = sentence.replace(f" {first_person} ", f" CON_first_{idx} ")
sentence = sentence.replace(f" {second_person} ", f" CON_second_{idx} ")
idx += 1
idx = 0
for key in conjugations.keys():
first_person = key
second_person = conjugations[key]
sentence = sentence.replace(f"CON_first_{idx}", second_person)
sentence = sentence.replace(f"CON_second_{idx}", first_person)
idx += 1
for key in conjugation_fixes.keys():
incorrect = key
corrected = conjugation_fixes[key]
sentence = sentence.replace(f" {incorrect} ", f" {corrected} ")
return unpad_string(sentence)
conjugations = {
"I": "you",
"am": "are",
"was": "were",
"my": "your",
"mine": "yours",
"I'm": "you're",
"I've": "you've",
"I'll": "you'll",
"me": "you",
"myself": "yourself",
}
# array to post process correct our tenses of pronouns such as "I/me"
conjugation_fixes = {
"me am": "I am",
"am me": "am I",
"me can": "I can",
"can me": "can I",
"me have": "I have",
"me will": "I will",
"will me": "will I"
}
|
string=raw_input("Enter string:")
char=0
word=1
for i in string:
char=char+1
print("Number of characters in the string:")
print(char)
|
"""
Codefight
Note: Your solution should have only one BST traversal and O(1) extra space complexity, since this is what you will be asked to accomplish in an interview.
A tree is considered a binary search tree (BST) if for each of its nodes the following is true:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and the right subtrees must also be binary search trees.
Given a binary search tree t, find the kth smallest element in it.
"""
import sys
from tree import Tree
# Morris Traversal
#
# Definition for binary tree:
# class Tree(object):
# def __init__(self, x):
# self.value = x
# self.left = None
# self.right = None
def kthSmallestInBST(root, k):
# count to iterate over elements
count = 0
# store ksmall
ksmall = - sys.maxsize - 1
cur = root
while (cur is not None):
if (cur.left is None):
count += 1
# if found ksmall
if (count == k):
ksmall = cur.value
# go to parent right_child
cur = cur.right
else:
# create link for Inorder
pre = cur.left
while (pre.right is not None) and (pre.right != cur):
pre = pre.right
# building links
if (pre.right is None):
pre.right = cur
cur = cur.left
else:
# revert changes
pre.right = None
count += 1
if (count == k):
ksmall = cur.value
cur = cur.right
return ksmall
def main():
t = Tree(3)
t.left = Tree(1)
t.right = Tree(5)
t.right.left = Tree(4)
t.right.right = Tree(6)
a = kthSmallestInBST(t, 5)
print(a)
main()
|
# Question - The variable nested contains a nested list. Assign ‘snake’ to the variable output using indexing.
nested = [['dog', 'cat', 'horse'], ['frog', 'turtle', 'snake', 'gecko'], ['hamster', 'gerbil', 'rat', 'ferret']]
output = nested[1][2]
print(output)
# Question 2 - Below, a list of lists is provided. Use in and not in tests to create variables with Boolean values.
# See comments for farther instructions.
lst = [['apple', 'orange', 'banana'], [5, 6, 7, 8, 9.9, 10], ['green', 'yellow', 'purple', 'red']]
# Test to see if 'yellow' is in the third list of lst. Save to variable ``yellow``
if 'yellow' in lst[2]:
yellow = True
else:
yellow = False
print(yellow) # to check if variable 'yellow' is True
# Test to see if 4 is in the second list of lst. Save to variable ``four``
if 4 in lst[1]:
four = True
else:
four = False
print(four) # to check if variable "four" is False
# Test to see if 'orange' is in the first element of lst. Save to variable ``orange``
if 'orange' in lst[0]:
orange = True
else:
orange = False
print(orange)
# Question - Below, we’ve provided a list of lists.
# Use in statements to create variables with Boolean values - see the ActiveCode window for farther directions.
L = [[5, 8, 7], ['hello', 'hi', 'hola'], [6.6, 1.54, 3.99], ['small', 'large']]
# Test if 'hola' is in the list L. Save to variable name test1
if 'hola' in L:
test1 = True
else:
test1 = False
print(test1) # to check if variable "test1" is False
# Test if [5, 8, 7] is in the list L. Save to variable name test2
if [5, 8, 7] in L:
test2 = True
else:
test2 = False
print(test2)
# Test if 6.6 is in the third element of list L. Save to variable name test3
if 6.6 in L[2]:
test3 = True
else:
test3 = False
print(test3)
# Question - Provided is a nested data structure. Follow the instructions in the comments below. Do not hard code.
nested = {'data': ['finding', 23, ['exercises', 'hangout', 34]], 'window': ['part', 'whole', [], 'sum',
['math', 'calculus', 'algebra', 'geometry',
'statistics',
['physics', 'chemistry', 'biology']]]
}
# Check to see if the string data is a key in nested, if it is, assign True to the variable data, otherwise assign False.
if 'data' in nested:
data = True
else:
data = False
print(data)
# Check to see if the integer 24 is in the value of the key data, if it is then assign to the variable twentyfour the
# value of True, otherwise False.
if 24 in nested['data']:
twentyfour = True
else:
twentyfour = False
print(twentyfour)
# Check to see that the string 'whole' is not in the value of the key window. If it's not, then assign to the variable whole the value of True, otherwise False.
if 'whole' not in nested['window']:
whole = True
else:
whole = False
print(whole)
# Check to see if the string 'physics' is a key in the dictionary nested. If it is, assign to the variable physics, the value of True, otherwise False.
if 'physics' in nested:
physics = True
else:
physics = False
print(physics)
# Question - The variable nested_d contains a nested dictionary with the gold medal counts for the top four
# countries in the past three Olympics. Assign the value of Great Britain’s gold medal count from the London
# Olympics to the variable london_gold. Use indexing. Do not hardcode.
nested_d = {'Beijing':{'China':51, 'USA':36, 'Russia':22, 'Great Britain':19}, 'London':{'USA':46, 'China':38, 'Great Britain':29, 'Russia':22}, 'Rio':{'USA':35, 'Great Britain':22, 'China':20, 'Germany':13}}
london_gold = nested_d['London']['Great Britain']
print(london_gold)
# Question - Below, we have provided a nested dictionary.
# Index into the dictionary to create variables that we have listed in the ActiveCode window.
sports = {'swimming': ['butterfly', 'breaststroke', 'backstroke', 'freestyle'], 'diving': ['springboard', 'platform', 'synchronized'], 'track': ['sprint', 'distance', 'jumps', 'throws'], 'gymnastics': {'women':['vault', 'floor', 'uneven bars', 'balance beam'], 'men': ['vault', 'parallel bars', 'floor', 'rings']}}
# Assign the string 'backstroke' to the name v1
v1 = sports['swimming'][2]
print(v1)
# Assign the string 'platform' to the name v2
v2 = sports['diving'][1]
print(v2)
# Assign the list ['vault', 'floor', 'uneven bars', 'balance beam'] to the name v3
v3 = sports['gymnastics']['women']
print(v3)
# Assign the string 'rings' to the name v4
v4 = sports['gymnastics']['men'][-1]
print(v4)
# Question - Given the dictionary, nested_d, save the medal count for the USA from all three Olympics in the dictionary to the list US_count.
nested_d = {'Beijing': {'China': 51, 'USA': 36, 'Russia': 22, 'Great Britain': 19},
'London': {'USA': 46, 'China': 38, 'Great Britain': 29, 'Russia': 22},
'Rio': {'USA': 35, 'Great Britain': 22, 'China': 20, 'Germany': 13}
}
US_count = []
for key, value in nested_d.items():
if 'USA' in value.keys():
US_count.append(value['USA'])
print(US_count)
# Question - Iterate through the contents of l_of_l and assign the third element of sublist to a new list called third.
l_of_l = [['purple', 'mauve', 'blue'], ['red', 'maroon', 'blood orange', 'crimson'], ['sea green', 'cornflower', 'lavender', 'indigo'], ['yellow', 'amarillo', 'mac n cheese', 'golden rod']]
third = []
for elem in l_of_l:
third.append(elem[2])
print(third)
# Question - Given below is a list of lists of athletes. Create a list, t, that saves only the athlete’s name
# if it contains the letter “t”. If it does not contain the letter “t”, save the athlete name into list other.
athletes = [['Phelps', 'Lochte', 'Schooling', 'Ledecky', 'Franklin'], ['Felix', 'Bolt', 'Gardner', 'Eaton'], ['Biles', 'Douglas', 'Hamm', 'Raisman', 'Mikulak', 'Dalton']]
check = 't'
t = []
other = []
for letter in athletes[0]:
if check in letter:
t.append(letter)
else:
other.append(letter)
for letter_1 in athletes[1]:
if check in letter_1:
t.append(letter_1)
else:
other.append(letter_1)
for letter_2 in athletes[2]:
if check in letter_2:
t.append(letter_2)
else:
other.append(letter_2)
print(t)
print(other)
|
# handling errors in python socket programs
import socket #for sockets
import sys #for exit
try:
#create an AF_INET, STREAM socket (TCP)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except Exception as err:
code, msg = inst.args
print('Failed to create socket. Error code: ' + str(code) + ', Error message : ' + msg)
sys.exit()
print('Socket Created')
host = 'www.google.com'
port = 80
try:
remote_ip = socket.gethostbyname(host)
except Exception as err:
#could not resolve
print('Hostname could not be resolved. Exiting')
sys.exit()
print('Ip address of ' + host + ' is ' + remote_ip)
#Connect to remote server
s.connect((remote_ip, port))
print('Socket Connected to ' + host + ' on ip ' + remote_ip)
#Send some data to remote server
# socket.sendall accepts byte string (str in Python 2.x, bytes in Python 3.x). In Python 3.x, you should use bytes literal
message = b"GET / HTTP/1.1\r\n\r\n"
try:
#Set the whole string
s.sendall(message)
except Exception as err:
print('Send failed.')
sys.exit()
print('Message send successfully')
reply = s.recv(4096)
print(reply)
#close socket
s.close()
|
'''Create a class representing a concert ticket.
Its constructor takes two values: a ticket price,
and a section.
>>> my_ticket = ConcertTicket(22.0, 'floor')
>>> your_ticket = ConcertTicket(42.0, 'mezzanine')
You can access these two values through the price and section
attributes:
>>> my_ticket.price
22.0
>>> your_ticket.section
'mezzanine'
Once set, the price cannot be changed. If you try to set it,
it raises an error.
>>> my_ticket.price = 20.0
Traceback (most recent call last):
...
AttributeError: can't set attribute
The section can be changed, but can only be set to "floor", "lower",
"mezzanine", or "premier". If you try to change it to something
different, a ValueError is raised, with a descriptive error message:
>>> my_ticket.section = "lower"
>>> my_ticket.section
'lower'
>>> my_ticket.section = "premier"
>>> my_ticket.section
'premier'
>>> my_ticket.section = "upper_mezzanine"
Traceback (most recent call last):
...
ValueError: Invalid section "upper_mezzanine"
'''
# Write your code here:
# Do not edit any code below this line!
if __name__ == '__main__':
import doctest
doctest.testmod()
# Copyright 2015-2016 Aaron Maxwell. All rights reserved.
|
import re
sub_name = 'REEILsEMKKV'
sub_name=sub_name.strip()
pattern = r'[a-z]'
matches = re.findall(pattern,sub_name)[0]
print(matches)
print(filter(str.islower,sub_name)) |
ex=["left","right","up","down"]
for i,j in enumerate(ex):
print(i,j)
new_dict = dict(enumerate(ex))
print(new_dict)
[print(i,j) for i,j in enumerate(new_dict)] |
from collections import defaultdict
''' This is my attempt at doing this from scratch.
Helper file for encoding the Suduko Board.
The display function is borrowed from a course.
This question was inspired from a course on AI and deep-learning
'''
# Variables to encode the board. Rows are horizontal labels. I'm directionally impaired.
rows = 'ABCDEFGHI'
cols = '123456789'
boxes = [r + c for r in rows for c in cols]
def extract_unit(unitList, boxes):
# Extract the units, each box has respective units as per the game of Suduko.
# The rows, coloumns and squares in which each box are present.
# Argument: unitList, list that contains all the boxes in general.
# boxes, all the squares.
# Returns: Dictionary with units for each box.
unitDict = defaultdict(list)
for box in boxes:
for item in unitList:
if box in item:
unitDict[box].append(item)
return unitDict
def extract_peers(unit, boxes):
# Read extract_Unit.
# This encodes box:unit in dictionary form.
# unit is what extract_unit returns.
peerDict = defaultdict(set) # to remove duplication
for box in boxes:
for item in unit[box]:
for unitBoxes in item:
peerDict[box].add(unitBoxes)
return peerDict
def cross(rows, cols):
# Refactor crossing code.
return [r + c for r in rows for c in cols]
def generate_dictionary(grid, boxes):
# Generate the key:Value mapping for boxes:values. I.e, A1 is the upper most top left box that may have '1' lets say.
# Grid is the string that holds the encoded table with 'x' or '.' representing an empty box.
# The output is the dictionary with Box:Number.
dictionary = dict(zip(boxes,grid))
for item in dictionary:
if dictionary[item] == '.' or dictionary[item] == 'x':
dictionary[item] = '123456789'
else:
dictionary[item] = dictionary[item]
return dictionary
def display(values):
width = 1+max(len(values[s]) for s in boxes)
line = '+'.join(['-'*(width*3)]*3)
for r in rows:
print(''.join(values[r+c].center(width)+('|' if c in '36' else '')
for c in cols))
if r in 'CF': print(line)
print()
def menu():
# Menu to display all options.
# Has some basic test cases that were ranked "Evil" on many websites.
# Most of them were used extensively in debugging.
print('\n')
print ('\tMenu\t')
print ('1 - Try test case 1')
print ('2 - Try test case 2')
print ('3 - Try a difficult test case!')
print ('4 - Try out your own')
print('\n')
inputChoice = input('\n\nEnter your choice: ')
print('\n\n')
if (inputChoice == '1'):
diag_sudoku_grid = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'
elif (inputChoice == '2'):
diag_sudoku_grid = '.8..1..7.7..6.3..5..4...3...4.2.1.3.8.......7.7.8.6.4...1...2..9..4.2..8.2..6..9.'
elif (inputChoice == '3'):
diag_sudoku_grid = '1...5...4.4.6.7.5...3...1...8.5.1.6.6.......2.2.4.6.1...4...7...3.2.4.8.9...6...5'
elif (inputChoice == '4'):
diag_sudoku_grid = ''
print('Enter the input in rows. If a box is empty, enter . \nFor example, if the first row has 1 in the first box and 0 in the last, enter 1........0')
print('You can also use x to denote empty boxes.')
for i in range (0,9):
inputString = input('\n\nEnter the row: ')
if (len(inputString) != 9):
print('Something went wrong, not 9 values.')
print('\n\tTry Again\n\n')
exit()
diag_sudoku_grid += inputString
else:
print('Invalid String, restart program')
return diag_sudoku_grid
# Main
diag_sudoku_grid = menu()
myDict = generate_dictionary(diag_sudoku_grid, boxes)
display(myDict)
|
n=int(input("Enter the limit:"))
a=0
b=1
c=0
print(a,b,end=" ")
for i in range(0,n+1):
c=a+b
a=b
b=c
print(c,end=" ")
|
temperature = int(input("Enter the temperature (Celsius): "))
windspeed = int(input("Enter the wind speed (km/h): "))
print("The wind chill factor is:", end="")
print(13.12 + (0.6215 * temperature) - (11.37 * windspeed ** 0.16) + (0.3965 * temperature * windspeed ** 0.16))
|
minutes = int(input("Enter number of minutes: "))
print("This is", minutes // 1440, "days,", minutes % 1440 // 60, "hours &,", minutes % 60, "minutes") |
total = 0
number = int(input("Enter your number: "))
for i in range(number + 1):
total = total + i
print(total) |
'''
-------------------------------------------------------------------------------
Name: microbit_logical_demonstration_assignment.py
Purpose: When button is pressed while potentiometer is turned down, displays an
image on the screen while flashing the red led and playing a note on buzzer.
When button is pressed and potentiometer is turned up, displays an different
image on the screen while flashing the red led and playing the same note in a
different octave. If nothing is pressed, red led is turned off and image is
displayed on screen.
Authors: Ma.Charlie, Lui.Andrew
Created: 03/11/2019
------------------------------------------------------------------------------
'''
#import microbit module to control microbit,
#import music module to control sound
from microbit import *
import music
# name variables, setup pins
crash_sensor = pin2
buzzer = pin15
ad_keypad = pin0
potentiometer = pin1
red_led = pin16
# crash sensor setup
crash_sensor.set_pull(crash_sensor.PULL_UP)
while True:
# if button a is pressed while potentiometer is turned down display
# happy face, flash red led and play note c on the 4th octave
if (ad_keypad.read_analog() > 0 and ad_keypad.read_analog() < 20
and potentiometer.read_analog() > 0
and potentiometer.read_analog() <= 511):
display.show(Image.HAPPY)
red_led.write_digital(1)
music.play("c4:2", pin=buzzer)
# if button b is pressed while potentiometer is turned down display
# happy face, flash red led and play note d on the 4th octave
if (ad_keypad.read_analog() > 40 and ad_keypad.read_analog() < 60
and potentiometer.read_analog() > 0
and potentiometer.read_analog() <= 511):
display.show(Image.HAPPY)
red_led.write_digital(1)
music.play("d4:2", pin=buzzer)
# if button c is pressed while potentiometer is turned down display
# happy face, flash red led and play note e on the 4th octave
if (ad_keypad.read_analog() > 90 and ad_keypad.read_analog() < 100
and potentiometer.read_analog() > 0
and potentiometer.read_analog() <= 511):
display.show(Image.HAPPY)
red_led.write_digital(1)
music.play("e4:2", pin=buzzer)
# if button d is pressed while potentiometer is turned down display
# happy face, flash red led and play note e on the 4th octave
if (ad_keypad.read_analog() > 130 and ad_keypad.read_analog() < 150
and potentiometer.read_analog() > 0
and potentiometer.read_analog() <= 511):
display.show(Image.HAPPY)
red_led.write_digital(1)
music.play("f4:2", pin=buzzer)
# if button e is pressed while potentiometer is turned down display
# happy face, flash red led and play note f on the 4th octave
if (ad_keypad.read_analog() > 500 and ad_keypad.read_analog() < 550
and potentiometer.read_analog() > 0
and potentiometer.read_analog() <= 511):
display.show(Image.HAPPY)
red_led.write_digital(1)
music.play("g4:2", pin=buzzer)
# if crash sensor is pressed display angry face, flash red led
# and play funk melody
if crash_sensor.read_digital() == 0:
display.show(Image.ANGRY)
red_led.write_digital(1)
music.play(music.FUNK, pin=buzzer)
# if button a is pressed while potentiometer is turned up display
# surprised face, flash red led and play note c on the 3rd octave
elif (ad_keypad.read_analog() > 0 and ad_keypad.read_analog() < 20
and potentiometer.read_analog() > 511
and potentiometer.read_analog() <= 1023):
display.show(Image.SURPRISED)
red_led.write_digital(1)
music.play("c3:2", pin=buzzer)
# if button b is pressed while potentiometer is turned up display
# surprised face, flash red led and play note d on the 3rd octave
elif (ad_keypad.read_analog() > 40 and ad_keypad.read_analog() < 60
and potentiometer.read_analog() > 511
and potentiometer.read_analog() <= 1023):
display.show(Image.SURPRISED)
red_led.write_digital(1)
music.play("d3:2", pin=buzzer)
# if button c is pressed while potentiometer is turned up display
# surprised face, flash red led and play note e on the 3rd octave
elif (ad_keypad.read_analog() > 90 and ad_keypad.read_analog() < 100
and potentiometer.read_analog() > 511
and potentiometer.read_analog() <= 1023):
display.show(Image.SURPRISED)
red_led.write_digital(1)
music.play("e3:2", pin=buzzer)
# if button d is pressed while potentiometer is turned up display
# surprised face, flash red led and play note f on the 3rd octave
elif (ad_keypad.read_analog() > 135 and ad_keypad.read_analog() < 140
and potentiometer.read_analog() > 511
and potentiometer.read_analog() <= 1023):
display.show(Image.SURPRISED)
red_led.write_digital(1)
music.play("f3:2", pin=buzzer)
# if button e is pressed while potentiometer is turned up display
# surprised face, flash red led and play note g on the 3rd octave
elif (ad_keypad.read_analog() > 535 and ad_keypad.read_analog() < 545
and potentiometer.read_analog() > 511
and potentiometer.read_analog() <= 1023):
display.show(Image.SURPRISED)
red_led.write_digital(1)
music.play("g3:2", pin=buzzer)
# if nothing is done turn off red led and display music note
else:
red_led.write_digital(0)
display.show(Image.MUSIC_QUAVER)
|
n = int(input("Enter your number: "))
i = n
while i <=n:
if 2 ** i < n:
print("exponent:", i)
print("2**n:", 2**i)
break
else:
i -= 1
|
s1=input()
l1=[0]
if "ab1" not in s1:
print("0")
else:
for i1 in range(len(s1)):
c1=1
for j1 in range(i1,len(s1)-1):
if s1[j1]=="a1" and s1[j1+1]=="b":
c1=c1+1
elif s1[j1]=="b1" and s1[j1+1]=="a1":
c1=c1+1
else:
l1.append(c1)
c1=1
break
if s1[i1]=="a1":
l1.append(c1)
else:
l1.append(c1-1)
print(max(l1))
|
import sys
def read_file(file_location):
"""
Reads the file stored at :param file_location
:param file_location: absolute path for the file to be read (string)
:return: contents of file (string)
"""
try:
with open(file_location, "r") as file:
return file.read()
except FileNotFoundError:
print("[ERROR] Error: FileNotFoundError, Response: Failed to read {0}".format(file_location), file=sys.stderr)
return ""
def write_file(file_location, data):
"""
Writes :param data to the file stored at :param file_locations
:param file_location: absolute path for the file that is being written too (string)
:param data: data that will be written to the file (string)
:return: (None)
"""
with open(file_location, "w") as file:
file.write(data)
class SortedDictionary:
"""
SortedDictionary Class
Class that sorts a dictionary based on the length of the value data item
"""
def __init__(self, dictionary):
"""
SortedDictionary Constructor
:param dictionary: dictionary to be sorted. In format {key:value}, where key is string
and value is data item(dict)
"""
self._dictionary = self._sort_dictionary(dictionary)
def _sort_dictionary(self, dictionary):
"""
Private method that sorts the dictionary
:param dictionary: dictionary to be sorted
:return: Sorted dictionary (list of tuples)
"""
return sorted(dictionary.items(), key=lambda x: len(str(x[1])))
def names(self):
"""
Returns names for an ascii-table Table object
:return: (dict)
"""
return {
"Header": "Name",
"Contents": map(lambda x: str(x[0]), self._dictionary)
}
def values(self):
"""
Returns values for an ascii-table Table object
:return: (dict)
"""
return {
"Header": "Value",
"Contents": map(lambda x: str(x[1]), self._dictionary)
}
def __getitem__(self, key):
"""
Returns a value from a (key, value) pair in the SortedDictionary object. Uses simple linear search algorithm.
:param key: key of (key, value) pair in dictionary (string)
:return: value of (key, value) pair
"""
value = list(filter(lambda x: key == x[0], self._dictionary))
if not len(value):
return ""
return value[0][1]
def __delitem__(self, key):
"""
Removes a key, value pair from the SortedDictionary object.
:param key: key of (key, value) pair in dictionary
:return: (None)
"""
self._dictionary = list(filter(lambda x: x[0] != key, self._dictionary))
def __len__(self):
"""
Returns the length of the SortedDictionary object
:return: length (integer)
"""
return len(self._dictionary)
def __repr__(self):
"""
Returns string representation of the SortedDictionary object
:return: string representation of the SortedDictionary object (string)
"""
return str(self._dictionary)
|
>>> print ("hello world!")
hello world!
>>> print ('hello world!')
hello world!
>>> print ('hello William')
hello William
>>> #print ('hello world')
>>> print ('Γειά σου Κόσμε')
Γειά σου Κόσμε
>>> print ('Olá Mundo')
Olá Mundo
>>> print ('안녕 세상')
안녕 세상
>>> ('你好,世界')
'你好,世界'
>>> print ('Salamu, Dunia')
Salamu, Dunia
>>> ('Jambo Dunia')
'Jambo Dunia'
>>> ("您好世界 is how you say Hello world in chinese.")
您好世界 is how you say Hello world in chinese.
|
import argparse
import re
def string_type(string):
"""
@param string: Type of the string to be checked
0: both name and value
1: only the value
2: only the name
"""
if any(char.isdigit() for char in string):
if re.search(r"\D{3,}\s", string):
return 0
else:
return 1
return 2
def position_definer(center_y, ymin, ymax):
"""
@param center_y: y coordinate of the search box
@param ymin: minimum y coordinate of the box to be tested for
@param ymax: maximum y coordinate of the box to be tested for
"""
return ymin < center_y < ymax
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("-s", "--string", required=True, help="string to be checked")
args = ap.parse_args()
print(string_type(args.string))
|
'''
Multiples of 3 and 5
'''
def multiples(num1, num2, maxNum):
nums = []
for i in range(2, maxNum):
if i % num1 == 0:
nums.append(i)
elif i % num2 == 0:
nums.append(i)
else:
pass
return nums
def sum_multiples(num1, num2, maxNum):
nums = multiples(num1, num2, maxNum)
print(nums)
result = sum(nums)
return result
if __name__ == "__main__":
print(sum_multiples(3, 5, 1000)) |
###################################################
#################[ Module: Utils ]#################
###################################################
"""
Miscellaneous utilities for caspanda.
"""
def paste(x, sep=", "):
"""
Custom string formatting function to format (???) output.
"""
out = ""
for i in x:
out += i + sep
return out.strip(sep)
def print_ls(ls, ident = '', braces=1):
""" Recursively prints nested lists."""
out = ""
for value in ls:
if isinstance(value, list):
out = out + print_ls(value, ident+'\t', braces+1)
else:
out = out + ident+'%s' %(value if isinstance(value, basestring) else value.name) + '\n'
return out |
print("1. Add Number")
print("2. Search Number")
print("3. Exit the program")
dictContact = {}
loop = True
while loop:
user_choice = input("Enter your choice:")
if user_choice == '1':
inp_name = input("Enter your name: ")
inp_number = input("Enter your number: ")
print()
dictContact[inp_name] = inp_number
elif user_choice == '2':
dictContact[inp_name] = inp_number
search = input("Enter the name: ")
print(dictContact[search])
else:
break
|
list1 = ["Arteezy","Noone","Sumail","Crit"]
for i in range (len(list1)):
print(list1[i])
print("\n")
list2 = ["A","N","S","C"]
for z in range (len(list2)):
print(list2[z])
print("\n")
list3 = [1,3,2,4]
for x in range(len(list3)):
print(list3[x])
print("\n")
list4 = ["EG","VP","TNC","MNSK"]
for y in range(len(list4)):
print(list4[y])
|
string = "This is a string"
string = string.split(" ")
print(string)
string = "hej".join(string)
print(string) |
foods = ["taco", "pizza", "Mom's spaghetti", "IKEA MEATBALLS DALAHORSE FTW", "taco"]
not_foods = ["shoes", "fox", "mom", "warlock"]
def has_equal_ends(list):
x = len(list)
if list[0] == list[x-1]:
return True
else:
return False
print(has_equal_ends(foods))
print(has_equal_ends(not_foods)) |
# print('안녕하세요') #프린트함수=> 화면출력
# print('이름이 무엇인가요?')
# myName = input() #입력받기
# print('반갑습니다. ' + myName)
# print('당신의 이름 길이는: ')
# print(len('myName')) #len 문자열의 길이
# print('당신의 나이는?')
# myAge = input()
# print('당신은 내년에 ' + str(int(myAge)+1) + '살 입니다.')
# print('안녕', 1, 2)
# # print('안녕' + 1 + 2) #이 경우는 오류
# print('안녕' + str(1) + str(2))
|
TAX_RATE = 0.20
STANDARD_DEDUCTION = 10000.0
DEPENDENT_DEDUCTION = 3000.0
from breezypythongui import EasyFrame
class TaxCalculator(EasyFrame):
"""Application window for the tax calculator."""
def __init__(self):
"""Sets up the window and the widgets."""
EasyFrame.__init__(self, title="Tax Calculator")
self.addLabel(text="Income", row=0, column=0)
self.incomeField = self.addFloatField(value=0.0, row=0, column=1)
self.addLabel(text="Dependents", row=1, column=0)
self.depField = self.addIntegerField(value=0, row=1, column=1)
self.addButton(text="Compute", row=2, column=0, columnspan=2, command=self.computeTax)
self.addLabel(text="Total tax", row=3, column=0)
self.taxField = self.addFloatField(value=0.0, row=3, column=1, precision=2)
def computeTax(self):
"""Obtains the data from the input fields and uses
them to compute the tax, which is sent to the
output field."""
income = self.incomeField.getNumber()
numDependents = self.depField.getNumber()
tax = (income - STANDARD_DEDUCTION - numDependents*DEPENDENT_DEDUCTION) * TAX_RATE
self.taxField.setNumber(tax)
def main():
TaxCalculator().mainloop()
if __name__ == '__main__':
main()
|
#Assignment 06
print("This is Program06 - Armando Castro")
print("This program uses lists, strings, tuples, and dictionaries.")
# Two Tuples
weeks = ('Week One', 'Week Two')
days = ('Thursday', 'Friday', 'Saturday')
# Sales reps names and locations
sales_rep_names = ['Frank Fleming', 'Domingo Depue', 'Ema Endicott']
sales_rep_locations = ['Austin', 'Dallas', 'Houston']
# get names and locations
# create 3 lists
boats_sold_thursday = []
boats_sold_friday = []
boats_sold_saturday = []
boats_sold_thursday2 = []
boats_sold_friday2 = []
boats_sold_saturday2 = []
# Populate boats sold list
# Enter Sales Results
print('\n-----Entering boats sold for :', weeks[0], '-----')
for items in sales_rep_names:
boats_sold_thursday.append(int(input(
'\nThursday boats sold by ' + items + ':')))
boats_sold_friday.append(int(input(
'\nFriday boats sold by :' + items + ':')))
boats_sold_saturday.append(int(input(
'\nSaturday boats sold by :' + items + ':')))
print('\n-----Entering boats sold for :', weeks[1], '-----')
for items in sales_rep_names:
boats_sold_thursday2.append(int(input(
'\nThursday boats sold by ' + items + ':')))
boats_sold_friday2.append(int(input(
'\nFriday boats sold by :' + items + ':')))
boats_sold_saturday2.append(int(input(
'\nSaturday boats sold by :' + items + ':')))
# Print Sales Results
print("\n-----", weeks[0], "Results -----")
for y in range(3):
print(sales_rep_names[y], "sold ", boats_sold_thursday[y], "on Thursday")
print(sales_rep_names[y], "sold ", boats_sold_friday[y], "on Friday")
print(sales_rep_names[y], "sold ", boats_sold_saturday[y], "on Saturday")
print("\n")
print("-----", weeks[1], "Results -----")
for z in range(3):
print(sales_rep_names[y], "sold ", boats_sold_thursday2[z], "on Thursday")
print(sales_rep_names[y], "sold ", boats_sold_friday2[z], "on Friday")
print(sales_rep_names[y], "sold ", boats_sold_saturday2[z], "on Saturday")
# Create a dictionary to store the website URL's for each boat dealer
dealer_URLs = []
name1 = 'frank_flemming'
name2 = 'domingo_depue'
name3 = 'ema_endicott'
#populate the dictionary
print("\n")
urlOne = input("Enter the URL for " + sales_rep_locations[0] + ": ")
urlTwo = input("Enter the URL for " + sales_rep_locations[1] + ": ")
urlThree = input("Enter the URL for " + sales_rep_locations[2] + ": ")
#Print sales reps email addresses
print("\n------ Contact sales reps are their email addresses ------\n")
print(name1 + "@" + urlOne)
print(name2 + "@" + urlTwo)
print(name3 + "@" + urlThree)
print("\nI had some issues here pairing the key pairs to the dictionary. ")
print("The dictionary was seen as a tuple, which has immutable items. ")
print("I had to convert the dictionary to a list to get it to work. ")
print("I am still unsure how to use both the dictionary and get the correct output.")
print("Could you please tell me how in your feedback? ")
|
from collections import Counter
def uniqueOccurrences(arr):
"""
Given an array of integers arr, write a function that returns true if and
only if the number of occurrences of each value in the array is unique.
>>> uniqueOccurrences([1,2,2,1,1,3])
True
>>> uniqueOccurrences([-3,0,1,-3,1,1,1,-3,10,0])
True
>>> uniqueOccurrences([1,2])
False
"""
dict = Counter(arr)
unique = set()
for key, value in dict.items():
if value in unique:
return False
else:
unique.add(value)
return True
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print('\n✨ ALL TESTS PASSED!\n') |
def reverseWords(s):
"""
Given a string, you need to reverse the order of characters in each word
within a sentence while still preserving whitespace and initial word order.
>>> reverseWords("Let's take LeetCode contest")
"s'teL ekat edoCteeL tsetnoc"
"""
s = (s).split(' ')
ret = ''
for word in s:
ret += ' ' + word[::-1]
return ret.lstrip()
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print('\n✨ ALL TESTS PASSED!\n') |
"""Return the number of students that were working during the queryTime.
>>> busyStudent([9,8,7,6,5,4,3,2,1],[10,10,10,10,10,10,10,10,10],10)
9
>>> busyStudent([1,1,1,1], [1,3,2,4], 7)
0
>>> busyStudent([1,2,3], [3,2,7], 4)
1
"""
def busyStudent(startTime, endTime, queryTime):
#for each student in start time, check if value is < > query time
#add 1 to return value if true
# i = index
i = 0
output = 0
while i <= len(startTime) - 1:
if queryTime in range(startTime[i], endTime[i]+1):
output += 1
i += 1
return output
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print('\n✨ ALL TESTS PASSED!\n') |
def lastStoneWeight(stones):
"""
We have a collection of stones, each stone has a positive integer weight.
Each turn, we choose the two heaviest stones and smash them together.
Suppose the stones have weights x and y with x <= y. The result of this smash is:
If x == y, both stones are totally destroyed;
If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x.
At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.)
>>> lastStoneWeight([2,7,4,1,8,1])
1
"""
while len(stones) > 1:
x = stones.pop(stones.index(max(stones)))
y = stones.pop(stones.index(max(stones)))
if x != y:
stones.append(abs(y - x))
return stones[0] if len(stones) == 1 else 0
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print('\n✨ ALL TESTS PASSED!\n') |
def romanToInt(s):
"""
Given a roman numeral, convert it to an integer.
>>> romanToInt("MCMXCIV")
1994
>>> romanToInt("LVIII")
58
"""
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100,'D': 500,'M':1000}
num = 0
for idx, x in enumerate(s):
value = roman_dict.get(x)
minus = 0
if idx == 0:
pass
elif (x == 'V' or x == 'X') and s[idx-1] == 'I':
minus = 1
num -= 1
elif (x == 'L' or x == 'C') and s[idx-1] == 'X':
minus = 10
num -= 10
elif (x == 'D' or x == 'M') and s[idx-1] == 'C':
minus = 100
num -= 100
num += value - minus
# print(f'x is {x}, minus is {minus}, num is {num}')
return num
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print('\n✨ ALL TESTS PASSED!\n') |
"""
Write a function that prints a string, fitting its characters within char
limit.
It should take in a string and a character limit (as an integer). It should
print the contents of the string without going over the character limit
and without breaking words. For example:
>>> fit_to_width('hi there', 50)
hi there
Spaces count as characters, but you do not need to include trailing whitespace
in your output:
>>> fit_to_width('Hello, world! I love Python and Hackbright',
... 10)
...
Hello,
world! I
love
Python and
Hackbright
Your test input will never include a character limit that is smaller than
the longest continuous sequence of non-whitespace characters:
>>> fit_to_width('one two three', 8)
one two
three
"""
def fit_to_width(string, limit):
"""Print string within a character limit."""
#loop over every character of the string
#count characters while looping
#when character limit is hit insert new line
#how to account for when character hits in the middle of the word?
#start count over
if len(string) <= limit:
print(string)
else:
char_count = 0
word_list = string.split()
new_string=''
for word in word_list:
if limit - char_count >= len(word):
new_string += word + ' '
char_count += len(new_string)
else:
print(new_string)
char_count = 0
new_string = ''
new_string += word + ' '
char_count += len(new_string)
print(new_string)
# for char in string:
# char_count += 1
# new_string += char
# if char_count == limit:
# print(new_string)
# char_count = 0
# new_string = ' '
# '\n'
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print('\n✨ ALL TESTS PASSED!\n')
|
def findOcurrences(text, first, second):
"""
Given words first and second, consider occurrences in some text of the form
"first second third", where second comes immediately after first, and third
comes immediately after second.
For each such occurrence, add "third" to the answer, and return the answer.
>>> findOcurrences("alice is a good girl she is a good student", "a", "good")
['girl', 'student']
>>> findOcurrences("we will we will rock you", "we", "will")
['we', 'rock']
"""
ret = []
text = text.split(' ')
for i, word in enumerate(text):
if i == len(text) -2:
break
if word == first and text[i+1] == second:
ret.append(text[i+2])
return ret
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print('\n✨ ALL TESTS PASSED!\n') |
def minSubsequence(nums):
"""
Given the array nums, obtain a subsequence of the array whose sum of elements
is strictly greater than the sum of the non included elements in such subsequence.
>>> minSubsequence([4,3,10,9,8])
[10, 9]
>>> minSubsequence([4,4,7,6,7])
[7, 7, 6]
"""
ret = []
tot = sum(nums)
for num in reversed(sorted(nums)):
ret.append(num)
if sum(ret) > tot//2:
return ret
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print('\n✨ ALL TESTS PASSED!\n') |
#Escreva um programa que converta uma temperatura digitada em °C e converta para °F.
c = float (input('Informe a temperatura em °C: '))
f = (9*c / 5) + 32
print('A temperatura em {} ° C corresponde a {}°F! '.format(c,f)) |
#Crie um algoritimo que leia um número e mostre o seu dobro, triplo e raiz quadrada
n = int(input('Digite um numero: '))
print('O dobro do numero é: ',n*2)
print('O triplo do numero é: ',n*3)
print('A raiz do numero é: ',n**(1/2)) |
#Desenvolva um programa que leia as duas notas de um aluno, calculo e mostre sua media
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
media = (n1 + n2) / 2
print ('A media do aluno é: {}'.format(media)) |
# -*- coding: utf-8 -*-
"""
Rock, Paper, Scissors.
Created on Sun Mar 8 10:48:11 2020
@author: Laura
Rock Paper Scissors Game
- Create a rock-paper-scissors game.
- Ask the player to pick rock, paper or scissors.
- Have the computer chose its move.
- Compare the choices and decide who wins.
- Print the results.
- Give the player the option to play again.
- Keep a record of the score (e.g. Player: 3 / Computer: 6).
"""
import random
class RockPaperScissors:
"""Playing Rock, Paper, Scissors."""
def __init__(self):
"""Set initial scores and values. Play game."""
self.player_score = 0
self.computer_score = 0
self.player_choice = None
self.computer_choice = None
self.play_again = True
self.play_game()
def print_score(self):
"""Print scores."""
print("Player score:", self.player_score)
print("Computer score:", self.computer_score)
def input_player(self):
"""Choose rock, paper, scissors."""
player_choice = input("Choose rock, paper, or scissors: ")
player_choice = player_choice.lower()
print("You chose " + player_choice)
if player_choice not in ["rock", "paper", "scissors"]:
print("Please try again.")
player_choice = None
self.input_player()
else:
self.player_choice = player_choice
def input_computer(self):
"""Assign rock, paper, scissors to computer."""
options = ["rock", "paper", "scissors"]
self.computer_choice = random.choice(options)
print("The computer chose " + self.computer_choice)
def choose_winner(self):
"""Determine winner."""
# draw
if self.player_choice == self.computer_choice:
print("Draw")
# you chose rock
elif (self.player_choice == "rock"
and self.computer_choice == "paper"):
print("Computer wins")
self.computer_score += 1
elif (self.player_choice == "rock"
and self.computer_choice == "scissors"):
print("Player wins")
self.player_score += 1
# you chose paper
elif (self.player_choice == "paper"
and self.computer_choice == "scissors"):
print("Computer wins")
self.computer_score += 1
elif (self.player_choice == "paper"
and self.computer_choice == "rock"):
print("Player wins")
self.player_score += 1
# you chose scissors
elif (self.player_choice == "scissors"
and self.computer_choice == "rock"):
print("Computer wins")
self.computer_score += 1
elif (self.player_choice == "scissors"
and self.computer_choice == "paper"):
print("Player wins")
self.player_score += 1
else:
print("unknown error")
def play_game_again(self):
"""Play again."""
play_again = input("Play again (yes/no)? ")
if play_again.lower() in ["y", "yes", "ye"]:
self.play_again = True
else:
self.play_again = False
def print_final_score(self):
"""Print final score."""
if self.player_score > self.computer_score:
print("Player wins")
elif self.computer_score > self.player_score:
print("Computer wins")
else:
print("Draw")
def play_game(self):
"""Play the actual game."""
while self.play_again is True:
self.input_player()
self.input_computer()
self.choose_winner()
self.print_score()
self.play_game_again()
self.print_final_score()
# Play the game
play = RockPaperScissors()
|
import random
numbers = [random.randint(0,1000000) for x in range(1000000)]
def radix_sort(numbers):
buckets = [[] for x in range(10)]
for i in range(1, 7):
digit = 10**i
for x in numbers:
d = (x%digit)//10**(i-1)
buckets[d].append(x)
numbers = []
for b in buckets:
numbers += b
buckets = [[] for x in range(10)]
return numbers
print(numbers)
print(radix_sort(numbers))
|
import unittest
from ..foobar.classes.foobar import FooBar, Multiple
class TestMultiple(unittest.TestCase):
def test_multiple_10(self):
"""Testes if 100 is multiple of 10"""
self.assertEqual(Multiple.is_multiple(100, 10), True, 'Should be True')
def test_multiple_5(self):
"""Testes if 43 is multiple of 5"""
self.assertEqual(Multiple.is_multiple(43, 5), False, 'Should be False')
class TestFooBar(unittest.TestCase):
def test_foobar_printable_value_bar(self):
"""Tests the printable value of 10. Should be bar"""
foobar = FooBar(10)
self.assertEqual(foobar.get_printable_value(), "Bar", "Should be Bar")
def test_foobar_printable_value_number(self):
"""Tests the printable value of 43. Should be the number itself"""
foobar = FooBar(43)
self.assertEqual(foobar.get_printable_value(), "43", "Should be 43")
def test_foobar_printable_value_foobar(self):
"""Tests the printable value of 30. Should be FooBar"""
foobar = FooBar(30)
self.assertEqual(foobar.get_printable_value(), "FooBar", "Should be FooBar")
def test_foobar_printable_value_foo(self):
"""Tests the printable value of 66. Should be Foo"""
foobar = FooBar(66)
self.assertEqual(foobar.get_printable_value(), "Foo", "Should be Foo")
if __name__ == '__main__':
unittest.main()
|
# KDR
# Simulization & optimization problems:
# The Whitt Window Company, a company with only three employees, makes two
# different types of hand-crafted windowns: a wood-framed and an aluminum framed window.
# The comapny earms $300 profit for each wood-framed window and $180 profit for each
# aluminum-framed window.
# Doug makes the wood frame and can make 6 per day.
# Linda makes the aluminum frames and can make 5 per day.
# Bod forms and cuts the glass and can make 48 square feet of glass per day.
# Each wood-framed window uses 6 square feet of glass and
# each aluminum-framed window uses 8 square feet of glass.
# The company wishes to determine how many windows of each type to produce per day
# to maximize total profit.
# Formulate a linear programming model for the problem above:
# Max: Z = 300x1 +180x2 (profit for wood-framed and aluminum-framed)
# 6x1 <= 6 wood-frames per day
# 8x2 <= 5 aluminum-frames oer day
# 6x1 + 8x2 <= 48 ft glass per day
# x1 AND x2 >= 0
# Solve the problem:
from pulp import *
# Define the Model
prob = LpProblem("Whitt Window Company", LpMaximize)
x1 = LpVariable('x1', lowBound = 0)
x2 = LpVariable('x2', lowBound = 0)
# Objective function
prob += 300*x1 + 180*x2, "Obj"
# Constraints
prob += x1 <= 6
prob += x2 <= 5
prob += 6*x1 + 8*x2 <=48
print(prob)
prob.solve()
print("status: " + LpStatus[prob.status])
for variable in prob.variables():
print("{}* = {}".format(variable.name, variable.varValue))
print(value(prob.objective))
# Shadow pricing for constrains above:
for name, c in prob.constraints.items():
print("\n", name, ":", c , ", Slack =" ,c.slack, ", Shadow Price= ", c.pi)
# Output shows we should produce 6 wood-frames and 1.5 (practically 1) aluminum-frame.
# If we produced 6 wfs and 1 afs, that would equal 44 square feet of glass.
# Profit = $2070 according to the output, but in reality, we would likely not make 0.5 of a product,
# thus profit would actually = $1980.00
#
# The above output shows:
# Constraint 1 is binding b/c it has a slack of 0.
# Constraint 2 has a shadow price of 0, meaning it is non-binding
# Constraint 3 is binding b/c it has a slack of 0.
# Constraint 1 has a Shadow Price of 165.0
# Meaning, if we can increase the amount of wood-frames produced by 1 unit,
# we can increase profit by $165
# Constraint 3 also has a shadow price, which is equal to 22.5, meaning if we
# could increase production of the glass we are able to make by 1 unit per day,
# we could then increase profits by $22.5.
#
# How would the optimal solution (the number of windows of each type) change (is at all)
# if the profit per wood-framed window decreases from $300 to $200?
from pulp import *
# Define the Model
prob = LpProblem("Whitt Window Company", LpMaximize)
x1 = LpVariable('x1', lowBound = 0)
x2 = LpVariable('x2', lowBound = 0)
# Objective function
prob += 200*x1 + 180*x2, "Obj"
# Constraints
prob += x1 <= 6
prob += x2 <= 5
prob += 6*x1 + 8*x2 <=48
print(prob)
prob.solve()
print("status: " + LpStatus[prob.status])
for variable in prob.variables():
print("{}* = {}".format(variable.name, variable.varValue))
print(value(prob.objective))
# Shadow pricing for constrains above:
for name, c in prob.constraints.items():
print("\n", name, ":", c , ", Slack =" ,c.slack, ", Shadow Price= ", c.pi)
# According to the output, after decreasing profit for wooden-frames from $300 to $200,
# the optimal solution would remain the same; procude 6 wood-frames and 1.5 aluminum-frames.
# Practically, we would produce 1 aluminum frame and not 1.5 of a product.
# This would decrease profit to 1470, but realistically to 1380 (since again, we are not
# producing half of a product.)
#
# How would the optimal solution (number of windows of each type) change if Doug makes only
# 5 wooden frames per day?
from pulp import *
# Define the Model
prob = LpProblem("Whitt Window Company", LpMaximize)
x1 = LpVariable('x1', lowBound = 0)
x2 = LpVariable('x2', lowBound = 0)
# Objective function
prob += 300*x1 + 180*x2, "Obj"
# Constraints
prob += x1 <= 5
prob += x2 <= 5
prob += 6*x1 + 8*x2 <=48
print(prob)
prob.solve()
print("status: " + LpStatus[prob.status])
for variable in prob.variables():
print("{}* = {}".format(variable.name, variable.varValue))
print(value(prob.objective))
# Shadow pricing for constrains above:
for name, c in prob.constraints.items():
print("\n", name, ":", c , ", Slack =" ,c.slack, ", Shadow Price= ", c.pi)
# The output shows a new optimal solution, and we should now produce 5 wooden-frames
# and 2.25 aluminum-frames (realistically, 2 aluminum frames.) if Doug cuts his production
# of wooden-frames from 6 to 5 per day.
# This change would decrease profits to $1905.00 per day (but realistically $1860.00, since
# we will only produce 2 aluminum-frames and not 2.25)
# Implement the following LP Minimization model:
# Min
#Z = 3x_1 + 3x_2 + 5x_3
# St.
# 2x_1 + x_3 >= 8
# x_2 + x_3 >= 6
# 6x_1 + 8x_2 >= 48
# x_1, x_2, x_3 >= 0
from pulp import *
# Define the Model
prob = LpProblem("LP Minimization model", LpMinimize)
x1 = LpVariable('x_1', lowBound = 0)
x2 = LpVariable('x_2', lowBound = 0)
x3 = LpVariable('x_3', lowBound = 0)
# Objective function
prob += 3*x1 + 3*x2 + 5*x3, "Obj"
# Constraints:
prob += 2*x1 + x3 >= 8
prob += x2 + x3 >= 6
prob += 6*x1 + 8*x2 >= 48
print(prob)
prob.solve()
print("status: " + LpStatus[prob.status])
for variable in prob.variables():
print("{}* = {}".format(variable.name, variable.varValue))
print(value(prob.objective))
# We add these lines for sensitivity analysis
print("\n Sensitivity Analysis: ")
for name, c in prob.constraints.items():
print("\n", name, ":", c, ", Slack=", c.slack, ", Shadow Price=", c.pi)
for v in prob.variables():
print ("\n", v.name, "=", v.varValue, ", Reduced Cost=", v.dj)
# Problem 2 a)
# The optimal solution: we should produce 4 of x1, 6 of x2, and 0 of x3, for an objective value of 30.
#
# Lets look at x_3: If we reduce x_3 by 0.05:
# prob += 3*x1 + 3*x2 + (5 - 0.05)*x3, "Obj"
# Then the reduced cost would turn to 0, and we'd have a value for x_3
# Let's demonstrate:
from pulp import *
# Define the Model
prob = LpProblem("LP Minimization model", LpMinimize)
x1 = LpVariable('x_1', lowBound = 0)
x2 = LpVariable('x_2', lowBound = 0)
x3 = LpVariable('x_3', lowBound = 0)
# Objective function
prob += 3*x1 + 3*x2 + (5-0.5)*x3, "Obj"
# Constraints:
prob += 2*x1 + x3 >= 8
prob += x2 + x3 >= 6
prob += 6*x1 + 8*x2 >= 48
print(prob)
prob.solve()
print("status: " + LpStatus[prob.status])
for variable in prob.variables():
print("{}* = {}".format(variable.name, variable.varValue))
print(value(prob.objective))
# We add these lines for sensitivity analysis
print("\n Sensitivity Analysis: ")
for name, c in prob.constraints.items():
print("\n", name, ":", c, ", Slack=", c.slack, ", Shadow Price=", c.pi)
for v in prob.variables():
print ("\n", v.name, "=", v.varValue, ", Reduced Cost=", v.dj)
# After reducing x_3 by 0.05 in the objective function, we now have a x_3 value of 2.18
# along w/ changed values for x_1 and x_2; 2.90 and 3.81.
# A trust officer at the Blackburg National Bank need to determine how to invest $500,000
# in the following collection of bonds to maximize the annual return:
# Bond Annual Maturity Risk Tax-Free
# Return
# A 9.5% Long High Yes
# B 8.0% Short Low Yes
# C 9.0% Long Low No
# D 9.0% Long High Yes
# E 9.0% Short High No
# The officer wants to invest in at least 50% of the money in short-term issues
# and no more than 50% in high-risk issues.
# Also, at least 30% of the funds should go into tax-free investments.
# Formulate an LP model and implement in Python:
# Max
# Z = 0.095x1 + 0.08x2 + 0.09x3 + 0.09x4 + 0.09x5
# x1 + x2 + x3 + x4 + x5 = 500000
# x2 + x5 >= 250000
# x1 + x4 + x5 <=250000
# x1 + x2 + x4 >= 150000
from pulp import *
# Create the problem:
prob = LpProblem("National Bank Stock Returns", pulp.LpMaximize)
x1 = LpVariable('BondA', lowBound = 0)
x2 = LpVariable('BondB', lowBound = 0)
x3 = LpVariable('BondC', lowBound = 0)
x4 = LpVariable('BondD', lowBound = 0)
x5 = LpVariable('BondE', lowBound = 0)
# Objective function to maximize return
prob += 0.095*x1 + 0.08*x2 + 0.09*x3 + 0.09*x4 + 0.09*x5, "Obj"
# Constraints
prob += x1 + x2 + x3 + x4 + x5 == 500000, "Portfolio"
prob += x2 + x5 >= 250000, "Short-term"
prob += x1 + x4 + x5 <= 250000, "High-Risk"
prob += x1 + x2 + x4 >= 150000, "TaxFree"
print(prob)
prob.solve()
print("status: " + LpStatus[prob.status])
for variable in prob.variables():
print("{}* = {}".format(variable.name, variable.varValue))
print(value(prob.objective))
# We add these lines for sensitivity analysis
print("\n Sensitivity Analysis:")
for name, c in prob.constraints.items():
print("\n{}: Slack={}, Shadow Price = {}".format(name, c.slack, c.pi)) # OR
# print("\n", name, ":", ", Slack=", c.slack, ", Shadow Price=", c.pi)
print("\n ========================================")
for variable in prob.variables():
print("\n{}* = {}, Reduced Cost = {}".format(variable.name, variable.varValue, variable.dj))
# Optimal solution:
# Put $75,000 into A Bonds, $75,000 into B Bonds, $175,000 into C Bonds,
# and $175,000 into E Bonds. $ 0.00 into D Bonds.
# Binding Constraints: All constraints are binding, as they all have slack of 0.
# Constraint 1 has a Shadow Price of 0.09
# Meaning, if we can increase the amount we are able to invest by 1 unit (1 dollar in this case),
# we can increase profit by $.09
# Constraint 2 has a Shadow Price of -0.0075
# Constraint 3 has a Shadow Price of 0.0075, meaning if we increase our investment amount
# in bonds that are High-Risk by one unit, we can increase annual return by 0.0075.
# Constraint 4 has a Shadow Price of -0.0025
# The CitruSun Corporation ships frozen orange juice concentrate from processing
# plants in Eustis and Clermond to distributions in Miami, Orlando, and Tallahassee.
# Each plant can produce 20 tons of concentrate each week. .The company has just
# Received orders for 10 tons from Miami for the coming week, 15 tons from Orlando,
# and 10 tons for Tallahassee. The cost per ton for supplying each of the distributors
# from each of the processing plants is shown in the following table:
# Miami Orlando Tallahassee
# Eustis $260 $220 $290
# Clermont $220 $240 $320
# The company wants to determine the minimum costly plan for filling their orders
# for the coming week.
# ormulate an Integer LP model for this problem
# Z = 260*Eustis_Miami + 220*Eustis_Orlando + 290*Eustis_Tall + 220*Clermont_Miami + 240*Clermont_Orlando + 320*Clermont_Tall
# Eutis_Miami + Eutis_Orlando + Eutis_Tall <= 20
# Clermont_Miami + Clermont_Orlando + Clermont_Tall <= 20
# Eustis_Miami + Clermont_Miami == 10
# Eustis_Orlando + Clermond_Orlando == 15
# Eustis_Tall + Clermont_Tall == 10
from pulp import *
# Create a list of all processing plants:
plant =["Eustis", "Clermont"]
# Create a dictionary for the capacity:
capacity = {"Eustis": 20,
"Clermont": 20}
# Create a list of all distributors
dc = ["Miami", "Orlando", "Tallahassee"]
# Create a dictionary for the number of units of demand for each DC
demand = {"Miami": 10,
"Orlando": 15,
"Tallahassee": 10}
# Create a list of costs of each transportation path
costs = [
[260, 220, 290],
[220, 240, 320]
]
# Creates the prob
prob = LpProblem("Transportatin Problem", LpMinimize)
# Creates a list of tuples containing all the possible routes for transport.
Routes = [(i,j) for i in range(0,len(plant)) for j in range(0,len(dc))]
# A dictionary called route_vars is created to contain the referenced decision variables (the routes)
route_vars = LpVariable.dicts("Routes",(plant,dc), lowBound=0)
# The objective function is added to prob first
prob += lpSum([route_vars[plant[i]][dc[j]]*costs[i][j] for (i,j,) in Routes]), "Sum of Supplying Costs"
# The capacity constraints are added to prob for each supply node (plant)
for i in plant:
prob += lpSum([route_vars[i][j] for j in dc]) <= capacity[i], "Cost to supply plants %s"%i
for j in dc:
prob += lpSum([route_vars[i][j] for i in plant]) >= demand[j], "Cost to supply DCenters %s"%j
print(prob)
prob.solve()
print("Status:", LpStatus[prob.status])
for variable in prob.variables():
print("{} = {}".format(variable.name, variable.varValue))
print("Z* = ", value(prob.objective))
# We add these lines for sensitivitty analyysis
print("\n Sensitivity Analysis: ")
for name, c in prob.constraints.items():
print("\n", name, ":", ", Slack=", c.slack, ", Shadow Price=", c.pi)
for v in prob.variables():
print("\n", v.name, "=", v.varValue, ", Reduced Cost=", v.dj)
# A young couple, Eve and Steven, want to divide their main household tasks (shopping,
# cooking, dishwashing, and laundering) between them so that each has two tasks but
# the total time they spend on household duties is kept to a minimum. Their efficiencies
# on these tasks differ, where the time each would need to perform the task is given by
# the following table:
# Time Needed Per Week
# Shopping Cooking Dishwashing Laundry
# Eve 4.5 Hours 7.5 Hours 3.5 Hours 3.0 Hours
# Steven 5.0 Hours 7.2 Hours 4.5 Hours 3.2 Hours
# Problem 5 a) Formulate a BIP model:
# Z = 4.5*x1 + 7.5*x2 + 3.5*x3 + 3.0*x4 + 5.0*x5 + 7.2*x6 + 4.5*x7 + 3.2*x8
# x1 <= y1
# x5 <= y1
# x2 <= y2
# x6 <= y2
# x3 <= y3
# x7 <= y3
# x4 <= y4
# x8 <= y4
from pulp import *
prob = LpProblem("Eva and Steven Chores", pulp.LpMinimize)
x1 = LpVariable('Eve_Shopping', lowBound=0, upBound=1, cat='Integer')
x2 = LpVariable('Eve_Cooking', lowBound=0, upBound=1, cat= 'Integer')
x3 = LpVariable('Eve_Dishwashing', lowBound=0, upBound=1, cat= 'Integer')
x4 = LpVariable('Eve_Laundering', lowBound=0, upBound=1, cat= 'Integer')
x5 = LpVariable('Steven_Shopping', lowBound=0, upBound=1, cat= 'Integer')
x6 = LpVariable('Steven_Cooking', lowBound=0, upBound=1, cat= 'Integer')
x7 = LpVariable('Steven_Dishwashing', lowBound=0, upBound=1, cat='Integer')
x8 = LpVariable('Steven_Laundering', lowBound=0, upBound=1, cat='Integer')
y1 = LpVariable('ShoppingTask', lowBound=0, upBound=1, cat='Integer')
y2 = LpVariable('CookingTask', lowBound=0, upBound=1, cat='Integer')
y3 = LpVariable('DishwashingTask', lowBound=0, upBound=1, cat='Integer')
y4 = LpVariable('LaunderingTask', lowBound=0, upBound=1, cat='Integer')
# Objective function:
prob += 4.5*x1 + 7.5*x2 + 3.5*x3 + 3.0*x4 \
+ 5.0*x5 + 7.2*x6 + 4.5*x7 + 3.2*x8, "Obj"
# Constraints:
# Constraints:
prob += x1 + x5 == 1, "Shopping"
prob += x2 + x6 == 1, "Cooking"
prob += x3 + x7 == 1, "Dishwashing"
prob += x4 + x8 == 1, "Laundering"
prob += x1 + x2 + x3 + x4 == 2, "Eve's Number of Tasks"
prob += x5 + x6 + x7 + x8 == 2, "Steven's Number of Tasks"
prob += y1 + y2 + y3 + y4 == 4, "Number of Tasks"
# Constraints for whether Eve/Steven is tasked with Shopping:
prob += x1 <= y1
prob += x5 <= y1
# Constraints for whether Eve/Steven is tasked with Cooking:
prob += x2 <= y2
prob += x6 <= y2
# Constraints for whether Eve/Steven is tasked with Dishwashing:
prob += x3 <= y3
prob += x7 <= y3
# Constraints for whether Eve/Steven is tasked with Laundering:
prob += x4 <= y4
prob += x8 <= y4
print(prob)
prob.solve()
print(LpStatus[prob.status])
for variable in prob.variables():
print("{} = {}".format(variable.name, variable.varValue))
print("Optimal Function Value = {}".format(value(prob.objective)))
# Results: Steven will do laundry and cook (10.4 Hours weekly). Eve will do the dishes and shop (8 Hours weekly.
|
from typing import List
class Solution: # passed 34/66 test cases
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
if (len(coordinates) < 2): return False
if len(coordinates) == 2: return True # got this without the hint
for i in range(1, len(coordinates) - 1):
x_cord = coordinates[i][0]
y_cord = coordinates[i][1]
next_x = coordinates[i+1][0]
next_y = coordinates[i+1][1]
prev_x = coordinates[i-1][0]
prev_y = coordinates[i-1][1]
if (abs(next_x - x_cord) != abs(x_cord - prev_x) or abs(next_y - y_cord) != abs(y_cord - prev_y)):
return False
return True
# Hide Hint #3
# Use cross product to check collinearity.
# [[-3,-2],[-1,-2],[2,-2],[-2,-2],[0,-2]] basically a horizontal line. so hint 3 and hint 2 would have to do it.
# trying hint 2 first
class Hint2Solution: # passed 6/66 y=mx+c passed 4/66 y=mx
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
if (len(coordinates) < 2): return False
if len(coordinates) == 2: return True
# m = (coordinates[1][1] - coordinates[0][1]) - (coordinates[1][0] - coordinates[0][0]) # put - instead of /
m = (coordinates[1][1] - coordinates[0][1]) / (coordinates[1][0] - coordinates[0][0]) # guessing float problems.
print(m) # gives 0 for horizontal line y = mx + c ??
for i in range(1, len(coordinates) - 1):
if (coordinates[i][1] != (m * coordinates[i][0] + coordinates[i][1])): # trailing brackets. Stop forgeting
return False
return True
class Hint2SolutionV2: # passed 5/66
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
if (len(coordinates) < 2): return False
if len(coordinates) == 2: return True
# m = (coordinates[1][1] - coordinates[0][1]) - (coordinates[1][0] - coordinates[0][0]) # put - instead of /
m = (coordinates[1][1] - coordinates[0][1]) / (coordinates[1][0] - coordinates[0][0]) # guessing float problems.
print(m) # gives 0 for horizontal line
for i in range(1, len(coordinates)):
newM = (coordinates[i][1] - coordinates[i-1][1]) / (coordinates[i][0] - coordinates[i-1][0])
if newM != m: return False # Shouldn't I use epsilon check?
return True
# Division by zero problems. Only solved it in for loop initially. Forgot to correct the problem in initial assignment for value 'm's
class AcceptedSolution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
if (len(coordinates) < 2): return False
if len(coordinates) == 2: return True
# m = (coordinates[1][1] - coordinates[0][1]) - (coordinates[1][0] - coordinates[0][0]) # put - instead of /
m = (coordinates[1][1] - coordinates[0][1]) / (coordinates[1][0] - coordinates[0][0]) if (coordinates[1][0] - coordinates[0][0]) != 0 else float('inf') # guessing float problems.
print(m) # gives 0 for horizontal line
for i in range(1, len(coordinates)):
newM = (coordinates[i][1] - coordinates[i-1][1]) / (coordinates[i][0] - coordinates[i-1][0]) if (coordinates[i][0] - coordinates[i-1][0]) != 0 else float('inf')
if newM != m: return False # Shouldn't I use epsilon check?
return True
# lemme check for collinearity solution
# Just a shortcut for assignment in the python3 solution:
# (x1, y1), (x2, y2) = coordinates[:2]
# So basically at any point of time, any three coordinate should satisfy following condition to be colinear.
# (y2 - y1)(x3 - x1) == (x2 - x1)(y3 - y1)
class DiscussSolution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
(x1, y1), (x2, y2) = coordinates[:2]
for i in range(2, len(coordinates)):
(x, y) = coordinates[i]
if((y2 - y1) * (x1 - x) != (y1 - y) * (x2 - x1)):
return False
return True
# Great job. I liked the way you avoided division by not having to compute slope. This certainly made code simpler.
# Just one more shortcut for python3 solution:
# for (x,y) in coordinates[2:]: |
#
# Ex. 1: Conta de energia
# =======================
#
# A função conta_de_energia(consumo, tipo) deve retornar o valor da conta de
# energia em função da faixa de consumo e tipo de estabelecimento:
#
# Tipo | Faixa (kWh) | Valor por kWh
# ================+=============+===============
# residencial (r) | até 500 | 0.42
# | 500+ | 0.65
# | |
# comercial (c) | até 1000 | 0.55
# | 1000+ | 0.60
# | |
# industrial (i) | até 5000 | 0.55
# | 5000+ | 0.50
#
# A variável tipo deve ser igual a um dos três valores de string "r", "c" ou
# "i" e a variável consumo corresponde a um número que representa o consumo
# em kWh
#
def conta_de_energia(consumo: float, tipo: str) -> str:
"""
Retorna o valor da conta de energia.
"""
# seu código aqui!
return 42.0
#
# Ex. 2: Estatísticas
# ===================
#
# A função estatisticas(numeros) recebe uma lista de números e retorna uma tupla
# com a soma de todos os valores e a média deles. Ex.:
#
# estatisticas([1, 2, 3, 4]) == (10.0, 2.5)
#
def estatisticas(numeros: list) -> (float, float):
"""
Retorna a (soma, media) dos números na lista de entrada
"""
# seu código aqui!
soma = 1
media = 3
return soma, media
if __name__ == '__main__':
assert estatisticas([1, 2, 3, 4]) == (10.0, 2.5)
assert estatisticas([0, 0, 0]) == (0, 0)
assert estatisticas([]) == (0, 0)
def estatisticas(numeros):
soma = sum(numeros)
e = 1e-50
return soma, soma / (len(numeros) + e)
|
from board import TicTacToeBoard
from move import BoardMove
class Game:
X = "X"
O = "O"
def __init__(self):
self._board = TicTacToeBoard()
self._player = self.X
self._running = True
self._has_winner = False
self._moves = []
@property
def running(self):
return self._running
@property
def has_winner(self):
return self._has_winner
@property
def board(self):
return self._board
@property
def player(self):
return self._player
@property
def opponent(self):
if self.player == self.X:
return self.O
return self.X
@property
def winning_move(self):
return [self.player] * self.board.BOARD_SIZE
def count_empty_squares(self):
return (self.board.BOARD_SIZE ** 2) - len(self._moves)
def change_turn(self):
if self.running:
self._player = self.opponent
def play_turn(self, move):
if self.running:
if self.valid_move(move):
self._moves.append(move)
self.board.make_move(move, self.player)
self.check_game_over()
self.change_turn()
def check_game_over(self):
if self.is_game_won():
self.set_game_won()
self.end_game()
if self.board_filled():
self.end_game()
def board_filled(self):
return self.board.full_board()
def at(self, position):
return self.board.at(position)
def has_moves_on_board(self):
return bool(self._moves)
def last_move(self):
if self.has_moves_on_board():
self._moves[-1]
def undo_move(self, move):
self.board.clear_square(move)
def valid_move(self, move):
return self.board.valid_move(move)
def is_game_won(self):
if self.check_rows() or self.check_columns() or self.check_diagonal() or self.check_antidiagonal():
return True
return False
def set_game_won(self):
self._has_winner = True
self.winner = self.player
def check_rows(self):
for i in range(self.board.BOARD_SIZE):
if self.winning_move == self.board.get_row(i):
return True
return False
def check_columns(self):
for i in range(self.board.BOARD_SIZE):
if self.winning_move == self.board.get_column(i):
return True
return False
def check_diagonal(self):
return self.winning_move == self.board.get_diagonal()
def check_antidiagonal(self):
return self.winning_move == self.board.get_antidiagonal()
def all_possible_moves(self):
moves = []
for i in range(self.board.BOARD_SIZE):
for j in range(self.board.BOARD_SIZE):
move = BoardMove(i, j)
if self.board.is_empty(move):
moves.append(move)
return moves
def end_game(self):
self._running = False
|
"""
Les décorateurs singleton
On peut créer des décorateurs dans des classes et dans ce cas on dit que la classe qui a un décorateur est une classe
singleton, ce qui signifie qu'elle ne peut être instanciée qu'une seule fois.
À titre d'exemple : la création d'une base de données...
Éditeur : Laurent REYNAUD
Date : 01-12-2020
"""
def singleton(c):
myDict = {}
def getInstance(*args, **kwargs):
"""Si la classe n'est pas dans mon dictionnaire, ajout des données de la classe dans le dictionnaire"""
if c not in myDict:
myDict[c] = c(*args, **kwargs)
return myDict[c]
return getInstance
@singleton
class MyClass:
def __init__(self, val):
"""Constructeur"""
self.val = val
@property
def getVal(self):
"""Getter"""
return self.val
myItem1 = MyClass('premier')
myItem2 = MyClass('second')
"""Comme la classe est déjà 'décorée' par le décorateur singleton, lors de l'instanciation du premier objet myItem1,
l'instanciation du deuxième objet myItem2 n'a aucun effet car un décorateur singleton a été mis sur la classe MyClass"""
print(f"Valeur de 'myItem1' : {myItem1.val}, valeur de 'myItem2' : {myItem2.val}")
|
# 1.去掉字符串中的所有空格
x = input('input something')
print(x.split(' '))
# 2.根据完整的路径从路径中分离文件路径、文件名及扩展名
x = 'D:\resource\py入门.pdf'
print(x.split('.'))
# 3.获取字符串中汉字的个数
x = 'Z:\share\Python人工智能1909\part_1第一阶段\随堂录屏\2019.9.26\2019.9.26_4循环控制.mp4'
for i in x:
if 0x4e00 <= ord(i) <= 0x9fa5:
print(i, end='')
# 4.对字符串进行加密与解密
# 5.将字母全部转换为大写或小写
x = '''D:\resource\py入门.pdf'''
print(x.lower())
# 6.根据标点符号对字符串进行分行
x = 'Z:\share\Python人工智能1909\part_1第一阶段\随堂录屏\2019.9.26\2019.9.26_4循环控制.mp4'
for i in range(len(x.split('.'))):
print(x.split('.')[i])
# 7.去掉字符串数组中每个字符串的空格
list1 = ['af asdeww', 'arqwe we rq']
for i in range(len(list1)):
list1[i] = list1[i].replace(' ', '')
print(list1)
# 8.随意输入你心中想到的一个书名,然后输出它的字符串
# 长度。 (len()属性:可以得字符串的长度)
x = input('book name')
print('它的字符串长度%s' % (len(x)))
# 9.两个学员输入各自最喜欢的游戏名称,判断是否一致,如
# 果相等,则输出你们俩喜欢相同的游戏;如果不相同,则输
# 出你们俩喜欢不相同的游戏。
x = input('game name1')
y = input('game name2')
if x == y:
print('你们俩喜欢相同的游戏')
else:
print('你们俩喜欢不相同的游戏')
# 10.上题中两位同学输入 lol和 LOL代表同一游戏,怎么办?
x = input('game name1')
y = input('game name2')
if x == y or x.lower() == y.lower():
print('你们俩喜欢相同的游戏')
else:
print('你们俩喜欢不相同的游戏')
# 11.让用户输入一个日期格式如“2008/08/08”,将 输入的日
# 期格式转换为“2008年-8月-8日” 。
x = input('input date like 2008/08/08')
print(x.replace('/', '-'))
# 12.接收用户输入的字符串,将其中的字符进行排序(升序),并以逆序的顺序输出,“cabed”→"abcde"→“edcba”。
s = 'cabed'
list1 = []
for i in s:
list1.append(i)
for i in range(len(list1)):
for j in range(len(list1) - 1):
if ord(list1[j]) > ord(list1[j + 1]):
list1[j], list1[j + 1] = list1[j + 1], list1[j]
print(list1)
list1.reverse()
print(''.join(list1))
# 13.接收用户输入的一句英文,将其中的单词以反序输出,“hello c sharp”→“sharp c hello”。
s = 'hello c sharp'
list1 = s.split(' ')
list1.reverse()
print(' '.join(list1))
# 14.从请求地址中提取出用户名和域名 http://www.163.com?userName=admin&pwd=123456
# 15.有个字符串数组,存储了10个书名,书名有长有短,现在将他们统一处理,若书名长度大于10,则截取长度8的
# 子串并且最后添加“...”,加一个竖线后输出作者的名字。
# 16.让用户输入一句话,找出所有"呵"的位置。
s = '呵的位置呵的位置呵的'
for i in range(len(s)):
if s[i] == '呵':
print(i)
# 17.让用户输入一句话,找出所有"呵呵"的位置。
# 18.让用户输入一句话,判断这句话中有没有邪恶,如果有邪恶就替换成这种形式然后输出,如:“老牛很邪恶”,输出后变
# 成”老牛很**”;
if s.find('邪恶'):
s = s.replace('邪恶', '**')
print(s)
# 75/75
# 19.如何判断一个字符串是否为另一个字符串的子串
if y.find(x) > 0:
print('yes')
else:
print('no')
# 20.如何验证一个字符串中的每一个字符均在另一个字符串中出现过
x = 'ab'
y = 'yabc'
# 21.如何随机生成无数字的全字母的字符串
# 22.如何随机生成带数字和字母的字符串
# 23.如何判定一个字符串中既有数字又有字母
x = 'aderty'
a = False
b = False
for i in x:
if 48 <= ord(i) <= 57:
a = True
elif 65 <= ord(i) <= 90 or 97 <= ord(i) <= 122:
b = True
if a and b:
print('既有数字又有字母')
# 24.字符串内的字符排序(只按字母序不论大小写)
s = 'aABFGTcd'
list1 = list(s)
list2 = [(x.lower(), x) for x in list1]
list2.sort()
print(list2)
list3 = [x[1] for x in list2]
print(list3)
# 25.字符串的补位操作
# 1 =》001
# 2 =》002
# 10=》010
s='1'
list1=list(s)
if len(s)==2:
list1.insert(0,'0')
elif len(s)==1:
list1.insert(0, '0')
list1.insert(1, '0')
else:
list1.append(000)
print(list1) |
import calendar
import datetime
# yy=2015
# mm=6
# print(calendar.month(yy, mm))
# with open('test.txt','wt')as out_file:
# out_file.write('该文本会写入到文件中\n看到我了吧!')
#
# with open('test.txt','rt')as in_file:
# text=in_file.read()
# print(text)
# mothrange=calendar.monthrange(2016,9)
# print(mothrange)
# today=datetime.date.today()
# print(today)
# print(datetime.timedelta(days=2))
# print((today - (datetime.timedelta(days=1))))
# list1 = []
# for i in range(13):
# list1.append(i + 1)
# print(list1)
# x = 0 # 统计人数
# i = 0
# # a = 0
# while True:
# z = 1
# a = 0
#
# if z == 9:
# if i > len(list1):
# print(list1[i])
# list1.pop(i)
# x += 1
# else:
# print(list1[i + 1])
# list1.pop(i + 1)
# b = list1[i + 2]
# x += 1
# else:
# z += 1
# i += 1
# if x == 15:
# break
# a = [x for x in range(1, 31)] # 生成编号
# del_number = 8 # 该删除的编号
# for i in range(15):
# print(a[del_number])
# a.pop(del_number)
# del_number = (del_number + 8) % len(a)
#
# a = [x for x in range(1, 31)]
# x = 9
#
# index = 0
# for i in range(30):
# count = 0
# while count < 9:
# if a[index] != 0:
# count += 1
# if count==9:
# print(a[index])
# a[index]==0
# index=(index+1)%30
# people=list(range(30))
# # while len(people)>15:
# # # i=1
# # # while i<9:
# # # people.append(people.pop(0))
# # # i+=1
# # # print('{:2d}号下船了'.format(people.pop(0)))
# # #
# # #
# print(people.pop(0)) |
import random
money = 0
print('欢迎来到皇家竞猜'.center(50, '*'))
while True:
while True:
temp = int(input('请购买筹码'))
if temp < 50:
print('购买筹码50起')
else:
if money > 0:
money += temp
print('购买成功,余额:', money)
break
else:
money = temp
print('购买成功,余额:', money)
break
while True:
while True:
out_money = int(input('请下注'))
if out_money < 50 or money > money:
print('下注金额 50-全部')
else:
print('下注成功')
money -= out_money
break
while True:
user_end = input('买大买小,买定离手')
if user_end not in ('大', '小'):
print('买大买小,买定离手')
else:
break
x = random.randint(1, 6)
if x <= 3:
pc_end = '小'
else:
pc_end = '大'
if pc_end == user_end:
print('pc:%s,you:%s,你赢了')
money += 2 * out_money
print('剩余金额:', money)
else:
print('pc:%s,you:%s,你输了')
print('剩余金额:', money)
cho = input('是否继续 y / n')
if cho == 'y':
if money < 50:
print('剩余不足,少于50')
break
else:
print('欢迎下次再来'.center(50, '*'))
exit()
|
#variable set to a string of formatters
formatter = "%s %s %s %s"
#print line- "format variable" % then references the (1,2,3,4)
print formatter % (1, 2, 3, 4)
#print line- quotes will be visible for %r but not for %s
print formatter % ("one", "two", "three", "four")
#print line- "format variable" % referencing the ()
print formatter % (True, False, False, True)
#this is the line with the formatter inside the formatter
print formatter % (formatter, formatter, formatter, formatter)
print formatter % (
"I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight."
)
|
#line 1-3: uses argv to get a filename.
from sys import argv
#line asking for argument variable. Script=__.py filename=whatever file you want
#to open. MAKE SURE FILE IS IN SAME DIRECTORY AS SCRIPT.
script, filename = argv
#NEW COMMAND: JUST THE FILE attached to variable "txt"
txt = open(filename)
#Printing a friendly line
print "Here's your file, %r:" % filename
#Printing the file-- variable(attached to file).read() --no parameters
print txt.read()
#Print another friendly line
print "Type the filmname again:"
#">" asks for data -- data gets assigned to variable "file_again"
file_again = raw_input("> ")
#OPEN = ATTACHED -- so this line only attaches the file to the variable
txt_again = open(file_again)
#Print line - .read() displays variable.
print txt_again.read()
|
'''
Design and implement a data structure for Least Recently Used (LRU) cache. It
should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists
in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present.
When the cache reached its capacity, it should invalidate the least recently
used item before inserting a new item.
'''
class Node(object):
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
def __str__(self):
return '(%s, %d)' % (self.key, self.value)
class LRUCache(object):
def __init__(self, capacity):
'''
:type capacity: int
'''
self.capacity = capacity
self.items = {}
self.head = None
self.tail = None
def check(self):
if not len(self.items):
return
assert self.head
assert self.head.prev == self.tail
assert self.tail
assert self.tail.next == self.head
node = self.head
num_nodes = 1
while node != self.tail:
next_node = node.next
assert next_node.prev == node
node = next_node
num_nodes += 1
assert num_nodes == len(self.items)
def get(self, key):
'''
:rtype: int
'''
node = self.items.get(key)
if node is None:
return -1
# If we're already the head, bail
if self.head == node:
return node.value
# Plop node
node.prev.next = node.next
node.next.prev = node.prev
# If removing tail, set new tail
if self.tail == node:
self.tail = node.prev
# Set new head
node.next = self.head
self.head.prev = node
node.prev = self.tail
self.tail.next = node
self.head = node
return node.value
def set(self, key, value):
'''
:type key: int
:type value: int
:rtype: nothing
'''
# 0 capacity? Noop.
if not self.capacity:
return
# If we already have the key, update it's value and mark as lru
if key in self.items:
self.items[key].value = value
self.get(key)
return
# Are we full? Kick out tail element
if len(self.items) == self.capacity:
old_tail = self.tail
old_tail.prev.next = old_tail.next
old_tail.next.prev = old_tail.prev
self.tail = old_tail.prev
del self.items[old_tail.key]
assert len(self.items) < self.capacity
node = Node(key, value)
self.items[key] = node
if len(self.items) == 1:
node.next = node.prev = node
self.head = self.tail = node
else:
node.next = self.head
self.head.prev = node
node.prev = self.tail
self.tail.next = node
self.head = node
if __name__ == '__main__':
lru = LRUCache(2)
lru.set('a', 1)
lru.set('b', 2)
assert lru.get('a') == 1
assert lru.get('b') == 2
assert lru.get('c') == -1
lru.set('c', 3)
assert lru.get('a') == -1
assert lru.get('b') == 2
assert lru.get('c') == 3
lru = LRUCache(1)
lru.set('a', 1)
lru.set('b', 2)
assert lru.get('a') == -1
assert lru.get('b') == 2
assert lru.get('c') == -1
lru.set('c', 3)
assert lru.get('a') == -1
assert lru.get('b') == -1
assert lru.get('c') == 3
lru = LRUCache(10)
def set(key, value):
lru.set(key, value)
lru.check()
def get(key):
value = lru.get(key)
lru.check()
return value
[set(10, 13), set(3, 17), set(6, 11), set(10, 5), set(9, 10), get(13),
set(2, 19), get(2), get(3), set(5, 25), get(8), set(9, 22), set(5, 5),
set(1, 30), get(11), set(9, 12), get(7), get(5), get(8), get(9),
set(4, 30), set(9, 3), get(9), get(10), get(10), set(6, 14), set(3, 1),
get(3), set(10, 11), get(8), set(2, 14), get(1), get(5), get(4),
set(11, 4), set(12, 24), set(5, 18), get(13), set(7, 23), get(8), get(12),
set(3, 27), set(2, 12), get(5), set(2, 9), set(13, 4), set(8, 18),
set(1, 7), get(6), set(9, 29), set(8, 21), get(5), set(6, 30), set(1, 12),
get(10), set(4, 15), set(7, 22), set(11, 26), set(8, 17), set(9, 29),
get(5), set(3, 4), set(11, 30), get(12), set(4, 29), get(3), get(9),
get(6), set(3, 4), get(1), get(10), set(3, 29), set(10, 28), set(1, 20),
set(11, 13), get(3), set(3, 12), set(3, 8), set(10, 9), set(3, 26),
get(8), get(7), get(5), set(13, 17), set(2, 27), set(11, 15), get(12),
set(9, 19), set(2, 15), set(3, 16), get(1), set(12, 17), set(9, 1),
set(6, 19), get(4), get(5), get(5), set(8, 1), set(11, 7), set(5, 2),
set(9, 28), get(1), set(2, 2), set(7, 4), set(4, 22), set(7, 24),
set(9, 26), set(13, 28), set(11, 26)]
|
'''
A small frog wants to get to the other side of a river. The frog is initially
located on one bank of the river (position 0) and wants to get to the opposite
bank (position X+1). Leaves fall from a tree onto the surface of the river.
You are given a zero-indexed array A consisting of N integers representing the
falling leaves. A[K] represents the position where one leaf falls at time K,
measured in seconds.
The goal is to find the earliest time when the frog can jump to the other side
of the river. The frog can cross only when leaves appear at every position
across the river from 1 to X (that is, we want to find the earliest moment when
all the positions from 1 to X are covered by leaves). You may assume that the
speed of the current in the river is negligibly small, i.e. the leaves do not
change their positions once they fall in the river.
For example, you are given integer X = 5 and array A such that:
A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4
In second 6, a leaf falls into position 5. This is the earliest time when
leaves appear in every position across the river.
Write a function:
def solution(X, A)
that, given a non-empty zero-indexed array A consisting of N integers and
integer X, returns the earliest time when the frog can jump to the other side
of the river.
If the frog is never able to jump to the other side of the river, the function
should return -1.
For example, given X = 5 and array A such that:
A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4
the function should return 6, as explained above.
Assume that:
N and X are integers within the range [1..100,000];
each element of array A is an integer within the range [1..X].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(X), beyond input storage (not
counting the storage required for input arguments).
Elements of input arrays can be modified.
'''
def solution(X, A):
leaves_seen = set()
for i, pos in enumerate(A):
leaves_seen.add(pos)
if len(leaves_seen) == X:
return i
return len(A)
if __name__ == '__main__':
assert solution(5, [1, 3, 1, 4, 2, 3, 5, 4]) == 6
|
from __future__ import print_function
from math import log
from timeit import timeit
from functools import reduce
def prod_div(arr):
# Make a copy of the input array to make this a functional solution.
arr = list(arr)
# If there is only one 0 in the array, the solution should have the product
# of all the other numbers at that index and 0 in all other indices.
if arr.count(0) == 1:
zero_index = arr.index(0)
arr[zero_index] = reduce(lambda x,y: x*y, arr[:zero_index] + arr[zero_index+1:])
arr = [0 if i != zero_index else x for i,x in enumerate(arr)]
return arr
# If there is more than one 0 in the array, the solution is all zeros.
elif arr.count(0) > 1:
return [0 for x in arr]
# Otherwise, each index of the solution is the product divided by the
# original value at that index.
answer = []
product = reduce(lambda x,y: x*y, arr)
for i in range(len(arr)):
answer.append(int(product / arr[i]))
return answer
def prod_no_div_n_squared(arr):
# Make a copy of the input array to make this a functional solution.
arr = list(arr)
# If there is only one 0 in the array, the solution should have the product
# of all the other numbers at that index and 0 in all other indices.
if arr.count(0) == 1:
zero_index = arr.index(0)
arr[zero_index] = reduce(lambda x,y: x*y, arr[:zero_index] + arr[zero_index+1:])
arr = [0 if i != zero_index else x for i,x in enumerate(arr)]
return arr
# If there is more than one 0 in the array, the solution is all zeros.
elif arr.count(0) > 1:
return [0 for x in arr]
answer = []
for i in range(len(arr)):
copy = arr[:i] + arr[i+1:]
product = reduce(lambda x,y: x*y, copy)
answer.append(product)
return answer
def prod_no_div_log_trick(arr):
# Make a copy of the input array to make this a functional solution.
arr = list(arr)
# If there is only one 0 in the array, the solution should have the product
# of all the other numbers at that index and 0 in all other indices.
if arr.count(0) == 1:
zero_index = arr.index(0)
arr[zero_index] = reduce(lambda x,y: x*y, arr[:zero_index] + arr[zero_index+1:])
arr = [0 if i != zero_index else x for i,x in enumerate(arr)]
return arr
# If there is more than one 0 in the array, the solution is all zeros.
elif arr.count(0) > 1:
return [0 for x in arr]
# Here we can leverage the log property: log(a/b) = log(a) - log(b)
# to circumvent the division operation...just exponentiate the result of
# subracting the log of the value at each index by the log of the product.
answer = []
product = reduce(lambda x,y: x*y, arr)
for i in range(len(arr)):
answer.append(int(round(10**(log(product, 10)-log(arr[i], 10)))))
return answer
def prod_no_div_memo(arr):
# Make a copy of the input array to make this a functional solution.
arr = list(arr)
# This solution remains correct even without this `if-else` block, but the
# runtime is much slower.
if arr.count(0) == 1:
zero_index = arr.index(0)
arr[zero_index] = reduce(lambda x,y: x*y, arr[:zero_index] + arr[zero_index+1:])
arr = [0 if i != zero_index else x for i,x in enumerate(arr)]
return arr
elif arr.count(0) > 1:
return [0 for x in arr]
answer = []
cum_prod = 1
for i in range(len(arr)):
answer.append(cum_prod)
cum_prod *= arr[i]
cum_prod = 1
for i in reversed(range(len(arr))):
answer[i] *= cum_prod
cum_prod *= arr[i]
return answer
if __name__ == '__main__':
# Set up the 3 different cases involving 0, 1, or 2+ zeros.
arr_1 = list(range(1, 17))
arr_2 = [0] + list(range(1, 17))
arr_3 = [0, 0] + list(range(1, 17))
# Test equality of solutions.
sol_1_1 = prod_div(arr_1)
sol_1_2 = prod_no_div_n_squared(arr_1)
sol_1_3 = prod_no_div_log_trick(arr_1)
sol_1_4 = prod_no_div_memo(arr_1)
sol_2_1 = prod_div(arr_2)
sol_2_2 = prod_no_div_n_squared(arr_2)
sol_2_3 = prod_no_div_log_trick(arr_2)
sol_2_4 = prod_no_div_memo(arr_2)
sol_3_1 = prod_div(arr_3)
sol_3_2 = prod_no_div_n_squared(arr_3)
sol_3_3 = prod_no_div_log_trick(arr_3)
sol_3_4 = prod_no_div_memo(arr_3)
sol_1_valid = all(sol_1_1[i] == sol_1_2[i] == sol_1_3[i] == sol_1_4[i] for i in range(len(arr_1)))
sol_2_valid = all(sol_2_1[i] == sol_2_2[i] == sol_2_3[i] == sol_2_4[i] for i in range(len(arr_2)))
sol_3_valid = all(sol_3_1[i] == sol_3_2[i] == sol_3_3[i] == sol_3_4[i] for i in range(len(arr_3)))
print('All methods have the same solution when:')
print('\tall values are non-zero:', sol_1_valid)
print('\tone zero value is present:', sol_2_valid)
print('\tmore than one zero value is present:', sol_3_valid)
# Time the different solutions.
sol_1_time = timeit('prod_div(arr_1)', 'from __main__ import prod_div, arr_1', number=100000)
sol_2_time = timeit('prod_no_div_n_squared(arr_1)', 'from __main__ import prod_no_div_n_squared, arr_1', number=100000)
sol_3_time = timeit('prod_no_div_log_trick(arr_1)', 'from __main__ import prod_no_div_log_trick, arr_1', number=100000)
sol_4_time = timeit('prod_no_div_memo(arr_1)', 'from __main__ import prod_no_div_memo, arr_1', number=100000)
print('\nAll four solutions have the same runtime for cases that' \
'\ninclude zero values so their runtimes aren\'t compared here...')
print('\nThe division solution has the following runtimes for the non-zero case:\n\t', sol_1_time)
print('The O(n^2) solution has the following runtimes for the non-zero case:\n\t', sol_2_time)
print('The log trick solution has the following runtimes for the non-zero case:\n\t', sol_3_time)
print('The memo solution has the following runtimes for the non-zero case:\n\t', sol_4_time)
|
from BinaryTree import BinaryTree, Node
def num_unival_trees(node):
count = [0]
helper(node, count)
return count[0]
def helper(node, count):
if node is None:
return True
left = helper(node.left, count)
right = helper(node.right, count)
if left == False or right == False:
return False
if node.left and node.data != node.left.data:
return False
if node.right and node.data != node.right.data:
return False
count[0] += 1
return True
if __name__ == '__main__':
bt = BinaryTree(0)
bt.root.left = Node(1)
bt.root.right = Node(0)
bt.root.right.left = Node(1)
bt.root.right.right = Node(0)
bt.root.right.left.left = Node(1)
bt.root.right.left.right = Node(1)
assert num_unival_trees(bt.root) == 5
|
def partition(arr, low, high):
i = (low-1)
pivot = arr[high]
for j in range(low, high):
if arr[j] <= pivot:
i = i+1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return (i+1)
def quickSort(arr, low, high):
if len(arr) == 1:
return arr
if low < high:
pi = partition(arr, low, high)
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
if __name__ == '__main__':
arr=[]
n= int(input("Enter total no of elements : "))
for i in range(n):
print("Enter value",i+1," : ")
arr.append(int(input()))
# arr = [6, 5, 1, 8, 3, 10, 11, 12, 13]
print ("\nGiven array is")
print(arr)
n = len(arr)
quickSort(arr, 0, n-1)
print("Sorted array is:")
print(arr)
|
import Encryption
import os
class Login:
def __init__(self):
self.encryption = Encryption.Encryption()
# stores the current username and password
self.__currentUsername = ""
self.__currentPassword = ""
# stores all the usernames and passwords
self.__username = []
self.__password = []
self.accounts = []
try:
credentialsFile = open('Login.txt', 'r')
self.accounts = credentialsFile.readlines()
for account in self.accounts:
uname, pwd = account.strip().split(":")
# decrypting the username and password stored in Login.txt
uname = self.encryption.decryptText(uname.encode())
pwd = self.encryption.decryptText(pwd.encode())
self.__username.append(uname)
self.__password.append(pwd)
credentialsFile.close()
except:
print("No accounts present\n")
def runLogin(self):
while(True):
print("\nPress 1 : For Sign In")
print("Press 2 : For Sign Up")
print("Press 3 : Quit")
answer = int(input())
# Sign In
if answer == 1:
self.__currentUsername = str(input("\nEnter the username : "))
self.__currentPassword = str(input("Enter the password : "))
if (not self.__username.__contains__(self.__currentUsername)
or not self.__username.__contains__(self.__currentPassword)):
self.__currentUsername = ""
self.__currentPassword = ""
print("\nWrong Username or Password")
continue
return True
# Sign Up
elif answer == 2:
# before creating a new account checking whether we reached the accounts limit
if len(self.accounts) == 10:
print("\nMaximum Limit for account reached. Cannot create account")
return False
credentialsFile = open('Login.txt', 'a+')
print()
self.__currentUsername = str(input("Enter the username : "))
self.__currentPassword = str(input("Enter the password : "))
if self.__username.__contains__(self.__currentUsername):
print("Username already exist. Please try again.")
continue
# encrypting the journal data for storing in a file
data = (self.encryption.encryptText(self.__currentUsername).decode('utf-8') + ":" +
self.encryption.encryptText(self.__currentPassword).decode('utf-8') + "\n")
credentialsFile.write(data)
credentialsFile.close()
return True
# quit
elif answer == 3:
return False
else:
print("\nPlease enter a valid choice")
continue
def getUsername(self):
s = self.__currentUsername
return s
def getCurrentUserName(self):
if self.__currentUsername == "":
return "No User Signed In"
return self.__currentUsername
def showAllUsernames(self):
print(self.__username)
|
""" Task that intakes and evaluates SA ID and outputs year born, month born, date of birth, gender,
citizen/noncitizen. This SA ID program only works for years 1922 - 2021(a century) """
_id = 'global'
year = 'global'
# function asks user for ID and checks to see if ID given is valid. If not, it repeats itself until valid ID is given
def valid_id():
global _id
global year
while True:
try:
_id = input("Enter your ID: ")
int(_id) # makes sure value isn't string
if type(_id) == float:
raise ValueError
list31 = ["01", "03", "05", "07", "08", "10", "12"] # Represents all months with 31 days
list30 = ["04", "06", "09", "11"] # Represents all months with 30 days
if 22 <= int(_id[0:2]) <= 99:
year = 1900 + int(_id[0:2])
if len(_id) != 13 or (12 < int(_id[2: 4]) < 1):
raise ValueError
if (_id[2:4]) in list31:
if int(_id[4:6]) not in range(1, 32):
raise ValueError
elif (_id[2:4]) in list30:
if int(_id[4:6]) not in range(1, 31):
raise ValueError
elif (_id[2:4]) == "02": # if month is february, checks if it is leap year
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
if int(_id[4:6]) not in range(1, 30):
raise ValueError
else:
if int(_id[4:6]) not in range(1, 29):
raise ValueError
elif int(_id[6:10]) not in range(10000):
raise ValueError
elif _id[10] != "0" or _id[10] != "1":
raise ValueError
break
else:
if 00 <= int(_id[0:2]) <= 21:
year = 2000 + int(_id[0:2])
if len(_id) != 13 or (12 < int(_id[2: 4]) < 1):
raise ValueError
if (_id[2:4]) in list31:
if int(_id[4:6]) not in range(1, 32):
raise ValueError
elif (_id[2:4]) in list30:
if int(_id[4:6]) not in range(1, 31):
raise ValueError
elif (_id[2:4]) == "02": # if month is february, checks if it is leap year
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
if int(_id[4:6]) not in range(1, 30):
raise ValueError
else:
if int(_id[4:6]) not in range(1, 29):
raise ValueError
elif int(_id[6:10]) not in range(10000):
raise ValueError
elif _id[10] != "0" or _id[10] != "1":
raise ValueError
break
except ValueError:
print("Invalid entry")
print("")
return None
valid_id()
months = {"01": "January", "02": "February", "03": "March", "04": "April", "05": "May", "06": "June",
"07": "July", "08": "August", "09": "September", "10": "October", "11": "November", "12": "December"}
print("")
print("Year born: {}".format(year))
print("Month born: {}".format(months[_id[2:4]]))
print("Date of birth(dd/mm/yyyy): {}/{}/{}".format(_id[4:6], _id[2:4], year))
if 0 <= int(_id[6:10]) <= 4999:
print("Gender: Female")
else:
print("Gender: Male")
if _id[10] == "0":
print("Citizenship: SA citizen")
else:
print("Citizenship: Permanents resident")
|
import json
a = {'name': 'she', 'age': 21}
for i in a.keys():
print(i)
data = json.dumps(a)
print(data)
print(a) |
#!usr/bin/python3
# -*- coding: utf-8 -*-
"""
:authors: DELECLUSE MARILLESSE
:date: 27/09/16
:object: TP2 Codage
"""
##### Fonctions à réaliser pour le TP #####
# Question 5
def integer_to_digit(integer):
"""
Converts an integer into the corresponding hexadecimal digit.
The integer given should be between 0 and 15 and return a string.
:param integer: *(int)*
:return: the hexadecimal digit representing the integer
:rctype: *str*
:UC: 0 <= integer < 16
:Examples:
>>> integer_to_digit(0)
'0'
>>> integer_to_digit(10)
'A'
>>> integer_to_digit(-3)
Traceback (most recent call last):
AssertionError: Veuillez entrer un entier entre 0 et 15
>>> integer_to_digit(3.2)
Traceback (most recent call last):
AssertionError: Veuillez entrer un entier
"""
assert(type(integer) == int), "Veuillez entrer un entier"
assert(integer >= 0 and integer <= 15), "Veuillez entrer un entier entre 0 et 15"
if(integer <= 9):
res = chr(ord('0') + integer)
else:
res = chr(ord('A') - 10 + integer)
return res
# Question 6
def integer_to_string(n, b):
"""
Converts an integer n into base b.
The result is returned as a string.
:param n, b: *(int)*
:return: a string representing the number converted into base b.
:rctype: *str*
:UC: b > 1 and n >= 0
:Examples:
>>> integer_to_string(8,2)
'1000'
"""
res = ""
temp = n
while(temp // b > 0):
res = res + integer_to_digit(temp % b)
temp = temp // b
res = res + integer_to_digit(temp) # Adds the last digit of the converted number
res = res[::-1] # Reverses the string
return res
# Question 9
def deux_puissance(n):
"""
Returns 2 to the power of n.
:param n: *(int)*
:rctype: *int*
:UC: n >= 0
:Examples:
>>> deux_puissance(0)
1
>>> deux_puissance(3)
8
"""
return 1 << n
# Question 12
def integer_to_binary_str(n):
"""
Returns a string representing the conversion into binary of the integer entered as a parameter.
:param: *(int)*
:rctype: *str*
:UC: n >= 0
:Examples:
>>> integer_to_binary_str(0)
'0'
>>> integer_to_binary_str(8)
'1000'
>>> integer_to_binary_str(-8)
Traceback (most recent call last):
AssertionError: Entrez un entier positif!
"""
# Tests of n
assert(n >= 0), "Entrez un entier positif!"
if(n == 0):
return "0"
else:
# Initialisation
res = ''
temp = n
i = 0
# Extract all bits from temp and concatenate the result
while(temp > 0):
res = res + str(((n >> i) & 1))
temp = temp >> 1
i += 1
# Reverse the resulting string
res = res[::-1]
return res
# Question 13
def binary_str_to_integer(b):
"""
Returns an int representing the conversion into decimal of the binary string entered as a parameter.
:param: *(str)*
:rctype: *int*
:UC: b is a string composed of '0's and '1's
:Examples:
>>> binary_str_to_integer('1000')
8
>>> binary_str_to_integer('0')
0
>>> binary_str_to_integer(10001)
Traceback (most recent call last):
AssertionError: Entrez une chaîne de caractères!
"""
# Test de b
assert(type(b) == str), "Entrez une chaîne de caractères!"
# Initialisation
res = 0
temp = b
i = 0
return int(b, 2)
##### Tests et réponses aux autres question #####
if __name__ == "__main__":
import doctest
doctest.testmod()
# Question 1
n = 999
print(n, 'converti en hexadécimal: {:x}'.format(n))
print(n, 'converti en hexadécimal et MAJUSCULES: {:X}'.format(n))
print(n ,'converti en octal: {:o}'.format(n))
# Question 2
n = 1331
print('{:d} en binaire est {:s}'.format(n, bin(n)[2:]))
print('{:d} en octal est {:s}'.format(n, oct(n)[2:]))
print('{:d} en hexadécimal est {:s}'.format(n, hex(n)[2:]))
# Question 3
n = 1
print("Question 3:")
print("ch(ord('0') + 1 =", chr(ord('0') + n))
print(ord('0'))
# De 0 à 9 on obtient les chiffres décimaux 0...9.
# Ensuite, pour n >=10, les caractères selon l'ordre de la table de
# caractères Unicode
# Question 4
n = 10
print("Pour n =", n, "on obtient", chr(ord('A') - 10 + n))
# Question 5 - Test de la fonction integer_to_digit()
print("Question 5:")
for j in range(0, 16):
print(integer_to_digit(j))
# Question 7 - Affichage du tableau de conversion
print("Question 7:")
for i in range(0, 21):
print("{:4d}".format(i, integer_to_string(i, 2)),
":", "{:>5s}".format(integer_to_string(i, 2)),
"{:>3s}".format(integer_to_string(i, 8)),
"{:>3s}".format(integer_to_string(i, 16)))
# Question 8 et 9
n = 5
m = 3
print(bin(n), "AND", bin(m), "donne", bin(n & m), "en opération bit à bit")
print(bin(n), "OR", bin(m), "donne", bin(n | m), "en opération bit à bit")
print(bin(n), "XOR", bin(m), "donne", bin(n ^ m), "en opération bit à bit")
print("NOT", bin(m), "donne", bin(~(m)), "en opération bit à bit")
print(n, "décalé à gauche de 1 bit donne", n << 1)
print(n, "décalé à droite de 1 bit donne", n >> 1)
# Le décalage à gauche rajoute un 0 en bit de poids fort, ce qui revient à multiplier
# le nombre par 2.
# Le décalage à droite fait l'inverse, il divise par 2 (division euclidienne).
# Question 11
# Pour tester si un entier est pair, il suffit de le comparer avec le même entier décalé à droite
# puis à gauche, bit à bit. Le décalage à droite enlève de bit de poids faible et le décalage à
# gauche met "0" à sa place. Si les 2 nombres sont égaux, c'est que l'entier de départ avait aussi
# un 0 en bit de poids faible et était donc pair.
# Question 12
print("Question 12:")
print(integer_to_binary_str(15))
# Question 13
print("Question 13:")
print(binary_str_to_integer('1111'))
|
def factorial (number):
fact = 1
if number < 0:
return 'negative'
elif number <= 1:
return fact
else:
for n in range(number):
fact *= n+1
return fact
def alt_factorial (number): #This finds factorial by recussion
if number < 0:
return 'negative'
elif number <= 1:
return 1
else:
return number * alt_factorial(number - 1) # the factorial of a number is the product of the number and the factorial of it's smaller number
|
import math
from src.Utilities import PriorityQueue
# AStarSearch is based on Amit Patel's tutorial: "Implementation of A*" at:
# http://www.redblobgames.com/pathfinding/a-star/implementation.html
def heuristic(point_a, point_b):
"""
Estimated cost of travelling between two points
:param point_a: start point
:param point_b: goal point
:return: Euclidean distance
"""
# Sanity checks
# Check that points have same number of dimensions
len_a = len(point_a)
len_b = len(point_b)
if not len_a == len_b:
raise Exception("a has " + str(len_a) + " dimensions, b has " + str(len_b) + " dimensions.")
# Euclidean distance
difference_squared = [(a - b) ** 2 for a, b in zip(point_a, point_b)]
summed = sum(difference_squared)
root = math.sqrt(summed)
return root
def a_star_search(graph, start, goal):
"""
A* Search
:param graph: graph to search
:param start: start point
:param goal: goal point
:return: path from start to goal
"""
# Sanity checks
# Check that points have same number of dimensions as graph
len_start = len(start)
len_goal = len(goal)
len_graph = len(graph.dimensions)
if not len_start == len_graph:
raise Exception("start has " + str(len_start) + " dimensions, graph has " + str(len_graph) + " dimensions.")
if not len_goal == len_graph:
raise Exception("goal has " + str(len_goal) + " dimensions, graph has " + str(len_graph) + " dimensions.")
frontier = PriorityQueue()
frontier.put(start, 0)
came_from = {}
cost_so_far = {}
came_from[start] = None
cost_so_far[start] = 0
while not frontier.empty():
current = frontier.get()
if current == goal:
break
for next in graph.neighbors(current):
new_cost = cost_so_far[current] + graph.cost(current, next)
if next not in cost_so_far or new_cost < cost_so_far[next]:
cost_so_far[next] = new_cost
priority = new_cost + heuristic(goal, next)
frontier.put(next, priority)
came_from[next] = current
return came_from, cost_so_far
def reconstruct_path(came_from, start, goal):
"""
Build path after searching
:param came_from: node came from
:param start: starting point
:param goal: goal point
:return: list representing path
"""
current = goal
path = [current]
while current != start:
current = came_from[current]
path.append(current)
# path.append(start) # optional
path.reverse() # optional
return path
|
# * Map
# - next_scene
# - opening_scene
# * Engine
# - play
# * Scene
# - enter
# * Death
# * Central Corridor
# * Laser Weapon Armory
# * The Bridge
# * Escape Pod
from sys import exit
from random import randint
class Map(object):
"""The map of all the rooms."""
def __init__(self, start_scene):
pass
def next_scene(self):
pass
def opening_scene(self):
pass
class Engine(object):
"""The cental loop that runs the game"""
def __init__(self, scene_map):
self.description = """
Aliens have invaded a space ship
and our hero has to go through a maze of rooms defeating them
so he can escape into an escape pod to the planet below.
The game will be more like a Zork or Adventure type game
with text outputs and funny ways to die.
The game will involve an engine that runs a map full of rooms or scenes.
Each room will print its own description when the player enters it
and then tell the engine what room to run next out of the map.
"""
pass
def play(self):
pass
class Scene(object):
"""Parent class for individual rooms."""
def __init__(self):
pass
def enter(self):
pass
class Death(Scene):
"""This is when the player dies and should be something funny."""
def __init__(self, why):
self.why = why
def enter(self):
print "\n", self.why, "You die. Good job!"
exit(0)
class CentralCorridor(Scene):
"""
This is the starting point.
It has a Gothon already standing there
they have to defeat with a joke before continuing.
"""
def enter(self):
print """
The Gothons have invaded your ship.
You are standing in the Central Corridor.
There is a Gothon in front of you.
He says, 'Tell me a joke.'
"""
joke = raw_input('> ')
if len(joke) < 5:
print "He says, 'That was pathetic.' "
death = Death("He throws a giant, rotten tomato at you.")
death.enter()
else:
print "He chuckles. He laughs. He chokes on his own spit and dies."
print "Behind where he was standing, a door says 'Armory.'"
print "You go through the door."
return 'laser_weapon_armory'
class LaserWeaponArmory(Scene):
"""
This is where the hero gets a neutron bomb
Use the bomb to blow up the ship before getting to the escape pod.
It has a keypad the hero has to guess the number for.
"""
def enter(self):
print "There is a neutron bomb here, locked to the wall."
print "The sign above it says, 'Enter digit to remove.'"
print "There is a keypad on it with the numbers 0-9."
n = randint(0,9)
resp = int(raw_input('> '))
print "you type %d, the lock wanted %d" % (resp, n)
if n == resp:
print "You hear an audible click, and the lock opens."
print "An alarm sounds."
print "You take the bomb and walk to the door marked 'Bridge'"
return 'the_bridge'
else:
print "The sign clears, then prints, 'Wrong-o.'"
print "The bomb explodes."
death = Death("The ship, the Gothons, and you are blown to pieces.")
death.enter()
class TheBridge(Scene):
"""Another battle scene with a Gothon where the hero places the bomb."""
def __init__(self):
self.rock_paper_scissors = ['rock', 'paper', 'scissors']
def enter(self):
print "You enter the Bridge."
print "Another Gothon has heard the alarm, and rushes into the bridge."
print "He is heavily armed."
print "You say, 'Rock, Paper, Scissors?'"
print "The Gothon says, 'Sure!'"
while True:
raw_input('Press "enter" to play.')
you = randint(0, 2)
gothon = randint(0, 2)
print "You show: ", self.rock_paper_scissors[you]
print "He shows: ", self.rock_paper_scissors[gothon]
if you == (gothon + 1) % 3:
print "The Gothon loses."
print "He shrieks and disappears in a puff of smoke."
print "You head for the door marked 'Escape pod.'"
return 'escape_pod'
elif gothon == (you + 1) % 3:
print "You lose."
death = Death("You shriek and disappear in a puff of smoke.")
death.enter()
else:
print "Rats. Go again."
class EscapePod(Scene):
"""Where the hero escapes but only after guessing the right escape pod."""
def enter(self):
print "You enter the room and see two escape pods."
print "A sign overhead flashes, 'Escape pod needs refueling.'"
print ("The lights for the arrows underneath, "
"to show which pod needs fuel, "
"are burnt out.")
print "The five minute warning for the bomb begins beeping."
while True:
pod = raw_input("Do you choose the right pod or the left? ")
if pod == 'right' or pod == 'left':
break
else:
print "Please type 'right' or 'left.' Time is short."
action = "You guess, jump into the %s pod, " % pod
action += "and press the button marked 'Go.'"
print action
print "The pod launches, you rush into space."
if randint(0, 1) == 0:
print "You speed away. Five minutes later, the bomb explodes."
print "The spaceship and Gothons are destroyed."
print "You head to the planet below."
return 'you_win'
else:
print "The pod sputters to a halt, feet outside the exit."
print "No fuel. No way back."
death = Death("Four-and-a-half minutes later, the bomb explodes.")
death.enter()
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
|
"""
As you can see, the code is broken.
Create the missing functions, use default arguments.
Sometimes you have to use 'return' and sometimes you dont.
Start by creating the functions
"""
def is_on_list():
if day in days:
print(True)
else:
print(False)
def get_x():
pass
def add_x():
pass
def remove_x():
pass
print("days" + str(add_x))
# \/\/\/\/\/\/\ DO NOT TOUCH AREA \/\/\/\/\/\/\ #
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
print("Is Wed on 'days' list?", is_on_list(days, "Wed"))
print("The fourth item in 'days' is:", get_x(days, 3))
add_x(days, "Sat")
print(days)
remove_x(days, "Mon")
print(days)
# /\/\/\/\/\/\/\ END DO NOT TOUCH AREA /\/\/\/\/\/\/\ # |
#!/usr/bin/env python3
"""
From F(1) = 1, F(2) = 1, F(n) = F(n-1) + F(n-2),
we see that F(3) is even, F(4), F(5) are odd, and F(6) is even,
since even = odd + odd and odd = evev + odd. Thus the even
Fibonacci numbers occur at F(n) where n % 3 == 0. We see if we can
express an even F(n) in terms of earlier even Fibonacci numbers.
F(n) = F(n-1) + F(n-2) = 2 F(n-2) + F(n-3) = 3 F(n-3) + 2 F(n-4)
= 3 F(n-3) + 2 F(n-5) + 2 F(n-6) = 4 F(n-3) - F(n-4) + F(n-5) + 2 F(n-6)
= 4 F(n-3) + F(n-6)
"""
if __name__ == "__main__":
INCLUSIVE_UPPER_BOUND = 4_000_000
s = 0
Fn6, Fn3 = 2, 8
while Fn6 <= INCLUSIVE_UPPER_BOUND:
s, Fn6, Fn3 = s+Fn6, Fn3, Fn6 + 4 * Fn3
print(s)
|
# cook your dish here
def isprime(n):
if n==1 or n==0:
return False
else:
for i in range(2,int(n**0.5)+1):
if(n%i==0):
return False
return True
for _ in range(int(input())):
x,y=map(int, input().split())
i=1
while(isprime(x+y+i)==False):
i+=1
print(i) |
for _ in range(int(input())):
s=list(input())
if len(s)<=10:
print(''.join(s))
else:
print(s[0]+str(len(s)-2)+s[len(s)-1]) |
# cook your dish here
for _ in range(int(input())):
s=list(input())
n=len(s)
pair=0
for i in range(n):
if s[i]=='<':
s[i]='>'
elif s[i]=='>':
s[i]='<'
#print(s)
for i in range(n-1):
if s[i]=='>' and s[i+1]=='<':
pair+=1
print(pair) |
# cook your dish here
for _ in range(int(input())):
k=int(input())
a=[[],[],[],[],[],[],[],[]]
for i in range(8):
for j in range(8):
a[i].append(0)
a[0][0]='O'
k-=1
for i in range(8):
for j in range(8):
if(j==0 and i==0):
continue
if(k!=0):
a[i][j]='.'
k-=1
else:
a[i][j]='X'
for i in range(8):
for j in range(8):
print(a[i][j],end="")
print() |
####### ---- Import Modules Here ---- #######
import sys
input = sys.stdin.readline
pstr = sys.stdout.write
####### ---- Input Functions ---- #######
def intinp():
return(int(input()))
def intlist():
return (list(map(int,input().split())))
def strlist():
s = input()
return (list(s[:len(s) - 1]))
def strinp():
return (input())
def inpmul():
return(map(int,input().split()))
####### ---- Start Your Program From Here ---- #######
for _ in range(intinp()):
n=intinp()
a=intlist()
b=intlist()
max_a=0
max_b=0
sum_a=0
sum_b=0
for i in range(n):
if a[i]>max_a:
max_a=a[i]
if b[i]>max_b:
max_b=b[i]
sum_a+=a[i]
sum_b+=b[i]
if sum_a-max_a>sum_b-max_b:
print("Bob")
elif sum_a-max_a<sum_b-max_b:
print("Alice")
else:
print("Draw") |
a=list(map(float, input().split()))
withdraw=a[0]
balance=a[1]
if(withdraw+0.5<=balance and withdraw<=2000 and withdraw%5==0):
balance=balance-withdraw-0.5
print("%.2f"%balance) |
n=int(input())
print("Bob" if n%2==0 else "Alice") |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.