text stringlengths 37 1.41M |
|---|
import turtle
class Draw3D:
def __init__(self, edges, verticies):
self.edges = edges
self.verticies = verticies
self.t = turtle.Turtle()
self.s = turtle.Screen()
def show3D(self):
#init turtle
self.s.title("3D")
self.s.screensize(800,800,bg="white")
self.t.pencolor("black")
self.t.pensize(3)
self.t.speed(10)
#find max X (the less dept)
max = self.FindMaxX()
#for each edge
for edge in self.edges:
#stat vertex in a edge
start = self.verticies[edge[0]]
#end vertex in a edge
end = self.verticies[edge[1]]
#for the less dept plane
if start[0] == max :
#go to start point
self.JumpTo(start[1],start[2])
self.t.pendown()
#draw horizon edge to end point
if start[0] == end[0] and start[1] < end[1] :
self.GoRight(start, end)
#draw vertical edge to end point
elif start[0] == end[0] and start[2] < end[2] :
self.GoUp(start, end)
#draw slanting edge to end point
elif start[0] > end[0] and start[0] == max:
self.GoBackPlane(start[0], end[0])
#for the other plane
else :
#go to (y, z) of start point
self.JumpTo(start[1],start[2])
#go to the plane that start point is in
self.GoBackPlane(max, start[0])
self.t.pendown()
#draw horizon edge to end point
if start[0] == end[0] and start[1] < end[1] :
self.GoRight(start, end)
#draw vertical edge to end point
elif start[0] == end[0] and start[2] < end[2] :
self.GoUp(start, end)
#draw slanting edge to end point
elif start[0] > end[0] :
self.GoBackPlane(start[0], end[0])
self.t.hideturtle()
turtle.done()
def FindMaxX(self):
max = 0
for vertex in self.verticies:
if vertex[0] > max: #vertex[0] = x
max = vertex[0]
return max
def JumpTo(self, startY, startZ):
self.t.penup()
self.t.goto(startY*10, startZ*10)
def GoRight(self, start, end) :
goRight = end[1]*10 - start[1]*10
self.t.forward(goRight)
def GoUp(self, start, end) :
self.t.left(90)
goUp = end[2]*10 - start[2]*10
self.t.forward(goUp)
self.t.right(90)
def GoBackPlane(self, startX, endX):
self.t.left(30)
goback = startX*5 - endX*5
self.t.forward(goback)
self.t.right(30) |
# Enter your code here.
num_test_cases = int(input())
for i in range(num_test_cases):
test_str = input()
even_ind_char = ''
odd_ind_char = ''
for j in range(len(test_str)):
if j % 2 == 0:
even_ind_char += test_str[j]
else:
odd_ind_char += test_str[j]
print('{} {}'.format(even_ind_char, odd_ind_char))
|
#Given an array of integers, find the one that appears an odd number of times.
#There will always be only one integer that appears an odd number of times.
#Attempt 1
numberList = (1, 4, 2, 9, 7, 8, 9, 3, 1)
def find_it(seq):
'''Returns the intger that appears an odd number of times
input: An array of integers
output: (int) that appears an odd number of times'''
intcount = 0
for n in seq:
if seq.count(n) > intcount:
intcount = seq.count(n)
return n
print(find_it(numberList))
#Attempt 2
def findOdd(seq):
'''Returns the integer that appears an odd number of times
input: An array of integers
output: (int) that appears an odd number of times'''
oddInteger = 0
for n in seq:
if seq.count(n) % 2 != 0:
oddInteger = n
return oddInteger
print(findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5])) #5
#checks how many iterations of n there are in the array & if the amount is divisible by multiples of 2 are unequal to 0
#changes the value of oddInteger into the current iteration of n when the 'if' condition is met
|
#Implementing and testing a Binary Sort Algorithm
def binarysort(array,element):
beg = array[0]
end = array [-1]
mid = array[0] + array[-1] // 2
if element == mid:
return len(array) // 2
for i in array:
if element < mid:
beg = array[0]
end = mid
mid = beg + end // 2
return 'element is smaller'
elif element > mid:
beg = mid
end = array[-1]
mid = beg + end //2
return 'element is larger'
print(binarysort([1,2,3,4,5,6,7,8,9,10], 4)) |
# Write a function which returns the same words between 2 arrays storing fruits.
# In the list storing the similarities return the longest fruit and shortest fruit
listoffruits = ["Cherry", "Mango", "Apple", "Peach", "Grapefruit", "Guava", "Banana", "Plum", "Grape", "Orange",
"Lemon", "Jackfruit"]
listoffruits2 = ["Blackberries", "Grapefruit", "Guava", "Mango", "Kiwi", "Orange", "Pineapple", "Plum", "Raspberries",
"Melon", "Cherry"]
def same_fruit(any, any2):
newlist = []
maxlen = -1
minlen = 10
for i in any:
if i in any and any2:
newlist.append(i)
for k in newlist:
if len(k) > maxlen:
maxlen = len(k)
largest = k
for n in newlist:
if len(n) < minlen:
minlen = len(n)
smallest = n
return largest, smallest, newlist
print(same_fruit(listoffruits, listoffruits2))
# traverse the first list
# traverse the second list
# find fruit that are in both lists
# append those said fruit into new list
# find out the character length of each fruit in the new list
# using those given numbers (e.g. 3 and 7) print said fruit if it is <4
# print said fruit >6
|
#Implementing and testing a Quick Sort Algorithm
def quickSort(array):
if len(array) <= 1:
return array
else:
y = array.pop()
low = []
high = []
for x in array:
if x > y:
high.append(x)
else:
low.append(x)
return quickSort(low) + [y] + quickSort(high)
print(quickSort([1,88,33,88,899, 2, 4, 6, 5, 3])) |
#Attempt 1
def remove_duplicate_words(s):
half = s.split()
uw = []
for i in half:
checker = i
if i == i:
uw.append(i)
return uw
#return ' '.join(unique_word)
print(remove_duplicate_words("my cat is my cat fat")) |
#No user input is implemented here, this is only
#for illustration/testing purposes
#The matrix-turning is implemented here by layers:
# a counter runs from the center of the matrix
# towards the outer of it, and every layer
# is rotated at a time
#Function for rotation of matrix by 90deg
def turned(original_matrix):
#Printing original matrix
print "\n"
print "Original matrix:"
print original_matrix
#Matrix rotation throught the use of layers, as
#descripted above; the -1 at the end is because
#of Python starts counting from 0
layers_counter = int(len(original_matrix)/2)-1
#Rotating each layer at a time throught the use of
#a buffer variable
while layers_counter >= 0:
for subcounter in range(layers_counter, len(original_matrix)- \
layers_counter-1):
buff_var = original_matrix[layers_counter,subcounter]
original_matrix[layers_counter,subcounter] = \
original_matrix[subcounter,len(original_matrix)-1-layers_counter]
original_matrix[subcounter,len(original_matrix)-1-layers_counter] = \
original_matrix[len(original_matrix)-1-layers_counter,len(original_matrix)-1-subcounter]
original_matrix[len(original_matrix)-1-layers_counter, \
len(original_matrix)-1-subcounter] = original_matrix[len(original_matrix)-1- \
subcounter,layers_counter]
original_matrix[len(original_matrix)-1-subcounter,layers_counter] = buff_var
layers_counter -= 1
#Printing final output matrix
print "\n"
print "Rotated matrix:"
print original_matrix
#-----MAIN PROGRAM
import numpy
#Matrix definition with numpy
matrix_test = numpy.matrix([[1, 2, 3, 4, 5],[3, 4, 5, 6, 7], \
[5, 6, 7, 8, 9], [5, 6, 7, 8, 9], [5, 6, 7, 8, 9]])
#Call to the function for matrix rotation
turned(matrix_test)
|
import json
with open('precipitation.json') as file:
rain_levels = json.load(file)
print(rain_levels) #printing all data for all stations
# precipitation values for Seattle
seattle_levels = [0]*12
for entry in rain_levels:
if entry['station'] == 'GHCND:US1WAKG0038':
#seattle_levels.append(entry)
# calculating total values of seattle precipitation per month
months = int(entry['date'].split('-')[1]) # turning monthly date values into integers
seattle_levels[months - 1] += entry['value'] # ensuring that values are added together to result in total monthly precip
print(seattle_levels)
# calculating total annual level of precipitation for seattle.
total_rainfall = sum(seattle_levels)
print(total_rainfall)
# calculating monthly percentage based on total annual precip
monthly_percentages = [x / total_rainfall for x in seattle_levels]
print(monthly_percentages)
# converting final results into a json file
with open('result.json', 'w') as file:
json.dump(seattle_levels, file),
json.dump(total_rainfall, file),
json.dump(monthly_percentages, file)
|
import maze
import pygame
class GameLoop():
# General settings
screen_width = 800
screen_height = 600
# Running flag for main loop
running = True
font = None
clock = pygame.time.Clock()
m = maze.Maze((25, 25))
# Handle events
def events(self):
# Check event queue
for event in pygame.event.get():
# Print the current event
print(event)
# Check if the event is a keydown event
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.running = False
# Check if the event is a pygame quit event
if event.type == pygame.QUIT:
print("TRIED TO QUIT!")
self.running = False
# Update logic in the program.
def update(self):
self.fps = self.font.render(str(self.clock.get_fps()), 1, (255, 0, 0))
def render(self):
# Clear the display
self.display.fill((0, 0, 0))
# Blit the fps to the screen
self.display.blit(self.fps, (0, 0))
# Flip the buffers.
pygame.display.flip()
# Tick the clock for the fps counter
self.clock.tick()
# Called when the program requires cleanup
def close(self):
# Close the pygame instance and deload all modules
pygame.quit()
# Runs initialization for pygame and other required libraries
def initialize(self):
# Initialize PyGame
pygame.init()
# Setup a PyGame Screen for rendering.
self.display = pygame.display.set_mode(
(self.screen_width, self.screen_height)
)
self.font = pygame.font.Font(None, 24)
# The constructor for the class
def __init__(self):
self.initialize()
while self.running:
self.events()
self.update()
self.render()
self.close()
window = GameLoop()
|
from Classes_Of_Properties import dict_of_props, dict_of_rail, water_works, electric_company, go, go_to_jail, chance, community_chest, income_tax, luxury_tax, jail
from Properties import panda_of_placements
import random
import pandas as pd
class Player:
def __init__(self, name):
self.name = name
self.bank = 2000000
self.properties = []
self.cards = []
self.placement = 0
player = Player('Mark')
placement_on_board = 1
buyable_in_dict = ['dict_of_props', 'dict_of_rail']
buyable = ['water_works', 'electric_company']
charges = ['income_tax', 'luxury_tax']
def get_right_pool(roll):
x = pd.DataFrame(panda_of_placements)
x = x == roll
list_of_column_names = x.keys()
for column in list_of_column_names:
if any(x[column]):
name_of_dictionary = column
return name_of_dictionary
else:
continue
def roll_dice():
dice_one = random.randint(1, 6)
dice_two = random.randint(1, 6)
num = dice_one + dice_two
return num
def bank(player_bank_account, property_amount):
if player_bank_account >= property_amount:
return True
else:
return False
def other_landing_spots():
x = 'You did not land on a property'
return x
m = 105
while m > 0:
placement_on_board += roll_dice()
'''Gets the dictionary name based on positioning.'''
type_of_property = get_right_pool(placement_on_board)
print(type_of_property)
print(placement_on_board)
flag = 0
'''Testing to see if I landed on a buy-able property and can afford it.'''
if type_of_property in buyable_in_dict:
can_you_afford = bank(player.bank, eval(type_of_property)[placement_on_board].price)
flag = 1
elif type_of_property in buyable:
can_you_afford = bank(player.bank, eval(type_of_property).price)
flag = 2
elif type_of_property in charges:
can_you_afford = bank(player.bank, eval(type_of_property).cost)
flag = 3
else:
can_you_afford = other_landing_spots()
flag = 4
if flag == 1 and can_you_afford:
option = input("Do you want to buy the property for " + str(eval(type_of_property)[placement_on_board].price)
+ "?")
if option == 'yes':
player.bank -= eval(type_of_property)[placement_on_board].price
print("You now have " + str(player.bank) + ' dollars left in your bank.')
else:
print("You decided to not buy this property.")
if flag == 2 and can_you_afford:
option = input("Do you want to buy the property for " + str(eval(type_of_property)[placement_on_board].price)
+ "?")
if option == 'yes' or 'y':
player.bank -= eval(type_of_property).price
print("You now have " + str(player.bank) + ' dollars left in your bank.')
else:
print("You decided to not buy this property.")
if flag == 3 and can_you_afford:
player.bank -= eval(type_of_property).cost
print("You were charges tax, you now have " + str(player.bank) + ' in your bank account.')
if flag == 4:
print("you landed on a special spot. I will deal with this later.")
m -= 1
|
#register
#-first name, last name, password, email
#-generate user id
#login
# - account number, email and password
#bank operations
#Initializing the system
import random
database ={} #dictionary
def init():
print("Welcome to Bank PHP")
haveAccount = int(input("Do you have an account with us: 1 (yes) 2 (no)? \n"))
if(haveAccount == 1):
login()
elif(haveAccount == 2):
print(register())
else:
print("You have selected an invalid option")
init()
def login():
print("******* Login *******")
accountNumberFromUser = int(input("What is your account number? \n"))
password = input("What is your password? \n")
for accountNumber, userDetails in database.items():
if(userDetails[3] == password):
operations(userDetails)
print('Invalid account or password')
login()
def register():
print('****** Register ******')
email = input("What is your email address? \n")
first_name = input("What is your first name? \n")
last_name = input ("What is your last name? \n")
password = input('Create a password? \n')
accountNumber = generateAccountNumber()
database[accountNumber] = [ first_name, last_name, email, password ]
print("Your account has been created")
print(" == ==== ===== ===== ===")
print('Your account number is: %d' % accountNumber)
print('Make sure you keep it safe')
print(" == ==== ===== ===== ===")
login()
def operations(user):
print('Welcome %s %s' %( user[0], user[1] ) )
selectedOption = int(input("What would you like to do? (1) deposit (2) deposit (3) Logout (4) Exit \n"))
if(selectedOption == 1):
deposit()
elif(selectedOption == 2):
withdrawal()
elif(selectedOption == 3):
logout()
elif(selectedOption == 4):
exit()
else:
print("Invalid option selected")
operations(user)
def withdrawal():
print('Withdrawal')
def deposit():
print('Deposit')
def generateAccountNumber():
return random.randrange(111111,999999)
def logout():
login()
#### ACTUAL BANKING SYSTEM
init() |
#basic implementation of a tree node class.
class Tree_Node(object):
def __init__(self, id):
self.__parent = None;
self.__children = None;
self.__id = id;
def append(self, child):
if (self.__children != None):
if (child in self.__children):
return;
self.__children.append(child);
else:
self.__children = [child];
child.__set_parent__(self);
def __set_parent__(self,parent):
self.__parent = parent;
def get_parent(self):
return self.__parent;
def get_children(self):
return self.__children;
def get_id(self):
return self.__id
if __name__ == "__main__":
myNode = Tree_Node(0);
print (myNode.get_id());
two = Tree_Node(1);
myNode.append(two);
myNode.append(two);
print (myNode.get_children()); |
class Characteristics:
def __init__(self, sample):
self.sample = sample
self.size = len(sample)
def mean(self):
s = 0
for elem in self.sample:
s += elem
return s / self.size
def variance(self):
mean = self.mean()
s = 0
for elem in self.sample:
s += (elem - mean) ** 2
return s / self.size
def max(self):
return max(self.sample)
def min(self):
return min(self.sample)
|
N=int(raw_input())
Z=N
R=0
while(N>0):
D=N%10
R=R*10+D
N=N//10
if(Z==R):
print("yes")
else:
print("no")
ANOTHER PROGRAM
n=raw_input()
N=n[::-1]
if(n==N):
print("Yes")
else:
print("No")
|
N=input()
if N%7==0:
print("yes")
else:
print("no")
|
#!/usr/bin/python3
import csv
import sys
import sqlite3
import re
import os
def parse(filename, c):
csvreader = csv.reader(open(filename, 'r', encoding='UTF-8', newline=''), delimiter=',')
for row in csvreader:
# ignore headers
try:
if not int(row[0]):
continue
except ValueError:
continue
# convert Minguo calendar to Gregorian Calendar
match = re.search(r'(\d+)\w(\d+)\w(\d+)\w', row[1])
year = "%d" % (1911+int(match.group(1)))
date = "%s-%s-%s" % (year, match.group(2), match.group(3))
applicationid = "%s-%s" % (year, row[0])
people = row[3]
c.execute("INSERT INTO applications VALUES ('%s','%s', '%s', %s, %s, '%s')" % (applicationid, date, year, row[2], people, row[4]))
# break down locations as row in location table.
for area in row[4].split("/"):
match = re.search(r'(^[\w、()]+)\((\w{3})(\w+)\)$', area)
if(match == None):
# Yes, there is application going nowhere.
continue
# make you easy to read
mountain = match[1]
city = match[2]
district = match[3]
# clean up typos
if(mountain == "水樣森林"):
mountain = "水漾森林"
# mountain = area.split('(')[0]
c.execute("INSERT INTO location VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (applicationid, date, year, people, row[4], city, district, mountain))
if __name__ == "__main__":
# always recreate the db
if os.path.exists("data.db"):
os.remove("data.db")
conn = sqlite3.connect('data.db')
c = conn.cursor()
# Create table
c.execute('''CREATE TABLE applications (id int, date text, year int, days int, people int, plan text)''')
c.execute('''CREATE TABLE location (id int, date text, year int, people int, area text, city text, district text, mountain text)''')
c.execute('''CREATE UNIQUE INDEX index_applications_id on applications (id)''')
c.execute('''CREATE INDEX index_location_id on location (id)''')
c.execute('''CREATE INDEX index_mountain on location (mountain)''')
c.execute('''CREATE INDEX index_area on location (city, district, mountain)''')
# parse every csv file passed in.
for filename in sys.argv[1:]:
parse(filename, c)
# save the dataabse
conn.commit()
conn.close()
|
from functools import reduce
def append(list1: list, list2: list) -> list:
return list1 + list2
def concat(lists: list) -> list:
result = []
for i in lists:
if i:
if type(i) is list:
result.extend(i)
else:
result.append(i)
return result
def filter(function, list: list) -> list:
return [i for i in list if function(i)]
def length(list: list) -> int:
if not list:
return 0
return reduce(lambda x,_: x+1, list)
def map(function, list: list) -> list:
return [function(i) for i in list]
def foldl(function, list: list, initial: int) -> int:
for i in list:
initial = function(initial, i)
return initial
def foldr(function, list: list, initial: int) -> int:
for i in reverse(list):
initial = function(i, initial)
return initial
def reverse(list: list) -> list:
return list[::-1]
|
from itertools import islice
from functools import reduce
def largest_product(series: str, size: int):
if size == 0:
return 1
if not series.isdigit() or size > len(series) or size < 0:
raise ValueError("Size cannot less than zero AND must be equal or less than series' length")
generate_series = (islice(series, i, None) for i in range(size))
# For a series like "9184939" and a length of 3, the result will be
# ( ['9', '1', '8', '4', '9', '3', '9'],
# ['1', '8', '4', '9', '3', '9'],
# ['8', '4', '9', '3', '9'] )
# Note that the datatype is generator
# And then we unzip it
generate_series = zip(*generate_series)
# It'll be resulting in zip object with value
# ('9', '1', '8'), ('1', '8', '4'), ('8', '4', '9'), ('4', '9', '3'), ('9', '3', '9')
# Two lines above is taken from ../029_series/series.py
# Then turn values inside generate_series to int
result = ((int(j) for j in i) for i in generate_series)
largest_serial = 0
for serial in result:
serial_multiplied = reduce((lambda x,y: x*y), serial) # Count the sum of multiplication of the serial
if serial_multiplied > largest_serial:
largest_serial = serial_multiplied
return largest_serial
|
from itertools import islice
def slices(series: str, length: int):
result = []
if not series or length > len(series) or length < 1:
raise ValueError("Series cannot be empty AND slice length must be more than 0 but less or equal than the series' length")
generate_series = (islice(series, i, None) for i in range(length))
# For a series like "9184939" and a length of 3, the result will be
# ( ['9', '1', '8', '4', '9', '3', '9'],
# ['1', '8', '4', '9', '3', '9'],
# ['8', '4', '9', '3', '9'] )
# Note that the datatype is generator
# And then we unzip it
generate_series = zip(*generate_series)
# It'll be resulting in zip object with value
# ('9', '1', '8'), ('1', '8', '4'), ('8', '4', '9'), ('4', '9', '3'), ('9', '3', '9')
# If you are debugging and want to see the value of generate_series using print,
# you need to assign generate_series to a new variable first.
# If you dont, generate_series below will be empty.
# Find out about generator and zip iterator if you're unfamiliar about this.
for i in generate_series:
result.append(''.join(i))
return result
|
from operator import add, mul, sub, truediv
from re import findall
OPERATIONS_DICT = {
"plus": add,
"minus": sub,
"multiplied": mul,
"divided": truediv
}
def answer(question: str) -> int:
question = question.lower()
equation = findall(r'what is (.+)\?', question)
if not equation:
raise ValueError("No equation is found")
# `equation` is a list with only one string element, like this one: ['4 plus 4 minus 8']
# Here we extract the element and split it
# And in case of multiplication and division, we need to remove the 'by'-s
equation = equation[0].split()
while "by" in equation:
equation.remove("by")
result = 0
operation = ""
# This flag is set to check for equations where the number has no pair, like: '4 plus 5 minus'
operation_is_used = False
try:
result = int(equation[0])
except ValueError:
raise ValueError("The question must be: 'What is <number> <operation> ... <number>?'")
for i in range(1, len(equation)):
operation_is_used = False
if i % 2 == 0:
try:
result = OPERATIONS_DICT[operation](result, int(equation[i]))
operation_is_used = True
except:
raise ValueError(f"Invalid input after {equation[i-1]}")
else:
if equation[i] in OPERATIONS_DICT:
operation = equation[i]
else:
raise ValueError(f"Invalid input after {equation[i-1]}")
# To avoid cases like 'What is 5?' gets an exception, `operation` needs to be added to the statement
if operation and not operation_is_used:
raise ValueError("Numbers being operated has no pair")
return result |
def is_isogram(string):
# replace hyphens and spaces from string, then make it lowercase
string = string.replace("-", "").replace(" ", "").lower()
if len(string) != len(set(string)):
return False
return True
|
def rotate(text:str, key:int):
result = ""
for char in text:
if char.isupper():
result += chr((ord(char) + key-65) % 26 + 65) # Because A-Z is 65-90 (26 in total) in unicode
elif char.islower():
result += chr((ord(char) + key-97) % 26 + 97) # Because a-z is 97-122 in unicode
else:
result += char
return result
|
NODE, EDGE, ATTR = range(3)
class Node:
def __init__(self, name, attrs):
self.name = name
self.attrs = attrs
def __eq__(self, other):
return self.name == other.name and self.attrs == other.attrs
class Edge:
def __init__(self, src, dst, attrs):
self.src = src
self.dst = dst
self.attrs = attrs
def __eq__(self, other):
return (self.src == other.src and
self.dst == other.dst and
self.attrs == other.attrs)
class Graph:
def __init__(self, data=None):
self.nodes = []
self.edges = []
self.attrs = {}
if data:
if type(data) is not list:
raise TypeError("Inserted data must be a list.")
for d in data:
if len(d) < 2:
raise TypeError("Value cannot be empty.")
if d[0] == NODE:
if len(d) != 3:
raise ValueError("NODE takes exactly 3 parameters.")
self.nodes.append(Node(d[1], d[2]))
elif d[0] == EDGE:
if len(d) != 4:
raise ValueError("EDGE takes exactly 4 parameters.")
self.edges.append(Edge(d[1], d[2], d[3]))
elif d[0] == ATTR:
if len(d) != 3:
raise ValueError("ATTR takes exactly 2 parameters.")
self.attrs[d[1]] = d[2]
else:
raise ValueError('Inserted item is unknown or the format is invalid.')
|
from collections import Counter
def find_anagrams(word: str, candidates: list):
# Lower the word, split it to list of characters, then map it to a dictionary
map_word = Counter(list(word.lower()))
anagrams = []
for candidate in candidates:
# Exclude the candidate if it has the exact same word as `word` input
if candidate.lower() == word.lower():
continue
map_candidate = Counter(list(candidate.lower()))
if map_candidate == map_word:
anagrams.append(candidate)
return anagrams
|
def response(hey_bob):
hey_bob = hey_bob.strip()
# If you address him without actually saying anything
if hey_bob.isspace() or hey_bob == "":
return "Fine. Be that way!"
# If you YELL AT HIM
if hey_bob.isupper():
# Yelling but ends with question mark
if hey_bob[-1] == "?":
return "Calm down, I know what I'm doing!"
return "Whoa, chill out!"
# Other than yelling
else:
# Asking a casual question
if hey_bob[-1] == "?":
return "Sure."
# Saying anything else
return "Whatever."
|
VOWELS = ("a", "i", "u", "e", "o")
SPECIALS = ("xr", "yt")
SUFFIX = "ay"
def translate(text: str):
text = text.lower().split()
return " ".join(translate_word(word) for word in text)
def translate_word(word: str):
return arrange_word(word) + SUFFIX
def arrange_word(word: str):
if word.startswith(VOWELS) or word.startswith(SPECIALS) or (word.startswith("y") and word[1] not in VOWELS):
return word
elif word.startswith("qu"):
return word[2:] + "qu"
else:
return arrange_word(word[1:] + word[0]) |
###########Question3###########################################################
'''
Question 3
Given an undirected graph G, find the minimum spanning tree within G.
A minimum spanning tree connects all vertices in a graph with the smallest
possible total weight of edges.
Vertices are represented as unique strings.
The function definition should be question3(G)
The keys of the dictionary are the nodes of our graph.
The corresponding values are lists with the nodes,
which are connecting by an edge.
An edge size is given as a 2-tuple with nodes , i.e. ("A","3")
'''
'''
This part og the codes auired from https://programmingpraxis.com for
minimum-spanning-tree-kruskals-algorithm.
And modified accordingly in order to use purpose of this project
'''
class DisjointSet(dict):
def add(self, item):
self[item] = item
def find(self, item):
parent = self[item]
while self[parent] != parent:
parent = self[parent]
self[item] = parent
return parent
def union(self, item1, item2):
self[item2] = self[item1]
import pprint
pp = pprint.PrettyPrinter(indent=2)
from operator import itemgetter
## Use Kruskal algorithum to determine minimum spaning tree path
## The procedure returns edge lists that contains the minimum spaniing tree
def kruskal(nodes, edges):
forest = DisjointSet()
mst = []
for n in nodes:
forest.add( n )
#print(forest)
sz = len(nodes) - 1
for e in sorted( edges, key=itemgetter(2)):
n1, n2, _ = e
t1 = forest.find(n1)
t2 = forest.find(n2)
if t1 != t2:
mst.append(e)
sz -= 1
if sz == 0:
#print(forest)
return mst
forest.union(t1, t2)
'''
This function get in and return an adjacensy list structure like this:
{'A': [('B', 2)],
'B': [('A', 2), ('C', 5)],
'C': [('B', 5)]}
'''
def question3(g):
g_key_list = list(g.keys())
## convert g to list of edges
edge_list = []
for node in g_key_list:
for edge in g[node]:
edge_list.append((node, edge[0], edge[1]))
min_span_path_list = kruskal(g_key_list, edge_list)
pp.pprint(min_span_path_list)
## convert to dictionary
min_path_dict = {}
for edge in min_span_path_list:
if edge[0] in min_path_dict.keys():
min_path_dict[edge[0]].append((edge[1], edge[2]))
else:
min_path_dict[edge[0]] = [(edge[1], edge[2])]
pp.pprint(min_path_dict)
## Test cases
g = {'A' : [('B', 7), ('C', 9), ('F', 14)],
'B' : [('A', 7), ('C', 10), ('D', 15)],
'C' : [('A', 9), ('B', 10), ('D', 11), ('F', 2)],
'D' : [('B', 15), ('C', 11), ('E', 6)],
'E' : [('D', 6), ('F', 9)],
'F' : [('A', 14), ('C', 2), ('E', 9)]
}
g1 = {'A': [('B', 2)],
'B': [('A', 2), ('C', 5)],
'C': [('B', 5)]}
g2 = {'A': [('B', 2)],
'B': [('A', 2), ('C', 1000000)],
'C': [('B', 1000000)]}
g3 = {'A' : [('B', 7), ('C', 9), ('F', 14)],
'B' : [('A', 7), ('C', 10), ('D', 15)],
'C' : [('A', 9), ('B', 10), ('D', 11), ('F', 2), ('G', 4)],
'D' : [('B', 15), ('C', 11), ('E', 6)],
'E' : [('D', 6), ('F', 9), ('G', 3)],
'F' : [('A', 14), ('C', 2), ('E', 9), ('G', 5)],
'G' : [('F', 5), ('E', 3), ('C', 4)]
}
g4 = {'A' : [('B', 10000), ('C', 9), ('F', 14)],
'B' : [('A', 10000), ('C', 10), ('D', 15)],
'C' : [('A', 9), ('B', 10), ('D', 11), ('F', 10000), ('G', 4)],
'D' : [('B', 15), ('C', 11), ('E', 6)],
'E' : [('D', 6), ('F', 100000), ('G', 3)],
'F' : [('A', 14), ('C', 10000), ('E', 100000), ('G', 5)],
'G' : [('F', 5), ('E', 3), ('C', 4)]
}
print('Questinn 3 tests results')
question3(g)
question3(g1)
question3(g2)
question3(g3)
question3(g4)
print()
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
# search for <table> tags and parses all text within the tags
tables = pd.read_html("https://en.wikipedia.org/wiki/1998_in_film")
# print the number of DataFrames in the list
len(tables)
# In[2]:
df_1998oct = tables[8]
df_1998oct.tail(25)
# In[3]:
# Correct the errors
df_1998oct.loc[26,'Title'] = df_1998oct.loc[26,'Studio']
df_1998oct.loc[26,'Studio'] = df_1998oct.loc[26,'Cast and crew']
df_1998oct.loc[26,'Cast and crew'] = df_1998oct.loc[26,'Genre']
df_1998oct.loc[26,'Genre'] = df_1998oct.loc[26,'Medium']
df_1998oct.loc[26,'Medium'] = df_1998oct.loc[26,'Unnamed: 7']
df_1998oct.loc[27,'Opening.1'] = 25
df_1998oct.loc[27,'Title'] = 'Babe: Pig in the City'
df_1998oct.loc[28,'Opening.1'] = 25
df_1998oct.loc[28,'Title'] = 'Home Fries'
df_1998oct.loc[29,'Opening.1'] = 25
df_1998oct.loc[29,'Title'] = 'Ringmaster'
df_1998oct.loc[30,'Medium'] = df_1998oct.loc[30,'Genre']
df_1998oct.loc[30,'Genre'] = df_1998oct.loc[30,'Cast and crew']
df_1998oct.loc[30,'Cast and crew'] = df_1998oct.loc[30,'Studio']
df_1998oct.loc[30,'Studio'] = df_1998oct.loc[30,'Title']
df_1998oct.loc[30,'Title'] = df_1998oct.loc[30,'Opening.1']
df_1998oct.loc[30,'Opening.1'] = 25
# In[4]:
df_1998oct.columns
# In[5]:
# Delete the last column
df_1998oct.drop(columns=['Unnamed: 7'], inplace=True)
df_1998oct.tail(25)
# In[6]:
# Concatenate the tables for 1998
df_1998jan = tables[5]
df_1998apr = tables[6]
df_1998jul = tables[7]
df_1998 = pd.concat([df_1998jan, df_1998apr, df_1998jul, df_1998oct])
df_1998.insert(0, 'Year', '1998')
df_1998.head()
# In[7]:
# Concatenate the tables for all years
list_years = ['1990','1991','1992','1993','1994','1995','1996','1997','1998','1999']
df_1990s = pd.DataFrame()
for year in list_years:
if year == '1998':
df_1990s = pd.concat([df_1990s, df_1998])
else:
tables = pd.read_html('https://en.wikipedia.org/wiki/' + year + '_in_film')
df_jan = tables[5]
df_apr = tables[6]
df_jul = tables[7]
df_oct = tables[8]
df = pd.concat([df_jan, df_apr, df_jul, df_oct])
df.insert(0, 'Year', year)
df_1990s = pd.concat([df_1990s, df])
# In[8]:
len(df_1990s)
# In[9]:
# Rename two columns, reset the row index
df_1990s.rename(columns={'Opening':'Month', 'Opening.1':'Opening Date'}, inplace=True)
df_1990s.reset_index(inplace=True, drop=True)
df_1990s.tail()
# In[10]:
# Split the data into separate columns
df_genre = df_1990s['Genre'].str.split(',', expand=True)
df_castandcrew = df_1990s['Cast and crew'].str.split(';', expand=True)
# In[11]:
df_genre.tail()
# In[12]:
df_castandcrew.head()
# In[13]:
# Rename the new columns, delete the old columns
df_1990s['Genre1'] = df_genre[0]
df_1990s['Genre2'] = df_genre[1]
df_1990s['Genre3'] = df_genre[2]
df_1990s['Genre4'] = df_genre[3]
df_1990s['Genre5'] = df_genre[4]
df_1990s['Crew1'] = df_castandcrew[0]
df_1990s['Crew2'] = df_castandcrew[1]
df_1990s['Cast1'] = df_castandcrew[2]
df_1990s['Cast2'] = df_castandcrew[3]
df_1990s.drop(columns=['Cast and crew','Genre'], inplace=True)
df_1990s.head()
# In[14]:
# Create the CSV file
df_1990s.to_csv('films_1990s.csv', sep = ',', index = False)
|
# sort algorthms and methods for reference
# selection_sort
# sorting an array from smallest to largest
def find_smallest(arr):
smallest = arr[0] # store smallest value
smallest_index = 0 # store index of smallest value
# start from the second item
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
arr = [9,8,3,1,4,6]
print(find_smallest(arr))
def selection_sort(arr):
new_array = []
# start from the beginning
for i in range(0, len(arr)):
smallest_index = find_smallest(arr)
# append it
new_array.append(arr[smallest_index])
# remove from the array
arr.pop(smallest_index)
return new_array
print(selection_sort(arr))
# Python built in methods
l = [9,1,8,2,7,3,6,4,5]
# sorted() works on any iterable like tuples, dictionaries
# Returns a new sorted object
sorted_l = sorted(l)
print(l)
print(sorted_l)
# sort method motifies the list-in place. Returns None
l.sort()
print(l)
# sorted can take in a reverse parameter
l = [9,1,8,2,7,3,6,4,5]
sorted(l, reverse=True)
# same with sort()
l.sort(reverse=True)
# but, sort() only works with lists
tup = (9,1,8,2,7,3,6,4,5)
tup.sort() # does not works
sorted(tup)
# what if I want to sort by the absolute value?
li_negs = [-6,-5,-4,1,2,3]
# One numpy way
import numpy as np
# get indices, apply abs on the array
indices = np.argsort(abs(np.array(li_negs)))
# li_negs, sorted by abs value
[li_negs[i] for i in indices][::-1] # descending by abs
[li_negs[i] for i in indices] # ascending by abs
# using Python sorted, it's ONE line!
# use key parameter, which takes a function to be called on each element
# prior to making comparisions!
sorted(li_negs, key=abs)
# another example
class Employee:
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
def __repr__(self):
return f'({self.name}, {self.age}, {self.salary})'
e1 = Employee('Carl', 37, 70_000)
e2 = Employee('Sarah', 29, 80_000)
e3 = Employee('John', 20, 90_000)
employees = [e1,e2,e3]
# in order to sort this, you have to specify what to sort by
def e_sort(emp):
return emp.name
e_sort(e1)
sorted(employees, key=e_sort)
sorted(employees, key=lambda x: x.age) # good place to use lambda functions
sorted(employees, key=lambda x: x.salary, reverse=True)
|
"""
Electricity bill estimator v2.0 by Kyaw Phyo Aung (13822414)
"""
tariff_costs = {"11": "0.244618", "31": "0.136928"}
tariffs = []
def fun_one():
print("Electricity bill Estimator")
cents = float(input("Enter cents per kWh: "))
dailyuse = float(input("\nEnter daily use in kWh: "))
days = float(input("\nEnter number of billing days: "))
cost = cents*0.01
bill = cost*dailyuse*days
print("Estimated bill: ",bill)
def fun_two():
print("Electricity bill Estimator 2.0")
# Reterieve key from tariff dictionary
for tariff in tariff_costs:
tariffs.append(tariff)
# show only from dictionary
tariff = int(input("Which tariff? {} or {} :".format(tariffs[0],tariffs[1])))
dailyuse = float(input("\nEnter daily use in kWh: "))
days = float(input("\nEnter number of billing days: "))
if(tariff == 11):
bill = int(tariffs[0]) * dailyuse * days
print("Estimated bill: ", bill)
elif(tariff == 31):
bill = int(tariffs[1]) * dailyuse * days
print("Estimated bill: ", bill)
print("")
else:
print("Tariff Wrong!!")
MENU = """C - Cents per kWh
T - Tariff
Q - Quit"""
print(MENU)
choice = input(">>> ").upper()
while choice != "Q":
if choice == "C":
fun_one()
elif choice == "T":
fun_two()
else:
print("Invalid option")
print(MENU)
choice = input(">>> ").upper()
print("Thank you.") |
"""
Program to calculate and display a user's bonus based on sales.
If sales are under $1,000, the user gets a 10% bonus.
If sales are $1,000 or over, the bonus is 15%.
"""
sales = float(input("Enter Sales: S$ \n"))
tenbounus = sales*0.1
fifteen = sales*0.15
while sales > 0 :
if sales < 1000 :
sales += tenbounus
salary = sales
print("Your salary is : S$", salary)
sales = float(input("Enter Sales: S$ \n"))
else :
sales += fifteen
salary = sales
print("Your salary is : S$", salary)
sales = float(input("Enter Sales: S$ \n"))
|
income_list = []
income_total_list = []
profit = 0
income = 0
def main():
calculate_income()
print("")
print("Income Report")
print("--------------")
user_output()
def calculate_income():
try:
mmcount = 1
totalincome = 0
print("How many months?")
months = int(input(">>>"))
while mmcount <= months:
income = float(input("Enter income for month {}: ".format(mmcount)))
mmcount += 1
income_list.append(income)
totalincome += income
income_total_list.append(totalincome)
except ValueError:
print("Invalid Input Try Again!")
calculate_income()
def user_output():
for i in range(len(income_total_list)):
mmcount = i + 1
print("Month {0} - Income: $ {1:10.2f} Total: $ {2:10.2f}".format(mmcount, income_list[i],
income_total_list[i]))
main() |
from prac_08.taxi import Taxi
from prac_08.silverservicetaxi import SilverServiceTaxi
MENU = """Let's Drive!
q)uit, c)hoose taxi, d)rive
"""
current_taxi = None
taxis = [Taxi("Prius", 100), SilverServiceTaxi("Limo", 100, 2), SilverServiceTaxi("Hummer", 200, 4)]
bill_to_date = 0
def main():
global bill_to_date
print(MENU)
option = input(">>>")
while option != "q":
if option == "c":
taxi_available()
current_taxi = int(input("Choose taxi:"))
print("Bill to Date", bill_to_date)
print("")
option = input(MENU)
elif option == "d":
bill_to_date = drive(current_taxi, bill_to_date)
print("")
option = input(MENU)
print("Total Trip cost: ${:.2f}".format(bill_to_date))
print(taxi_now())
def taxi_available():
taxi_count = 0
print("Taxis available:")
for taxi in taxis:
print("{} - {}".format(taxi_count, taxi))
taxi_count += 1
def taxi_now():
taxi_count = 0
print("Taxis available:")
for taxi in taxis:
print("{} - {}".format(taxi_count, taxi))
taxi_count += 1
def drive(choose_taxi, bill_to_date):
drive_km = int(input("Drive how far?"))
for taxi in taxis:
if taxi == taxis[choose_taxi]:
taxi.drive(drive_km)
bill = taxi.get_fare()
print("Your Prius trip cost you ${}".format(bill))
bill_to_date += bill
print("Bill to date: ${}".format(bill_to_date))
return bill_to_date
main()
|
def verificar_senha(s):
"""
Verifica se s é a senha correta
:param s: Senha a ser testada
:return: True se s for a senha correta
"""
return s == senha
def contar_semelhanca(s):
"""
Conta quantos digitos são semelhantes entre s e a senha correta
:param s: Senha a ser comparada com a senha correta
:return: Quantos digitos são iguais entre s e a senha correta
"""
semelhanca = 0
if len(s) != len(senha):
return "Erro: quantidade de digitos incongruente"
for j in range(len(senha)):
if list(s)[j] == list(senha)[j]:
semelhanca += 1
return semelhanca
info = input().split(' ')
senha = info[0]
tentativas = int(info[1])
for i in range(tentativas):
senha_testada = input()
if verificar_senha(senha_testada):
print('Senha reconhecida. Desativando defesas...')
break
else:
tentativas -= 1
print("Senha incorreta")
print('Semelhanca:', contar_semelhanca(senha_testada))
print('Tentativas restantes:', tentativas, '\n')
if tentativas == 0:
print('Tentativas esgotadas. Acionando defesas...')
break
|
# a = '北京,南京,天津'
# b = list(a) # 字符串列表化
# # c = ','.join(b) # 列表字符串化
# d = a.split(',') # split对单词列表化不是对每个字母
# print('b is :', b)
# print('d is :', d)
#
# # print('c is:', c)
#
# for i in d:
# print(i)
import copy
m = [34,94,35,78,45,67,23,90,1,0]
t = copy.deepcopy(m)
# 求m个最大的数值及其索引
max_number = []
max_index = []
for _ in range(2):
number = max(t)
index = t.index(number)
t[index] = 0
max_number.append(number)
max_index.append(index)
t = []
print(max_number)
print(max_index)
|
from tkinter import *
root = Tk()
root.geometry("655x333")
root.title("Register yourself to join our Dance academy")
def getvals():
print(f"You have enter your first name as : {fnamevalue.get()}")
print(f"You have enter middle name as : {mnamevalue.get()}")
print(f"You have enter last name as : {lnamevalue.get()}")
print(f"You have enter Dob as :{Dobvalue.get()}")
print(f"You have enter email as : {emailvalue.get()}")
print(f"You have enter password as : {passwordvalue.get()}")
file = open("user.txt","a")
file.write("Your first name : " + fnamevalue.get())
file.write("\n")
file.write("Your middle name : " + mnamevalue.get())
file.write("\n")
file.write("Your last name : " + lnamevalue.get())
file.write("\n")
file.write("Your date of birth : " + (Dobvalue.get()))
file.write("\n")
file.write("Your email id : " + emailvalue.get())
file.write("\n")
file.write("Your password : " + passwordvalue.get())
file.close()
fname = Label(root,text="First name")
mname = Label(root,text="Middle name")
lname = Label(root,text="Last name")
Dob = Label(root,text="Date of birth")
email = Label(root,text="Email id")
password = Label(root,text="Create a password")
fname.grid()
mname.grid()
lname.grid()
Dob.grid()
email.grid()
password.grid()
fnamevalue = StringVar()
mnamevalue = StringVar()
lnamevalue = StringVar()
Dobvalue = StringVar()
emailvalue = StringVar()
passwordvalue = StringVar()
fnameentry = Entry(root,textvariable = fnamevalue)
mnameentry = Entry(root,textvariable = mnamevalue)
lnameentry = Entry(root,textvariable = lnamevalue)
Dobentry = Entry(root,textvariable = Dobvalue)
emailentry = Entry(root,textvariable = emailvalue)
passwordentry = Entry(root,textvariable = passwordvalue)
fnameentry.grid(row=0,column=1)
mnameentry.grid(row=1,column=1)
lnameentry.grid(row=2,column=1)
Dobentry.grid(row=3,column=1)
emailentry.grid(row=4,column=1)
passwordentry.grid(row=5,column=1)
# making button
Button(text = "submit",command = getvals).grid()
# # creating a file to store data
# f = open("Register_details.txt"."a") as f:
root.mainloop() |
import random
import string
def main():
size = int(input("How many digits will your password have?\n"))
chars = string.ascii_letters + string.digits + "!@#$%&*()-ç^{}[];:/<>|=+,."
rnd = random.SystemRandom()
print("\nPassword: ")
print("".join(rnd.choice(chars) for i in range(size)))
if __name__ == '__main__':
main()
|
#Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
#and write a program that prints out all the elements #of the list that are less than 5.
a.sort(reverse=True)
print(a.index(89))
for i in range(len(a)):
print( str(i)+': '+str(a[i]))
max = 0;
for item in a:
if item>max:
max = item
print('Max: ' + str(max))
min = float('inf');
for item in a:
if item<min:
min = item
print('Min: '+str(min)) |
def gcd_iter(a, b):
c = min(a, b)
# 当a除以c余数为0,并且b除以c余数为0时,while条件为False or False,即跳出循环
while a % c != 0 or b % c != 0:
c -= 1
return c
print(gcd_iter(2, 12))
print(gcd_iter(6, 12))
print(gcd_iter(9, 12))
print(gcd_iter(17, 12)) |
# 利用http://pythontutor.com可视化工具
def fixed_month_pay(balance, annnual_interest_rate):
"""
函数接收2个参数,分别是贷款总额, 年利率
"""
# 将贷款的年利率转换为月利率
month_interest_rate = annnual_interest_rate / 12
# 为while循环设置一个旗帜为True,如果满足条件则把旗帜变为False,退出循环
flag = True
# 设置精确度
epsilon = 0.01
# 假设不产生利息,那么每个月还款额为贷款总额/12
low = balance / 12
# 假设每个月没有还款,根据复利公式计算一年后贷款总额和利息总额
# 再除以12得到每个月应还款的额度
high = (balance * (1 + month_interest_rate)**12) / 12
# 用2分法确定月还款额
fixed_month_paid = (low + high) / 2
# 统计运行的次数
count = 0
# 开始while循环
while flag:
pre_balance = balance
for month in range(1, 13):
count += 1
unpaid_balance = pre_balance - fixed_month_paid
interest = unpaid_balance * month_interest_rate
pre_balance = unpaid_balance + interest
print(f'month: {month}, low: {low}, high: {high}, interest: {interest}, pre_balance: {pre_balance}')
# 精确度达标, 退出循环
if abs(pre_balance) < epsilon:
flag = False
# 如果当前额度大于0, 说明月还款额太低,设置low=fixed_month_paid
elif pre_balance > 0:
low = fixed_month_paid
# 如果当前额度小于0, 说明月还款额太高,设置high=fixed_month_paid
elif pre_balance < 0:
high = fixed_month_paid
# 根据上面新的low和high,重新制定fixed_month_paid
fixed_month_paid = (low + high) / 2
print(f'月还款额为:{round(fixed_month_paid, 2)}, 运行了:{count}次')
fixed_month_pay(5000, 0.18) |
funcionario = int(input())
horas = int(input())
valor_horas = float(input())
salary = horas * valor_horas
print(f'NUMBER = {funcionario}')
print(f'SALARY = U$ {salary:.2f}')
|
# user defined-exceptions
# an exception handler class for operand errors
# and extend or inherits CalculatorError
from calculatorerror import CalculatorError
class OperandError(CalculatorError):
""" exception handler for operand error """
def __init__(self, operand):
self.operand = operand
def raise_OperandError(self):
""" raises an OperandError (this is Calculators version ValueError
TypeError - values must of type int or float)
when the operand type is neither an int or float and returns
a bool, False else True """
operand_types = [int, float]
if type(self.operand) not in operand_types:
print(
f"OperandError: {repr(self.operand)}, is not of type int or \
float but of {type(self.operand)}")
return False
return True
def raise_OperandZeroError(self):
""" raises an OperandZeroError (this is calculators version of
ZeroDivisionError) - when (especially) the second operand passed,
is zero and returns a bool,False else True """
if self.operand == 0:
print(
f"OperandZeroError: a Non-Zero operand required, \
{repr(self.operand)} given")
return False
return True
|
import os.path
def addPainting():
while True:
melyik_fajl=input("\n\tMelyik fájlban szeretne menteni?irja be a nevét, és kiterjesztését: ")
if os.path.isfile(melyik_fajl):
break
print("\tNem létezik a fájl, próbálja újra!")
f=open(melyik_fajl, 'a')
festmenynev=input("\tÍrja be a festmény nevét: ")
festmenyar=input("\tÍrja be a festmény árát[Ft]: ")
f.write(f'{festmenynev};{festmenyar}\n')
f.close()
print("\tMentve\n")
input("\tMenübe való vissza téréshez nyomjon Entert!\n")
#addPainting() |
"""
The primary goal of this file is to demonstrate
a simple unittest implementation.
"""
import unittest
from triangle import classify_triangle
class TestTriangleInputs(unittest.TestCase):
"""
Test the inputs of the triangle function.
"""
def test_invalid_string_input(self):
"""
Test classify_triangle when input(s) are of type string.
"""
self.assertEqual(classify_triangle('10', '7', '4'),
'InvalidInput', 'All inputs must be integers')
def test_invalid_float_input(self):
"""
Test classify_triangle when input(s) are of type float.
"""
self.assertEqual(classify_triangle(10.0, 7.0, 4.0),
'InvalidInput', 'All inputs must be integers')
def test_invalid_over_max_input(self):
"""
Test classify_triangle when input(s) are slightly over maximum.
"""
self.assertEqual(classify_triangle(201, 201, 201),
'InvalidInput', 'All inputs must be 0 < input <= 200')
def test_invalid_at_max_input(self):
"""
Test classify_triangle when input(s) are slightly over maximum.
"""
self.assertNotEqual(classify_triangle(200, 200, 200),
'InvalidInput',
'All inputs must be 0 < input <= 200')
def test_invalid_under_min_input(self):
"""
Test classify_triangle when input(s) are slightly under minimum.
"""
self.assertEqual(classify_triangle(0, 0, 0),
'InvalidInput', 'All inputs must be 0 < input <= 200')
def test_invalid_at_min_input(self):
"""
Test classify_triangle when input(s) are slightly under minimum.
"""
self.assertNotEqual(classify_triangle(1, 1, 1),
'InvalidInput',
'All inputs must be 0 < input <= 200')
class TestTriangles(unittest.TestCase):
"""
Test the outputs of the triangle function.
"""
def test_invalid_sum_sides_a(self):
"""
Test classify_triangle when inputs do not form a triangle.
"""
self.assertEqual(classify_triangle(10, 7, 2),
'NotATriangle', '10,7,2 is not a triangle')
def test_invalid_sum_sides_b(self):
"""
Test classify_triangle when inputs do not form a triangle.
"""
self.assertEqual(classify_triangle(7, 10, 2),
'NotATriangle', '7,10,2 is not a triangle')
def test_invalid_sum_sides_c(self):
"""
Test classify_triangle when inputs do not form a triangle.
"""
self.assertEqual(classify_triangle(7, 2, 10),
'NotATriangle', '7,2,10 is not a triangle')
def test_valid_equilateral_triangle(self):
"""
Test classify_triangle when inputs for an equilateral triangle.
"""
self.assertEqual(classify_triangle(1, 1, 1),
'Equilateral', '1,1,1 should be equilateral')
def test_valid_right_triangle_a(self):
"""
Test classify_triangle when inputs for a right triangle.
"""
self.assertEqual(classify_triangle(3, 4, 5), 'Right',
'3,4,5 is a Right triangle')
def test_valid_right_triangle_b(self):
"""
Test classify_triangle when inputs for a right triangle.
"""
self.assertEqual(classify_triangle(5, 3, 4), 'Right',
'5,3,4 is a Right triangle')
def test_valid_right_triangle_c(self):
"""
Test classify_triangle when inputs for a right triangle.
"""
self.assertEqual(classify_triangle(4, 5, 3), 'Right',
'4,5,3 is a Right triangle')
def test_valid_scalene_triangle_a(self):
"""
Test classify_triangle when inputs for a scalene triangle.
"""
self.assertEqual(classify_triangle(4, 6, 9), 'Scalene',
'4,6,9 is a Scalene triangle')
def test_valid_scalene_triangle_b(self):
"""
Test classify_triangle when inputs for a scalene triangle.
"""
self.assertEqual(classify_triangle(9, 4, 6), 'Scalene',
'9,4,6 is a Scalene triangle')
def test_valid_scalene_triangle_c(self):
"""
Test classify_triangle when inputs for a scalene triangle.
"""
self.assertEqual(classify_triangle(6, 9, 4), 'Scalene',
'6,9,4 is a Scalene triangle')
def test_valid_isosceles_triangle_a(self):
"""
Test classify_triangle when inputs for an isosceles triangle.
"""
self.assertEqual(classify_triangle(3, 2, 2),
'Isosceles', '3,2,2 is a Isosceles triangle')
def test_valid_isosceles_triangle_b(self):
"""
Test classify_triangle when inputs for an isosceles triangle.
"""
self.assertEqual(classify_triangle(2, 3, 2),
'Isosceles', '2,3,2 is a Isosceles triangle')
def test_valid_isosceles_triangle_c(self):
"""
Test classify_triangle when inputs for an isosceles triangle.
"""
self.assertEqual(classify_triangle(2, 2, 3),
'Isosceles', '2,2,3 is a Isosceles triangle')
# if __name__ == '__main__':
# unittest.main()
|
from main import el_length as L, usiliya as arrayUsiliy, uz_num as el, gestkosti as array
# Валидность
def pravilnoLi(name, flt, mns, null, one):
# Убираем пробелы
name = name.strip()
# Пустая строка
if name == '':
name = None
warning = print('Вы ввели пустую строку. Повторите попытку ввода.')
# Буквы или цифры
elif name.isalnum() is True:
# Цифра
if name.isdigit() is True:
# 0
if int(name) == 0:
if null is False:
if flt is False and mns is False and null is False:
name = None
warning = print('Вы ввели 0. Необходимо как минимум 2 элемента. Повторите попытку ввода.')
elif null is False and one is True:
name = None
warning = print('Вы ввели 0. Необходимо ввести корректную величину. Повторите попытку ввода.')
# else:
# правильное усилие
# else:
# 1
elif int(name) == 1 and flt is False and one is False:
name = None
warning = print('Вы ввели меньше 2. Необходимо как минимум 2 элемента. Повторите попытку ввода.')
# Правильно
# else:
# Буква
elif name.isalpha() is True:
# Мат
if name == 'hyu' or name == 'cyka' or name == 'pidr' or name == 'blyad':
name = None
warning = print('Материться нельзя!')
nakazanie = 'Неудачник'
# Буква
else:
name = None
warning = print('Вы ввели буквы. Повторите попытку ввода.')
# Буква и цифра
else:
name = None
warning = print('Вы ввели буквы и цифры. Повторите попытку ввода.')
# Спецсимволы
else:
tochka = False
for i in range(len(name)):
if name[i] == '.':
tochka = True
# Отрицательное
if name[0] == '-' and mns is False:
name = None
warning = print('Вы ввели отрицательное значение. Повторите попытку ввода.')
elif name[0] == '-' and mns is True:
name
# Цифра с плавающей запятой
elif tochka is True:
if float(name) % 2 != float(0) and float(name) % 2 != float(1):
if flt is False and null is False:
name = None
warning = print(
'Вы ввели число c плавающей запятой. Количество элементов может быть только целым числом Повторите попытку ввода.')
elif null is True:
name = None
warning = print(
'Вы ввели число c плавающей запятой. Количество точек может быть только целым числом Повторите попытку ввода.')
# Правильно
else:
name = str(name.rstrip('0,.'))
# Спецсимвол
else:
name = None
warning = print('Вы ввели спецсимвол либо опечатались. Повторите попытку ввода.')
return name
def hotiteLi(text):
m = ''
while m != '1' and m != '0' and m.lower() != 'да' and m.lower() != 'нет':
m = input(text)
return m
def roundNum(num, kolZnakPoslZap):
num = round(num * 10 ** int(kolZnakPoslZap))/(10 ** int(kolZnakPoslZap))
return num
balka = []
def chertezUzlov():
print('Предварительный чертеж балки, включите воображение')
for i in range(len(array) * 2 + 1):
if i % 2 == 0:
balka.append('F' + str(round(i / 2 + 1)))
else:
balka.append('----')
print('F1' + ' и ' + 'F' + str(round(i / 2 + 1)) + '- заделки')
return balka
chertezUzlov()
print(balka, ' --> X', '\n')
# masiveLength()
# masiveYsiliy()
# вывод массивов
print('Массив жесткостей элементов EF\n', array, '\n')
print('Массив длин элементов L\n', L, '\n')
print('Массив узловых усилий F\n', arrayUsiliy, '\n')
balkaM = []
def chertezUzlovM():
print('Чертеж балки в масштабе с узловыми усилиями')
for i in range(len(array) * 2 + 1):
if i % 2 == 0:
balkaM.append(arrayUsiliy[round(i / 2)])
else:
balkaM.append(('-' * int(L[round((i - 1) / 2)])))
balkaM[0] = 'F1'
balkaM[-1] = 'F' + str(round(i / 2 + 1))
print('F1' + ' и ' + 'F' + str(round(i / 2 + 1)) + '- заделки')
return balkaM
chertezUzlovM()
print(balkaM, ' --> X', '\n')
# обьявление вспомогательной матрицы
arrayG = [[1, -1],
[-1, 1]]
# формируем заготовку для массива матриц жесткостей
arrayGes = []
for i in range(len(array)):
arrayGes.append([])
for j in range(len(arrayG)):
arrayGes[i].append([])
# на выходе получим [ [ [], [] ], [ [], [] ],
# [ [], [] ], [ [], [] ] ]
# считаем матрицу жесткостей элементов
def makeMatricaGestcosti():
for i in range(len(array)):
for j in range(len(arrayG)):
for k in range(len(arrayG[j])):
arrayGes[i][j].append(float(array[i]) * float(arrayG[j][k]))
return arrayGes
makeMatricaGestcosti()
# выводим матрицы жесткостей элементов
def vivod(arrayGes):
k = 0
for i in range(len(arrayGes)):
for j in range(len(arrayGes[i])):
if k % 2 == 0:
print('Матрица жесткости ', i + 1, '-го элемента: \n', arrayGes[i][j])
k += 1
else:
print('', arrayGes[i][j])
k = 0
vivod(arrayGes)
print('')
# формируем заготовку для матрицу жесткости системы
matGes = []
for i in range(len(array) + 1):
matGes.append([])
# считаем матрицу жесткости системы
def makeMatricaGestcostiSistemi():
matGes[0].append(arrayGes[0][0][0])
for i in range(len(array) + 1):
for j in range(len(array) + 1):
if i == j and i != 0 and i != len(array):
matGes[i].append(arrayGes[i][0][0] + arrayGes[i - 1][0][0])
elif j == i - 1 and i != 0 and i != len(array) + 1:
matGes[i].append(arrayGes[i - 1][0][1])
elif j == i + 1 and i != len(array) + 1:
matGes[i].append(arrayGes[i][0][1])
elif j != i and j != -1 and i != -1:
matGes[i].append(0)
matGes[-1].append(arrayGes[-1][0][0])
return matGes
makeMatricaGestcostiSistemi()
print('Матрица жесткости системы')
for i in range(len(matGes)):
print(matGes[i])
print('')
def vvodGranichnihUsloviy():
for i in range(len(matGes)):
for j in range(len(matGes[i])):
if j == 0 or j == len(matGes) - 1 or i == 0 or i == len(matGes) - 1:
matGes[i][j] = 0
matGes[0][0] = 1
matGes[-1][-1] = 1
return matGes
vvodGranichnihUsloviy()
print('Матрица жесткости системы с граничными условиями')
for i in range(len(matGes)):
print(matGes[i])
print('')
arrayUzlovihPeremesheniy = []
def matrichnoeUravnenie():
for i in range(len(array) + 1):
arrayUzlovihPeremesheniy.append('U' + str(i + 1))
print(str(matGes[i]) + ' * ' + str(arrayUzlovihPeremesheniy[i]) + ' = ' + str(arrayUsiliy[i]))
print('Матричное уравнение')
matrichnoeUravnenie()
print('')
arrayReshenie = []
arr1 = []
arr = []
for i in range(len(arrayUsiliy) - 2):
arr.append([])
def makeArr():
for i in range(1, len(arrayUsiliy) - 1):
for j in range(1, len(arrayUsiliy) - 1):
for k in range(1):
arr[i - 1].append(matGes[i][j])
return arr
makeArr()
arrU = []
def makeArrU():
for i in range(1, len(arrayUsiliy) - 1):
arrU.append(arrayUsiliy[i])
return arrU
makeArrU()
print('Убираем лишнее')
for i in range(len(arr)):
print(str(arr[i]) + ' = ' + str(arrU[i]))
print('')
def mnogitel(i, elem):
for j in range(len(elem)):
if i == j:
m = elem[i - 1][j] / elem[i][j]
return m
okr = False
m = hotiteLi('Хотите округлить результаты? ')
if m == '1' or m.lower() == 'да':
okr = True
kolZnakPoslZap = None
while kolZnakPoslZap == None:
kolZnakPoslZap = input('Сколько знаков оставить после запятой? ')
kolZnakPoslZap = pravilnoLi(kolZnakPoslZap, False, False, False, True)
def triangleArray():
for i in range(len(arr) - 1, 0, -1):
mn = mnogitel(i, arr)
b = float(arrU[i - 1]) - float(arrU[i]) * mn
if okr is True:
b = roundNum(b, kolZnakPoslZap)
arrU[i - 1] = b
for j in range(len(arr[i]) - 1, -1, -1):
a = arr[i - 1][j] - arr[i][j] * mn
if okr is True:
a = roundNum(a, kolZnakPoslZap)
arr[i - 1][j] = a
return arr
triangleArray()
print('Приводим к диагональному виду')
for i in range(len(arr)):
print(str(arr[i]) + ' = ' + str(arrU[i]))
print('')
def intU():
for i in range(len(arrU)):
arrU[i] = float(arrU[i])
return arrU
intU()
resh = 0
uLoc = 0
U = []
def reshenieSlay():
arrayReshenie.append(0)
for i in range(len(arrU)):
for j in range(len(arrU)):
if i == j and i == 0:
resh = arrU[i] / arr[i][j]
if okr is True:
resh = roundNum(resh, kolZnakPoslZap)
uLoc = resh
elif i == j:
resh = (arrU[i] - uLoc * arr[i][j - 1]) / arr[i][j]
if okr is True:
resh = roundNum(resh, kolZnakPoslZap)
uLoc = resh
arrayReshenie.append(resh)
arrayReshenie.append(0)
return arrayReshenie
U = reshenieSlay()
print('Столбец возможных перемещений')
print(U)
print('')
N = []
for i in range(len(array)):
N.append([])
def masssiveFunFormForEachElementInTochka(x):
for i in range(len(array)):
N[i] = []
for i in range(len(array)):
N1 = 1 - x / float(L[i])
N2 = x / float(L[i])
N[i].append(N1)
N[i].append(N2)
return N
# PeremeshenieElementaVTochke = 0
def sluchPeremeshenie():
PeremeshenieElementaVTochke = 0
element = None
while element == None:
element = input('Введите номер элемента от 1 до ' + str(len(array)) + ' ')
element = pravilnoLi(element, False, False, False, True)
if element != None:
element = int(element)
if element <= len(array) and element > 0:
m = '1'
while m == '1':
x = input('Введите координату от 0 до 1 в ' + str(element) + ' элементе в долях от ' + str(
L[element - 1]) + ' м ')
x = float(x)
if x <= 1 and x >= 0:
masssiveFunFormForEachElementInTochka(x)
PeremeshenieElementaVTochke = N[element - 1][0] * U[element - 1] + N[element - 1][1] * U[
element]
if okr is True:
PeremeshenieElementaVTochke = roundNum(PeremeshenieElementaVTochke, kolZnakPoslZap)
print(PeremeshenieElementaVTochke)
m = hotiteLi('Хотите снова найти перемещение в ' + str(element) + ' элементе? ')
else:
print('Непрвильная координата\n')
else:
print('Непрвильный номер элемента\n')
return PeremeshenieElementaVTochke
m = hotiteLi('Хотите найти перемещение в указанной точке? ')
if m == '1' or m.lower() == 'да':
m = '1'
while m == '1' or m.lower() == 'да':
sluchPeremeshenie()
m = hotiteLi('Хотите снова найти перемещение в указанной точке? ')
print('')
arrT = []
rasDef = False
maxDef = False
def skolkoTochek(rasDef, maxDef):
kolT = None
while kolT == None:
if rasDef is True:
kolT = input('Сколько точек хотите рассмотреть в каждом элементе? (Не считая узловых точек) ')
elif maxDef is True:
kolT = input('На сколько точек хотите разбить элементы? ')
kolT = pravilnoLi(kolT, False, False, True, True)
for i in range(int(kolT) + 2):
arrT.append(1 / (int(kolT) + 1) * i)
return arrT
arrRas = []
for i in range(len(array)):
arrRas.append([])
def makeArrayRaspredelenya():
skolkoTochek(True, False)
for i in range(len(array)):
for j in range(len(arrT)):
masssiveFunFormForEachElementInTochka(arrT[j])
PeremeshenieElementaVTochke = N[i][0] * U[i] + N[i][1] * U[i + 1]
if okr is True:
PeremeshenieElementaVTochke = roundNum(PeremeshenieElementaVTochke, kolZnakPoslZap)
arrRas[i].append(PeremeshenieElementaVTochke)
return arrRas
m = hotiteLi('Хотите посмотреть распределение перемещений по элементам? ')
if m == '1' or m.lower() == 'да':
makeArrayRaspredelenya()
print(arrRas)
print('')
arrRas = []
for i in range(len(array)):
arrRas.append([])
a = roundNum(40, 2)
arrT = []
Max = ['','','']
def seekMax():
skolkoTochek(False, True)
for i in range(len(array)):
for j in range(len(arrT)):
masssiveFunFormForEachElementInTochka(arrT[j])
PeremeshenieElementaVTochke = N[i][0] * U[i] + N[i][1] * U[i + 1]
if okr is True:
PeremeshenieElementaVTochke = roundNum(PeremeshenieElementaVTochke, kolZnakPoslZap)
arrRas[i].append(PeremeshenieElementaVTochke)
Max[0] = arrRas[0][0]
for i in range(len(arrRas)):
for j in range(len(arrRas[i]) - 1):
if arrRas[i][j + 1] > arrRas[i][j]:
if okr is True:
arrRas[i][j + 1] = roundNum(arrRas[i][j + 1], kolZnakPoslZap)
Max[0] = arrRas[i][j + 1]
Max[1] = i
Max[2] = j
return Max
m = hotiteLi('Хотите найти максимальное перемещение? ')
if m == '1' or m.lower() == 'да':
max = seekMax()
print('Максимальное значение перемещения ' + str(max[0]) + ' в элементе ' + str(max[1]) + ' в точке ' + str(max[2]))
print('\n' + 'Конец решения') |
#!/usr/bin/python3
import itertools
import math
import threading
N = 0
m = 0
DIRECT = 0
INFERIOR = 1
INVERSE = 2
SUPERIOR = 3
BLOCK_TYPES = [DIRECT, INFERIOR, INVERSE, SUPERIOR]
result = None
THREADS = 4
def generate_all_posibilities(nr_of_blocks):
"""
Generates all possible block types variations
:param nr_of_blocks: the total number of blocks in the network
:return: generated possibilities
"""
blocks = [BLOCK_TYPES] * nr_of_blocks
product = itertools.product(*blocks)
return product
def go_through_level(start, values, blocks):
"""
Simulates the shuffled input going through a level
:param start: index or first block from level
:param values: shuffled values
:param blocks: all blocks
:return: input processed through level
"""
output = [0] * N
for i in range(int(start), int(start + (N / 2))):
j = int(2 * (i - start))
if blocks[i] == DIRECT:
output[j] = values[j]
output[j + 1] = values[j + 1]
elif blocks[i] == INFERIOR:
output[j] = values[j + 1]
output[j + 1] = values[j + 1]
elif blocks[i] == INVERSE:
output[j] = values[j + 1]
output[j + 1] = values[j]
elif blocks[i] == SUPERIOR:
output[j] = values[j]
output[j + 1] = values[j]
return output
def shuffle(i):
"""
Shuffling
:param i: number of input value before shuffle
:return: position of value after shuffle
"""
return int((int(2 * i) + int(2 * i / N)) % N)
def print_output(INPUT, OUTPUT, steps, nr_of_rows, nr_of_blocks):
"""
:param INPUT: input values
:param OUTPUT: output values
:param steps: steps in each level
:param nr_of_rows: N/2
:param nr_of_blocks: N/2*log(N)
"""
global result
# Print result
print("N: {}\nk: {}\n".format(N, m))
print("Input: {}\nOutput: {}\n".format(INPUT, OUTPUT))
print("Block types (as seen on the scheme):")
network = []
for i in range(nr_of_rows):
blocks = []
for j in range(0 + i, nr_of_blocks + i, nr_of_rows):
if result[j] == DIRECT:
blocks.append("DIRECT")
elif result[j] == INFERIOR:
blocks.append("INFERIOR")
elif result[j] == INVERSE:
blocks.append("INVERSE")
elif result[j] == SUPERIOR:
blocks.append("SUPERIOR")
network.append(blocks)
col_width = max(len(word) for row in network for word in row) + 2
for row in network:
padded_row = [word.ljust(col_width) for word in row]
blocks_to_string = ""
for block in padded_row:
blocks_to_string += str(block)
print(blocks_to_string)
print("\nDetailed steps per level:")
col_width = max(len(steps[step]) for step in steps) + 2
step_nr = 0
for step in steps:
if step_nr % 3 == 0:
print("Level {}:".format(int(step_nr / 3 + 1)))
step_nr += 1
print("{}: {}".format(str(step).ljust(col_width), str(steps[step]).ljust(col_width)))
def check_possibility(INPUT, OUTPUT, possibilities, start, end, nr_of_rows, nr_of_blocks):
global result
shuffled_values = [0] * N
output_values = [0] * N
# Find block types
count = -1
steps = {}
for possibility in possibilities:
if result is not None: # other thread might have found the solution
return
count += 1
if count not in range(start, end):
continue
input_values = INPUT.copy()
for level in range(m):
for i in range(N):
shuffled_value = shuffle(i)
shuffled_values[shuffled_value] = input_values[i]
output_values = go_through_level(level * N / 2, shuffled_values, list(possibility)).copy()
steps["{}_Input".format(level)] = input_values.copy()
steps["{}_Shuffled".format(level)] = shuffled_values.copy()
steps["{}_Output".format(level)] = output_values.copy()
input_values = output_values.copy()
# Here we check if we found the result.
# If we want to also check for networks with another number of `shuffle` connections (different than log(N)),
# then this `if` section should be inside the `for` loop: `for level in range(m):` - so just \tab this `if`
if output_values == OUTPUT:
result = list(possibility)
print_output(INPUT, OUTPUT, steps, nr_of_rows, nr_of_blocks)
return
return
def set_input_output_values():
"""
Here you can choose/set the input values for this program
:return: INPUT and OUTPUT values for Omega network
"""
""" !!!!!!!!!!!!!!!! MODIFY HERE THE INPUT AND OUTPUT VALUES !!!!!!!!!!!!!!!!!!!!!! """
# these should give only DIRECT blocks - easy computation
INPUT = [0, 1, 2, 3, 4, 5, 6, 7]
OUTPUT = [0, 1, 2, 3, 4, 5, 6, 7]
# # this should give an INFERIOR block - bottom right - easy computation
# INPUT = [0, 1, 2, 3, 4, 5, 6, 7]
# OUTPUT = [0, 1, 2, 3, 4, 5, 7, 7]
# # this should give an INVERSE block - top right - hard computation, goes through many possibilities
# INPUT = [0, 1, 2, 3, 4, 5, 6, 7]
# OUTPUT = [1, 0, 2, 3, 4, 5, 6, 7]
# # this should give an error - no possibility for this - very hard computation, goes through all the possibilities
# INPUT = [0, 1, 2, 3, 4, 5, 6, 7]
# OUTPUT = [0, 1, 2, 3, 4, 5, 6, 8]
return INPUT, OUTPUT
def main():
"""
Gives INPUT and OUTPUT and computes all the block types that connect the INPUT to the OUTPUT
:return:
"""
global N, m
INPUT, OUTPUT = set_input_output_values()
# Computing N and m
N = len(INPUT)
assert math.log2(N) == int(math.log2(N)) # check if the number of inputs is power of 2
m = int(math.log2(N))
# Computing network values
nr_of_levels = int(math.log2(N))
nr_of_rows = int(N / 2)
nr_of_blocks = nr_of_levels * nr_of_rows
# Generating all possibilities
possibilities = generate_all_posibilities(nr_of_blocks)
# Testing all possibilities
nr_of_possibilities = len(BLOCK_TYPES) ** nr_of_blocks
threads = []
for thread in range(THREADS):
start = int(nr_of_possibilities / THREADS * len(threads))
end = int(nr_of_possibilities / THREADS * (len(threads) + 1))
threads.append(threading.Thread(target=check_possibility, args=(INPUT, OUTPUT, possibilities, start, end, nr_of_rows, nr_of_blocks)))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
if result is None:
print("There is no Omega network of size {0}x{0} that can convert {1} to {2}!".format(N, INPUT, OUTPUT))
if __name__ == '__main__':
main()
|
class animal():
def run(self):
print("Animal is running")
class cat(animal):
def run(self):
print("cat is running")
def run_two_times(self,animal):
animal.run()
animal.run()
oneCat=cat()
oneCat.run()
print(isinstance(oneCat,cat))
print(dir(animal))
|
############## 07/11/2019
# 1. weather类中包含方法:1.输入daytime返回可见度,2.根据input返回温度
class WeatherSearch():
def __init__(self, input_daytime):
self.input_daytime=input_daytime
def search_visibility(self):
visible_degree=0
if self.input_daytime=="morning":
visible_degree=2
if self.input_daytime=="night":
visible_degree=9
return visible_degree
def search_temperature(self):
tem=0
if self.input_daytime=="morning":
tem=10
if self.input_daytime=="night":
tem=15
return tem
# 2.OutAdvice 中包含2个方法:1.根据daytime返回建议的交通工具(覆盖父类的温度查找方法,返回工具),2. 返回整体的建议
class OutAdvice(WeatherSearch):
def __init__(self,input_daytime):
WeatherSearch.__init__(self,input_daytime)
def search_temperature(self):
vehicle=""
if self.input_daytime=="morning":
vehicle= "bike"
if self.input_daytime=="night":
vehicle= "taxi"
return vehicle
def out_advice(self):
visible_leave=self.search_visibility()
if visible_leave==2:
print("the weather is good, suggest to use %s" %self.search_temperature())
elif visible_leave==9:
print("the weather is not good, suggest to use %s" %self.search_temperature())
else:
print("I don't know!!")
use=OutAdvice("night")
use.out_advice()
|
list = ['Pizza', 'Burgers', 'Chips']
print("Here are the items in the food list:")
print(list)
print()
change = input("Which item should I change? ")
new = input("Enter the new value: ")
print()
if change in list:
i = list.index(change)
list.remove(change)
list.insert(i, new)
print("Here is the revised list: ")
print(list)
|
# Lina Kang
# 1072568
# HW 03 PS 1 - Stock Transaction Program
# receive input from user regarding the stocks
def userInput()->(str, int, float, float, float):
name = input("Enter Stock name: ")
shares = int(input("Enter Number of shares: "))
purchasePrice = float(input("Enter Purchase price: "))
sellingPrice = float(input("Enter Selling Price: "))
commission = float(input("Enter Commission: "))
print()
return name, shares, purchasePrice, sellingPrice, commission
# calculate the amount paid and sold for the stock, broker commission, and the profit
def calculate(shares:int, purchasePrice:float, sellingPrice:float, commission: float)->(float, float, float, float, float):
stockPaid = shares * purchasePrice
commissionBought = stockPaid * commission
stockSold = shares * sellingPrice
commissionSold = stockSold * commission
moneyleft = (stockSold - commissionSold) - (stockPaid + commissionBought)
return stockPaid, commissionBought, stockSold, commissionSold, moneyleft
# output the calculated data from calculate function
def display(name:str, stockPaid:float, commissionBought:float, stockSold:float, commissionSold:float, moneyLeft:float)->None:
print("Stock Name: ", name)
print()
print("Amount paid for the stock: $ ", format(stockPaid, '10,.2f'), sep='')
print("Commission paid on the purchase: $ ", format(commissionBought, '10,.2f'), sep='')
print("Amount the stock sold for: $ ", format(stockSold, '10,.2f'), sep='')
print("Commission paid on the sale: $ ", format(commissionSold, '10,.2f'), sep='')
print("Profit(or loss if negative): $ ", format(moneyLeft, '10,.2f'), sep='')
def main():
# number of loops to run according to the number of transactions
sentinel = input("Would you like to make a transaction? (Y/N): ")
print()
print("*************************")
while sentinel == 'y' or sentinel == 'Y':
# call function userInput, calculate, and display within this loop for every transaction
name, shares, purchasePrice, sellingPrice, commission = userInput()
print()
stockPaid, commissionBought, stockSold, commissionSold, moneyLeft = calculate(shares, purchasePrice, sellingPrice, commission)
display(name, stockPaid, commissionBought, stockSold, commissionSold, moneyLeft)
print()
sentinel = input("Would you like to make another transaction? (Y/N): ")
print()
print("*************************")
if __name__=="__main__":
main()
## Test Case 1.
##
##Would you like to make a transaction? (Y/N): y
##
##*************************
##Enter Stock name: Kaplack Inc.
##Enter Number of shares: 10000
##Enter Purchase price: 33.92
##Enter Selling Price: 35.92
##Enter Commission: 0.04
##
##
##Stock Name: Kaplack Inc.
##
##Amount paid for the stock: $ 339,200.00
##Commission paid on the purchase: $ 13,568.00
##Amount the stock sold for: $ 359,200.00
##Commission paid on the sale: $ 14,368.00
##Profit(or loss if negative): $ -7,936.00
##
##Would you like to make another transaction? (Y/N): y
##
##*************************
##Enter Stock name: Monsters Inc
##Enter Number of shares: 2000
##Enter Purchase price: 45.92
##Enter Selling Price: 53.20
##Enter Commission: 0.03
##
##
##Stock Name: Monsters Inc
##
##Amount paid for the stock: $ 91,840.00
##Commission paid on the purchase: $ 2,755.20
##Amount the stock sold for: $ 106,400.00
##Commission paid on the sale: $ 3,192.00
##Profit(or loss if negative): $ 8,612.80
##
##Would you like to make another transaction? (Y/N): y
##
##*************************
##Enter Stock name: Bottles Corp
##Enter Number of shares: 3000
##Enter Purchase price: 23.94
##Enter Selling Price: 19.99
##Enter Commission: 0.045
##
##
##Stock Name: Bottles Corp
##
##Amount paid for the stock: $ 71,820.00
##Commission paid on the purchase: $ 3,231.90
##Amount the stock sold for: $ 59,970.00
##Commission paid on the sale: $ 2,698.65
##Profit(or loss if negative): $ -17,780.55
##
##Would you like to make another transaction? (Y/N): y
##
##*************************
##Enter Stock name: Wheat TinTins
##Enter Number of shares: 2048
##Enter Purchase price: 12.80
##Enter Selling Price: 25.50
##Enter Commission: 0.08
##
##
##Stock Name: Wheat TinTins
##
##Amount paid for the stock: $ 26,214.40
##Commission paid on the purchase: $ 2,097.15
##Amount the stock sold for: $ 52,224.00
##Commission paid on the sale: $ 4,177.92
##Profit(or loss if negative): $ 19,734.53
##
##Would you like to make another transaction? (Y/N): y
##
##*************************
##Enter Stock name: Jacobson Inc.
##Enter Number of shares: 12345
##Enter Purchase price: 7.98
##Enter Selling Price: 10.11
##Enter Commission: 0.012
##
##
##Stock Name: Jacobson Inc.
##
##Amount paid for the stock: $ 98,513.10
##Commission paid on the purchase: $ 1,182.16
##Amount the stock sold for: $ 124,807.95
##Commission paid on the sale: $ 1,497.70
##Profit(or loss if negative): $ 23,615.00
##
##Would you like to make another transaction? (Y/N): n
##
##*************************
##
## Test Case 2.
##
##Would you like to make a transaction? (Y/N): y
##
##*************************
##Enter Stock name: Lenovo Group LTD
##Enter Number of shares: 8000
##Enter Purchase price: 0.5075
##Enter Selling Price: 0.8023
##Enter Commission: 0.02
##
##
##Stock Name: Lenovo Group LTD
##
##Amount paid for the stock: $ 4,060.00
##Commission paid on the purchase: $ 81.20
##Amount the stock sold for: $ 6,418.40
##Commission paid on the sale: $ 128.37
##Profit(or loss if negative): $ 2,148.83
##
##Would you like to make another transaction? (Y/N): y
##
##*************************
##Enter Stock name: Netflix Inc
##Enter Number of shares: 4300
##Enter Purchase price: 32.93
##Enter Selling Price: 37.92
##Enter Commission: 0.06
##
##
##Stock Name: Netflix Inc
##
##Amount paid for the stock: $ 141,599.00
##Commission paid on the purchase: $ 8,495.94
##Amount the stock sold for: $ 163,056.00
##Commission paid on the sale: $ 9,783.36
##Profit(or loss if negative): $ 3,177.70
##
##Would you like to make another transaction? (Y/N): n
##
##*************************
##
## Test Case 3.
##
##Would you like to make a transaction? (Y/N): y
##
##*************************
##Enter Stock name: HP Inc
##Enter Number of shares: 2300
##Enter Purchase price: 14.23
##Enter Selling Price: 12.12
##Enter Commission: 0.04
##
##
##Stock Name: HP Inc
##
##Amount paid for the stock: $ 32,729.00
##Commission paid on the purchase: $ 1,309.16
##Amount the stock sold for: $ 27,876.00
##Commission paid on the sale: $ 1,115.04
##Profit(or loss if negative): $ -7,277.20
##
##Would you like to make another transaction? (Y/N): n
##
##*************************
##
## Test Case 4.
##
##Would you like to make a transaction? (Y/N): y
##
##*************************
##Enter Stock name: Awesome Company
##Enter Number of shares: 6000
##Enter Purchase price: 93.23
##Enter Selling Price: 86.23
##Enter Commission: 0.02
##
##
##Stock Name: Awesome Company
##
##Amount paid for the stock: $ 559,380.00
##Commission paid on the purchase: $ 11,187.60
##Amount the stock sold for: $ 517,380.00
##Commission paid on the sale: $ 10,347.60
##Profit(or loss if negative): $ -63,535.20
##
##Would you like to make another transaction? (Y/N): y
##
##*************************
##Enter Stock name: Awesome Company Jr.
##Enter Number of shares: 300
##Enter Purchase price: 86.23
##Enter Selling Price: 120.34
##Enter Commission: 0.01
##
##
##Stock Name: Awesome Company Jr.
##
##Amount paid for the stock: $ 25,869.00
##Commission paid on the purchase: $ 258.69
##Amount the stock sold for: $ 36,102.00
##Commission paid on the sale: $ 361.02
##Profit(or loss if negative): $ 9,613.29
##
##Would you like to make another transaction? (Y/N): y
##
##*************************
##Enter Stock name: Awesome Company Jr. Jr.
##Enter Number of shares: 1200
##Enter Purchase price: 12.34
##Enter Selling Price: 12.53
##Enter Commission: 0.04
##
##
##Stock Name: Awesome Company Jr. Jr.
##
##Amount paid for the stock: $ 14,808.00
##Commission paid on the purchase: $ 592.32
##Amount the stock sold for: $ 15,036.00
##Commission paid on the sale: $ 601.44
##Profit(or loss if negative): $ -965.76
##
##Would you like to make another transaction? (Y/N): n
##
##*************************
##
## Test Case 5.
##
##Would you like to make a transaction? (Y/N): n
##
##*************************
|
def main():
print("Enter 5 numbers: ")
numbers = []
for x in range(5):
temp = int(input(""))
numbers.append(temp*10)
for x in range(4, -1, -1):
print(float(numbers[x]), end =" ")
if __name__ == "__main__":
main()
|
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("yes")
|
class Weapon:
def __init__(self, name, damage):
'''Sätter namn och damage'''
self.name = name
self.damage = damage
def __str__(self):
'''Returnerar en läsbar sträng för objekt i Weapon'''
return "- {}".format(self.name)
|
import requests
a = raw_input('Enter currency to convert from ?')
a = a.upper()
b = raw_input('Enter currency to convert to ?')
b = b.upper()
c = float(raw_input('Enter value to convert ?'))
url = ('https://currency-api.appspot.com/api/%s/%s.json') % (a, b)
print url
r = requests.get(url)
rate= r.json()['rate']
print "rate is => "+str(rate)
value= c*float(r.json()['rate'])
print "value is => "+str(value)
|
q=input()
c=0
for i in q:
if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':
c+=1
if c>0:
print("yes")
else:
print("no")
|
count=0
a=0
while count<10:
if a%2==0:
print(a)
count=count+1
a=a+1
|
b=eval(input(" enter breadth :"))
h=eval(input(" height :"))
ar=.5*b*h
print("square is ",ar)
|
quite = "brexit"
while quite == "brexit":
set1= input("Say rock ,paper or scizzor:")
set2= input("Say rock ,paper or scizzor:")
f = [set1,set2]
if len(f) != 0 :
while set1 == set2 :
print ("Draw");break
while set1 != set2 :
if "rock" in f and "scizzor" in f :
print("Rock wins"); break
if "rock" in f and "paper" in f :
print("Paper wins"); break
if "scizzor" in f and "paper" in f:
print("Scizzor wins"); break
quit = input('Type "exit" to quit and "@" to continue:')
if quit != "exit" :
continue
else:
print("The Game Has ended",quite);break
|
#in chi tra lai mot trong hai gia tri true or false
strA=('rabiloo')
strB=('u')
strC=strB in strA
#lay chuoi cat chuoi
print(strC)
print(strA[0])
print(strA[-2])
print(strA[len(strA)-1])
strD=strA[3:len(strA)]
print(strD)
#cat theo [tu:den:buoc nhay]
strE = strA[None:None:3]
print(strE)
#in ra chuoi
e='My name is %s %d'%("Thuong",5)
print(e)
s='%s %s'
result=s %('hai','ba')
print(result)
print(f'a\tb')
Kteam='Kteam'
result=f'{Kteam}- Free education'
print(result)
#gan,can le
r= '1: {one},2: {two}' .format(one=111,two=777)
print(r)
l='How{:*^50}Free education'.format('Kteam')
l1='Nguyen{:<30}Thuong'.format('')
print(l)
print(l1)
#Kieu chuoi
#viet hoa dau dong
a1='how kteam'
b1=a1.capitalize()
print(b1)
c1=a1.swapcase()
print(c1)
d1=a1.title()
print(d1)
e1=a1.center(50,'*')
print(e1)
g1=a1.join(['1','2','3'])
print(g1)
h1=a1.replace('o','a',1)#thay o thanh a
print(h1)
t1=a1.strip('h')#cat hai dau
print(t1)
a2='how kteam free education'
b2=a2.split('e',2)#cat theo ki tu va so lan cat trong split .rsplit cat tu ben phai
print(a2)
print(b2)
c2=a2.partition('k')#cat truoc sau va chu k
d2=a2.count('t',0,6)
e2=a2.startswith('how',6)
print(e2)
g2=a2find('kteam') |
# -*- coding: utf-8 -*-
#!/usr/bin/python
import numpy as np
# 18. Sắp xếp các hàng theo thứ tự giảm dần của giá trị (numeric value) của cột thứ 3
# Viết chương trình thực hiện nhiệm vụ trên.
# Dùng lệnh sort để xác nhận (trong bài tập này, kết quả của chương trình của bạn với lệnh sort có thể khác nhau do có thể có các giá trị giống nhau trong cột thứ 3).
# Confirm with sort command
# % sort -r -n -k 3 ../../data/hightemp.txt
def sort_by_col3():
f = open('../../data/hightemp.txt', 'rU')
keys = []
lines = []
for line in f:
line = line.rstrip()
cols = line.split()
val = float(cols[2])
keys.append(val)
lines.append(line)
f.close()
# get original indexes of sorted array using lambda
# reference: http://stackoverflow.com/questions/6422700/how-to-get-indices-of-a-sorted-array-in-python
# Python Lambda Function for anonymous function:
# http://www.secnetix.de/olli/Python/lambda_functions.hawk
# Python sorting:
# https://wiki.python.org/moin/HowTo/Sorting#Key_Functions
# try the solution with numpy.argsort
# http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html#numpy-argsort
# indexes = np.array(keys).argsort()[::-1]
indexes = sorted(range(len(keys)),key=lambda x:keys[x], reverse=True)
for i in indexes:
print lines[i]
def main():
sort_by_col3()
if __name__ == '__main__':
main()
|
import random
import numpy
import math
#########MAIN##########
#Returns a randomly weighted matrix
def generate_weights(size):
weights = []
for i in xrange(0,size):
weights.append([float("{0:.1f}".format(random.uniform(-0.5, 0.5))), float("{0:.1f}".format(random.uniform(-0.5, 0.5)))])
return numpy.asarray(weights)
def step_function(value):
return 1 if value >= 0 else 0
#FIKS RESULT
def activation(input,weights,threshold):
dot_product = (input * weights)
result = []
err = []
index = 0
for x in dot_product:
result.append(step_function(sum(x)-threshold))
#result = step_function(result)
print "result: ", result
return result
def update_weights(input,weights,learning_rate, error):
index = 0
updated_weights = []
for w in weights:
updated_weights.append( [w[0] + (input[index][0] * learning_rate * error[index]),
w[1] + (input[index][1] * learning_rate * error[index])])
index += 1
return numpy.asarray(updated_weights)
def toString(output,error,weights):
print "--------- \n weights: \n", weights, "\n Output: ",output, "\n ----------"
def main(AND_OR):
#Decides based on input if its using AND or OR as input
if AND_OR == "AND":
desired_output = [0,0,0,1]
elif AND_OR == "OR":
desired_output = [0,1,1,1]
input = numpy.array([[0, 0],
[0, 1],
[1, 0],
[1, 1]])
#Init some variables
threshold = float("{0:.1f}".format(random.uniform(-0.5, 0.5)))
#threshold = 0.0
learning_rate = 0.1
error = [0,0,0,1]
timeout = 100
weights = generate_weights(len(desired_output))
print "Start weights: \n", weights, "\n"
print "Threshhold: ", threshold
while error != [0,0,0,0]:
output = activation(input,weights,threshold)
error = [x1 - x2 for (x1, x2) in zip(desired_output, output)]
weights = update_weights(input,weights,learning_rate,error)
toString(output,error,weights)
timeout -= 1
if timeout == 0:
raise RuntimeError("Combination of weights and threshold may have caused a deadlock. Program timed out. Initial threshold was: ", threshold)
print "Finished! Final output: ", output
main("OR")
|
def check_integer(num):
if 45 < num < 67:
return num
raise NotInBoundsError
def error_handling(num):
try:
print(check_integer(num))
except NotInBoundsError as exc:
print(exc) |
# the list "walks" is already defined
# your code here
sum = 0
for w in walks:
sum = sum + w["distance"]
print(sum // len(walks)) |
def count(numbers, target):
res = 0
for i in numbers:
if i == target:
res += 1
return res
numbers_i = input().split(' ')
target_i = input()
print(count(numbers_i, target_i))
|
text = input()
print(text.strip("*_~`"))
# if text.startswith("**") and text.endswith("**"):
# print(text[2:-2:])
# elif text.startswith("*") and text.endswith("*"):
# print(text[1:-1:])
# elif text.startswith("~~") and text.endswith("~~"):
# print(text[2:-2:])
# elif text.startswith("`") and text.endswith("`"):
# print(text[1:-1:]) |
from .htmlbuilder import HtmlBuilder
class TableGen(HtmlBuilder):
""" This Module allows to create tables
"""
def __init__(self, ClassName):
""" Loads constructor of superclass and constructs HtmlCode
with a table skeleton
"""
super().__init__(ClassName)
# Construct the skeleton of a table
self.HtmlCode = ("<table>\n\t<tr>\n"+
"\t\t<!-- Header -->\n"+
"\t</tr>\n\t<tr>\n"+
"\t\t<!-- Row_0 -->\n"+
"\t</tr>\n </table>\n")
# debug print(self.HtmlCode)
def add_html(self,prop, name,row=0):
""" Overweites superclass method
Creates main functionallity to modify a table... When done
put stuff in superclass together
returns string on error
"""
code = ""
tag = ""
# Table Header
if prop == "header":
# Configurate the tag
tag = "<th>"
# If more than 1 header is given, iterate over each and put the
# code together
if(len(name) > 1):
#headerS = ""
for i in name:
code = code + "\t\t<th>"+i+"</th>\n"
else:
code = "\t\t<th>"+name[0]+"</th>\n"
pos = self.find_html_index("\t\t<!-- Header -->\n")
elif prop == "row":
try:
# Fi
pos = self.find_html_index("\t\t<!-- Row_{} -->\n".format(row))
if(pos != False):
code = "\t\t<tr>"+name+"</tr>\n"
else:
# Todo Create a New row!
pass
#super().add(pos, "<tr>", "\t\t<tr>"+name+"</tr>\n")
#self.HtmlCode = self.HtmlCode[:pos]+ "\t\t<tr>"+name+"</tr>\n"
#+ self.HtmlCode[pos:]
except IndexError:
return "Row not found"
result = super().add_html(pos, code, tag)
return "Done." |
#!/usr/bin/python
'''
Writes plots for mach. learning presentation
'''
def gauss(x, sigma, x0, A):
import numpy as np
return A * np.exp(-(x - x0)**2 / (2.0 * sigma**2))
def gauss_1st_deriv(x, sigma, x0, A):
''' Returns the first derivative of a Gaussian. See gauss_4thderiv.nb
mathematica code.
'''
import numpy as np
expo = np.exp(-(x - x0)**2 / (2 * sigma**2))
result = - A * expo * (x - x0) / sigma**2
return result
def gauss_2nd_deriv(x, sigma, x0, A):
''' Returns the fourth derivative of a Gaussian. See gauss_4thderiv.nb
mathematica code.
'''
import numpy as np
expo = np.exp(-(x - x0)**2 / (2.0 * sigma**2))
result = A * expo * (x - x0)**2.0 / sigma**4.0 - \
A * expo * (x - x0)**0.0 / sigma**2.0
return result
def gauss_3rd_deriv(x, sigma, x0, A):
''' Returns the fourth derivative of a Gaussian. See gauss_4thderiv.nb
mathematica code.
'''
import numpy as np
expo = np.exp(-(x - x0)**2 / (2.0 * sigma**2))
result = -A * expo * (x - x0)**3.0 / sigma**6.0 + \
3.0 * A * expo * (x - x0)**1.0 / sigma**4.0
return result
def gauss_4th_deriv(x, sigma, x0, A):
''' Returns the fourth derivative of a Gaussian. See gauss_4thderiv.nb
mathematica code.
'''
import numpy as np
expo = np.exp(-(x - x0)**2 / (2.0 * sigma**2))
result = A * expo * (x - x0)**4.0 / sigma**8.0 - \
6.0 * A * expo * (x - x0)**2.0 / sigma**6.0 + \
3.0 * A * expo / sigma**4.0
return result
def gauss(x, sigma, x0, A):
import numpy as np
return A * np.exp(-(x - x0)**2 / (2.0 * sigma**2))
def plot_temps():
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100, 0.1)
gauss1 = gauss(x, 5, 50, 1)
gauss2 = gauss(x, 10, 50, 1)
gauss3 = gauss(x, 15, 50, 1)
gauss1 /= np.sum(gauss1)
gauss2 /= np.sum(gauss2)
gauss3 /= np.sum(gauss3)
scale = np.max(np.array((gauss1, gauss2, gauss3)))
gauss1 /= scale
gauss2 /= scale
gauss3 /= scale
# Set up plot aesthetics
plt.clf()
plt.close()
plt.rcdefaults()
colormap = plt.cm.gist_ncar
font_scale = 20
params = {#'backend': .pdf',
'axes.labelsize': font_scale,
'axes.titlesize': font_scale,
'text.fontsize': font_scale,
'legend.fontsize': font_scale * 4.0 / 4.0,
'xtick.labelsize': font_scale,
'ytick.labelsize': font_scale,
'font.weight': 500,
'axes.labelweight': 500,
'text.usetex': False,
#'figure.figsize': (8, 8 * y_scaling),
#'axes.color_cycle': color_cycle # colors of different plots
}
plt.rcParams.update(params)
fig, ax = plt.subplots(1, 1, figsize=(7, 7))
ax.plot(x, gauss1, label='Cold', linewidth=3)
ax.plot(x, gauss2, label='Warm', linewidth=3)
ax.plot(x, gauss3, label='Hot', linewidth=3)
ax.set_xlabel('Velocity (km/s)')
ax.set_ylabel('Intensity')
ax.legend()
plt.savefig('gauss_temps.png')
def plot_gauss():
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100, 0.1)
gauss1 = gauss(x, 15, 50, 1)
gauss1 /= np.sum(gauss1)
scale = np.max(np.array((gauss1,)))
gauss1 /= scale
# Set up plot aesthetics
plt.clf()
plt.close()
plt.rcdefaults()
colormap = plt.cm.gist_ncar
font_scale = 20
params = {#'backend': .pdf',
'axes.labelsize': font_scale,
'axes.titlesize': font_scale,
'text.fontsize': font_scale,
'legend.fontsize': font_scale * 4.0 / 4.0,
'xtick.labelsize': font_scale,
'ytick.labelsize': font_scale,
'font.weight': 500,
'axes.labelweight': 500,
'text.usetex': False,
#'figure.figsize': (8, 8 * y_scaling),
#'axes.color_cycle': color_cycle # colors of different plots
}
plt.rcParams.update(params)
fig, ax = plt.subplots(1, 1, figsize=(7, 7))
ax.plot(x, gauss1, linewidth=3)
ax.set_xlabel('Velocity (km/s)')
ax.set_ylabel('Intensity')
plt.savefig('gauss.png')
def plot_data():
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-100, 100, 0.1)
gauss1 = gauss(x, 1, 20, 10)
gauss2 = gauss(x, 10, 5, 15)
gauss3 = gauss(x, 15, 50, 4)
gauss4 = gauss(x, 7, 60, 30)
gauss5 = gauss(x, 50, 35, 4)
noise = np.random.normal(0, 0.5, len(x))
gauss_list = [gauss1, gauss2, gauss3, gauss4, gauss5, ]
gauss_tot = np.zeros(len(x))
for comp in gauss_list:
gauss_tot += comp
gauss_tot += noise
scale = np.max(gauss_tot)
gauss_tot /= scale
for i, comp in enumerate(gauss_list):
gauss_list[i] = comp / scale
# Set up plot aesthetics
plt.clf()
plt.close()
plt.rcdefaults()
colormap = plt.cm.gist_ncar
font_scale = 15
params = {#'backend': .pdf',
'axes.labelsize': font_scale,
'axes.titlesize': font_scale,
'text.fontsize': font_scale,
'legend.fontsize': font_scale * 4.0 / 4.0,
'xtick.labelsize': font_scale,
'ytick.labelsize': font_scale,
'font.weight': 500,
'axes.labelweight': 500,
'text.usetex': False,
#'figure.figsize': (8, 8 * y_scaling),
#'axes.color_cycle': color_cycle # colors of different plots
}
plt.rcParams.update(params)
fig, ax = plt.subplots(1, 1, figsize=(7, 7))
ax.plot(x, gauss_tot, linewidth=1, color='k')
ax.set_xlabel('Velocity (km/s)')
ax.set_ylabel('Intensity')
fig.savefig('data.png')
fig, ax = plt.subplots(1, 1, figsize=(7, 7))
ax.plot(x, gauss_tot, linewidth=1, color='k')
ax.set_xlabel('Velocity (km/s)')
ax.set_ylabel('Intensity')
for comp in gauss_list:
ax.plot(x, comp, linewidth=1,)
fig.savefig('data_comps.png')
def plot_derivs():
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100, 0.1)
params = (x, 15, 50, 1)
gauss1 = gauss(*params)
gauss1d = gauss_1st_deriv(*params)
gauss2d = gauss_2nd_deriv(*params)
gauss3d = gauss_3rd_deriv(*params)
gauss4d = gauss_4th_deriv(*params)
deriv_list = [gauss1d, gauss2d, gauss3d, gauss4d,]
for i, comp in enumerate(deriv_list):
deriv_list[i] = comp / np.max(comp)
# Set up plot aesthetics
plt.clf()
plt.close()
plt.rcdefaults()
colormap = plt.cm.gist_ncar
font_scale = 15
params = {#'backend': .pdf',
'axes.labelsize': font_scale,
'axes.titlesize': font_scale,
'text.fontsize': font_scale,
'legend.fontsize': font_scale * 4.0 / 4.0,
'xtick.labelsize': font_scale,
'ytick.labelsize': font_scale,
'font.weight': 500,
'axes.labelweight': 500,
'text.usetex': False,
#'figure.figsize': (8, 8 * y_scaling),
#'axes.color_cycle': color_cycle # colors of different plots
}
plt.rcParams.update(params)
fig, ax = plt.subplots(1, 1, figsize=(7, 7))
ax.plot(x, gauss1, linewidth=3, color='k')
ax.set_ylim(-2.5, 1.1)
ax.set_xlabel('Velocity (km/s)')
ax.set_ylabel('Intensity')
plt.savefig('gauss_deriv0.png')
for i, deriv in enumerate(deriv_list):
ax.plot(x, deriv, linewidth=1)
plt.savefig('gauss_deriv' + str(i+1) + '.png')
def main():
plot_temps()
plot_gauss()
plot_data()
plot_derivs()
if __name__ == '__main__':
main()
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
def helper(arr, start, end):
if start > end:
return
node = TreeNode(arr[start])
part = start + 1
while part <= end and arr[start] > arr[part]:
part += 1
node.left = helper(arr, start + 1, part - 1)
node.right = helper(arr, part, end)
return node
return helper(preorder, 0, len(preorder) - 1) |
class Solution:
# Time complexity O(N*MlogM) | Space complexity O(1)
def groupAnagrams(self, strs):
anagram = {}
for i, s in enumerate(strs):
sortedString = "".join(sorted(s))
group = anagram.get(sortedString, [])
group.append(s)
anagram[sortedString] = group
return list(anagram.values()) |
class Solution:
# Time Complexity - O(2^n) | Space Complexity - O(n)
def recursion(self, n):
self.cache = {}
return self.recursionHelper(0, n)
def recursionHelper(self, i ,n):
if i > n:
return 0
if i == n:
return 1
if i in self.cache:
return self.cache[i]
ways = self.recursionHelper(i+1, n) + self.recursionHelper(i+2, n)
self.cache[i] = ways
return self.cache[i]
# Time Complexity - O(n) | Space Complexity - O(n)
def ways_dp(self, n):
if n < 2:
return 1
dp = [1] * (n+1)
for i in range(2, n+1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
# Time Complexity - O(n) | Space Complexity - O(1)
def ways_dp_optimized(self, n):
if n < 2:
return 1
first = 1
second = 1
for i in range(2, n+1):
ways = first + second
first = second
second = ways
return second |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
# ================================
# ================================
# ================================
def confusion_matrix(gt, pred) -> np.ndarray:
"""
Returns confusion matrix of classification on a set of objects, specifically
a matrix where element [i, j] is how many objects of class j got label i.
NOTE: number of classes is inferred from ground truth labels
Parameters:
----------------
gt : 1D np.ndarray[int]
Ground truth, array containing true labels of objects being classified
pred : 1D np. ndarray of int
Model predictions of objects being classified
Returns:
----------------
cm : 2D np.ndarray[int]
Confusion matrix, element [i, j] equals to number of objects of true class j
and predicted class i.
"""
# Number of classes inferred from gt. Assuming classes are enumerated 0 ..
n_classes = gt.max() + 1
cm = np.zeros((n_classes, n_classes), dtype=np.uint32)
# Fill matrix
for gt_class in range(n_classes):
for pred_class in range(n_classes):
cm[pred_class, gt_class] = ((pred == pred_class) & (gt == gt_class)).sum()
return cm
def accuracy(gt, pred):
"""
Calculated accuracy score of classification
"""
return np.mean(gt == pred)
def clf_scores(cm) -> float:
"""
Returns overall and per-class classification scores based on confusion matrix
Scores returned are:
- accuracy
- precision
- recall
- F1
Accuracy is calculated overall, other metrics - per each class
Parameters:
----------------
cm : square np.ndarray[int]
Confusion matrix, element [i, j] equals to number of objects of true class j
and predicted class i.
Returns:
----------------
scores : dict of {str: (float, np.array[float])}
Dict with overall and per-class scores.
"""
# Number of correct elements of given class - diagonal
acc = cm.trace()/np.sum(cm)
# Total number of elements with true class j - sum of column j
# Total number of elements with predicted class i - sum of row i
precision_class = cm.diagonal()/cm.sum(axis=1)
recall_class = cm.diagonal()/cm.sum(axis=0)
f1_class = 2*precision_class*recall_class/(precision_class + recall_class)
return {
'accuracy': acc,
'precision': precision_class,
'recall': recall_class,
'F1': f1_class
} |
"""
print('Hello world')
a = 1
b = 'this is a string'
c = [1, 2, 3, 4]
d = (5, 6, 7, 8)
e = {'name': 'Perry', 'number': 1}
print(a)
print(b)
print(c)
print(d)
print(len(c))
c.append(42)
print(c)
c.append('will this work?')
print(c)
print(e)
print(e['name'])
e['number'] += 9000
print(e['number'])
for n in c:
for m in d:
print(n * m)
"""
def count_to_one_hundred():
for x in range(1, 101):
print(x)
def stub_function():
pass
def multiply_two_numbers(x, y):
return x * y
def main():
print ('Hello world!')
# count_to_one_hundred()
print(multiply_two_numbers(6, 8))
if __name__ == "__main__":
main() |
# a=int(input("Enter the age :"))
# if a>=18:
# print("Eligible to vote")
# else:
# print("Not eligible to vote")
#
# # Find the odd or even
# a=int(input('enter the number'))
# if a%2==0:
# print('the given number is even')
# else:
# print('the number is odd')
# print even numbers from 1 to 100
# for x in range(2,100+1,2):
# print(x,end=' ')
# for a in range(1,100):
# if a==5:
# exit(0)
# print(a)
# print("end")
# for x in range(10,0-2,-1):
# print(x)
#
# for x in range(1,4):
# for y in range(1,4):
# print(y)
# print(x)
# a=100
# while True:
# print(a)
# a=a+1
# if a>15:
# break
|
# # Q1 Create a new list with values and find the length of it
# l = [10,20,30,90,10,10,40,50]
# print(l)
# print(type(l))
# print(len(l))
# #
# # # Q2 Create a new list with values and find the length of it
# l=[105,205,305,405,505,605,705,805]
# print(len(l))
# #
# # # Q3 Create a new list with values and find the length of it
# l=['Java','Python','Selenium','java',10,20,10]
# print(len(l))
#
# # Q4.1 Get the index value of 10
# l=[10,20,30,90,10,50]
# print(l[0])
# print(l[4])
# print(l[5])
#
# #Q4.7 Add a value [100,200,300] at the last position of list and find index value of 200
# l=[10,20,30,90,10,10,40,50]
# l.append([100,200,300])
# print(l)
#
# # Q4.8 Add a value [100,200,300] at the last position of list and find index value of 200
# l=[10,20,30,90,10,10,40,50,100,200,300]
# l.append([100,200,300])
# print(l)
# Q5.1 Get the value present at 2nd index
# l=[10,20,30,40,50,60]
# print(l[2])
# l=[100,200,300,400,500,600,700]
# print(l[4])
# l=[105,205,305,405,505,605,705,805]
# print(l[-2])
# l=[105,205,305,405,505,605,705,805]
# print(l[-10]) ----------IndexError
# Q6 Remove the value present at 2nd index and print the removed value
# a=[10,20,30,40,50,60]
# a.remove(20)
# print(a)
#
# l=[10,20,30,90,10,10,40]
# l.remove(40)
# print(l)
#
# l=[10,20,30,90,10,10,40]
# l.remove(10)
# print(l)
#
# l=[10,20,30,90,10,10,40]
# l.remove(40)
# print(l)
#
# l=[10,20,30,90,10,10,40,60,80,100]
# l.remove(80)
# print(l)
#
# l=[10,20,30,90,10,10,40,60,80,100]
# l.remove(50)
# print(l)
# Q6.8 delete the value present in (-5th to -1st) index in the list
# l=[10,20,30,90,10,10,40,60,80,100]
# del l[-5:-1]
# print(l)
#
# # Q6.9 delete the value present in (2nd to last) index in the list
# l=[10,20,30,90,10,10,40,60,80,100]
# del l[2:9]
# print(l)
#
# # Q6.9 clear all the value present in the list
# l=[10,20,30,90,10,10,40,60,80,100]
# l.clear()
# print(l)
#
# # Q7 Replace the value 300 into 350 in the list
# l=[100,200,300,400,500,600,700]
# l[2]=350
# print(l)
#
# # Q7.1 Replace the value present in 7th index as 90
# l=[10,20,30,90,10,10,40,50,10]
# l[7]=90
# print(l)
#
# # Q7.2 Replace the 10 into 100 in List
# l=[10,20,30,90,10,10,40,50,30]
# l[0]=100
# print(l)
# Q8 Add a value 50 in the 2nd index and display the list after adding.
# l=[10,20,30,90,10,10,40,50]
# l.insert(2,50)
# print(l)
#
# # Q8.1 Add a value 70 at the end of the list
# l=[10,20,30,90,10,10,40,50]
# l.append([70])
# print(l)
# # Q8.2 Add a value 80 at the 30th index of list
# l=[10,20,30,90,10,10,40,50]
# # l[30]=80 ---------- IndexError
#
# #Q8.3 Add a value 100 at the last index of 10 in the list
# l=[10,20,30,90,10,10,40,50]
# l.insert(10,100)
# print(l)
#
# #Q8.4 Add a value 100,200,300 at the last position of list
# l=[10,20,30,90,10,10,40,50]
# l.append([100,200,300])
# print(l)
#
# #Q10 Add a value [100,200,300] at the last position of list
# l=[10,20,30,90,10,10,40,50]
# l.append([100,200,300])
# l.append(20)
# print(l)
# print(l[9])
# Q10 count the 10 value present in the list
# l=[10,20,30,90,10,10,40,50]
# print(l.count(10))
# l=[10,20,30,90,10,10,40,50]
# print(max(l))
# print(min(l))
# l=['java','python','selenium','Java','Python','Selenium']
# print(max(l))
# print(min(l))
#
# # Q11 Reverse the values present in list
# l=[10,20,30,50,90,40,100,60,10,70]
# l.sort(reverse=True)
# print(l)
#
# #Q11.2 Sort the values (Ascending &Descending ) order present in list
# l=[10,20,30,50,90,40,100,60,10,70]
# l.sort()
# print(l)
# l.sort(reverse=True)
# print(l)
#
# #Q12 Copy the values in list
# l=[10,20,30,90,10,10,40,50]
# c=l.copy()
# print(l)
#
# # Q12.1 Create a lists with values and compare the two list
# l=[10,20,30,90,10,10,40,50]
# l1=[30,40,50,60,80]
# print(l==l1)
#q13 Get the each value of list by using Enumarate for loop
# l=[105,205,305,405,505,605,705,805]
# for i in enumerate(l):
# print(i)
#
# l=[105,205,305,405,505,605,705,805]
# for i in range(0,len(l)):
# print(l[i])
# Get the each value of list by using Enumarate for loop and print only odd index value
# l=[105,205,305,405,505,605,705,805]
# for i in enumerate(1,7,2):
# print(l[i])
# for i in enumerate(l):
# print(i)
|
import time
import random
def swap(arr, a, b):
temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
#O(N^2)
def bubbleSort(arr):
for i in range(len(arr)):
for j in range(len(arr)):
if arr[i] <= arr[j]:
swap(arr, i, j)
return arr
#O(N^2)
def selectionSort(arr):
for i in range(len(arr)):
min = i
for j in range(i, len(arr)):
if arr[min] > arr[j]:
min = j
swap(arr, i, min)
return arr
#O(N^2)
def insertionSort(arr):
sorted = []
for i in range(len(arr)):
if i is 0:
sorted.append(arr[i])
elif(sorted[i-1] <= arr[i]):
sorted.append(arr[i])
else:
for j in range(len(sorted)):
if sorted[j] > arr[i]:
sorted.insert(j, arr[i])
break
return sorted
#Helper function for MergeSort
def merge(n1, n2):
a = 0
b = 0
arr = []
for i in range(len(n1) + len(n2)):
if(b >= len(n2) or (a < len(n1) and n1[a] < n2[b])):
arr.append(n1[a])
a += 1
else:
arr.append(n2[b])
b +=1
return arr
#O(N log(N))
def mergeSort(arr):
if len(arr) is 1:
return arr
middle = len(arr)//2
left = arr[:middle]
right = arr[middle:]
result = merge(mergeSort(left), mergeSort(right))
return result
def test1():
array = [5,4,3,2,1,2,3,4,5, 8, 9, 6, 1, 10]
print(mergeSort(array))
print(bubbleSort(array))
print(selectionSort(array))
print(insertionSort(array))
def test2():
array = []
elements = 20
for i in range(elements):
array.append(int(random.random() * 1000000))
print("array: ", array)
print(mergeSort(array))
print(bubbleSort(array))
print(selectionSort(array))
print(insertionSort(array))
array.sort()
print(array)
def timeTrial():
array = []
elements = 10000
for i in range(elements):
array.append(random.random() * 1000000)
#Bubble Sort
t1 = time.time()
bubbleSort(array)
t2 = time.time()
print("this is how much time it takes to do bubbleSort: ", (t2-t1))
#Selection Sort
t1 = time.time()
selectionSort(array)
t2 = time.time()
print("this is how much time it takes to do selectionSort: ", (t2-t1))
#Insertion Sort
t1 = time.time()
insertionSort(array)
t2 = time.time()
print("this is how much time it takes to do insertionSort: ", (t2-t1))
#Merge Sort
t1 = time.time()
mergeSort(array)
t2 = time.time()
print("this is how much time it takes to do mergeSort: ", (t2-t1))
#Merge Sort
t1 = time.time()
array.sort()
t2 = time.time()
print("this is how much time it takes to do provided sort: ", (t2-t1))
test1()
test2()
timeTrial() |
# Given two equal-size strings s and t. In one step you can choose any character of t and replace it with another character.
#
# Return the minimum number of steps to make t an anagram of s.
#
# An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.
#
#
# Example 1:
#
#
# Input: s = "bab", t = "aba"
# Output: 1
# Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s.
#
#
# Example 2:
#
#
# Input: s = "leetcode", t = "practice"
# Output: 5
# Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.
#
#
# Example 3:
#
#
# Input: s = "anagram", t = "mangaar"
# Output: 0
# Explanation: "anagram" and "mangaar" are anagrams.
#
#
# Example 4:
#
#
# Input: s = "xxyyzz", t = "xxyyzz"
# Output: 0
#
#
# Example 5:
#
#
# Input: s = "friend", t = "family"
# Output: 4
#
#
#
# Constraints:
#
#
# 1 <= s.length <= 50000
# s.length == t.length
# s and t contain lower-case English letters only.
#
#
class Solution:
def minSteps(self, s: str, t: str) -> int:
if not s and not t:
return 0
if not s or not t or len(s) != len(t):
return None
from collections import Counter
count_s = Counter(s)
count_t = Counter(t)
res = 0
for key in count_s:
res += max(0, count_s[key] - count_t[key])
return res
|
# -*- coding:utf-8 -*-
# Given a string, your task is to count how many palindromic substrings in this string.
#
# The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
#
# Example 1:
#
#
# Input: "abc"
# Output: 3
# Explanation: Three palindromic strings: "a", "b", "c".
#
#
#
#
# Example 2:
#
#
# Input: "aaa"
# Output: 6
# Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
#
#
#
#
# Note:
#
#
# The input string length won't exceed 1000.
#
#
#
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
cnt=0
for i in range(len(s)):
j =i
#check with s[i] as middle
l=j
r=j
while l >=0 and r <= len(s)-1 and s[l] == s[r]:
cnt+=1
l-=1
r+=1
#check with s[i] s[i+1] as middle
l=j
r=j+1
while l >=0 and r <= len(s)-1 and s[l] == s[r]:
cnt+=1
l-=1
r+=1
return cnt
|
# You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters.
#
# You can return the answer in any order.
#
#
# Example 1:
#
#
# Input: s = "barfoothefoobarman", words = ["foo","bar"]
# Output: [0,9]
# Explanation: Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively.
# The output order does not matter, returning [9,0] is fine too.
#
#
# Example 2:
#
#
# Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
# Output: []
#
#
# Example 3:
#
#
# Input: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
# Output: [6,9,12]
#
#
#
# Constraints:
#
#
# 1 <= s.length <= 104
# s consists of lower-case English letters.
# 1 <= words.length <= 5000
# 1 <= words[i].length <= 30
# words[i] consists of lower-case English letters.
#
#
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
if not s or not words:
return []
import collections
word_length = len(words[0])
s_length = len(s)
word_count = len(words)
index = 0
word2index = {}
index_count = {}
s2index = [-1 for _ in s]
for w in words:
if w not in word2index:
word2index[w] = index
index += 1
index_count[word2index[w]] = index_count.get(word2index[w], 0) + 1
for i in range(s_length):
w = s[i:i+word_length]
if i+word_length <= s_length and s[i:i+word_length] in word2index:
s2index[i] = word2index[w]
else:
s2index[i] = -1
res = []
for i in range(s_length - word_count * word_length + 1):
if collections.Counter([s2index[i + j * word_length] for j in range(word_count)]) == index_count:
res.append(i)
return res
|
# There are a total of n courses you have to take labelled from 0 to n - 1.
#
# Some courses may have prerequisites, for example, if prerequisites[i] = [ai, bi] this means you must take the course bi before the course ai.
#
# Given the total number of courses numCourses and a list of the prerequisite pairs, return the ordering of courses you should take to finish all courses.
#
# If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.
#
#
# Example 1:
#
#
# Input: numCourses = 2, prerequisites = [[1,0]]
# Output: [0,1]
# Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1].
#
#
# Example 2:
#
#
# Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
# Output: [0,2,1,3]
# Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
# So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].
#
#
# Example 3:
#
#
# Input: numCourses = 1, prerequisites = []
# Output: [0]
#
#
#
# Constraints:
#
#
# 1 <= numCourses <= 2000
# 0 <= prerequisites.length <= numCourses * (numCourses - 1)
# prerequisites[i].length == 2
# 0 <= ai, bi < numCourses
# ai != bi
# All the pairs [ai, bi] are distinct.
#
#
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
repre = [set() for _ in range(numCourses)]
pre = [set() for _ in range(numCourses)]
for item in prerequisites:
pre[item[0]].add(item[1])
repre[item[1]].add(item[0])
queue = [i for i in range(numCourses) if len(pre[i]) == 0]
res = []
while queue:
node = queue.pop()
res.append(node)
for next_level in repre[node]:
pre[next_level].remove(node)
if len(pre[next_level]) == 0:
queue.append(next_level)
if len(res) == numCourses:
return res
else:
return []
|
# You are given an integer array nums sorted in ascending order (with distinct values), and an integer target.
#
# Suppose that nums is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
#
# If target is found in the array return its index, otherwise, return -1.
#
#
# Example 1:
# Input: nums = [4,5,6,7,0,1,2], target = 0
# Output: 4
# Example 2:
# Input: nums = [4,5,6,7,0,1,2], target = 3
# Output: -1
# Example 3:
# Input: nums = [1], target = 0
# Output: -1
#
#
# Constraints:
#
#
# 1 <= nums.length <= 5000
# -104 <= nums[i] <= 104
# All values of nums are unique.
# nums is guaranteed to be rotated at some pivot.
# -104 <= target <= 104
#
#
class Solution:
# def search(self, nums: List[int], target: int) -> int:
# if len(nums) == 0:
# return -1
# pivot_index = max(0, self.binarySearch(nums, target, True))
# if pivot_index == 0:
# pivot_index = len(nums)
# if target >= nums[0]:
# return self.binarySearch(nums[:pivot_index], target, False)
# else:
# res = self.binarySearch(nums[pivot_index:], target, False)
# if res == -1:
# return res
# else:
# return pivot_index + res
# def binarySearch(self, nums, target, findpivot):
# l, r = 0, len(nums) - 1
# if findpivot:
# while l <= r:
# mid = int((l + r) / 2)
# if mid == len(nums) - 1:
# return 0
# elif nums[mid] >= nums[mid+1]:
# return mid + 1
# elif nums[mid] >= nums[0]:
# l = mid + 1
# elif nums[mid] < nums[0]:
# r = mid - 1
# else:
# if len(nums) == 0:
# return -1
# while l < r:
# mid = int((l + r) / 2)
# if nums[mid] == target:
# return mid
# elif nums[mid] > target:
# r = mid
# elif nums[mid] < target:
# l = mid + 1
# if nums[r] == target:
# return r
# else:
# return -1
def search(self, nums, target):
if not nums:
return -1
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if target == nums[mid]:
return mid
if nums[low] <= nums[mid]:
if nums[low] <= target <= nums[mid]:
high = mid - 1
else:
low = mid + 1
else:
if nums[mid] <= target <= nums[high]:
low = mid + 1
else:
high = mid - 1
return -1
|
# You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order.
#
# Return the intersection of these two interval lists.
#
# A closed interval [a, b] (with a < b) denotes the set of real numbers x with a <= x <= b.
#
# The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].
#
#
# Example 1:
#
#
# Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]
# Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
#
#
# Example 2:
#
#
# Input: firstList = [[1,3],[5,9]], secondList = []
# Output: []
#
#
# Example 3:
#
#
# Input: firstList = [], secondList = [[4,8],[10,12]]
# Output: []
#
#
# Example 4:
#
#
# Input: firstList = [[1,7]], secondList = [[3,10]]
# Output: [[3,7]]
#
#
#
# Constraints:
#
#
# 0 <= firstList.length, secondList.length <= 1000
# firstList.length + secondList.length >= 1
# 0 <= starti < endi <= 109
# endi < starti+1
# 0 <= startj < endj <= 109
# endj < startj+1
#
#
class Solution:
def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
if not A or not B:
return []
i, j = 0, 0
res = []
while i < len(A) and j < len(B):
i, j = self.helper(A, B, i, j, res)
return res
def helper(self, A, B, i, j, res):
a, b = A[i], B[j]
if a[0] > b[1]:
j += 1
elif a[1] < b[0]:
i += 1
else:
start, end = max(a[0], b[0]), min(a[1], b[1])
if end >= start:
res.append([start, end])
if a[1] >= b[1]:
j += 1
else:
i += 1
return i, j
|
# -*- coding:utf-8 -*-
# You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.
#
# Return the number of servers that communicate with any other server.
#
#
# Example 1:
#
#
#
#
# Input: grid = [[1,0],[0,1]]
# Output: 0
# Explanation: No servers can communicate with others.
#
# Example 2:
#
#
#
#
# Input: grid = [[1,0],[1,1]]
# Output: 3
# Explanation: All three servers can communicate with at least one other server.
#
#
# Example 3:
#
#
#
#
# Input: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]
# Output: 4
# Explanation: The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.
#
#
#
# Constraints:
#
#
# m == grid.length
# n == grid[i].length
# 1 <= m <= 250
# 1 <= n <= 250
# grid[i][j] == 0 or 1
#
#
class Solution(object):
def countServers(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
count_r = {}
count_c = {}
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
count_r[i] = count_r.get(i, 0) + 1
count_c[j] = count_c.get(j, 0) + 1
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
if count_r[i] == 1 and count_c[j] == 1:
pass
else:
count += 1
return count
|
# Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.
#
# Return the quotient after dividing dividend by divisor.
#
# The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.
#
# Note:
#
#
# Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, assume that your function returns 231 − 1 when the division result overflows.
#
#
#
# Example 1:
#
#
# Input: dividend = 10, divisor = 3
# Output: 3
# Explanation: 10/3 = truncate(3.33333..) = 3.
#
#
# Example 2:
#
#
# Input: dividend = 7, divisor = -3
# Output: -2
# Explanation: 7/-3 = truncate(-2.33333..) = -2.
#
#
# Example 3:
#
#
# Input: dividend = 0, divisor = 1
# Output: 0
#
#
# Example 4:
#
#
# Input: dividend = 1, divisor = 1
# Output: 1
#
#
#
# Constraints:
#
#
# -231 <= dividend, divisor <= 231 - 1
# divisor != 0
#
#
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
if divisor == 0:
return None
res = int(dividend / divisor)
if res > 2 ** 31 -1 or res < - 2 ** 31:
return 2 ** 31 -1
else:
return res
|
# Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
#
#
# Example 1:
#
#
# Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
# Output: 6
# Explanation: [4,-1,2,1] has the largest sum = 6.
#
#
# Example 2:
#
#
# Input: nums = [1]
# Output: 1
#
#
# Example 3:
#
#
# Input: nums = [0]
# Output: 0
#
#
# Example 4:
#
#
# Input: nums = [-1]
# Output: -1
#
#
# Example 5:
#
#
# Input: nums = [-100000]
# Output: -100000
#
#
#
# Constraints:
#
#
# 1 <= nums.length <= 3 * 104
# -105 <= nums[i] <= 105
#
#
#
# Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums is None or len(nums) == 0:
return None
global_sum = local_sum = nums[0]
for i in range(1, len(nums)):
local_sum = max(local_sum + nums[i], nums[i])
global_sum = max(global_sum, local_sum)
return global_sum
|
# For some fixed N, an array A is beautiful if it is a permutation of the integers 1, 2, ..., N, such that:
#
# For every i < j, there is no k with i < k < j such that A[k] * 2 = A[i] + A[j].
#
# Given N, return any beautiful array A. (It is guaranteed that one exists.)
#
#
#
# Example 1:
#
#
# Input: 4
# Output: [2,1,4,3]
#
#
#
# Example 2:
#
#
# Input: 5
# Output: [3,1,2,5,4]
#
#
#
#
# Note:
#
#
# 1 <= N <= 1000
#
#
#
#
#
class Solution:
def beautifulArray(self, N):
"""
:type N: int
:rtype: List[int]
"""
if N==1:
return [1]
else:
l=self.beautifulArray(N//2)
r=self.beautifulArray(N-N//2)
return [x*2 for x in l]+[x*2-1 for x in r]
|
# A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
#
# The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
#
# How many possible unique paths are there?
#
#
# Example 1:
#
#
# Input: m = 3, n = 7
# Output: 28
#
#
# Example 2:
#
#
# Input: m = 3, n = 2
# Output: 3
# Explanation:
# From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
# 1. Right -> Down -> Down
# 2. Down -> Down -> Right
# 3. Down -> Right -> Down
#
#
# Example 3:
#
#
# Input: m = 7, n = 3
# Output: 28
#
#
# Example 4:
#
#
# Input: m = 3, n = 3
# Output: 6
#
#
#
# Constraints:
#
#
# 1 <= m, n <= 100
# It's guaranteed that the answer will be less than or equal to 2 * 109.
#
#
class Solution:
# def uniquePaths(self, m: int, n: int) -> int:
# self.count = 0
# self.searchPath(m, n, 0, 0)
# return self.count
# def searchPath(self, m, n, r, c):
# if r == m - 1 and c == n - 1:
# self.count += 1
# dx = [0, 1]
# dy = [1, 0]
# for i in range(2):
# x = r + dx[i]
# y = c + dy[i]
# if 0 <= x <= m - 1 and 0 <= y <= n - 1:
# self.searchPath(m, n, x, y)
# return
def uniquePaths(self, m: int, n: int) -> int:
res = [[0] * m for i in range(n)]
for i in range(m):
res[0][i] = 1
for i in range(n):
res[i][0] = 1
for i in range(1, n):
for j in range(1, m):
res[i][j] = res[i-1][j] + res[i][j-1]
return res[n-1][m-1]
|
# -*- coding:utf-8 -*-
# Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.
#
# Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.
#
# You may return any answer array that satisfies this condition.
#
#
#
# Example 1:
#
#
# Input: [4,2,5,7]
# Output: [4,5,2,7]
# Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
#
#
#
#
# Note:
#
#
# 2 <= A.length <= 20000
# A.length % 2 == 0
# 0 <= A[i] <= 1000
#
#
#
#
#
class Solution(object):
def sortArrayByParityII(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
l = len(A) # l is even
if l == 0:
return A
i, j = 0, l - 1
while i <= l - 1 and j >= 0:
if A[i] % 2 == 0:
i += 2
continue
if A[j] % 2 == 1:
j -= 2
continue
if A[i] % 2 == 1 and A[j] % 2 == 0:
A[i], A[j] = A[j], A[i]
return A
|
# Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
#
# Find all the elements of [1, n] inclusive that do not appear in this array.
#
# Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
#
# Example:
#
# Input:
# [4,3,2,7,8,2,3,1]
#
# Output:
# [5,6]
#
#
#
# @lc app=leetcode id=448 lang=python3
#
# [448] Find All Numbers Disappeared in an Array
#
# https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/
#
# algorithms
# Easy (54.07%)
# Total Accepted: 172.6K
# Total Submissions: 319.2K
# Testcase Example: '[4,3,2,7,8,2,3,1]'
#
# Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some
# elements appear twice and others appear once.
#
# Find all the elements of [1, n] inclusive that do not appear in this array.
#
# Could you do it without extra space and in O(n) runtime? You may assume the
# returned list does not count as extra space.
#
# Example:
#
# Input:
# [4,3,2,7,8,2,3,1]
#
# Output:
# [5,6]
#
#
#
class Solution:
def findDisappearedNumbers(self, nums):
return list(set([ i+1 for i in range(len(nums))]) - set(nums))
|
# Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
#
# Note:
#
# The length of both num1 and num2 is < 5100.
# Both num1 and num2 contains only digits 0-9.
# Both num1 and num2 does not contain any leading zero.
# You must not use any built-in BigInteger library or convert the inputs to integer directly.
#
#
#
# @lc app=leetcode id=415 lang=python3
#
# [415] Add Strings
#
# https://leetcode.com/problems/add-strings/description/
#
# algorithms
# Easy (44.37%)
# Total Accepted: 109.9K
# Total Submissions: 247.7K
# Testcase Example: '"0"\n"0"'
#
# Given two non-negative integers num1 and num2 represented as string, return
# the sum of num1 and num2.
#
# Note:
#
# The length of both num1 and num2 is < 5100.
# Both num1 and num2 contains only digits 0-9.
# Both num1 and num2 does not contain any leading zero.
# You must not use any built-in BigInteger library or convert the inputs to
# integer directly.
#
#
#
class Solution:
def addStrings(self, num1, num2):
res = []
if len(num1) < len(num2):
num1 = '0' * ( len(num2) - len(num1) ) + num1
else:
num2 = '0' * ( len(num1) - len(num2) ) + num2
i, j = len(num1) - 1, len(num2) - 1
tmp = 0
while i >= 0 and j >= 0:
s = int(num1[i]) + int(num2[j]) + tmp
if s >= 10:
s -= 10
tmp = 1
else:
tmp = 0
res.append(str(s))
i -= 1
j -= 1
if tmp == 1:
res.append('1')
res.reverse()
return ''.join(res)
|
# There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.
#
# A province is a group of directly or indirectly connected cities and no other cities outside of the group.
#
# You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.
#
# Return the total number of provinces.
#
#
# Example 1:
#
#
# Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
# Output: 2
#
#
# Example 2:
#
#
# Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
# Output: 3
#
#
#
# Constraints:
#
#
# 1 <= n <= 200
# n == isConnected.length
# n == isConnected[i].length
# isConnected[i][j] is 1 or 0.
# isConnected[i][i] == 1
# isConnected[i][j] == isConnected[j][i]
#
#
class Solution:
def findCircleNum(self, M: List[List[int]]) -> int:
student = set([i for i in range(len(M))])
count = 0
while len(student) > 0:
start = list(student)[0]
self.dfs(start, M, student)
count += 1
return count
def dfs(self, start, M, student):
for i in range(len(M[0])):
if M[start][i] == 1 and i in student:
student.remove(i)
self.dfs(i, M, student)
|
# Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
#
# Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
#
# The order of output does not matter.
#
# Example 1:
#
# Input:
# s: "cbaebabacd" p: "abc"
#
# Output:
# [0, 6]
#
# Explanation:
# The substring with start index = 0 is "cba", which is an anagram of "abc".
# The substring with start index = 6 is "bac", which is an anagram of "abc".
#
#
#
# Example 2:
#
# Input:
# s: "abab" p: "ab"
#
# Output:
# [0, 1, 2]
#
# Explanation:
# The substring with start index = 0 is "ab", which is an anagram of "ab".
# The substring with start index = 1 is "ba", which is an anagram of "ab".
# The substring with start index = 2 is "ab", which is an anagram of "ab".
#
#
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if not s or not p or len(s) < len(p):
return []
from collections import Counter
len_p = len(p)
counter_p = Counter(p)
counter_s = Counter(s[:len_p])
for i in counter_s:
if i not in counter_p:
counter_p[i] = 0
res = []
for i in range(len_p, len(s)):
if counter_s == counter_p:
res.append(i - len_p)
counter_s[s[i - len_p]] -= 1
counter_s[s[i]] += 1
if s[i] not in counter_p:
counter_p[s[i]] = 0
if counter_s == counter_p:
res.append(len(s) - len_p)
return res
|
# Given an integer array nums, return the length of the longest strictly increasing subsequence.
#
# A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
#
#
# Example 1:
#
#
# Input: nums = [10,9,2,5,3,7,101,18]
# Output: 4
# Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
#
#
# Example 2:
#
#
# Input: nums = [0,1,0,3,2,3]
# Output: 4
#
#
# Example 3:
#
#
# Input: nums = [7,7,7,7,7,7,7]
# Output: 1
#
#
#
# Constraints:
#
#
# 1 <= nums.length <= 2500
# -104 <= nums[i] <= 104
#
#
#
# Follow up:
#
#
# Could you come up with the O(n2) solution?
# Could you improve it to O(n log(n)) time complexity?
#
#
class Solution:
# Brute Force
# def lengthOfLIS(self, nums: List[int]) -> int:
# if not nums:
# return 0
# return self.findLength(nums, min(nums) - 1, 0)
# def findLength(self, nums, prev, index):
# if index == len(nums):
# return 0
# taken = 0
# if nums[index] > prev:
# taken = 1 + self.findLength(nums, nums[index], index+1)
# untaken = self.findLength(nums, prev, index+1)
# return max(taken, untaken)
# # DP
# def lengthOfLIS(self, nums: List[int]) -> int:
# if not nums: return 0
# dp = [1] * len(nums)
# for i in range(len(nums)):
# for j in range(0, i):
# if nums[j] < nums[i] and dp[i] < dp[j] + 1:
# dp[i] = dp[j] + 1
# return max(dp)
# nlgn
def lengthOfLIS(self, nums: List[int]) -> int:
if not nums:
return 0
B = []
B.append(nums[0])
for i in range(1, len(nums)):
B = self.insertB(B, nums[i])
print(B)
return len(B)
def insertB(self, B, nums):
if nums < B[0]:
B[0] = nums
elif nums > B[-1]:
B.append(nums)
else:
i, j = 0, len(B) - 1
while i < j:
mid = int((i+j)/2)
if B[mid] == nums:
return B
elif B[mid] > nums:
j = mid
elif B[mid] < nums:
i = mid + 1
if B[i-1] < nums < B[i]:
B[i] = nums
elif B[i] < nums < B[i+1]:
B[i+1] = nums
return B
|
# Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
#
# Note:
#
#
# Given target value is a floating point.
# You are guaranteed to have only one unique value in the BST that is closest to the target.
#
#
# Example:
#
#
# Input: root = [4,2,5,1,3], target = 3.714286
#
# 4
# / \
# 2 5
# / \
# 1 3
#
# Output: 4
#
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def closestValue(self, root: TreeNode, target: float) -> int:
diff = float('inf')
res = None
cur = root
while cur:
cur_diff = abs(target - cur.val)
if cur_diff <= diff:
diff, res = cur_diff, cur.val
if target >= cur.val:
cur = cur.right
else:
cur = cur.left
return res
|
# Given a positive integer K, you need to find the length of the smallest positive integer N such that N is divisible by K, and N only contains the digit 1.
#
# Return the length of N. If there is no such N, return -1.
#
# Note: N may not fit in a 64-bit signed integer.
#
#
# Example 1:
#
#
# Input: K = 1
# Output: 1
# Explanation: The smallest answer is N = 1, which has length 1.
#
#
# Example 2:
#
#
# Input: K = 2
# Output: -1
# Explanation: There is no such positive integer N divisible by 2.
#
#
# Example 3:
#
#
# Input: K = 3
# Output: 3
# Explanation: The smallest answer is N = 111, which has length 3.
#
#
#
# Constraints:
#
#
# 1 <= K <= 105
#
#
class Solution:
def smallestRepunitDivByK(self, K: int) -> int:
if K % 2 == 0:
return -1
i = 1
modeSet = set()
while True:
if i == 1:
mode = i % K
else:
mode = (10 * mode + 1) % K
if mode == 0:
return i
elif mode in modeSet:
return -1
else:
modeSet.add(mode)
i += 1
|
# Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.
#
# Example 1:
# Given tree s:
#
#
# 3
# / \
# 4 5
# / \
# 1 2
#
# Given tree t:
#
#
# 4
# / \
# 1 2
#
# Return true, because t has the same structure and node values with a subtree of s.
#
#
#
# Example 2:
# Given tree s:
#
#
# 3
# / \
# 4 5
# / \
# 1 2
# /
# 0
#
# Given tree t:
#
#
# 4
# / \
# 1 2
#
# Return false.
#
#
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
# Method1: O(|s||t|)
queue = [s]
res = False
while queue:
node = queue.pop(0)
if node.val == t.val:
res = res or (self.check(node, t))
if res:
return True
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return res
def check(self, node1, node2):
if node1 is None and node2 is None:
return True
elif node1 is None or node2 is None:
return False
return node1.val == node2.val and self.check(node1.left, node2.left) and self.check(node1.right, node2.right)
# Method2: convert to str and use str1.find(str2) O(|S| + |T|)
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
def convert(p):
return "^" + str(p.val) + "#" + convert(p.left) + convert(p.right) if p else "$"
return convert(t) in convert(s)
|
# You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.
#
# Given n, find the total number of full staircase rows that can be formed.
#
# n is a non-negative integer and fits within the range of a 32-bit signed integer.
#
# Example 1:
#
# n = 5
#
# The coins can form the following rows:
# ¤
# ¤ ¤
# ¤ ¤
#
# Because the 3rd row is incomplete, we return 2.
#
#
#
# Example 2:
#
# n = 8
#
# The coins can form the following rows:
# ¤
# ¤ ¤
# ¤ ¤ ¤
# ¤ ¤
#
# Because the 4th row is incomplete, we return 3.
#
#
#
# @lc app=leetcode id=441 lang=python3
#
# [441] Arranging Coins
#
# https://leetcode.com/problems/arranging-coins/description/
#
# algorithms
# Easy (38.51%)
# Total Accepted: 76.3K
# Total Submissions: 198K
# Testcase Example: '5'
#
# You have a total of n coins that you want to form in a staircase shape, where
# every k-th row must have exactly k coins.
#
# Given n, find the total number of full staircase rows that can be formed.
#
# n is a non-negative integer and fits within the range of a 32-bit signed
# integer.
#
# Example 1:
#
# n = 5
#
# The coins can form the following rows:
# ¤
# ¤ ¤
# ¤ ¤
#
# Because the 3rd row is incomplete, we return 2.
#
#
#
# Example 2:
#
# n = 8
#
# The coins can form the following rows:
# ¤
# ¤ ¤
# ¤ ¤ ¤
# ¤ ¤
#
# Because the 4th row is incomplete, we return 3.
#
#
#
# class Solution:
# def arrangeCoins(self, n):
# n = 2 * n
# i = 1
# # while i * (i + 1) <= n:
# # i += 1
# # return i - 1
# i, j = 0, n
# while i < j:
# m = int((i+j)/2)
# if m * (m+1) <= n:
# i = m + 1
# elif m * (m+1) > n:
# j = m - 1
# return i if i * (i + 1) <= n else i - 1
class Solution:
def arrangeCoins(self, n):
n = 2 * n
import math
# while i * (i + 1) <= n:
# i += 1
# return i - 1
res = int(math.sqrt(n))
return res - 1 if res * (res + 1) > n else res
|
# -*- coding:utf-8 -*-
# Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.
#
#
# Example 1:
#
#
# Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
# Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
#
#
# Example 2:
#
#
# Input: root = [5,1,7]
# Output: [1,null,5,null,7]
#
#
#
# Constraints:
#
#
# The number of nodes in the given tree will be in the range [1, 100].
# 0 <= Node.val <= 1000
#
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def increasingBST(self, root, tail=None):
if root is None:
return tail
x = TreeNode(root.val)
x.right = self.increasingBST(root.right, tail)
return self.increasingBST(root.left, x)
|
# Given an integer n, return true if it is a power of three. Otherwise, return false.
#
# An integer n is a power of three, if there exists an integer x such that n == 3x.
#
#
# Example 1:
# Input: n = 27
# Output: true
# Example 2:
# Input: n = 0
# Output: false
# Example 3:
# Input: n = 9
# Output: true
# Example 4:
# Input: n = 45
# Output: false
#
#
# Constraints:
#
#
# -231 <= n <= 231 - 1
#
#
#
# Follow up: Could you do it without using any loop / recursion?
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n == 0:
return False
while n != 1:
if n % 3 == 0:
n = n / 3
else:
return False
return True
|
# Given a list of non-negative integers nums, arrange them such that they form the largest number.
#
# Note: The result may be very large, so you need to return a string instead of an integer.
#
#
# Example 1:
#
#
# Input: nums = [10,2]
# Output: "210"
#
#
# Example 2:
#
#
# Input: nums = [3,30,34,5,9]
# Output: "9534330"
#
#
# Example 3:
#
#
# Input: nums = [1]
# Output: "1"
#
#
# Example 4:
#
#
# Input: nums = [10]
# Output: "10"
#
#
#
# Constraints:
#
#
# 1 <= nums.length <= 100
# 0 <= nums[i] <= 109
#
#
class compare(str):
def __lt__(x, y):
return x+y > y+x
class Solution:
def largestNumber(self, nums: List[int]) -> str:
s = ''.join(sorted(map(str, nums), key = compare))
return s if s[0] != '0' else '0'
# mathod 2
# def largestNumber(self, nums: List[int]) -> str:
# numsString = [str(num) for num in nums]
# self.length = len(str(max(nums))) + 1
# def convert(s):
# num = s
# while len(num) < self.length:
# num += s
# return int(num[:self.length])
# numsString.sort(key = convert,reverse = True)
# res = ''.join(numsString)
# if res[0] == '0':
# return '0'
# else:
# return res
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.