blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
d5b0d5d155c1733eb1a9fa27a7dbf11902673537 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/FunctionExercise/4.py | 1,166 | 4.1875 | 4 | # 4. Automobile Costs
# Write a program that asks the user to enter the monthly costs for the following expenses incurred from operating his or her automobile:
# loan payment, insurance, gas, oil, tires, andmaintenance.
# The program should then display the total monthly cost of these expenses,and the total annual cost of these expenses
loan = 0.0
insurance = 0.0
gas = 0.0
oil = 0.0
tire = 0.0
mx = 0.0
def main():
global loan, insurance, gas, oil, tire, mx
print("Enter the monthly loan cost")
loan = getcost()
print("Enter the monthly insurance cost")
insurance = getcost()
print("Enter the monthly gas cost")
gas = getcost()
print("Enter the monthly oil cost")
oil = getcost()
print("Enter the monthly tire cost")
tire = getcost()
print("Enter the monthly maintenance cost")
mx = getcost()
total()
def getcost():
return float(input())
def total():
monthly_amount = loan+insurance+gas+oil+tire+mx
print("Your monthly costs are $", monthly_amount)
annual_amount = monthly_amount*12
print("Your annual cost is $", annual_amount)
main() |
e51cbe700da1b5305ce7dfe9c1748ad3b2369690 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/Dictionaries and Sets/Sets/notes.py | 2,742 | 4.59375 | 5 | # Sets
# A set contains a collection of unique values and works like a mathematical set
# 1 All the elements in a set must be unique. No two elements can have the same value
# 2 Sets are unordered, which means that the elements are not stored in any particular order
# 3 The elements that are stored in a set can be of different data types
# Creating a set
my_set = set(['a', 'b', 'c'])
print(my_set)
my_set2 = set('abc')
print(my_set2)
# will remove the duplicates for us
my_set3 = set('aabbcc')
print(my_set3)
# will error, set can only take one argument
# my_set4 = set('one', 'two', 'three')
# print(my_set4)
# Brackets help
my_set5 = set(['one', 'two', 'three'])
print(my_set5)
# find length
print(len(my_set5))
# add and remove elements of a set
# initialize a blank set
new_set = set()
new_set.add(1)
new_set.add(2)
new_set.add(3)
print("New set", new_set)
# Update works
new_set.update([4, 5, 6])
print("After update: ", new_set)
new_set2 = set([7, 8, 9])
new_set.update(new_set2)
print(new_set)
# cannot do 10 instead would use .discard discard will do nothing if it won't work as opposed to return an error
new_set.remove(1)
print(new_set)
# using a for loop to iterate over a set
new_set3 = set(['a', 'b', 'c'])
for val in new_set3:
print(val)
# using in and not operator to test the value of a set
numbers_set = set([1, 2, 4])
if 1 in numbers_set:
print('The value 1 is in the set. ')
if 99 not in numbers_set:
print('The value 99 is not in the set. ')
# Find the union of sets
set1 = set([1, 2, 3, 4])
set2 = set([3, 4, 5, 6])
set3 = set1.union(set2)
print('set3', set3)
# the same as above
set5 = set1 | set2
print('set5', set5)
# Find the intersection of sets
set4 = set1.intersection(set2)
print('set 4', set4)
# same as above
set6 = set1 & set2
print('set6', set6)
char_set = set(['abc'])
char_set_upper = set(['ABC'])
char_intersect = char_set.intersection(char_set_upper)
print('character intersect upper and lower', char_intersect)
char_union = char_set.union(char_set_upper)
print('character union upper lower', char_union)
# find the difference of sets
set7 = set1.difference(set2)
print('1 and 2 diff', set7)
print('set 1', set1)
print('set 2', set2)
set8 = set2.difference(set1)
print('set 8', set8)
set9 = set1 - set2
print('set9', set9)
# finding symmetric difference in sets
set10 = set1.symmetric_difference(set2)
print('set10', set10)
set11 = set1 ^ set2
print('set11', set11)
# find the subsets and supersets
set12 = set([1,2,3,4])
set13 = set([1,2])
print(' is 13 a subset of 12', set13.issubset(set12))
print('is 12 a superset of 13', set12.issuperset(set13))
|
0ce57fc5296a09864fb1e75080a20c684bceef98 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Inheritance/car_truck_suv_demo.py | 1,521 | 4.1875 | 4 | # This program creates a Car object, a truck object, and an SUV object
import vehicles
import pprint
def main():
# Create a Car object
car = vehicles.Car('Bugatti', 'Veyron', 0, 3000000, 2)
# Create a truck object
truck = vehicles.Truck('Dodge', 'Power Wagon', 0, 57000, '4WD')
# Create an SUV object
suv = vehicles.SUV('Jeep', 'Wrangler', 200000, 5000, 4)
print('VEHICLE INVENTORY')
print('=================')
# Display the vehicles data
print('\nmake', car.get_make())
print('model', car.get_model())
print('mileage', car.get_mileage())
print(f'price {car.get_price():.2f}')
print('doors', car.get_doors())
print('\nmake', truck.get_make())
print('model', truck.get_model())
print('mileage', truck.get_mileage())
print(f'price {truck.get_price():.2f}')
print('doors',truck.get_drive_type())
print('\nmake', suv.get_make())
print('model', suv.get_model())
print('mileage', suv.get_mileage())
print(f'price {suv.get_price():.2f}')
print('doors', suv.get_pass_cap())
# shows cool info about the things
# print(help(vehicles.SUV))
# shows if an object is an instance of a class
print(isinstance(suv, vehicles.Automobile))
# shows if an object is a subclass of another
print(issubclass(vehicles.SUV, vehicles.Automobile))
# print or set object as the dictionary of the items
bob = suv.__dict__
pprint.pprint(bob, sort_dicts = False)
main() |
8a747dfb6d959c1e4774543b9dd4fa42eeda228a | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Tkinter/tkinter_intro.py | 1,459 | 3.890625 | 4 | '''
GUI - a graphical user interface allows the user to interact with the operating system and other programs using
graphical elements such as icons, buttons, and dialog boxes.
In python you can use the tkinter module to create simple GUI programs
There are other GUI modules available but tkinter comes with Python
******* tkinter widgets ********
Button - A button that can cuase an action to occur when it is clicked
Canvas - Rectangular area that can be used to display graphics
Checkbutton - A button that may be in either the 'on' or 'off' position
Entry - An area in which the user may type a single line of input from the keyboard
Frame - A container that can hold other widgets
Label - An area that displays one line of text or an image
Listbox - A list from which the user may select an item
Menu - A list of menu choices that are displayed when the user clicks a Menubutton widget
Menubutton - A menu that is displayed on the screen and may be clicked by the user
Radio - A widget that can be either selected or deselected. Can choose one option in a group
Scale - A widget that allows the user to select a value by moving a slider along a track
Scrollbar - Can be used with some other types of widgets to provide scrolling capability
Text - A widget that allows the user to enter multiple lines of text input
Toplevel - A container, like a Frame but displayed in its own window
IDLE is built using Tkinter
'''
|
d2e06b65113045bf009e371c53cc73750f8184a7 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/Recursion/Practice/7.py | 1,181 | 4.21875 | 4 | """
7. Recursive Power Method
Design a function that uses recursion to raise a number to a power. The function should
accept two arguments: the number to be raised and the exponent. Assume that the exponent is a
nonnegative integer.
"""
# define main
def main():
# Establish vars
int1 = int(input("Enter the first integer: "))
int2 = int(input("Enter the second integer: "))
# pass to function
exp(int1, int2, 1)
# define exponent
# def exp(x, y, z, a):
# if z is greater than the exponent then print the formatted number
# if z > y:
# print(f'{a:,.2f}')
# # If not cal lthe function again passing z, y and z plus 1 and the total times the base number
# else:
# return exp(x, y, z + 1, a * x)
# A better way less lines, simpler
def exp(x, y, a):
# While y is greater than 0 call the function again passing x, y - 1 and a (the total) times the base number
while y > 0: return exp(x, y - 1, a * x)
print(f'{a:,.2f}')
# call main
main()
# 7.
# def power(x,y):
# if y == 0:
# return 1
# else:
# return x * power(x, y - 1)
# print(power(3,3)) |
fafa7582c917c253c46b4e773ebe8ea1c0e84af7 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Inheritance/vehicles.py | 3,642 | 4.4375 | 4 | # The Automobile class holds general data about an auto in inventory
class Automobile:
# the __init__ method accepts arguments for the make, model, mileage, and price. It initializes the data attributes with these values.
def __init__(self, make, model, mileage, price):
self.__make = make
self.__model = model
self.__mileage = mileage
self.__price = price
# The following methods are mutators for the class's data attributes.
def set_make(self, make):
self.__make = make
def set_model(self, model):
self.__model = model
def set_mileage(self, mileage):
self.__mileage = mileage
def set_price(self, price):
self.__price = price
# The following methods are the accessors for the class's data attributes.
def get_make(self):
return self.__make
def get_model(self):
return self.__model
def get_mileage(self):
return self.__mileage
def get_price(self):
return self.__price
# The Car class represents a car. It is a subclass of the Automobile class
class Car(Automobile):
# The __init__ method accepts arguments for the cars make, model, mileage, price and doors
def __init__(self, make, model, mileage, price, doors):
# Call the superclass's __init__ method and pass the required arguments. Note
# t we also have to pass self as an argument can do Automobile(Superclass name)
# or can use super() without the self argument
super().__init__(make, model, mileage, price)
# Initialize the __doors attribute
self.__doors = doors
# The set_doors method is the mutator for the __doors attribute
def set_doors(self, doors):
self.__doors = doors
# The get_doors method is the accessor for the __doors attribute
def get_doors(self):
return self.__doors
# The Truck class represents a pickup truck. It is as subclass of the Automobile class
class Truck(Automobile):
# The __init__ method accepts arguments for the Truck's make, model, mileage, price, and drive type
def __init__(self, make, model, mileage, price, drive_type):
# Call the superclass's __init__ and pass the required arguments.
# Note that we also have to pass the reqd args
super().__init__(make, model, mileage, price)
# initialize the drive_type attribute
self.__drive_type = drive_type
# the set drive type method is the mutator for the __drive_type attribute
def set_drive_type(self, drive_type):
self.__drive_type = drive_type
# the get drive type is the accessor for the __drive_type attribute
def get_drive_type(self):
return self.__drive_type
# THe SUV class represents a sport utility vehicle. It is a subclass for the Automobile class
class SUV(Automobile):
# The __init__ method accepts arguments for the SUV's make, model, mileage,
# price, and pass capacity
def __init__(self, make, model, mileage, price, pass_cap):
# Call the superclass's __init__ method and pass the reqd args
super().__init__(make, model, mileage, price)
# initialize the pass_cap attribute
self.__pass_cap = pass_cap
# define the set_pass_cap method that is the mutator for the __pass_cap attribute
def set_pass_cap(self, pass_cap):
self.__pass_cap = pass_cap
# define the get_pass_cap method that is the accessor for the __pass_cap attribute
def get_pass_cap(self):
return self.__pass_cap
|
f149ee1bf7a78720f53a8688d83d226cb00dc5eb | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Practice/Cars.py | 2,383 | 4.8125 | 5 | """
2. Car Class
Write a class named Car that has the following data attributes:
• __year_model (for the car’s year model)
• __make (for the make of the car)
• __speed (for the car’s current speed)
The Car class should have an __init__ method that accept the car’s year model and make
as arguments. These values should be assigned to the object’s __year_model and __make
data attributes. It should also assign 0 to the __speed data attribute.
The class should also have the following methods:
• accelerate
The accelerate method should add 5 to the speed data attribute each time it is
called.
• brake
The brake method should subtract 5 from the speed data attribute each time it is called.
• get_speed
The get_speed method should return the current speed.
Next, design a program that creates a Car object, and then calls the accelerate method
five times. After each call to the accelerate method, get the current speed of the car and
display it. Then call the brake method five times. After each call to the brake method, get
the current speed of the car and display it.
"""
# define the class of cars
class Cars:
# define the init with all the variables
def __init__(self, year, make, model, speed):
self.__year = year
self.__make = make
self.__model = model
self.__speed = speed
# def setting the year of the car
def set_year(self, year):
self.__year = year
# def function to set the make of the car
def set_make(self, make):
self.__make = make
# def function to set the model of the car
def set_model(self, model):
self.__model = model
# def function to accelerate
def accelerate(self):
self.__speed += 5
return self.__speed
# def function to begin braking
def brake(self):
self.__speed -= 5
return self.__speed
# define a function to get the speed
def get_speed(self):
return self.__speed
# return the year
def get_year(self):
return self.__year
# returns the make
def get_make(self):
return self.__make
# return the model
def get_model(self):
return self.__model
|
eaa53c820d135506b1252749ab50b320d11d53b5 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Practice/5 - RetailItem.py | 1,427 | 4.625 | 5 | """
5. RetailItem Class
Write a class named RetailItem that holds data about an item in a retail store. The class
should store the following data in attributes: item description, units in inventory, and price.
Once you have written the class, write a program that creates three RetailItem objects
and stores the following data in them:
Description Units in Inventory Price
Item #1 Jacket 12 59.95
Item #2 Designer Jeans 40 34.95
Item #3 Shirt 20 24.95
"""
# import the important things
import RetailItem
# establish the dictionary with the data
item_dict = {1 : { 'description' : 'Jacket', 'units' : 12, 'price' : 59.95},
2 : { 'description' : 'Designer Jeans', 'units' : 40, 'price' : 34.95},
3 : { 'description' : 'Shirt', 'units' : 20, 'price' : 24.95}}
# define the main function
def main():
# set the variable to call the class and use dictionary info to populate it
item1 = RetailItem.RetailItem(item_dict[1]['description'], item_dict[1]['units'], item_dict[1]['price'])
item2 = RetailItem.RetailItem(item_dict[2]['description'], item_dict[2]['units'], item_dict[2]['price'])
item3 = RetailItem.RetailItem(item_dict[3]['description'], item_dict[3]['units'], item_dict[3]['price'])
# display the data
print(item1, item2, item3)
# call main
main() |
b046b95c144bbe51ac2c77b5363814b8b5d2b5cc | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/LoopsPractice/6.py | 503 | 4.46875 | 4 | # 6. Celsius to Fahrenheit Table
# Write a program that displays a table of the Celsius temperatures 0 through 20 and theirFahrenheit equivalents.
# The formula for converting a temperature from Celsius toFahrenheit is
# F = (9/5)C + 32 where F is the Fahrenheit temperature and C is the Celsius temperature.
# Your programmust use a loop to display the table.
fahr = [((9/5) * cel + 32) for cel in range(21)]
for x, y in enumerate(fahr):
print(f'{x:} celcius is {y:.2f} fahrenheit.')
|
6da08424b01dfcfcebb93cbeff93e76e72c53ea9 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/Unit Testing and Multithreading/MultiThreading/Multithreadingclassdemo1/multithreading5.py | 950 | 3.625 | 4 | # For editing further without losing multithreading og file
'''
Prove that these are actually coming in as they are completed
Lets pass in a range of seconds
Start 5 second thread first
'''
import concurrent.futures
import time
start = time.perf_counter()
def do_something(seconds):
print(f'Sleeping {seconds} second....')
time.sleep(seconds)
return f'Done Sleeping....{seconds}'
# using a context manager
with concurrent.futures.ThreadPoolExecutor() as executor:
seconds_list = [5, 4, 3, 2, 1]
# map will apply the function do_something to every item in the seconds_list
# insteatd of running the results as they complete, map returns in the order
# that they were started
results = executor.map(do_something, seconds_list)
for result in results:
print(result)
finished = time.perf_counter()
print(f'Our program finished in {finished - start:.6f} seconds.') |
9e6bdd3adc3e850240f3c9a94dd766ecdd4abe97 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/FileExercises/9.py | 1,013 | 4.28125 | 4 | # 9. Exception Handing
# Modify the program that you wrote for Exercise 6 so it handles the following exceptions:
# • It should handle any IOError exceptions that are raised when the file is opened and datais read from it.
# Define counter
count = 0
# Define total
total = 0
try:
# Display first 5 lines
# Open the file
infile = open("numbers.txt", 'r')
# Set readline
line = infile.readline()
while line != '':
# Convert line to a float
display = int(line)
# Increment count and total
count += 1
total += display
# Format and display data
print(display)
# Read the next line
line = infile.readline()
print(f"\n The average of the lines is {total/count:.2f}")
# If file doesn't exist, show this error message
except:
print(f"\n An error occured trying to read numbers.txt")
if count > 0:
print(f" to include line {count:} \n") |
c7576a385b6019af0393ec97ebdd0cf3c5aee69e | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/Algorithms and Data Structures/collections_lecture.py | 2,840 | 3.8125 | 4 | '''
collection - a group of 0 or more items that can be treated as a conceptual unit. Things like strings, lists, tuples, dictionaries
Other types of collections include stacks, queues, priority queues, binary search trees, heaps, graphs, and bags
************** Collection Types **************
linear collection - like people in a line, they are ordered by position, each item except athe first has a unique predecessor
Hierarchical collection - ordered in a structure resembling an upside down tree. Each data item except the one at the top, (the root),
has just one predecessor called its parent, but potentially has many successors called children
Some examples include a file directory system, a company's organizational tree, and a books table of contents
graph collection - also called graph, each item can have many predecessors and many successors. These are also called neighbors
some examples include airline routes between cities, electrical wiring diagrams, and the world wide web
unordered collections - these are not in any particular order, and its not possible to meaningfully speak of an item's predecessor or successor
an example includes a bag of marbles
************** Operation Types **************
Determine the size - Use Python's len() function to obtain the number of items currently in the collection
Test for item membership - Use Python's "in" operator to search for a given target item in the collection. Return's "True" if the item if found and "False" otherwise
Traverse the collection - Use Python's "for" loop to visit each item in the collection. The order in which items are visited depends on the type of the collection
Obtain a string representation - Use Python's str() function to obtain the string representation of the collection
Test for equality - Use Python's "==" operator to determine whether the two collections are equal. Two collections are equal if they are of the same type and contain the
same items. The order in which pairs of items are compared depends on the type of collection.
Concatenate two collections - use Pyhton's "+" operator to obtain a new collection of the same type as the operands and containing the items in the two operands
Convert to another type of collection - Create a new collection with the same items as a source collection
Insert an item - Add the item to the collection, possibly at a given position
Remove an item - Remove the item from the collection, possibly at a given position
Replace an item - Combine removal and insertion into one operation
Access or retrieve an item - Obtain an item, possibly at a given position
''' |
f1639f9b273a097c08d8e3d6236acf50befd9a99 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/regex/Practice/1.py | 285 | 3.75 | 4 | """
1. Recognize the following strings: “bat”, “bit”, “but”, “hat”,
“hit”, or “hut”.
"""
import re
string = '''
bat bit but hat hit hut
'''
pattern = re.compile(r'[a-z]{2}t')
matches = pattern.finditer(string)
for match in matches:
print(match)
|
2118efbe7e15e295f6ceea7b4a4c26696b22edb1 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/Unit Testing and Multithreading/MultiThreading/Multithreadingclassdemo1/multithreading.py | 1,434 | 4.15625 | 4 | '''
RUnning things concurrently is known as multithreading
Running things in parallel is known as multiprocessing
I/O bound tasks - Waiting for input and output to be completed
reading and writing from file system, network
operations.
These all benefit more from threading
You get the illusion of running code at the same time,
however other code starts running while other code is waiting
CPU bound tasks - Good for number crunching
Using CPU
Data Crunching
These benefit more from multiprocessing and running in parallel
Using multiprocessing might be slower if you have overhead from creating
and destroying files.
'''
import threading
import time
start = time.perf_counter()
def do_something():
print('Sleeping 1 second....')
time.sleep(1)
print('Done Sleeping....')
# how we did it
# do_something()
# do_something()
# create threads for new way
t1 = threading.Thread(target=do_something)
t2 = threading.Thread(target=do_something)
#start the thread
t1.start()
t2.start()
# make sure the threads complete before moving on to calculate finish time:
t1.join()
t2.join()
finished = time.perf_counter()
print(f'Our program finished in {finished - start:.6f} seconds.') |
5c78846587a1485c8a39a77ef8f4ec10dfe0f2bb | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Test Stuff/First Test/study/knowledge_lists_and_tuples.py | 3,523 | 4.15625 | 4 | """
Multiple Choice
1. This term refers to an individual item in a list.
a. element
b. bin
c. cubby hole
d. slot
2. This is a number that identifies an item in a list.
a. element
b. index
c. bookmark
d. identifier
3. This is the first index in a list.
a. -1
b. 1
c. 0
d. The size of the list minus one
4. This is the last index in a list.
a. 1
b. 99
c. 0
d. The size of the list minus one
5. This will happen if you try to use an index that is out of range for a list.
a. a ValueError exception will occur
b. an IndexError exception will occur
c. The list will be erased and the program will continue to run.
d. Nothing—the invalid index will be ignored
6. This function returns the length of a list.
a. length
b. size
c. len
d. lengthof
7. When the * operator’s left operand is a list and its right operand is an integer, the
operator becomes this.
a. The multiplication operator
b. The repetition operator
c. The initialization operator
d. Nothing—the operator does not support those types of operands.
8. This list method adds an item to the end of an existing list.
a. add
b. add_to
c. increase
d. append
9. This removes an item at a specific index in a list.
a. The remove method
b. The delete method
c. The del statement
d. The kill method
10. Assume the following statement appears in a program:
mylist = []
Which of the following statements would you use to add the string 'Labrador' to the
list at index 0?
a. mylist[0] = 'Labrador'
b. mylist.insert(0, 'Labrador')
c. mylist.append('Labrador')
d. mylist.insert('Labrador', 0)
11. If you call the index method to locate an item in a list and the item is not found, this
happens.
a. A ValueError exception is raised
b. An InvalidIndex exception is raised
c. The method returns -1
d. Nothing happens. The program continues running at the next statement.
12. This built-in function returns the highest value in a list.
a. highest
b. max
c. greatest
d. best_of
13. This file object method returns a list containing the file’s contents.
a. to_list
b. getlist
c. readline
d. readlines
14. Which of the following statements creates a tuple?
a. values = [1, 2, 3, 4]
b. values = {1, 2, 3, 4}
c. values = (1)
d. values = (1,)
True or False:
1. Lists in Python are immutable.
2. Tuples in Python are immutable.
3. The del statement deletes an item at a specified index in a list.
4. Assume list1 references a list. After the following statement executes, list1 and
list2 will reference two identical but separate lists in memory:
list2 = list1
5. A file object’s writelines method automatically writes a newline ('\n') after writing
each list item to the file.
6. You can use the + operator to concatenate two lists.
7. A list can be an element in another list.
8. You can remove an element from a tuple by calling the tuple’s remove method
""" |
f1923bf1fc1a3ab94a7f5d32c929cd6914fc7605 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Test Stuff/First Test/shapes1.py | 2,305 | 4.25 | 4 | class GeometricObject:
def __init__(self, color = "green", filled = True):
self.color = color
self.filled = filled
def getColor(self):
return self.color
def setColor(self, color):
self.color = color
def isFilled(self):
return self.filled
def setFilled(self, filled):
self.filled = filled
def toString(self):
return "color: " + self.color + " and filled: " + str(self.filled)
'''
(The Triangle class) Design a class named Triangle that extends the
GeometricObject class defined below. The Triangle class contains:
- Three float data fields named side1, side2, and side3 to denote the three
sides of the triangle.
- A constructor that creates a triangle with the specified side1, side2, and
side3 with default values 1.0.
- The accessor methods for all three data fields.
- A method named getArea() that returns the area of this triangle.
- A method named getPerimeter() that returns the perimeter of this triangle.
- A method named __str__() that returns a string description for the triangle.
'''
class TriangleObject:
def __init__(self, color = "green", filled = True, side1 = 1.0, side2 = 1.0, side3 = 1.0):
super().__init__(color, filled)
self.side1 = side1
self.side2 = side2
self.side3 = side3
def set_side1(self, side1):
self.side1 = side1
def set_side2(self, side2):
self.side2 = side2
def set_side3(self, side3):
self.side3 = side3
def get_side1(self, side1):
return self.side1
def get_side2(self, side2):
return self.side2
def get_side3(self, side3):
return self.side3
def getPerimeter(self):
self.perimeter = (self.side1 + self.side2 + self.side3)/2
return self.perimeter
def getArea(self):
self.area = (self.perimeter * (self.perimeter - self.side1) * (self.perimeter - self.side2) * (self.perimeter - self.side3)) ** (1/2.0)
return self.area
def __str__(self):
return f'A triangle is a 3 sided shape. The current sides have a length of {self.side1}, {self.side2}, and {self.side3}'
|
cd2b8237503c74dfc7864dd4ec64d7f334c9ecb0 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Practice/8 - trivia.py | 2,521 | 4.4375 | 4 | """
8. Trivia Game
In this programming exercise you will create a simple trivia game for two players. The program will
work like this:
• Starting with player 1, each player gets a turn at answering 5 trivia questions. (There
should be a total of 10 questions.) When a question is displayed, 4 possible answers are
also displayed. Only one of the answers is correct, and if the player selects the correct
answer, he or she earns a point.
• After answers have been selected for all the questions, the program displays the number
of points earned by each player and declares the player with the highest number of points
the winner.
To create this program, write a Question class to hold the data for a trivia question. The
Question class should have attributes for the following data:
• A trivia question
• Possible answer 1
• Possible answer 2
• Possible answer 3
• Possible answer 4
• The number of the correct answer (1, 2, 3, or 4)
The Question class also should have an appropriate __init__ method, accessors, and
mutators.
The program should have a list or a dictionary containing 10 Question objects, one for
each trivia question. Make up your own trivia questions on the subject or subjects of your
choice for the objects.
"""
question_dict = {"Blue, Black or Red?" : ['Blue', 'Red', 'Clear', 'Black'],
"Yes or No?" : ['Yes', 'Maybe', 'True', 'No'],
"Laptop or Desktop?" : ['Cell Phone', 'Tablet', 'Laptop', 'Desktop']}
import trivia
import random
def main():
global question_dict
questions = trivia.Trivia()
questions.bulk_add(question_dict)
for key in questions.get_questions():
print(key)
# print(questions.get_questions()[key])
answerlist = []
answerlist2 = []
for i in questions.get_questions()[key]:
answerlist.append(i)
answerlist2.append(i)
random.shuffle(answerlist2)
print("1", answerlist)
print("2", answerlist2)
count = 0
for i in answerlist2:
print(f"Number {count}: {i}")
count += 1
choice = int(input("Enter the number choice for your answer: "))
if answerlist[3] == answerlist2[choice]:
print("You got it right!")
else:
print("You got it wrong!")
main() |
2ae55026f82e336bd28809f87822da12d2a8f0a6 | Hackman9912/PythonCourse | /NetworkStuff/09_NetworkingExtended/Practice/04 Modules/04-5.py | 679 | 4.03125 | 4 | '''
### Working With modules ( sys, os, subprocess, argparse, etc....)
5. Create a script that will accept a single integer as a positional argument, and will print a hash symbol that amount of times.
'''
import os
import sys
import time
import subprocess
import argparse
def get_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--integer', help="Set the number of octothorps to print by hitting -i (your number). ")
return parser.parse_args()
def print_octothorp(octo, numb):
print('Getting this many octothorps: ' + numb + '\n' + str(octo))
options = get_arguments()
octo = '#' * int(options.integer)
print_octothorp(octo, options.integer) |
1658b421c637ec8ab3524446baccd8f30da4470c | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/Lists/tuples.py | 394 | 4.25 | 4 | # tuples are like an immutable list
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)
# printing items in a tuple
names = ('Holly', 'Warren', 'Ashley')
for n in names:
print(n)
for i in range(len(names)):
print (names[i])
# Convert between a list and a tuple
listA = [2, 4, 5, 1, 6]
type(listA)
tuple(listA)
type(listA)
tupA = tuple(listA)
type(tupA) |
8b72f14467bc40821bc0fb0c7c2ad9f05be58cd0 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Inheritance/Practice/Inheritance Exercises - 3.py | 2,460 | 4.46875 | 4 | """
3. Person and Customer Classes
Write a class named Person with data attributes for a person’s name, address, and
telephone number. Next, write a class named Customer that is a subclass of the
Person class. The Customer class should have a data attribute for a customer
number and a Boolean data attribute indicating whether the customer wishes to be
on a mailing list. Demonstrate an instance of the Customer class in a simple
program.
"""
import assets
import pprint
pppl_lst = []
cust_lst = []
def main():
global pppl_lst, cust_lst
pppl_num = int(input('Enter the number of people you need to add: '))
setthelist(pppl_num)
print("Not Customers: ")
print_list(pppl_lst)
print("Customers: ")
print_list(cust_lst)
def setthelist(theamount):
global pppl_lst, cust_lst
for i in range(theamount):
print("Person", i+1)
customerinput = int(input('Is this person a customer? 1 for yes 0 for no: '))
if customerinput == 1:
name = input('Enter the persons name: ')
address = input('Enter the address: ')
phone = input('Enter the phone number for the person: ')
cust_num = int(input('Enter the customer number: '))
mail = 2
while mail != 0 and mail != 1:
mail = int(input('Does the customer want to be on the mailing list? 1 = yes 0 = no: '))
print('mail', mail)
customer = assets.Customer(name, address, phone, cust_num, bool(mail))
cust_lst.append(customer)
elif customerinput == 0:
name = input('Enter the persons name: ')
address = input('Enter the address: ')
phone = input('Enter the phone number for the person: ')
notcustomer = assets.Person(name, address, phone)
pppl_lst.append(notcustomer)
def print_list(listss):
if listss is pppl_lst:
for i in listss:
print('Name: ', i.get_name())
print('Address: ', i.get_address())
print('Phone: ', i.get_phone())
elif listss is cust_lst:
for i in listss:
print('Name: ', i.get_name())
print('Address: ', i.get_address())
print('Phone: ', i.get_phone())
print('Customer Number: ', i.get_cust_num())
print('Is on mailing address: ', i.get_mail())
main()
|
ab93e5065c94a86f8ed6c812a3292100925a1bb5 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/IfElsePractice/5.py | 1,575 | 4.4375 | 4 | # 5. Color Mixer
# The colors red, blue, and yellow are known as the primary colors because they cannot be
# made by mixing other colors. When you mix two primary colors, you get a secondary color,
# as shown here:
# When you mix red and blue, you get purple.
# When you mix red and yellow, you get orange.
# When you mix blue and yellow, you get green.
# Design a program that prompts the user to enter the names of two primary colors to mix.
# If the user enters anything other than “red,” “blue,” or “yellow,” the program should display an
# error message. Otherwise, the program should display the name of the secondary color that results.
def main():
color_one = color()
checker(color_one)
color_two = color()
checker(color_two)
blender(color_one, color_two)
def checker(color):
if color == "red" or color == "blue" or color == "yellow":
print("You chose", color)
else:
print("Choose one of the primary colors!")
exit()
def color():
return input("Enter 'red', 'blue', or 'yellow'. ")
def blender(first, second):
if (first == "red" or second == "red") and (first == "blue" or second == "blue"):
print("Your blend is purple")
elif (first == "yellow" or second == "yellow") and (first == "blue" or second == "blue"):
print("Your blend is green")
elif (first == "red" or second == "red") and (first == "yellow" or second == "yellow"):
print("Your blend is orange")
else:
print("Your colors were the same")
main() |
5a57c7b45ccb3df1adb3ebad30f2a4d2defba1d7 | stephaniecheng1124/CIS-01 | /InClassB.py | 941 | 3.984375 | 4 | # Stephanie Cheng
# CIS 41B Spring 2019
# In-class assignment B
# Problem B1
#
# This program writes a script to perform various basic math and string operations.
def string_count():
name = raw_input("Please enter your name: ")
print(name.upper())
print(len(name))
print(name[3])
name2 = name.replace("o", "x")
print(name2)
print(name)
print("\n")
quote = "Believe you can and you're halfway there."
print("Number of occurrences of letter 'a' in quote:")
print(quote.count("a"))
print("\n")
print("Indices of letter 'a' in quote:")
if quote.count("a") > 0:
start = quote.find("a")
print(start)
if quote.count("a") > 1:
start += 1
while quote.find("a", start) != -1:
start = quote.find("a", start)
print(start)
start += 1
string_count()
|
d2d9ad0905e398f8509b6ad6e70f59ee578f0adc | stephaniecheng1124/CIS-01 | /InClassC.py | 871 | 3.6875 | 4 | # Stephanie Cheng
# CIS 41B Spring 2019
# In-class assignment C
# Problem C1
#
#List Script
from copy import deepcopy
def list_script():
list1 = [2, 4.1, 'Hello']
list2 = list1
list3 = deepcopy(list1)
print("list1 == list2: " + str(list1==list2))
print("list1 == list3: " + str(list1==list3))
print("list2 == list3: " + str(list2==list3))
print("list1 is list2: " + str(list1 is list2))
print("list1 is list3: " + str(list1 is list3))
print("list2 is list3: " + str(list2 is list3))
print("list1 ID: " + str(id(list1)))
print("list2 ID: " + str(id(list2)))
print("list3 ID: " + str(id(list3)))
list1.append(8)
list2.insert(1, 'goodbye')
del list3[0]
print("list1 printed: " + str(list1))
print("list2 printed: " + str(list2))
print("list3 printed: " + str(list3))
list_script()
|
1821805f1bd83a8add850ac70f9ad17bf5a27431 | shaamimahmed/MITx---6.00.1x | /BFS.py | 700 | 3.859375 | 4 | class node():
def __init__(self,value,left,right):
self.value = value
self.left = left
self.right = right
def __str__(self):
return self.value
def __repr__(self):
return 'Node {}'.format(self.value)
def main():
g = node("G", None, None)
h = node("H", None, None)
i = node("I", None, None)
d = node("D", None, None)
e = node("E", g, None)
f = node("F", h, i)
b = node("B", d, e)
c = node("C", None, f)
a = node("A", b, c)
root = a
BFS(root)
def BFS(root):
nexts = [root]
while nexts != []:
current = nexts.pop(0)
if current.left:
nexts.append(current.left)
if current.right:
nexts.append(current.right)
print current,
main() |
1b2a7905075802782b7f57df0b08520ee13aaea4 | shaamimahmed/MITx---6.00.1x | /recursion.py | 730 | 3.828125 | 4 | def iterPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
total= base
if exp == 0:
total = 1
for n in range(1, exp):
total *= base
return total
def recurPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
if exp == 0:
return 1
return base * recurPower(base, exp - 1)
def recurPowerNew(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float; base^exp
'''
if exp == 0:
return 1
elif exp % 2 == 0:
return recurPowerNew(base*base, exp/2)
else:
return base * recurPowerNew(base, exp - 1)
|
890f3be1a967335d2aa8f3c4d31a5c5d33626428 | Kediel/DataScienceFromScratch | /chapter5.py | 1,230 | 3.53125 | 4 | # Statistics
from collections import defaultdict, Counter
num_friends = [100,49,41,40,25,21,21,19,19,18,18,16,15,15,15,15,14,14,13,13,13,13,12,12,11,10,10,10,10,10,10,10,10,10,
10,10,10,10,10,10,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,8,8,8,8,8,8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,
4,4,4,4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
def make_friend_counts_histogram(plt):
friend_counts = Counter(num_friends)
xs = range(101)
ys = [friend_counts[x] for x in xs]
plt.bar(xs, ys)
plt.axis([0,101,0,25])
plt.title("Histogram of Friend Counts")
plt.xlabel("# of friends")
plt.ylabel("# of people")
plt.show()
num_points = len(num_friends) # 204
largest_value = max(num_friends) # 100
smallest_value = min(num_friends) # 1
sorted_values = sorted(num_friends)
smallest_value = sorted_values[0] # 1
second_smallest_value = sorted_values[1] # 1
second_largest_value = sorted_values[-2] # 49
|
47332606f558cc9927e5f1d415dde6ce2ddfbf6d | smpss97058/c109156217 | /4-2D座標判斷及計算離原點距離.py | 860 | 3.84375 | 4 | x=int(input("X軸座標:"))
y=int(input("Y軸座標:"))
a=0
if x>0:
if y>0:
a=x**2+y**2
print("該點位於第一象限,離原點距離為根號"+str(a))
elif y<0:
a=x**2+y**2
print("該點位於第四象限,離原點距離為根號"+str(a))
else:
a=x**2+y**2
print("該點位於X軸上,離原點距離為根號"+str(a))
if x<0:
if y>0:
a=x**2+y**2
print("該點位於第二象限,離原點距離為根號"+str(a))
elif y<0:
a=x**2+y**2
print("該點位於第三象限,離原點距離為根號"+str(a))
else:
a=x**2+y**2
print("該點位於X軸上,離原點距離為根號"+str(a))
if x==0:
if y==0:
print("該點位於原點")
else:
a=x**2+y**2
print("該點位於Y軸上,離原點距離為根號"+str(a))
|
77acd1d223437c765fa54b6c2148332653bbe731 | smpss97058/c109156217 | /32新公倍數.py | 252 | 3.71875 | 4 | n=int(input("輸入一整數:"))
while n<11 or 1000<n:
n=int(input("輸入一整數(11<=n<=1000):"))
if n%2==0 and n%11==0:
if n%5!=0 and n%7!=0:
print(str(n)+"為新公倍數?:Yes")
else:
print(str(n)+"為新公倍數?:No") |
fcf81e26402c78334170997fe6b6f4f98807d47e | elizamakkt1218/CSVFileCombination | /main.py | 4,241 | 4.03125 | 4 | import tkinter as tk
from tkinter.filedialog import askdirectory
import csv
import os
import utilities
absolute_file_paths = []
def get_file_path():
"""
Prompts user to select the folder for Combining CSV files
:parameter: None
:return: The relative paths of all files contained in the folder
:exception:
1. UnspecifiedFolderError
2. EmptyFolderError
3. AbsenceOfCSVFileError
"""
tk.Tk().withdraw()
folder_path = ''
try:
folder_path = askdirectory(title='Select Folder')
# Raise UnspecifiedFolderError when user did not select a folder
if folder_path == '/':
raise utilities.UnspecifiedFolderError('Please select a folder.')
# Return None and stop the program when user click "Cancel"
elif folder_path == '':
return None
except utilities.UnspecifiedFolderError:
print('Please select a folder.')
get_file_path()
relative_file_paths = []
try:
relative_file_paths = os.listdir(folder_path)
# Raise EmptyFolderError when the folder is empty
if not relative_file_paths:
raise utilities.EmptyFolderError('Empty Folder!')
# The index of the two lists: relative_file_paths and absolute_file_paths are the same
for files in relative_file_paths:
ext = files.rpartition('.')[-1]
if ext != 'csv':
relative_file_paths.remove(files)
continue
absolute_file_paths.append(folder_path + '/' + files)
# Raise AbsentOfCSVFileError when no csv file exists
if not absolute_file_paths:
raise utilities.AbsentOfCSVFileError('No CSV File Exists.')
except utilities.EmptyFolderError:
print(folder_path + '\n' + 'The folder is empty.')
except utilities.AbsentOfCSVFileError:
print('No CSV File Exists.')
return relative_file_paths
def read():
"""
Reads all the CSV files and save the data as lists
:parameter: None
:return: a list of csv_reader objects(converted into lists)
:exception: None
"""
# Call get_file_path Method
# if it returns none, return to its caller
relative_file_paths = get_file_path()
if not relative_file_paths:
return
# Convert all the csv_reader objects into lists and save them to a list
index = 0
file_reader = []
for file in absolute_file_paths:
with open(file, newline='') as csv_file:
file_reader.append(list(csv.reader(csv_file)))
# Rename the column name into filenames
if index >= 1:
# Skip the first column if the files are loaded as the second one or onwards
for row in file_reader[index]:
row.pop(0)
file_reader[index][0][0] = os.path.splitext(relative_file_paths[index])[0]
else:
file_reader[index][0][1] = os.path.splitext(relative_file_paths[index])[0]
index += 1
return file_reader
def write():
"""
Writes all the data into a new CSV file called 'output.csv'
:return: None
:parameter: None
:exception: None
"""
# Call read Method
file_reader = read()
if not file_reader:
return
# Write the data to the "output.csv" file
count = 0
while count < len(file_reader):
if count == 0:
with open('output.csv', 'w', newline='')as csv_file:
writer = csv.writer(csv_file)
for row in file_reader[0]:
writer.writerow(row)
csv_file.close()
count += 1
else:
length = 0
with open('output.csv', 'r', newline='') as input_file:
reader = list(csv.reader(input_file))
with open('output.csv', 'w', newline='')as append_file:
writer = csv.writer(append_file)
for input_row in reader:
writer.writerow(input_row + file_reader[count][length])
length += 1
append_file.close()
count += 1
print('Output file has been saved to the current directory.')
def main():
write()
if __name__ == "__main__":
main()
|
dc1bbcc31eb28b89d15dac95bf107b5627667593 | JianyanLiang/SkyDrive | /Server/查看当前用户.py | 149 | 3.609375 | 4 | import sqlite3
conn = sqlite3.connect('Users.db')
cur = conn.cursor()
sql = 'select * from users'
cur.execute(sql)
print(cur.fetchall())
a = input()
|
d63f59488d65ba81d647da41c15424a0901d18b4 | DimitrisMaskalidis/Python-2.7-Project-Temperature-Research | /Project #004 Temperature Research.py | 1,071 | 4.15625 | 4 | av=0; max=0; cold=0; count=0; pl=0; pres=0
city=raw_input("Write city name: ")
while city!="END":
count+=1
temper=input("Write the temperature of the day: ")
maxTemp=temper
minTemp=temper
for i in range(29):
av+=temper
if temper<5:
pl+=1
if temper>maxTemp:
maxTemp=temper
if temper<minTemp:
minTemp=temper
temper=input("Write the temperature of the day: ")
print "The differance between highest and lowest temperature is",maxTemp-minTemp
av=av/30.0
if count==1:
max=av
if av>max:
max=av
maxname=city
if av>30:
pres+=1
if pl==30:
cold+=1
pl=0
city=raw_input("Write city name: ")
print "The percentage of the cities with average temperature more than 30 is",count/pres*100,"%"
print "The city with the highest average temperature is",maxname,"with",max,"average temperature"
if cold>0:
print "There is a city with temperature below 5 every day"
|
bafeb62820714891cf4f2082f45487e8d3db63a0 | treylitefm/euler | /misc-algos/tictactoe.py | 1,605 | 3.65625 | 4 | #arr = [['x','x','x'],['o','o','x'],['x','o','o']]
#rr = [['x','o','x'],['o','o','o'],['x','o','o']]
#arr = [['x','o','x'],['o','x','o'],['x','o','x']]
#arr = [['a','o','x'],['b','x','o'],['c','o','x']]
arr = [['a','b','g'],['d','g','f'],['g','h','i']]
def print_grid(grid):
for row in grid:
print row
def sol(grid):
tmp = None
for i in range(3): # tests down across top row
for k in range(3):
if tmp is None:
tmp = grid[i][k]
elif tmp is grid[i][k]:
if range(3)[-1] is k: # then we're done and there is indeed a win
return True
else: # tells us that current element doesnt match last element
tmp = None
break
tmp = None
for j in range(3): # tests down across top row
for l in range(3):
if tmp is None:
tmp = grid[l][j]
elif tmp is grid[l][j]:
if range(3)[-1] is k: # then we're done and there is indeed a win
return True
else: # tells us that current element doesnt match last element
tmp = None
break
tmp = grid[0][0]
for m in range(3):
if tmp is grid[m][m]:
if m is range(3)[-1]:
return True
else:
break
tmp = grid[-1][0]
for n1,n2 in zip(range(2,-1,-1),range(3)):
if tmp is grid[n1][n2]:
if n1 is range(2,-1,-1)[-1]:
return True
else:
break
print_grid(arr)
print sol(arr)
|
7592ee5998b54cc6e7b4f7773c45e960d0b1e80c | viniciuskurt/LetsCode-PracticalProjects | /2-AdvancedStructures/Inserindo_Novo_Valor_Lista.py | 313 | 3.53125 | 4 | # podemos inserir novos valores através do METODO INSERT
cidades = ['São Paulo', 'Brasilia', 'Curitiba', 'Avaré', 'Florianópolis']
print(cidades)
cidades.insert(0, 'Osasco')
print(cidades)
# Inserido vários valores
cidades.insert(1, 'Bogotá');
print(cidades)
cidades.insert(4, 'Manaus')
print(cidades)
|
0e878016fadab1f137f3dd61c37197ecafa4511e | viniciuskurt/LetsCode-PracticalProjects | /2-AdvancedStructures/Listas_com_While.py | 438 | 4.09375 | 4 | # Uma forma inteligente de trabalhar é combinar Listas com Whiles
numeros = [1, 2, 3, 4, 5] #Criando e atribuindo valores a lista
indice = 0 #definindo contador no índice 0
while indice < 5: #Definindo repetição do laço enquanto menor que 5
print(numeros[indice]) #Exibe posição de determinado índice da lista
indice = indice + 1 #Incrementa mais um a cada volta no laço |
4d1e19c830d0f41e51c4837a8792b8a054ee6655 | viniciuskurt/LetsCode-PracticalProjects | /1-PythonBasics/aula04_Operadores.py | 1,578 | 4.40625 | 4 | '''
OPERADORES ARITMETICOS
Fazem operações aritméticas simples:
'''
print('OPERADORES ARITMÉTICOS:\n')
print('+ soma')
print('- subtração')
print('* multiplicacao')
print('/ divisão')
print('// divisão inteira') #não arredonda o resultado da divisão, apenas ignora a parte decimal
print('** potenciação')
print('% resto da divisão\n')
x = 2
y = 5
m = x * y
print('x * y = ',m)
s = x + y
print('x + y = ',s)
sub = x - y
print('x - y = ',sub)
d = x / y
print('y / x = ',d)
di = x // y
print('x // y = ',di)
p = x ** y
print('x ** y = ',p)
rd = x % y
print('x % y = ',rd)
print('--' *30 )
print('OPERADORES LÓGICOS:\n')
print('OR - resultado Verdadeiro se UMA ou AMBAS expressões for verdadeira')
print('AND - resultado Verdadeiro somente se AMBAS as expressões forem verdadeiras')
print('NOT - inverte o valor lógico de uma expressão (negação)\n')
tem_cafe = True
tem_pao = False
#OR
print(tem_cafe or tem_pao)
print(tem_cafe or tem_cafe)
print(tem_pao or tem_pao)
#AND
print(tem_cafe and tem_pao)
print(tem_cafe and tem_cafe)
#NOT
print(not tem_cafe)
print(not tem_pao)
print('--' *30 )
print('OPERADORES RELACIONAIS:\n')
#O Python possui 6 operadores relacionais
print('Maior que: >')
print('Maior ou Igual: >=')
print('Menor que: <')
print('Menor ou Igual: <=')
print('Igual: ==')
print('Diferente: != \n')
comparador1 = 5
comparador2 = 3
print(comparador1 > comparador2)
print(comparador1 >= comparador2)
print(comparador1 < comparador2)
print(comparador1 <= comparador2)
print(comparador1 == comparador2)
print(comparador1 != comparador2) |
298f3dd303082910f64b333d378934a1184f2694 | viniciuskurt/LetsCode-PracticalProjects | /1-PythonBasics/Laco_Rep_Loop_Infinito.py | 534 | 4.09375 | 4 | """
Laço de repetição com loop infinito e utilizando break
NÃO É RECOMENDADO UTILIZAR ESSA FORMA.
"""
contador = 0
# while contador < 10:
while True: # criando loop infinito
if contador < 10: # se a condição passar da condição, é executado tudo de novo
contador = contador + 1
if contador == 1:
print(contador, "item limpo")
else:
print(contador, "itens limpos")
else:
break # aqui quebramos o loop mais recente
print("Fim da repetição do bloco while") |
e2f5debc42e10a689eeb1836901ce285481da9ce | viniciuskurt/LetsCode-PracticalProjects | /1-PythonBasics/Validacao_Entrada.py | 207 | 3.984375 | 4 | # Exemplo básico de validação de senha de acesso
texto = input("Digite a sua entrada: ")
while texto != 'LetsCode':
texto = input("Senha inválida. Tente novamente\n")
print('Acesso permitido') |
5a008394476ccf00e21f8de67622c2c683f933fc | maxicraftone/informatics | /shortest_path.py | 13,569 | 4.15625 | 4 | #!/usr/bin/python
import math
import time
import sys
class Node:
def __init__(self, name: str) -> None:
"""
Node class. Just holds the name of the node
:param name: Name/ Title of the node (only for representation)
"""
self.name = name
# Set string representation of node to just its name
def __repr__(self) -> str:
return self.name
# Set comparation between nodes to happen between their names
# (Only secondary after sorting by the distance later)
def __gt__(self, node2) -> bool:
return self.name > node2.name
class Edge:
def __init__(self, node1: Node, node2: Node, distance: int, direction: int) -> None:
"""
Edge class for connecting nodes through edges with distances and
directions
:param node1: First node
:param node2: Second node
:param distance: Weight of the edge
:param direction: Direction of the connection:
0 = both,
1 = in direction of the first node,
2 = in direction of the second node
"""
self.node1 = node1
self.node2 = node2
self.distance = distance
self.direction = direction
def facing(self) -> tuple:
"""
Returns the node(s) being faced by the edge
:return: Nodes
"""
# If facing both nodes
if self.direction == 0:
return (self.node1, self.node2)
# If facing the first node
elif self.direction == 1:
return (self.node1,)
# If facing the second node
elif self.direction == 2:
return (self.node2,)
def set_node1(self, node1: Node) -> None:
"""
Set the node1 parameter of the edge
:param node1: Value for node1
"""
self.node1 = node1
def set_node2(self, node2: Node) -> None:
"""
Set the node2 parameter of the edge
:param node2: Value for node2
"""
self.node2 = node2
def set_distance(self, distance: int) -> None:
"""
Set the distance parameter of the edge
:param distance: Value for distance/ weight of the edge
"""
self.distance = distance
def set_direction(self, direction: int) -> None:
"""
Set the direction parameter of the edge
:param direction: Value for direction of the edge:
0 = both directions,
1 = in direction of the first node,
2 = in direction of the second node
"""
self.direction = direction
def is_first(self, node: Node) -> bool:
"""
Checks whether the given node is node1
:param node: Given node
:return: True if node == node1; False if node != node1
"""
return node == self.node1
def is_second(self, node: Node) -> bool:
"""
Checks whether the given node is node2
:param node: Given node
:return: True if node == node2; False if node != node2
"""
return node == self.node2
# Set string representation of the edge
def __repr__(self) -> str:
# If the edge is facing both nodes
if self.direction == 0:
return self.node1.name + ' <-----> ' + self.node2.name
# If the edge is facing the first node
elif self.direction == 1:
return self.node1.name + ' <------ ' + self.node2.name
# If the edge is facing the second node
elif self.direction == 2:
return self.node1.name + ' ------> ' + self.node2.name
class Graph:
def __init__(self) -> None:
"""
Graph class containing nodes and edges with methods of path finding
"""
# Define nodes and edges lists
self.nodes = []
self.edges = []
def add_node(self, node: Node) -> None:
"""
Add node to graph
:param node: Node to be added
"""
self.nodes.append(node)
def add_nodes(self, nodes: list) -> None:
"""
Add nodes to graph
:param nodes: List of nodes to be added
"""
self.nodes.extend(nodes)
def set_nodes(self, nodes: list) -> None:
"""
Set nodes of the graph
:param nodes: List of nodes to be set
"""
self.nodes = nodes
def add_edge(self, edge: Edge) -> None:
"""
Add a new edge to the graph
:param edge: Edge to be added
"""
self.edges.append(edge)
def add_edges(self, edges: list) -> None:
"""
Add edges to graph
:param edges: List of edges to be added
"""
self.edges.extend(edges)
def set_edges(self, edges: list) -> None:
"""
Set edges of the graph
:param nodes: List of edges to be set
"""
self.edges = edges
def get_neighbors(self, node: Node) -> dict:
"""
Get all neighbors of a node, with the corresponding edges
:param node: Node to get neighbors of
:return: Dictionary with {<node>: <edge>, ...}
"""
neighbors = {}
# For all nodes
if node in self.nodes:
# For all edges
for e in self.edges:
# If the node is the first in the edge declaration
if e.is_first(node):
# Add the other node to the dictionary of neighbors
neighbors[e.node2] = e
# If the node is the second in the edge declaration
elif e.is_second(node):
# Add the other node to the dictionary of neighbors
neighbors[e.node1] = e
return neighbors
def find_path(self, start: Node, end: Node, algorithm: str = 'dijkstra') -> list:
"""
Find the shortest path from start node to end node using the
Dijkstra or Bellman-Ford algorithm
:param start: Node to start from
:param end: Node to end at
:return: Path from start to end [[<nodes_passed>], <length>]
"""
if start in self.nodes and end in self.nodes:
# Init path
path = {}
# Set all node distances to infinity and the start distance to 0
for node in self.nodes:
path[node] = [math.inf, None]
path[start] = [0, None]
# Calc path
if algorithm == 'bellman-ford':
path = self.bellman_ford(start, path)
elif algorithm == 'dijkstra':
path = self.dijkstra(start, path)
else:
print('Wrong algorithm provided, using Dijkstra ...')
path = self.dijkstra(start, path)
if path is None:
return None
# Create list of passed notes in the path
path_nodes = [end]
n = end
while n != start:
path_nodes.append(path[n][1])
n = path[n][1]
path_nodes.reverse()
# Return list with passed notes and length of the path
return [path_nodes, path[end][0]]
elif start not in self.nodes:
print('Start node not in graph')
elif end not in self.nodes:
print('End node not in graph')
def dijkstra(self, start: Node, path: dict) -> dict:
"""
Calculates the shortest possible path from a given start node using the
Dijkstra-Algorithm
:param start: Start Node
:param path: Dictionary of {Node: [distance, previous_node], ...} to describe the path
:return: Modified path dictionary with calculated distances
"""
nodes = path
distances = {}
while len(nodes) > 0:
# Sort by ascending distances
nodes = self.sort_dict(nodes)
# Get the node with the smallest distance
u = list(nodes.keys())[0]
# Remove that node from the dict
nodes.pop(u)
neighbors = self.get_neighbors(u)
# For all neighbors of this node
for n in neighbors:
# If the neighbor was not already calculated and can be accessed by the edge
if n in nodes and n in neighbors[n].facing():
if u in distances:
# If the new distance would be smaller than the current one
if nodes[n][0] > neighbors[n].distance + distances[u][0]:
# Set new distance
nodes[n] = [neighbors[n].distance + distances[u][0], u]
distances[n] = nodes[n]
# Only happens if the node is a neighbor of the start node
else:
# Set initial distance
nodes[n] = [neighbors[n].distance, u]
distances[n] = nodes[n]
return distances
def bellman_ford(self, start: Node, path: dict) -> dict:
"""
Calculates the shortest possible path from a given start node using the
Bellman-Ford-Algorithm
:param start: Start Node
:param path: Dictionary of {Node: [distance, previous_node], ...} to describe the path
:return: Modified path dictionary with calculated distances
"""
for i in range(len(self.nodes)-1):
# Iterate over all nodes
for u in self.nodes:
# Iterate over all neighbors of the current node
neighbors = self.get_neighbors(u)
for n in neighbors:
# If the new distance would be smaller than the current one and the edge is facing the right direction
if (path[u][0] + neighbors[n].distance) < path[n][0] and n in neighbors[n].facing():
# Change the current distance to the new one
path[n] = [path[u][0] + neighbors[n].distance, u]
# Check if there are remaining smaller distances
for u in self.nodes:
neighbors = self.get_neighbors(u)
for n in neighbors:
if (path[u][0] + neighbors[n].distance) < path[n][0]:
# If there are any, there might be negative weight loops
if n in neighbors[n].facing():
print('Negative weight loop found')
return None
return path
@staticmethod
def sort_dict(dictionary: dict) -> dict:
"""
Function used to sort a dictionary by its values
:param dictionary: The dictionary to be used
:return: The sorted dictionary
"""
return {k: v for k, v in sorted(dictionary.items(), key=lambda item: item[1])}
def benchmark(function) -> None:
"""
Prints the time used to execute the given function
:param function: Function to be measured
"""
time_before = time.time_ns()
function()
time_delta = (time.time_ns() - time_before)
print('Benchmark: ' + str(time_delta/1000000) + ' ms')
if __name__ == '__main__':
graph = Graph()
mue = Node('München')
frb = Node('Freiburg')
stg = Node('Stuttgart')
fkf = Node('Frankfurt')
kbl = Node('Koblenz')
kln = Node('Köln')
dsd = Node('Düsseldorf')
brm = Node('Bremen')
hmb = Node('Hamburg')
kil = Node('Kiel')
swr = Node('Schwerin')
bln = Node('Berlin')
drs = Node('Dresden')
lpg = Node('Leipzig')
eft = Node('Erfurt')
hnv = Node('Hannover')
mgd = Node('Magdeburg')
graph.set_nodes([mue, frb, stg, fkf, kbl, kln, dsd, brm, hmb, kil, swr, bln, drs, lpg, eft, hnv, mgd])
graph.set_edges([
Edge(mue, frb, 280, 1), Edge(frb, stg, 140, 1), Edge(stg, mue, 240, 1),
Edge(stg, fkf, 100, 1), Edge(fkf, kbl, 70, 1), Edge(kln, kbl, 70, 1),
Edge(kln, dsd, 70, 2), Edge(kbl, dsd, 150, 1), Edge(kbl, eft, 120, 2),
Edge(dsd, eft, 160, 1), Edge(fkf, eft, 90, 1), Edge(fkf, mue, 290, 2),
Edge(eft, mue, 320, 1), Edge(lpg, mue, 530, 2), Edge(lpg, eft, 300, 0),
Edge(dsd, lpg, 450, 1), Edge(dsd, brm, 230, 2), Edge(brm, eft, 330, 2),
Edge(hmb, brm, 130, 2), Edge(kil, hmb, 130, 1), Edge(swr, kil, 320, 1),
Edge(bln, swr, 190, 1), Edge(bln, lpg, 160, 2), Edge(drs, lpg, 70, 1),
Edge(drs, bln, 150, 2), Edge(lpg, mgd, 150, 2), Edge(mgd, hnv, 100, 2),
Edge(hnv, bln, 190, 0), Edge(hmb, bln, 220, 0), Edge(eft, hnv, 300, 2),
Edge(dsd, hnv, 270, 2), Edge(hnv, brm, 130, 2), Edge(hnv, hmb, 140, 2),
#33 Edges
])
nodes = {}
for node in graph.nodes:
nodes[node.name.lower()] = node
# Script callable with args -> "python shortest_path.py <node1> <node2> [algorithm]"
# node1 and node2 have to be names of nodes of the graph (can be lowercase or uppercase)
# algorithm is optional and can either be 'dijkstra' or 'bellman-ford', default is 'dijkstra'
args = sys.argv[1:]
if len(args) == 2:
node1 = nodes[args[0].lower()]
node2 = nodes[args[1].lower()]
benchmark(lambda: print(graph.find_path(node1, node2)))
elif len(args) == 3:
node1 = nodes[args[0].lower()]
node2 = nodes[args[1].lower()]
algorithm = args[2].lower()
benchmark(lambda: print(graph.find_path(node1, node2, algorithm)))
|
8faa0216ee950c7fbfd1dec6cb28a47d9c5aff7f | DCTyxx/opencv_study | /class25_分水岭算法.py | 2,272 | 3.53125 | 4 | #分水岭变换
#基于距离变换
#分水岭的变换 输入图像->灰度化(消除噪声)->二值化->距离变换->寻找种子->生成Marker->分水岭变换->输出图像->end
import cv2 as cv
import numpy as np
def watershed_demo():
print(src.shape)
blurred = cv.pyrMeanShiftFiltering(src,10,100)#边缘保留滤波
gray = cv.cvtColor(src,cv.COLOR_BGR2GRAY)
ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)#二值图像
cv.namedWindow("binary-image", cv.WINDOW_NORMAL)
cv.imshow("binary-image",binary)
#形态学操作
kernel = cv.getStructuringElement(cv.MORPH_RECT,(3,3))#结构元素
mb = cv.morphologyEx(binary,cv.MORPH_OPEN,kernel,iterations=2)#连续俩次进行开操作
sure_bg = cv.dilate(mb,kernel,iterations=3)#使用特定的结构元素来扩展图像 拓展三次
cv.namedWindow("mor-opt", cv.WINDOW_NORMAL)
cv.imshow('mor-opt',sure_bg)
#距离变化
dist = cv.distanceTransform(mb,cv.DIST_L2,3)#L2 为欧几里得距离,为此移动大小为3
dist_output = cv.normalize(dist,0,1.0,cv.NORM_MINMAX)#规范化数组的范数或值范围 当normType = NORM_MINMAX时(仅适用于密集数组)
#cv.imshow("distance-t",dist_output*50)#显示距离变化的结果
ret,surface = cv.threshold(dist,dist.max()*0.6,255,cv.THRESH_BINARY)#该函数通常用于从灰度图像中获取双级(二值)图像
#获得种子
#cv.imshow("surface-bin",surface)
surface_fg = np.uint8(surface)
unknown = cv.subtract(sure_bg,surface_fg)#除了种子以外的区域
ret,markers = cv.connectedComponents(surface_fg)#连通区域
print(ret)
#分水岭变化
markers = markers+1
markers[unknown==255] = 0
markers = cv.watershed(src,markers=markers)#分水岭
src[markers==-1]=[0,0,255] #将值为0的区域 赋值为255
cv.namedWindow("result", cv.WINDOW_NORMAL)
cv.imshow("result",src)
#读取图片,读取的数据为numpy的多元数组
src = cv.imread('F:\software\pic\Aluminum_alloy\pic\pic/3-2.jpg')
#opencv命名
cv.namedWindow("input image",cv.WINDOW_NORMAL)
#显示图片
cv.imshow("input image",src)
watershed_demo()
#等待用户响应
cv.waitKey(0)
#释放所有的类层
cv.destroyAllWindows() |
9bf5a15c654b19ab6457ad83a3d0a763bb301892 | wangyunge/algorithmpractice | /eet/Restore_IP_Addresses.py | 1,293 | 3.90625 | 4 | '''
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135",
return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
Subscribe to see which companies asked this question
Show Tags
'''
class Solution(object):
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
#Constraint:
#1.Less than 255. 2.Start with non-zero element.
self.res = []
self.s = s
stack = []
Depth = 0
index =0
self.DFS(stack,index,Depth)
return self.res
def DFS(self,stack,index,Depth):
if Depth == 4:
if index == len(self.s):
self.res.append(".".join(stack))
return None
if index < len(self.s) and self.s[index] == "0":
self.DFS(stack+["0"],index+1,Depth+1)
else:
for i in xrange(0,3):
if index+i < len(self.s) and int(self.s[index:index+i+1]) <= 255:
self.DFS(stack+[self.s[index:index+i+1]],index+i+1,Depth+1)
def main():
sol = Solution()
example = "25525511135"
res = sol.restoreIpAddresses(example)
print res
if __name__ == '__main__':
main() |
e8116a0ec63ed32ab24c42650a5e9c51789b5cd8 | wangyunge/algorithmpractice | /int/389_Valid_Sudoku.py | 858 | 3.890625 | 4 | '''
Determine whether a Sudoku is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character ..
Notice
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
Have you met this question in a real interview? Yes
Clarification
What is Sudoku?
http://sudoku.com.au/TheRules.aspx
https://zh.wikipedia.org/wiki/%E6%95%B8%E7%8D%A8
https://en.wikipedia.org/wiki/Sudoku
http://baike.baidu.com/subview/961/10842669.htm
Example
The following partially filed sudoku is valid.
Valid Sudoku
'''
class Solution:
def isValidSudoku(self, board):
seen = sum(([(c, i), (j, c), (i/3, j/3, c)]
for i, row in enumerate(board)
for j, c in enumerate(row)
if c != '.'), [])
return len(seen) == len(set(seen)) |
79db945c27a3797a29b9de46201352fa9e4f0a1b | wangyunge/algorithmpractice | /int/110_Minimum_Path_Sum.py | 888 | 3.859375 | 4 | '''
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Notice
You can only move either down or right at any point in time.
Have you met this question in a real interview? Yes
'''
class Solution:
"""
@param grid: a list of lists of integers.
@return: An integer, minimizes the sum of all numbers along its path
"""
def minPathSum(self, grid):
if not grid:
return 0
for i in xrange(1,len(grid)):
grid[i][0] = grid[i-1][0]+grid[i][0]
for j in xrange(1,len(grid[0])):
grid[0][j] = grid[0][j-1]+grid[0][j]
for i in xrange(1,len(grid)):
for j in xrange(1,len(grid[0])):
grid[i][j] = min(grid[i-1][j],grid[i][j-1]) + grid[i][j]
return grid[len(grid)-1][len(grid[0])-1] |
352bf4ce999b1f9d03c6b96f79e8cdbb2f7230bf | wangyunge/algorithmpractice | /int/98_Sorted_List.py | 1,324 | 3.953125 | 4 | '''
Sort a linked list in O(n log n) time using constant space complexity.
Have you met this question in a real interview? Yes
Example
Given 1->3->2->null, sort it to 1->2->3->null.
'''
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of the linked list.
@return: You should return the head of the sorted linked list,
using constant space complexity.
"""
def sortList(self, head):
if not head:
return head
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
h2 = self.sortList(slow.next)
slow.next = None
return self.merge(self.sortList(head),h2)
def merge(self,leftHead,righHead):
helper = ListNode(0,None)
index = helper
while leftHead and righHead:
if leftHead.val <= righHead:
index.next = leftHead
leftHead = leftHead.next
else:
index.next = righHead
righHead = righHead.next
index = index.next
index.next = leftHead if leftHead else righHead
return helper.next |
1bd27fbaa4aa4a3017d24929b4698cf48c3c1dbb | wangyunge/algorithmpractice | /int/82_Single_Number.py | 476 | 3.65625 | 4 | '''
Given 2*n + 1 numbers, every numbers occurs twice except one, find it.
Have you met this question in a real interview? Yes
Example
Given [1,2,2,1,3,4,3], return 4
'''
class Solution:
"""
@param A : an integer array
@return : a integer
"""
def singleNumber(self, A):
res = 0
for number in A:
res = res ^ number
return res
'''
Note:
1. Exclusive or produce 1 when two bits are different and 0 when they are same.
''' |
6e34a6e1dcf7b985b56e0b928a27b284d0c96c99 | wangyunge/algorithmpractice | /eet/Best_Time_to_Buy_and_Sell_Stock_IV.py | 1,809 | 4.0625 | 4 | '''
Say you have an array for which the i-th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Example 1:
Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
Example 2:
Input: [3,2,6,5,0,3], k = 2
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4.
Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.'''
class Solution(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
"""
Note:
1. You can Sell and Buy at the same day.
2. Keep recording the max profit while holding the stocks(means you can sell the next day), when you take last transcation.
t[i][j] = Math.max(t[i][j - 1], prices[j] + tmpMax); # Sell before or Sell now
tmpMax = Math.max(tmpMax, t[i - 1][j] - prices[j]); # Buy before or buy now
"""
class Solution(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
dp = [[0 for _ in range(prices)] for _ in range(k)]
b_max = float('-inf')
for j in range(1,len(prices)):
dp[0][j] = max(dp[0][j-1], b_max + prices[j])
b_max = max(b_max, 0-prices[j])
for i in range(1,k):
for j in range(1, len(prices)):
dp[i][j] = max(dp[i][j-1], b_max + prices[j])
b_max = max(b_max, dp[i-1][j]-prices[j])
return dp[-1][-1]
|
ea76677bfc6bfc1c602ddd530ccc593258bd27c0 | wangyunge/algorithmpractice | /eet/01_Matrix.py | 526 | 4 | 4 | """
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
Example 1:
Input:
[[0,0,0],
[0,1,0],
[0,0,0]]
Output:
[[0,0,0],
[0,1,0],
[0,0,0]]
Example 2:
Input:
[[0,0,0],
[0,1,0],
[1,1,1]]
Output:
[[0,0,0],
[0,1,0],
[1,2,1]]
"""
class Solution(object):
def updateMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
for i in range(len(matrix)):
|
431e4b3687f6e41381331f315f13108fc029d396 | wangyunge/algorithmpractice | /eet/Check_Completeness_of_a_Binary_Tree.py | 1,354 | 4.21875 | 4 | """
Given the root of a binary tree, determine if it is a complete binary tree.
In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Example 1:
Input: root = [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
Example 2:
Input: root = [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isCompleteTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
self.max_val = 0
self.sum = 0
def _dfs(node, value):
if node:
self.max_val = max(self.max_val, value)
self.sum += value
_dfs(node.left, 2 * value)
_dfs(node.right, 2 * value + 1)
_dfs(root, 1)
return self.sum == self.max_val/2 * (1+self.max_val)
|
d9cdb986d5d7d796156e0ef1cc51c21cd096f9b7 | wangyunge/algorithmpractice | /eet/Longest_Increasing_Path_in_a_Matrix.py | 3,306 | 4.125 | 4 | """
Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).
Example 1:
Input: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2:
Input: nums =
[
[3,4,5],
[3,2,6],
[2,2,1]
]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
"""
class Solution(object):
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not matrix:
return 0
if len(matrix[0]) == 0:
return 0
dec_DP = [[1 for _ in range(len(matrix[0]))] for _ in range(len(matrix))]
inc_DP = [[1 for _ in range(len(matrix[0]))] for _ in range(len(matrix))]
for j in range(1, len(matrix[0])):
if matrix[0][j] > matrix[0][j-1]:
dec_DP[0][j] = dec_DP[0][j-1] + 1
for j in range(0, len(matrix[0])-1)[::-1]:
if matrix[0][j] > matrix[0][j+1]:
inc_DP[0][j] = inc_DP[0][j+1] + 1
for i in range(1, len(matrix)):
if matrix[i][0] > matrix[i-1][0]:
dec_DP[i][0] = dec_DP[i-1][0] + 1
for i in range(0, len(matrix[0])-1)[::-1]:
if matrix[i][0] > matrix[i+1][0]:
inc_DP[i][0] = inc_DP[i+1][0] + 1
for i in range(1, len(matrix)):
for j in range(1, len(matrix[0])):
if matrix[i][j] > matrix[i-1][j] :
last_up = dec_DP[i-1][j]
else:
last_up = 0
if matrix[i][j] > matrix[i][j-1] :
last_left = dec_DP[i][j-1]
else:
last_left = 0
dec_DP[i][j] = max(last_left, last_up) + 1
for i in range(0, len(matrix)-1)[::-1]:
for j in range(0, len(matrix[0])-1)[::-1]:
if matrix[i][j] > matrix[i+1][j] :
last_up = inc_DP[i+1][j]
else:
last_up = 0
if matrix[i][j] > matrix[i][j+1] :
last_left = inc_DP[i][j+1]
else:
last_left = 0
inc_DP[i][j] = max(last_left, last_up) + 1
res = 0
for i in range(0, len(matrix)):
for j in range(0, len(matrix[0])):
res = max(res, inc_DP[i][j] + dec_DP[i][j] -1 )
return res
def longestIncreasingPath(self, matrix):
def dfs(i, j):
if not dp[i][j]:
val = matrix[i][j]
dp[i][j] = 1 + max(
dfs(i - 1, j) if i and val > matrix[i - 1][j] else 0,
dfs(i + 1, j) if i < M - 1 and val > matrix[i + 1][j] else 0,
dfs(i, j - 1) if j and val > matrix[i][j - 1] else 0,
dfs(i, j + 1) if j < N - 1 and val > matrix[i][j + 1] else 0)
return dp[i][j]
if not matrix or not matrix[0]: return 0
M, N = len(matrix), len(matrix[0])
dp = [[0] * N for i in range(M)]
return max(dfs(x, y) for x in range(M) for y in range(N)) |
597bdffceea740761f6280470d81b9deaf73f400 | wangyunge/algorithmpractice | /int/517_Ugly_Number.py | 926 | 4.125 | 4 | '''
Write a program to check whether a given number is an ugly number`.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
Notice
Note that 1 is typically treated as an ugly number.
Have you met this question in a real interview? Yes
Example
Given num = 8 return true
Given num = 14 return false
'''
class Solution:
# @param {int} num an integer
# @return {boolean} true if num is an ugly number or false
def isUgly(self, num):
if num < 1:
return False
while True:
if num % 2 == 0:
num = num/2
elif num % 3 == 0:
num = num/3
elif num % 5 == 0:
num = num/5
else:
break
if num != 1:
return False
else:
return True
|
6ae3a55543601626d59949db457edce81a02b2b9 | wangyunge/algorithmpractice | /eet/Add_Two_Numbers_II.py | 1,225 | 4.03125 | 4 | """
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
def _reverse(l1):
prev = None
while l1:
tmp = l1.next
l1.next = prev
prev = l1
l1 = tmp
return prev
l1 = _reverse(l1)
l2 = _reverse(l2)
carry = 0
while l1 and l2:
carry = (l1.val+l2.val) // 10
if __name__ == '__main__':
main() |
53b1b4043d4949f1aec2b18d909993cc049772e8 | wangyunge/algorithmpractice | /cn/572.py | 978 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
def _check(source, target):
if source and target:
if source.val == target.val:
return _check(source.left, target.left) and _check(source.right, target.right)
else:
return False
elif not source and not target:
return True
else:
return False
def _dfs(a, b):
if a:
if _check(a, b):
return True
return _check(a.left, b) or _check(a.right, b)
if not t:
return True
return _dfs(s, t)
|
2e3a39178816c77f9f212cb1629a8f17950da152 | wangyunge/algorithmpractice | /int/171_Anagrams.py | 692 | 4.34375 | 4 | '''
Given an array of strings, return all groups of strings that are anagrams.
Notice
All inputs will be in lower-case
Have you met this question in a real interview? Yes
Example
Given ["lint", "intl", "inlt", "code"], return ["lint", "inlt", "intl"].
Given ["ab", "ba", "cd", "dc", "e"], return ["ab", "ba", "cd", "dc"].
'''
class Solution:
# @param strs: A list of strings
# @return: A list of strings
def anagrams(self, strs):
table = {}
res = []
for word in strs:
setOfWord = set(word)
if setOfWord not in table:
table[setOfWord] = word
else:
res.append(word)
return res
|
f99cf09f6bdb40dd270f2a7845f6aa530f614795 | wangyunge/algorithmpractice | /eet/Find_K_Pairs_with_Smallest_Sums.py | 1,749 | 3.875 | 4 | """
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.
Define a pair (u,v) which consists of one element from the first array and one element from the second array.
Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums.
Example 1:
Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
Output: [[1,2],[1,4],[1,6]]
Explanation: The first 3 pairs are returned from the sequence:
[1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
Example 2:
Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
Output: [1,1],[1,1]
Explanation: The first 2 pairs are returned from the sequence:
[1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
Example 3:
Input: nums1 = [1,2], nums2 = [3], k = 3
Output: [1,3],[2,3]
Explanation: All possible pairs are returned from the sequence: [1,3],[2,3]
"""
from heapq import *
class Solution:
def kSmallestPairs(self, nums1, nums2, k):
if not nums1 or not nums2:
return []
visited = []
heap = []
output = []
heappush(heap, (nums1[0] + nums2[0], 0, 0))
visited.append((0, 0))
while len(output) < k and heap:
val = heappop(heap)
output.append((nums1[val[1]], nums2[val[2]]))
if val[1] + 1 < len(nums1) and (val[1] + 1, val[2]) not in visited:
heappush(heap, (nums1[val[1] + 1] + nums2[val[2]], val[1] + 1, val[2]))
visited.append((val[1] + 1, val[2]))
if val[2] + 1 < len(nums2) and (val[1], val[2] + 1) not in visited:
heappush(heap, (nums1[val[1]] + nums2[val[2] + 1], val[1], val[2] + 1))
visited.append((val[1], val[2] + 1))
return output |
cbc345e64aaa1883a5626e834e998addae622309 | wangyunge/algorithmpractice | /int/488_Happpy_Number.py | 979 | 3.78125 | 4 | '''
Write an algorithm to determine if a number is happy.
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Have you met this question in a real interview? Yes
Example
19 is a happy number
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
'''
class Solution:
# @param {int} n an integer
# @return {boolean} true if this is a happy number or false
def isHappy(self, n):
table = {}
while n not in table:
if n == 1:
return True
table[n] = 1
nextN = 0
while n > 0:
nextN += pow(n%10,2)
n = n/10
n = nextN
return False |
14e00c017aa35b3d0901ec3b9f83bf5d51c345be | wangyunge/algorithmpractice | /cn/234.py | 653 | 3.671875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
stack = []
cur = head
while cur:
stack.append(cur.val)
cur = cur.next
cnt = 0
cur = head
L = len(stack)
while cnt < L // 2:
if stack.pop() != cur.val:
return False
cur = cur.next
cnt += 1
return True
|
1f4cd6fa5f100f5fec1f7ebcadf8eb99dbf09fe6 | wangyunge/algorithmpractice | /eet/Counting_Bits.py | 1,765 | 3.765625 | 4 | """
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
Example 1:
Input: 2
Output: [0,1,1]
Example 2:
Input: 5
Output: [0,1,1,2,1,2]
Follow up:
It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
"""
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
even = 0
odds = 0
tmp = 1
for i in range(34):
if i % 2 == 0:
even += tmp
if i % 2 == 1:
odds += tmp
tmp = tmp * 2
res = [0 for _ in range(len(num))]
for i in range(len(num)):
a = even & item
b = odds & item
res[i] = res[a] + res[b]
return res
"""
Notes:
Dynamic Programming:
Current numbers has one more 1 than the one minus the highest postion 1000
1 1101 -- 0 1101
1 0001 -- 0 0001
"""
0
1 res[0] +1 01
2 res[0] + 1 10
3 res[1] + 1
4 res[2] + 1
5
6
7
8
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
k = 0
idx = 1
res = [0] * num
res[1] = 1
while idx <= num:
offset = 0
while idx < pow(2,k+1):
res[idx] = res[idx-pow(2,k)] + 1
idx += 1
offset += 1
k += 1
return res
|
c730b160e62fd19ed56a4dbd8740dceed38583c2 | wangyunge/algorithmpractice | /eet/Android_Unlock_Patterns.py | 1,583 | 4 | 4 | """
我们都知道安卓有个手势解锁的界面,是一个 3 x 3 的点所绘制出来的网格。用户可以设置一个 “解锁模式” ,通过连接特定序列中的点,形成一系列彼此连接的线段,每个线段的端点都是序列中两个连续的点。如果满足以下两个条件,则 k 点序列是有效的解锁模式:
解锁模式中的所有点 互不相同 。
假如模式中两个连续点的线段需要经过其他点,那么要经过的点必须事先出现在序列中(已经经过),不能跨过任何还未被经过的点。
以下是一些有效和无效解锁模式的示例:
无效手势:[4,1,3,6] ,连接点 1 和点 3 时经过了未被连接过的 2 号点。
无效手势:[4,1,9,2] ,连接点 1 和点 9 时经过了未被连接过的 5 号点。
有效手势:[2,4,1,3,6] ,连接点 1 和点 3 是有效的,因为虽然它经过了点 2 ,但是点 2 在该手势中之前已经被连过了。
有效手势:[6,5,4,1,9,2] ,连接点 1 和点 9 是有效的,因为虽然它经过了按键 5 ,但是点 5 在该手势中之前已经被连过了。
给你两个整数,分别为 m 和 n ,那么请你统计一下有多少种 不同且有效的解锁模式 ,是 至少 需要经过 m 个点,但是 不超过 n 个点的。
两个解锁模式 不同 需满足:经过的点不同或者经过点的顺序不同。
"""
class Solution(object):
def numberOfPatterns(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
""" |
1ae166cb04757e11a8ca03fe3c83cbd2e3c602f1 | wangyunge/algorithmpractice | /int/106_Convert_Sorted_List_to_Balanced_BST.py | 1,193 | 3.890625 | 4 | '''
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Have you met this question in a real interview? Yes
Example
2
1->2->3 => / \
1 3
'''
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param head: The first node of linked list.
@return: a tree node
"""
def sortedListToBST(self, head):
if not head:
return None
if not head.next:
return TreeNode(head.val)
index = head.next
mid = head
while index:
if index.next and index.next.next:
index = index.next.next
else:
break
mid = mid.next
root = TreeNode(mid.next.val)
right = mid.next.next
mid.next = None
root.left = self.sortedListToBST(head)
root.right = self.sortedListToBST(right)
return root
|
3e5582033c67af1213ba003cff4b3095dabb15b5 | wangyunge/algorithmpractice | /eet/Lowest_Common_Ancestor_of_a_Binary_Tree.py | 2,220 | 4.0625 | 4 | """
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.
Example 2:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
Note:
All of the nodes' values will be unique.
p and q are different and both values will exist in the binary tree.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
self.p = p
self.q = q
res, _, _ = self._dfs(root)
return res
def _dfs(self, root):
if not root:
return None, False, False
left_res, left_p, left_q = self._dfs(root.left)
right_res, right_p, right_q = self._dfs(root.right)
cur_p = True if root.val == p.val else False
cur_q = True if root.val == q.val else False
if left_res is not None:
return left_res, True, True
if right_res is not None:
return right_res, True, True
find_p = False
if cur_p or left_p or right_p:
find_p = True
find_q = False
if cur_q or left_q or right_q:
find_q = True
if find_p and find_q:
return root, True, True
return None, find_p, find_q
"""
Note:
Recurring can pass message back by using return. So we don't need to do the dfs twice(Check and Search)
""" |
854d5d19c39b60ed8b67150778a4bb015918c88b | wangyunge/algorithmpractice | /eet/Nth_Digit.py | 852 | 3.9375 | 4 | """
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).
Example 1:
Input:
3
Output:
3
Example 2:
Input:
11
Output:
0
Explanation:
The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
"""
class Solution(object):
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
carry = 9
incre = 1
def _move():
carry = (carry + 1) * 10 -1
incre += 1
idx = 0
last_idx = 0
number = 1
while idx < n:
if number > carry:
_move
idx += incre
number += 1
return str(number-1)[(n-(idx-incre))]
|
e39cd00b68b6eff21de3d1b8364de609b687a309 | wangyunge/algorithmpractice | /int/392_House_Robber.py | 1,002 | 3.625 | 4 | '''
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
Have you met this question in a real interview? Yes
Example
Given [3, 8, 4], return 8.
'''
class Solution:
# @param A: a list of non-negative integers.
# return: an integer
def houseRobber(self, A):
if not A:
return 0
DP = [[0,0] for i in xrange (len(A))]
DP[0][0] = 0
DP[0][1] = A[0]
for i in xrange(1,len(A)):
DP[i][0] = max(DP[i-1])
DP[i][1] = DP[i-1][0] + A[i]
return max(DP[len(A)-1]) |
e3ee7499abf955e0662927b7341e93fa81843620 | wangyunge/algorithmpractice | /eet/Arithmetic_Slices.py | 960 | 4.15625 | 4 | """
An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.
Given an integer array nums, return the number of arithmetic subarrays of nums.
A subarray is a contiguous subsequence of the array.
Example 1:
Input: nums = [1,2,3,4]
Output: 3
Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.
Example 2:
Input: nums = [1]
Output: 0
"""
class Solution(object):
def numberOfArithmeticSlices(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
diff = [nums[i] - num[i-1] for i in range(1, len(nums))]
consecutive = [0] * len(nums)
for i in range(2, len(nums)):
consecutive[i] = 2 * consecutive[i-1] - consecutive[i-2] + 1
for i in range(diff):
|
6c899e296237b144ba623fbbab473202cd0410ca | wangyunge/algorithmpractice | /eet/Insertion_Sorted_List.py | 887 | 3.9375 | 4 | '''
Sort a linked list using insertion sort.
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
newHead = ListNode(float("-inf"))
while head:
curr = head
head = head.next
L = newHead
while L:
if L.next:
if curr.val <= L.next.val:
tmp = L.next
L.next = curr
curr.next = tmp
break
else:
L.next = curr
curr.next = None
break
L = L.next
return newHead.next
|
36039a9ac17ee24da100aebe9dd7b00cd17ab7f3 | wangyunge/algorithmpractice | /eet/Palindrome_Partitioning_II.py | 1,029 | 3.859375 | 4 | """
Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
Example 1:
Input: s = "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
Example 2:
Input: s = "a"
Output: 0
Example 3:
Input: s = "ab"
Output: 1
Constraints:
1 <= s.length <= 2000
s consists of lower-case English letters only.
"""
class Solution(object):
def minCut(self, s):
"""
:type s: str
:rtype: int
"""
# build the palindrme end for every start
reach = [[] for _ in range(len(s))]
for i in range(len(s)):
for j in range(i, len(s))[::-1]:
if _check(i, j):
reach[j].append(j)
dp = [idx for idx in range(len(s))]
dp.append(0) # rr-1 = -1
for i in range(1, len(s)):
for rr in reach[i]:
dp[i] = min(dp[i] , dp[rr-1] + 1)
return dp[-2]
|
9735ec4ad9479d0b9fe83a05b0f7a597d2b0ddd7 | wangyunge/algorithmpractice | /int/408_Add_Binary.py | 1,126 | 3.671875 | 4 | '''
Given two binary strings, return their sum (also a binary string).
Have you met this question in a real interview? Yes
Example
a = 11
b = 1
Return 100
'''
class Solution:
# @param {string} a a number
# @param {string} b a number
# @return {string} the result
def addBinary(self, a, b):
longS = a if len(a) >= len(b) else b
shortS = b if len(a) >= len(b) else a
index = 1
carry = 0
res = []
while index <= len(longS):
if index <= len(shortS):
cal = int(longS[-index]) + int(shortS[-index]) + carry
else:
cal = int(longS[-index]) + carry
if cal == 0:
add = '0'
carry = 0
if cal == 1:
add = '1'
carry = 0
if cal == 2:
add = '0'
carry = 1
if cal == 3:
add = '1'
carry = 1
index += 1
res.append(add)
if carry == 1:
res.append('1')
res.reverse()
return ''.join(res)
|
9495b0f644bec8ff8727429271b3b4ffd1f11bbc | wangyunge/algorithmpractice | /int/426_Restore_IP_Address.py | 1,307 | 3.875 | 4 | '''
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Have you met this question in a real interview? Yes
Example
Given "25525511135", return
[
"255.255.11.135",
"255.255.111.35"
]
Order does not matter.
'''
class Solution:
# @param {string} s the IP string
# @return {string[]} All possible valid IP addresses
def restoreIpAddresses(self, s):
self.s = s
start = 0
self.res = []
if not s:
return []
if self.s[0] == '0':
self.DFS('0',1,1)
else:
for i in xrange(start+1,len(self.s)+1):
if int(self.s[start:i]) <= 255:
self.DFS(self.s[start:i],i,1)
else:
break
return self.res
def DFS(self,res,start,dot):
if start == len(self.s) and dot == 4:
self.res.append(res)
elif start != len(self.s) and dot != 4:
if self.s[start] == '0':
self.DFS(res +'.0',start+1,dot+1)
else:
for i in xrange(start+1,len(self.s)+1):
if int(self.s[start:i]) <= 255:
self.DFS(res+'.'+self.s[start:i],i,dot+1)
else:
break |
6eb1182dc9674ff9514f860b80c6eacaa3b54487 | wangyunge/algorithmpractice | /eet/Recover_Binary_Search_Tree.py | 3,165 | 3.8125 | 4 | '''
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
Subscribe to see which companies asked this question
Show Tags
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: None Do not return anything, modify root in-place instead.
"""
self.left = None
self.right = None
self.prev = None
def _inorder_traverse(node):
if node:
_inorder_traverse(node.left)
if self.prev and self.prev.val > node.val:
if not self.left:
self.left = self.prev
else:
self.right = node
_inorder_traverse(node.right)
_inorder_traverse(root)
self.left.val, self.right.val = self.right.val, self.left.val
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: None Do not return anything, modify root in-place instead.
"""
self.left = None
self.right = None
def _search_left(node):
if node:
_search_left(node.left)
if self.left and self.left.val > node.val:
return self.left
self.left = node
_search_left(node.right)
def _search_right(node):
if node:
_search_right(node.right)
if self.right and self.right.val < node.val:
return self.right
self.right = node
_search_right(node.right)
_search_left(root)
_search_right(root)
self.left.val, self.right.val = self.right.val, self.left.val
# 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 recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
self.last = float("-inf")
self.swapped = []
if root:
self.inOrderTraversal(root)
self.swapped[0].val,self.swapped[1] = self.swapped[1],self.swapped[0]
def inOrderTraversal(self,root):
if root.left:
self.inOrderTraversal(root.left)
if self.last > root.val:
self.swapped.append(root)
else:
self.last = root.val
if root.right:
self.inOrderTraversal(root.right)
|
3859966faca648ffe0b7e83166049c07676ba93b | wangyunge/algorithmpractice | /eet/Maximum_Units_on_a_Truck.py | 2,304 | 4.125 | 4 | """
You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]:
numberOfBoxesi is the number of boxes of type i.
numberOfUnitsPerBoxi is the number of units in each box of the type i.
You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize.
Return the maximum total number of units that can be put on the truck.
Example 1:
Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
Output: 8
Explanation: There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.
Example 2:
Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10
Output: 91
"""
class Solution(object):
def maximumUnits(self, boxTypes, truckSize):
"""
:type boxTypes: List[List[int]]
:type truckSize: int
:rtype: int
"""
if truckSize < 0:
return 0
last_dp = [0 for _ in range(truckSize+1)]
dp = [0 for _ in range(truckSize+1)]
for i in range(len(boxTypes)):
for j in range(1, truckSize+1):
for num in range(1, boxTypes[i][0]+1):
spare_track = j - num
if spare_track >= 0:
dp[j] = max(dp[j],last_dp[spare_track]+num*boxTypes[i][1])
last_dp = dp[:]
return dp[-1]
"""
Notes:
last dp and dp, need two states.
"""
class Solution(object):
def maximumUnits(self, boxTypes, truckSize):
"""
:type boxTypes: List[List[int]]
:type truckSize: int
:rtype: int
"""
order_box = sorted(boxTypes, key=lambda x: x[1])
space = 0
res = 0
for box_num, box_unit in order_box:
for num in range(1, box_num+1):
if 1 + space <= truckSize:
space += 1
res += box_unit
return res
|
fd3f8f5c834978e65253411de28c9177994120f9 | wangyunge/algorithmpractice | /int/186_Max_Points_on_a_Line.py | 1,782 | 3.609375 | 4 | '''
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Example
Given 4 points: (1,2), (3,6), (0,0), (1,3).
The maximum number is 3.
'''
# Definition for a point.
# class Point:
# def __init__(self, a=0, b=0):
# self.x = a
# self.y = b
class Solution:
# @param {int[]} points an array of point
# @return {int} an integer
def maxPoints(self, points):
res = 0
for i in xrange(len(points)):
table = {}
table['v'] = 1
same = 0
for j in xrange(i+1,len(points)):
if points[i].x == points[j].x and points[i].y == points[j].y:
same +=1
elif points[i].x == points[j].x:
table['v'] += 1
else:
slope = 1.0 * (points[i].y - points[j].y)/(points[i].x - points[j].x)
if slope in table:
table[slope] += 1
else:
table[slope] = 1
localMax = max(table.values()) + same
res = max(res,localMax)
return res
def maxPoints(self, points):
l = len(points)
m = 0
for i in range(l):
dic = {'i': 1}
same = 0
for j in range(i+1, l):
tx, ty = points[j].x, points[j].y
if tx == points[i].x and ty == points[i].y:
same += 1
continue
if points[i].x == tx: slope = 'i'
else:slope = (points[i].y-ty) * 1.0 /(points[i].x-tx)
if slope not in dic: dic[slope] = 1
dic[slope] += 1
m = max(m, max(dic.values()) + same)
return m |
76c084094d90c838b553d1e58b78252f55852e3d | wangyunge/algorithmpractice | /eet/Contiguous_Array.py | 893 | 4.0625 | 4 | """
Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
Example 1:
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Example 2:
Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
Note: The length of the given binary array will not exceed 50,000.
"""
class Solution(object):
def findMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
B = [1 if item==1 else -1 for item in nums]
table = {0:-1}
res = 0
level = 0
for idx in range(len(B)):
level += B[idx]
if level in table:
res = max(res, idx - table[level])
else:
table[level] = idx
return res
|
181bd6428a741980af6e7ce9d2947b88a579cc8e | wangyunge/algorithmpractice | /eet/Pairs_of_Songs_With_Total_Durations_Divisible_by_60.py | 1,133 | 3.8125 | 4 | """
You are given a list of songs where the ith song has a duration of time[i] seconds.
Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0.
Example 1:
Input: time = [30,20,150,100,40]
Output: 3
Explanation: Three pairs have a total duration divisible by 60:
(time[0] = 30, time[2] = 150): total duration 180
(time[1] = 20, time[3] = 100): total duration 120
(time[1] = 20, time[4] = 40): total duration 60
Example 2:
Input: time = [60,60,60]
Output: 3
Explanation: All three pairs have a total duration of 120, which is divisible by 60.
"""
class Solution(object):
def numPairsDivisibleBy60(self, time):
"""
:type time: List[int]
:rtype: int
"""
table = {}
res = 0
for idx in range(len(time)):
offset = time[idx] % 60
key = 60 - offset if offset != 0 else 0
res += table.get(key, 0)
cnt = table.get(offset, 0)
table[offset] = cnt + 1
return res
|
e8f4d5ca11f339e1fa8c13b85ae55e7de66c0bcd | wangyunge/algorithmpractice | /int/73_Construct_Binary_Tree_from_Preorder_and_Inorder_Travesal.py | 1,895 | 3.921875 | 4 | '''
Given preorder and inorder traversal of a tree, construct the binary tree.
Notice
You may assume that duplicates do not exist in the tree.
Have you met this question in a real interview? Yes
Example
Given in-order [1,2,3] and pre-order [2,1,3], return a tree:
2
/ \
1 3
'''
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param preorder : A list of integers that preorder traversal of a tree
@param inorder : A list of integers that inorder traversal of a tree
@return : Root of a tree
"""
def buildTree(self, preorder, inorder):
if not preorder:
return None
root = TreeNode(preorder[0])
for j in xrange(len(inorder)):
if inorder[j] == preorder[0]:
break
self.DFS(preorder[1:],inorder[:j],root,True)
self.DFS(preorder[1:],inorder[j+1:],root,False)
return root
def DFS(self,preorder,inorder,parent,left):
found = False
for i in xrange(0,len(preorder)):
for j in xrange(0,len(inorder)):
if inorder[j] == preorder[i]:
found = True
break
if found:
break
if found:
root = TreeNode(inorder[i])
if left:
parent.left = root
else:
parent.right = root
self.DFS(preorder[i+1:],inorder[:j],root,True)
self.DFS(preorder[i+1:],inorder[j+1:],root,False)
def buildTree(self, preorder, inorder):
if inorder:
ind = inorder.index(preorder.pop(0))
root = TreeNode(inorder[ind])
root.left = self.buildTree(preorder, inorder[0:ind])
root.right = self.buildTree(preorder, inorder[ind+1:])
return root
|
d620071842e6003015b2a9f34c72b85a64e00a04 | wangyunge/algorithmpractice | /eet/Multiply_Strings.py | 1,183 | 4.125 | 4 | """
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Constraints:
1 <= num1.length, num2.length <= 200
num1 and num2 consist of digits only.
Both num1 and num2 do not contain any leading zero, except the number 0 itself.
"""
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
l1 = len(num1)
l2 = len(num2)
res = [0] * (l1 + l2 +1)
for i in range(l1)[::-1]:
for j in range(l2)[::-1]:
pdc = int(num1[i]) * int(num2[j])
plus = res[i+j] + pdc
res[i+j] += pdc % 10
res[i+j+1] = pdc / 10
res = map(res, lambda x: str(x))
if res[0] == '0':
return ''.join(res[1:])
else:
return ''.join(res)
|
b956afb98967e9ca2fb6c320bcd360691e20b9f0 | wangyunge/algorithmpractice | /cn/29.py | 558 | 3.546875 | 4 | class Solution(object):
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
sign = 1 if dividend * divisor > 0 else -1
divisor = abs(divisor)
dividend = abs(dividend)
def _sub(res):
x = divisor
if res < divisor:
return 0
ans = 1
while 2 * x <= res:
x = 2 * x
ans = 2 * ans
return ans + _sub(res-x)
return _sub(dividend)
|
bdfc9caa3090f7727fd227548a83aaf19bf66c14 | wangyunge/algorithmpractice | /eet/Unique_Binary_Search_Tree_II.py | 1,269 | 4.25 | 4 | '''
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
Subscribe to see which companies asked this question
'''
# 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 generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
def generateByList(self,list):
root = TreeNode(list[0])
for i in xrange(1,len(list)):
self.BSTappend(root,list[i])
return root
def BSTappend(self,root,num):
parent = root
while root:
parent = root
if root.val < num:
root = root.right
else:
root = root.left
if parent.val < num:
parent.right = TreeNode(num)
else:
parent.left = TreeNode(num)
|
9eba4c97143250a68995688a62b41145ab39485f | wangyunge/algorithmpractice | /int/165_Merge_Two_Sorted_Lists.py | 944 | 4.125 | 4 | '''
Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.
Have you met this question in a real interview? Yes
Example
Given 1->3->8->11->15->null, 2->null , return 1->2->3->8->11->15->null.
'''
z"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param two ListNodes
@return a ListNode
"""
def mergeTwoLists(self, l1, l2):
helper = ListNode(0,None)
index = helper
while l1 and l2:
if l1.val <= l2.val:
index.next = l1
l1 = l1.next
else:
index.next = l2
l2 = l2.next
index = index.next
index.next = l1 if l1 else l2
return helper.next |
1ed697d41f7a62305a2bb7d82c3e945e47ac65b4 | wangyunge/algorithmpractice | /int/167_Add_Two_Numbers.py | 894 | 3.859375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param l1: the first list
# @param l2: the second list
# @return: the sum list of l1 and l2
def addLists(self, l1, l2):
# write your code here
helper = ListNode(0)
head = helper
digit=1
plus=0
while l1 or l2:
if l1:
a = l1.val
l1 = l1.next
else:
a = 0
if l2:
b = l2.val
l2 = l2.next
else:
b = 0
levelRes = (a+b+plus)%10
plus = (a+b+plus)/10
head.next = ListNode(levelRes)
head = head.next
if plus==1:
head.next = ListNode(1)
return helper.next
|
a1e44328e89eccd44eccdf0f5bcad629ac9c4688 | wangyunge/algorithmpractice | /cn/445.py | 1,087 | 3.640625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
s1 = []
s2 = []
while l1:
s1.append(l1.val)
l1 = l1.next
while l2:
s2.append(l2.val)
l2 = l2.next
carry = 0
res = []
while s1 and s2:
a1 = s1.pop()
a2 = s2.pop()
a3 = a1+a2+carry
res.append(a3 % 10)
carry = a3 // 10
rest = s1 if s1 else s2
while rest:
a1 = rest.pop()
a3 = a1+carry
res.append(a3 % 10)
carry = a3 // 10
if carry > 0:
res.append(carry)
dummy = ListNode(0)
cur = dummy
while res:
cur.next = ListNode(res.pop())
cur = cur.next
return dummy.next
|
8bbc714ce6bbf0420e2d320b0f9bccef01187ae8 | wangyunge/algorithmpractice | /eet/First_Unique_Character_in_a_String.py | 771 | 3.859375 | 4 | """
Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode"
return 2.
Note: You may assume the string contains only lowercase English letters.
"""
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
res = len(s)
table = {}
for idx in range(len(s)):
last_id, cnt = table.get(s[idx], (len(s), 0))
table[s[idx]] = (min(last_id, idx), cnt+1)
for last_id, cnt in table.keys():
if cnt == 1:
res = min(res, last_id)
if res == len(s):
return -1
else:
return res
|
c09cd743358e384ed520289eb8c09dab719ca8b3 | wangyunge/algorithmpractice | /int/101_Remove_Duplicates_from_Sorted_Array.py | 543 | 3.859375 | 4 | '''
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3],
Your function should return length = 5, and A is now [1,1,2,2,3].
'''
class Solution:
"""
@param A: a list of integers
@return an integer
"""
def removeDuplicates(self, A):
if len(A) < 2:
return len(A)
pos = 1
for i in xrange(2,len(A)):
if A[i] != A[pos-1]:
pos += 1
A[pos] = A[i]
return pos+1 |
47de9e81d4e95399dc6113ca3522b8f968f8e44d | wangyunge/algorithmpractice | /eet/86_Binary_Search_Tree_Iterator.py | 1,280 | 3.90625 | 4 | '''
Design an iterator over a binary search tree with the following rules:
Elements are visited in ascending order (i.e. an in-order traversal)
next() and hasNext() queries run in O(1) time in average.
Have you met this question in a real interview? Yes
Example
For the following binary search tree, in-order traversal by using iterator is [1, 6, 10, 11, 12]
10
/ \
1 11
\ \
6 12
'''
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
Example of iterate a tree:
iterator = BSTIterator(root)
while iterator.hasNext():
node = iterator.next()
do something for node
"""
class BSTIterator:
#@param root: The root of binary tree.
def __init__(self, root):
self.stack = []
while root:
self.stack.append(root)
root = root.left
#@return: True if there has next node, or false
def hasNext(self):
res = True if self.stack else False
return res
#@return: return next node
def next(self):
root = self.stack.pop()
toReturn = root.val
root = root.right
while root:
self.stack.append(root)
root = root.left
return toReturn
|
e1e3e1744e5e347e72bfcedaa53c873c09ad25f4 | wangyunge/algorithmpractice | /int/120_Word_Ladder.py | 1,302 | 3.796875 | 4 | '''
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
Notice
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
Have you met this question in a real interview? Yes
Example
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
'''
class Solution:
# @param start, a string
# @param end, a string
# @param dict, a set of string
# @return an integer
def ladderLength(self, start, end, dict):
from Queue import Queue
queue = Queue()
queue.put((start,1))
while not queue.empty():
(word,depth) = queue.get()
tmp = []
if self.adjcent(word,end):
return depth+1
for step in dict:
if self.adjcent(word,step):
queue.put((step,depth+1))
else:
tmp.append(step)
dict = tmp
return 0
def adjcent(self,A,B):
count = 0
for i in xrange(len(A)):
if A[i] != B[i]:
count += 1
return count == 1 |
7f5784b154c1472c0df8058521a96fa1233f257f | wangyunge/algorithmpractice | /eet/301_Remove_Invalid_Parentheses.py | 536 | 4.03125 | 4 | """
Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.
Return all the possible results. You may return the answer in any order.
Example 1:
Input: s = "()())()"
Output: ["(())()","()()()"]
Example 2:
Input: s = "(a)())()"
Output: ["(a())()","(a)()()"]
Example 3:
Input: s = ")("
Output: [""]
"""
class Solution(object):
def removeInvalidParentheses(self, s):
"""
:type s: str
:rtype: List[str]
"""
|
3bd025a7c52e92aedca526c54a1beeb5895a0a3e | wangyunge/algorithmpractice | /eet/Reverse_Linked_List_II.py | 2,241 | 4.09375 | 4 | '''
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
Subscribe to see which companies asked this question
Show Tags
Show Similar Problems
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
# 1. m < l, n< l
# 2.null input
# 3. m=1
# 4. n=L
if not head:
return head
# Find the start
# Find the end
dummy = ListNode()
dummy.next = head
start = dummy
idx = 1
while idx < m and start:
idx += 1
start = start.next
end = start
while idx <= n+1 and end:
idx +=1
end = end.next
# reverse start.next and end.prev
prev = end
cur = start.next
while cur != end:
tmp = cur.next
cur.next = prev
prev = cur
cur = tmp
start.next = prev
return head
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
i=1
if m!=1:
curr =head
while i<m-1:
curr = curr.next
i+=1
breakPoint = curr
breakHead = curr.next
c1 = curr.next
c2 = c1.next if c1 else None
i+=1
else:
c1 = head
c2 = c1.next if c1 else None
while i < n:
tmp = c2.next
c2.next = c1
c1 = c2
c2 = tmp
i+=1
if m!=1:
breakPoint.next = c1
if breakHead.next:
breakHead.next= c2
else:
head = c1
return head
|
9438d60a669a59fd1aa3f1d0d43ee3dc3c67f072 | wangyunge/algorithmpractice | /eet/Add_and_Search_Word.py | 2,265 | 4.03125 | 4 | '''
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.
For example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters a-z.
'''
class TrieNode(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.children = {}
self.character = None
self.val = None
class WordDictionary(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.root = TrieNode()
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: void
"""
currNode = self.root
for character in word:
if character in currNode.children:
currNode = currNode.children[character]
else:
currNode.children[character] = TrieNode()
currNode = currNode.children[character]
currNode.val = word
def search(self, word):
"""
Returns if the word is in the data structure. A word could
contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
found = False
def DFS(currNode,leftchar):
for i in xrange(len(leftchar)):
if leftchar[i] == '.':
for node in currNode.children:
DFS(node,leftchar[i+1:])
elif leftchar[i] in currNode.children:
currNode = currNode.children[leftchar[i]]
else:
return False
if currNode.val:
found = True
return False
DFS(self.root,word)
return found
# Your WordDictionary object will be instantiated and called as such:
# wordDictionary = WordDictionary()
# wordDictionary.addWord("word")
# wordDictionary.search("pattern") |
3f35390e3175f4c4d33e169a5078781b12ad839d | wangyunge/algorithmpractice | /cn/450.py | 1,530 | 3.953125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def deleteNode(self, root, key):
"""
:type root: TreeNode
:type key: int
:rtype: TreeNode
"""
def _find(node, parent, on_left):
if node:
if node.val == key:
if node.left and node.right:
_move(node.left, node.right)
if on_left:
parent.left = node.right
else:
parent.right = node.right
elif node.left:
if no_left:
parent.left = node.left
else:
parent.right = node.right
else:
if on_left:
parent.left = node.right
else:
parent.right = node.right
else:
_find(node.left, node, True)
_find(node.right, node, False)
def _move(need, cur):
if cur.left:
_move(need, cur.left)
else:
cur.left = need
dummy = TreeNode()
dummy.left = root
_find(dummy.left, dummy, True)
return dummy.left
|
ae968f7561fab037f39dba5e47eb745058a1ba24 | UchihaSean/ReinforcementLearningForDialogue | /bleu.py | 1,534 | 3.703125 | 4 | # -*- coding: UTF-8 -*-
import csv
import numpy as np
def evaluation_bleu(eval_sentence, base_sentence, n_gram=2):
"""
BLEU evaluation with n-gram
"""
def generate_n_gram_set(sentence, n):
"""
Generate word set based on n gram
"""
n_gram_set = set()
for i in range(len(sentence) - n + 1):
word = ""
for j in range(n):
word += sentence[i + j]
n_gram_set.add(word)
return n_gram_set
if n_gram > len(eval_sentence) or n_gram > len(base_sentence): return 0.0
base_n_gram_set = generate_n_gram_set(base_sentence, n_gram)
eval_n_gram_set = generate_n_gram_set(eval_sentence, n_gram)
# print(list(base_n_gram_set)[0])
# print(list(eval_n_gram_set)[1])
bleu = 0.0
for word in eval_n_gram_set:
if word in base_n_gram_set:
bleu += 1
return bleu / len(eval_n_gram_set)
def file_evaluation_bleu(file_name):
bleu_set = []
with open(file_name, 'r') as csvfile:
file_info = csv.reader(csvfile)
for i, line in enumerate(file_info):
if i==0: continue
bleu = evaluation_bleu(line[2].decode("utf-8"), line[1].decode("utf-8"))
# print(line[1])
# print(line[2])
bleu_set.append(bleu)
print(np.mean(bleu_set))
def main():
# print(evaluation_bleu("你们好".decode("utf-8"), "你们".decode("utf-8")))
file_evaluation_bleu("data/rl_output.csv")
if __name__ == '__main__':
main() |
133a87b450bcdb2cf9374d11cba74108cca68358 | seanws2/Using-search-to-operate-robot-arm | /mp2-code/template/search.py | 2,311 | 3.796875 | 4 | # search.py
# ---------------
# Licensing Information: You are free to use or extend this projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to the University of Illinois at Urbana-Champaign
#
# Created by Jongdeog Lee (jlee700@illinois.edu) on 09/12/2018
"""
This file contains search functions.
"""
# Search should return the path and the number of states explored.
# The path should be a list of tuples in the form (alpha, beta, gamma) that correspond
# to the positions of the path taken by your search algorithm.
# Number of states explored should be a number.
# maze is a Maze object based on the maze from the file specified by input filename
# searchMethod is the search method specified by --method flag (bfs,astar)
# You may need to slight change your previous search functions in MP1 since this is 3-d maze
from collections import deque
from heapq import heappop, heappush
import queue as queue
def search(maze, searchMethod):
return {
"bfs": bfs,
}.get(searchMethod, [])(maze)
def bfs(maze):
# Write your code here
"""
This function returns optimal path in a list, which contains start and objective.
If no path found, return None.
"""
start = maze.getStart()
BFS = queue.Queue()
BFS.put(maze.getStart())
# this is to log the path
history = {}
history[start] = None
notEmpty = True
keepGoin = True
output = []
while notEmpty:
front = BFS.get()
neighbors = maze.getNeighbors(front[0], front[1])
if maze.isObjective(front[0], front[1]):
output.append(front)
prev_front = history[front]
# build path taken
while keepGoin:
output.append(prev_front)
prev_front = history[prev_front]
if prev_front == start: keepGoin = False
output.append(start)
break
for i in neighbors:
if i in history:
continue
else:
history[i] = front
BFS.put(i)
if BFS.empty():
notEmpty = False
break
output.reverse()
if output == []:
return None
else:
return output |
45dd8e0c59db48f7f557a9d084454d9fe00da97e | egill12/machine_learning | /dataset/document/generate_trend.py | 1,306 | 3.640625 | 4 | '''
Author: Ed Gill
This is a process to return a randomly generated series of numbers.
change alpha from -0.2 to 0.2 to move from mean reversion to strong trend.
'''
import numpy as np
import pandas as pd
from create_model_features import trends_features
def generate_trend(n_samples, alpha, sigma):
'''
:return: Generate a trend
'''
# ( range from -0.2 to 0.2 to move from mean reversion to strong trend
trend_param = (1 / (1 - (alpha** 3)))
x = w = np.random.normal(size=n_samples)*sigma
for t in range(n_samples):
x[t] = trend_param*x[t - 1] + w[t]
# return the trend file as a a dataframe
trendy_ts = pd.DataFrame(x, columns = ["trend"])
return trendy_ts
def get_trendy_data(n_samples,trend_strength,pct_stdev,CCY_COL, short, medium, long, longest, medium_multiplier,long_multplier):
'''
Takes the trendy series and gets the model features
:return:
'''
trendy_df = generate_trend(n_samples, trend_strength, pct_stdev)
ccy_data = trends_features(trendy_df, CCY_COL, short, medium, long, longest, medium_multiplier, long_multplier)
ccy_data['CCY'] = trendy_df['trend']
# need to replace log ret with simpel return
ccy_data['logret'] = trendy_df['CCY'] - trendy_df['CCY'].shift(1)
return ccy_data.replace(np.nan, 0) |
168300928e12bcc8b469a010346a5632e2e98041 | JDOsborne1/Advent-of-code | /Day2/Puzzle1.py | 1,354 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 2 11:05:09 2018
@author: Joe
"""
# Puzzle 1
## Get the checksum
## Data import
#%% dictonary link for individual letter
alphanum = {'a':1,
'b':2,
'c':3,
'd':4,
'e':5,
'f':6,
'g':7,
'h':8,
'i':9,
'j':10,
'k':11,
'l':12,
'm':13,
'n':14,
'o':15,
'p':16,
'q':17,
'r':18,
's':19,
't':20,
'u':21,
'v':22,
'w':23,
'x':24,
'y':25,
'z':26}
#%% function def for individual string
def stringcheck(string):
string_out = zeros(1,26)
for s in string:
string_out[alphanum[s] - 1] += 1
return string_out
#%% Function def or checksum
def checksum(entry):
doubles = 0
trebles = 0
for i in entry:
if 3 in stringcheck(i):
trebles += 1
if 2 in stringcheck(i):
doubles += 1
return doubles * trebles
#%% testing
#testblock = inputtxt[:3]
print(checksum(inputtxt))
|
6988fe01eceba6c5f8bdba8dee341cdf6022f4b7 | iuliaL/dna_sequencing | /De_Bruijn_Graph.py | 799 | 3.84375 | 4 | def buildDeBruijnGraph(string, k):
""" Return a list holding, for each k-mer, its left
(k-1)-mer and its right (k-1)-mer in a pair """
edges = []
nodes = set()
for i in range(len(string) - k + 1):
curr_kmer = string[i:i+k]
left = curr_kmer[:-1]
right = curr_kmer[1:]
edges.append((left, right))
nodes.add(left)
nodes.add(right)
return nodes, edges
def visualize_De_Bruijn_Graph(st, k):
""" Visualize a directed multigraph using graphviz """
nodes, edges = buildDeBruijnGraph(st, k)
dot_str = 'digraph "DeBruijn graph" {\n'
for node in nodes:
dot_str += ' %s [label="%s"] ;\n' % (node, node)
for src, dst in edges:
dot_str += ' %s -> %s ;\n' % (src, dst)
return dot_str + '}\n'
|
8552f778aaf03e105a5d42e2e5421ec3acd522cd | cSquaerd/ccDiceSumming | /ccDiceSumming.py | 7,375 | 3.796875 | 4 | # Imports
import numpy as np
import matplotlib.pyplot as plot
# Recursively calculates how many ways to roll a value from a list of dice
def ways(value : int, diceCount : int, dice : list) -> int:
if value < 1 or diceCount < 1:
return 0
elif diceCount == 1:
return int(value <= dice[0])
else:
return sum(
ways(value - roll, diceCount - 1, dice[1:]) * ways(roll, 1, dice[0:1])
for roll in range(1, dice[0] + 1)
)
# Macro for getting list of ways to roll all possible values of a list of dice
allWays = lambda dice : [
ways(v, len(dice), dice) for v in range(len(dice), sum(dice) + 1)
]
# Macro for turning the above list into a list of probabilites
diceDistribution = lambda dice : np.array(allWays(dice)) / np.prod(dice)
# Calculates P(X >= value) for a random variable X of a list of dice
def probDiceGEQ(value : int, dice : list, precision : int = 4) -> float:
denom = np.prod(dice)
c = len(dice)
maxV = sum(dice)
return round(
sum([
ways(v, c, dice) / denom for v in range(value, maxV + 1)
]), precision
)
# Calculates P(X <= value) for a random variable X of a list of dice
def probDiceLEQ(value : int, dice : list, precision : int = 4) -> float:
denom = np.prod(dice)
c = len(dice)
return round(
sum([
ways(v, c, dice) / denom for v in range(value, c - 1, -1)
]), precision
)
# Calculates P(minVal <= X <= maxVal) for a random variable X of a list of dice
def probDiceInterval(
minV : int, maxV : int, dice : list, precision : int = 4
) -> float:
denom = np.prod(dice)
c = len(dice)
return round(
sum([
ways(v, c, dice) / denom for v in range(minV, maxV + 1)
]), precision
)
# Returns a formatted string describing a list of dice, largest dice first
def diceLabel(dice : list) -> str:
s = ""
S = set()
for d in sorted(set(dice), reverse = True):
s += str(dice.count(d)) + 'd' + str(d)
S.add(d)
if len(set(dice) - S) >= 1:
s += " + "
return s
# Produces a plot of a single dice list's ways to roll all values
def plotDiceWays(dice : list, color : str = "#4040B0"):
possibilities = list(range(len(dice), sum(dice) + 1))
f, a = plot.subplots()
f.set_facecolor('w')
f.set_figwidth(16)
f.set_figheight(12)
if len(possibilities) <= 32:
a.set_xticks(possibilities)
else:
l = len(dice)
s = sum(dice)
a.set_xticks(list(range(l, s + 1, (s - l) // 32)))
ways = allWays(dice)
if max(ways) <= 16:
a.set_yticks(list(range(1, max(ways) + 1)))
else:
a.set_yticks(list(range(1, max(ways) + 1, (max(ways) - min(ways)) // 16)))
a.grid()
a.set_title(
"Ways To Roll all values of " + diceLabel(dice), fontsize = "xx-large"
)
a.set_xlabel("Dice Roll Value", fontsize = "x-large")
a.set_ylabel("Ways To Roll", fontsize = "x-large")
a.scatter(possibilities, ways, marker = '*', s = 128, c = color)
a.plot(possibilities, ways, linestyle = "dotted", color = color)
return f, a
# Produces a plot of a single dice list's probability distribution
def plotDiceDist(dice : list, color : str = "#4040B0"):
possibilities = list(range(len(dice), sum(dice) + 1))
f, a = plot.subplots()
f.set_facecolor('w')
f.set_figwidth(16)
f.set_figheight(12)
minV = len(dice)
maxV = sum(dice)
if len(possibilities) <= 32:
a.set_xticks(possibilities)
else:
a.set_xticks(list(range(minV, maxV + 1, (maxV - minV) // 32)))
possibilities.insert(0, minV)
possibilities.append(maxV)
distribution = diceDistribution(dice)
distribution = np.insert(distribution, 0, 0)
distribution = np.append(distribution, 0)
a.grid()
a.set_title(
"Probability Distribution of " + diceLabel(dice), fontsize = "xx-large"
)
a.set_xlabel("Dice Roll Value", fontsize = "x-large")
a.set_ylabel("Probability", fontsize = "x-large")
a.fill(possibilities, distribution, color = color)
return f, a
# Produces a plot of multiple probability distributions from multiple dice lists
def plotDiceDistMulti(
diceSets : list, comments : list = None,
color : str = '#4040B0A0'
):
minX = min([len(d) for d in diceSets])
maxX = max([sum(d) for d in diceSets])
f, a = plot.subplots()
f.set_facecolor('w')
f.set_figwidth(16)
f.set_figheight(12)
if maxX - minX <= 32:
a.set_xticks(list(range(minX, maxX + 1)))
else:
a.set_xticks(list(range(minX, maxX + 1, (maxX - minX) // 32)))
a.grid()
a.set_title(
"Probability Distributions of multiple dice sets", fontsize = "xx-large"
)
a.set_xlabel("Dice Roll Value", fontsize = "x-large")
a.set_ylabel("Probability", fontsize = "x-large")
if comments is None:
comments = ['' for x in range(len(diceSets))]
c = 0
for dice in diceSets:
possibilities = list(range(len(dice), sum(dice) + 1))
distribution = diceDistribution(dice)
a.plot(
possibilities, distribution,
label = diceLabel(dice) + ' ' + comments[c]
)
possibilities.insert(0, len(dice))
possibilities.append(sum(dice))
distribution = np.insert(distribution, 0, 0)
distribution = np.append(distribution, 0)
a.fill(possibilities, distribution, color = color)
c += 1
a.legend()
return f, a
# Calculates all ways to roll n of a die where the lowest k dice are discarded
def allWaysDropN(
diceCount : int, dropCount : int,
die : int, target : int = 0
) -> list:
if diceCount - dropCount < 1:
return []
def increment(dice : list):
i = 0
while i < diceCount and (i == 0 or dice[i - 1] == 1):
dice[i] = (dice[i] % die) + 1
i += 1
def evaluate(dice : list):
diceSorted = sorted(dice)
value = 0
for v in range(diceCount - dropCount):
value += diceSorted.pop()
return value
effectiveDice = diceCount - dropCount
dice = [1 for d in range(diceCount)]
values = [0 for v in range(effectiveDice, die * effectiveDice + 1)]
for d in range(die ** diceCount):
value = evaluate(dice)
if value == target:
print(dice, value)
values[value - effectiveDice] += 1
increment(dice)
return values
# Macro for turning the above ways list into a probability distribution
diceDropDistribution = lambda count, drop, die : np.array(
allWaysDropN(count, drop, die)
) / die ** count
# Produces a plot comparing rolling n dice with k dropped vs. rolling n-k dice
def plotDiceDropDist(
diceCount : int, dropCount : int, die : int,
color : str = "#4040B080"
):
effectiveDice = diceCount - dropCount
effectiveDiceList = [die for x in range(effectiveDice)]
droppedLabel = str(diceCount) + 'd' + str(die) + "-drop-" + str(dropCount)
f, a = plotDiceDist(effectiveDiceList, color)
a.set_title(
"Probability Distributions of " + droppedLabel
+ " versus " + diceLabel(effectiveDiceList),
fontsize = "xx-large"
)
possibilities = list(range(effectiveDice, die * effectiveDice + 1))
distributionDropped = diceDropDistribution(diceCount, dropCount, die)
distributionEffective = diceDistribution(effectiveDiceList)
a.plot(possibilities, distributionDropped, label = droppedLabel)
a.plot(
possibilities, distributionEffective,
label = diceLabel(effectiveDiceList)
)
a.legend()
possibilities.insert(0, effectiveDice)
possibilities.append(die * effectiveDice)
distributionDropped = np.insert(distributionDropped, 0, 0)
distributionDropped = np.append(distributionDropped, 0)
distributionEffective = np.insert(distributionEffective, 0, 0)
distributionEffective = np.append(distributionEffective, 0)
a.fill(possibilities, distributionDropped, color = color)
a.fill(possibilities, distributionEffective, color = color)
return f, a
|
7f262c239659a7bc67048b7d88ad9890d6592260 | 9aa9/tabling | /tabling.py | 730 | 3.5625 | 4 | '''
$ Email : huav2002@gmail.com'
$ Fb : 99xx99'
$ PageFB : aa1bb2
'''
def TABLING(lines):
num = len(max(lines))
nums = [0 for i in range(num)]
for line in lines:
for a in range(len(line)):
if len(line[a]) > nums[a]:nums[a] = len(line[a])
for a in range(len(lines)):
lines[a] = [lines[a][b].center(nums[b]+4) for b in range(len(lines[a]))]
lin = ['']*len(nums)
for a in range(len(nums)):
if a == 0:lin[0] = '+'+(nums[a]+4)*'-'+'+'
else:lin[a] = (nums[a]+4)*'-'+'+'
for line in lines:
print(''.join(lin))
print('|'+'|'.join(line)+'|')
print(''.join(lin))
TABLING([
["name",'suname','age'],
['rahim','rahim','17'],
['ali','ali','16'],
['','','']
])
|
4022746f6eea714070df77e4d463a166801f3566 | alexanderankin/CSV-SQL-Import-Scripts | /create_counts_table.py | 1,473 | 3.625 | 4 | #!/usr/bin/python3
"""
This will produce a table definition from the length count matrix
"""
from sqlalchemy.dialects import mysql
from sqlalchemy.schema import CreateTable
from sqlalchemy import Table, Column, String, MetaData
import fileinput
import sys
import csv
def main():
table_name = 'import'
if len(sys.argv) == 1:
input_, output_ = fileinput.input(), sys.stdout
elif len(sys.argv) == 2:
input_, output_ = open(sys.argv[1]), sys.stdout
elif len(sys.argv) == 3:
table_name = sys.argv[2]
input_, output_ = open(sys.argv[1]), open(sys.argv[2], 'w+')
else:
print("Usage: ./create-csv-table.py [input] [output]")
sys.exit(1)
reader = csv.reader(input_)
next(reader) # discard "Field,Max Length"
matrix = []
for row in reader:
matrix.append([row[0], int(row[1]) + 1])
columns = [Column(n, String(l)) for n, l in matrix]
table = CreateTable(Table(table_name, MetaData(),
*columns
))
output_.write(str(table.compile(dialect=mysql.dialect())))
if __name__ == '__main__':
main()
"""
def read_input(input_):
""This function takes in an argument for csv.reader() and returns an
instance of CSVCounts where counts property is matrix of max field lengths
""
reader = csv.reader(input_)
counts = CSVCounts()
counts.establish_fields(next(reader))
for data in reader:
counts.compare_row(data)
return counts
"""
|
87ef927974942deb7d3140c57200e281ceaa389e | manh100004104234761/otodochoi | /findpath.py | 7,576 | 3.703125 | 4 | from math import sqrt
def getPossibleX(points):
set_x = set()
for point in points:
set_x.add(point[0])
return set_x
def getPossibleY(points):
set_y = set()
for point in points:
set_y.add(point[1])
return set_y
def findStartingAngle(start_point, next_point):
if start_point[0] == next_point[0]:
if start_point[1] < next_point[1]:
angle = -90
else:
angle = 90
else:
if start_point[0] < next_point[0]:
angle = 0
else:
angle = 180
return angle
def insertPoint(array, point_x, point_y):
if array[0][0] > int(point_x):
array.insert(0, [int(point_x), int(point_y)])
else:
done = False
if array[len(array) - 1][0] == int(point_x):
end_x = int(point_x)
end_index = len(array)
else:
for element in array:
if element[0] > int(point_x):
end_index = array.index(element) - 1
end_x = array[end_index - 1][0]
if end_x < int(point_x):
array.insert(end_index + 1, [int(point_x), int(point_y)])
done = True
break
if done == False:
for element in array:
if element[0] == end_x:
if element[1] > int(point_y):
array.insert(array.index(element), [int(point_x), int(point_y)])
done = True
break
if done == False:
array.insert(end_index, [int(point_x), int(point_y)])
return array
def readPoint():
points = []
f = open("middle_point.txt", "r")
lines = f.readlines()
#Make list of points
for line in lines:
x = line[:line.find(",")]
if x == "":
break
y = line[line.find(",")+1:line.find("\n")]
points.append([int(x), int(y)])
return points
def readEdge(points):
edges =[]
for point1 in points:
count_x = 0
count_y = 0
for point2 in points:
if point1[0] == point2[0] and point1[1] < point2[1] and count_x == 0:
edges.append([[point1, point2], point2[1]-point1[1]])
edges.append([[point2, point1], point2[1]-point1[1]])
count_x += 1
if point1[0] < point2[0] and point1[1] == point2[1] and count_y == 0:
edges.append([[point1, point2], point2[0]-point1[0]])
edges.append([[point2, point1], point2[0]-point1[0]])
count_y += 1
if count_x == 1 and count_y == 1:
break
#print(edges)
#Make the weight of non-exist edges a large number
for point1 in points:
for point2 in points:
if point1 != point2:
flag = True
for edge in edges:
if edge[0] == [point1, point2]:
flag = False
break
if flag:
edges.append([[point1, point2], 1000000])
else:
edges.append([[point1, point2], 0])
return edges
def findPath(starting_point_x, starting_point_y, ending_point_x, ending_point_y):
starting_point_x = int(starting_point_x)
starting_point_y = int(starting_point_y)
ending_point_x = int(ending_point_x)
ending_point_y = int(ending_point_y)
d = []
p = []
points = readPoint()
points = insertPoint(points, starting_point_x, starting_point_y)
points = insertPoint(points, ending_point_x, ending_point_y)
edges = readEdge(points)
start_point = [int(starting_point_x), int(starting_point_y)]
vertice = points.copy()
for vertex in vertice:
for edge in edges:
if edge[0] == [start_point, vertex]:
d.append([vertex, edge[1]])
break
p.append([vertex, start_point])
#print(p)
vertice.remove(start_point)
while (len(vertice) != 0):
min_d = 1000000
for vertex in vertice:
for d_e in d:
if d_e[0] == vertex:
if d_e[1] < min_d:
min_d = d_e[1]
u = d_e[0]
break
vertice.remove(u)
for vertex in vertice:
for edge in edges:
if edge[0] == [u, vertex]:
old_path = min_d + edge[1]
break
for d_e in d:
if d_e[0] == vertex:
if d_e[1] > old_path:
d_e[1] = old_path
for p_e in p:
if p_e[0] == vertex:
p_e[1] = u;
path = []
path.append([ending_point_x, ending_point_y])
currentPoint = [ending_point_x, ending_point_y]
while (currentPoint != [starting_point_x, starting_point_y]):
for p_e in p:
if p_e[0] == currentPoint:
currentPoint = p_e[1]
path.insert(0, p_e[1])
print(path)
def adjustPointToTheCenter(point_x, point_y):
point_x = int(point_x)
point_y = int(point_y)
points = readPoint()
edges = readEdge(points)
set_x = getPossibleX(points)
set_y = getPossibleY(points)
min_distance = 10000
for point in points:
if int(abs(point[0] - point_x)) < 23 and int(abs(point[1] - point_y)) < 23:
return point
for edge in edges:
if edge[1] != 0 and edge[1] != 1000000:
distance = int(abs((edge[0][1][1] - edge[0][0][1])*point_x - (edge[0][1][0] - edge[0][0][0])*point_y + edge[0][1][0]*edge[0][0][1] - edge[0][0][0]*edge[0][1][1])/sqrt(pow(edge[0][1][1] - edge[0][0][1], 2) + pow(edge[0][1][0] - edge[0][0][0], 2)))
if distance < min_distance:
min_distance = distance
for x in set_x:
if point_x - min_distance == x or point_x + min_distance == x:
return [x, point_y]
for y in set_y:
if point_y - min_distance == y or point_y + min_distance == y:
return [point_x, y]
def adjustAngle(angle):
angle = int(angle)
if angle >= 0:
if angle % 90 > 80:
angle = 90 * (int(angle / 90) + 1)
else:
angle = 90 * (int(angle / 90))
else:
if angle % -90 < -80:
angle = -90 * (int(angle / -90) + 1)
else:
angle = -90 * (int(angle / -90))
return angle
def isPositiveTurn(current_point, current_dest, next_dest):
if current_point[0] < current_dest[0]:
if current_dest[1] > next_dest[1]:
return True
else:
return False
elif current_point[0] > current_dest[0]:
if current_dest[1] > next_dest[1]:
return False
else:
return True
elif current_point[1] > current_dest[1]:
if current_dest[0] > next_dest[0]:
return True
else:
return False
else:
if current_dest[0] > next_dest[0]:
return False
else:
return True
#starting_point_x = input("Enter starting point x: ")
#starting_point_y = input("Enter starting point y: ")
#ending_point_x = input("Enter ending point x: ")
#ending_point_y = input("Enter ending point y: ")
#point = adjustPointToTheCenter(starting_point_x, starting_point_y)
#print(89/90)
#print(adjustAngle(-89))
print(-120 / -90)
#findPath(starting_point_x, starting_point_y, ending_point_x, ending_point_y)
|
c0e2797affe5d5bfde8219c5ef6ee717af281169 | tasver/python_course | /lab5_1.py | 125 | 4.0625 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
import sys
print("Enter your number: ")
num = int(input())
print(not(num&num-1))
|
f70962dff39951264b72468373fadb78663ea583 | tasver/python_course | /lab9_4.py | 1,905 | 4.0625 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
def input_number() -> int:
"""This function returns input number"""
number = input('Enter your number: ')
return number
def input_rome_number() -> str:
"""This function returns input rome number"""
number = input('Enter your rome number: ')
return number
def from_number_to_rome(number:int) -> str:
"""This funtion converted numbers to romes numbers"""
base = "I"*int(number)
base = base.replace("I"*5, "V")
base = base.replace("V"*2, "X")
base = base.replace("X"*5, "L")
base = base.replace("L"*2, "C")
base = base.replace("C"*5, "D")
base = base.replace("D"*2, "M")
base = base.replace("DCCCC", "CM")
base = base.replace("CCCC", "CD")
base = base.replace("LXXXX", "XC")
base = base.replace("XXXX", "XL")
base = base.replace("VIIII", "IX")
base = base.replace("IIII", "IV")
return base
def from_romes_to_number(string:str) ->str:
"""This funtion converted romes numbers to numbers"""
base = string
base = base.replace("I", "1 ")
base = base.replace("V", "5 ")
base = base.replace("X", "10 ")
base = base.replace("L", "50 ")
base = base.replace("C", "100 ")
base = base.replace("D", "500 ")
base = base.replace("M", "1000 ")
base = base.replace("CM", "900 ")
base = base.replace("CD", "400 ")
base = base.replace("XC", "90 ")
base = base.replace("XL", "40 ")
base = base.replace("IX", "9 ")
base = base.replace("IV", "4 ")
base = base.strip()
base_result = base.split(" ")
base_result = list(map(int, base_result))
base_result=sum(base_result)
return base_result
def output_str(string:str) -> None:
"""This function prints numbers"""
print(string)
output_str(from_number_to_rome(input_number()))
output_str(from_romes_to_number(input_rome_number()))
|
ba2b9d296a98edfb414c89aba262142b031014ea | tasver/python_course | /lab7_4.py | 782 | 4.375 | 4 |
#! /usr/bin/python3
# -*- coding: utf-8 -*-
def input_str() -> str:
""" This function make input of string data"""
input_string = str(input('Enter your string: '))
return input_string
def string_crypt(string: str) -> str:
""" This function make crypt string"""
result_string = str()
string = string.lower()
for symb in string:
result_string += chr(ord(symb) + 1)
return result_string
def string_check_crypt(check_str:str) -> str:
""" this funtion checking out of range crypt """
check_str = check_str.replace("{","a")
check_str = check_str.replace("ѐ","а")
print(check_str)
return check_str
def output_str(string:str) -> str:
""" This function print result"""
print(string)
output_str(string_check_crypt(string_crypt(input_str())))
|
c79e8895e05e1640469fb9d4ea21fbbf11f01262 | tasver/python_course | /lab8_1.py | 747 | 3.59375 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
def input_number() -> list:
""" This function make input of your data"""
number_step = []
number_step.append(input('Enter soldiers number: '))
number_step.append(input('Enter step killing: '))
return number_step
def killing_soldiers(number_step:list) -> int:
number, step = number_step
soldiers = [sold for sold in range(1,int(number)+1)]
count = int(step)
iterator = 1
while len(soldiers) > 1:
if iterator % count == 0:
soldiers.pop(0)
else:
next_sold = soldiers.pop(0)
soldiers.append(next_sold)
iterator += 1
return soldiers[0]
def output_str(string:str) -> str:
""" This function print result"""
print(string)
output_str(killing_soldiers(input_number()))
|
611f5ff5305ad4db517bb39313296f77acd0b773 | tasver/python_course | /lab17_tests.py | 430 | 3.75 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
import unittest
import math
def formula(a:float, b:float)-> float:
x = (math.sqrt(a*b))/(math.e**a * b) + a * math.e**(2*a/b)
return x
def output(x:float) -> str:
print(x)
class tests(unittest.TestCase):
def test_equal_first(self):
self.assertEqual(formula(0,1),0.0)
def test_equal_second(self):
self.assertAlmostEqual(formula(0.5,10),0.688209837593,7)
unittest.main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.