text stringlengths 37 1.41M |
|---|
# ARRAYS LESSON
# Python arrays are homogenous data structure.They are used to store multiple items but allow only the same type of data.
# They are available in Python by importing the array module.
# Lists, a built - in type in Python, are also capable of storing multiple values.
# But they are different from arrays because they are not bound to any specific type.
# Arrays are not fundamental type, but lists are internal to Python.
# An array accepts values of one kind while lists are independent of the data type.
# Arrays in Python
# What is Array in Python?
# An array is a container used to contain a fixed number of items.
# But, there is an exception that values should be of the same type.
# Array element – Every value in an array represents an element.
# Array index – Every element has some position in the array known as the index.
# Array Illustration
# The array is made up of multiple parts. And each section of the array is an element.
# We can access all the values by specifying the corresponding integer index.
# The first element starts at index 0 and so on.
# Declare Array in Python
# You have first to import the array module in your Python script.
# After that, declare the array variable as per the below syntax.
# Syntax
# How to declare an array variable in Python
from array import *
# array_var = array(TypeCode, [Initializers]
# In the above statements, “array_var” is the name of the array variable.And we’ve used the array() function which
# takes two parameters. “TypeCode” is the type of array whereas “Initializers” are the values to set in the array.
# The argument “TypeCode” can be any value from the below chart.
# Python array typecodes “i” for integers and “d” for floats
# Example
# Let’s consider a simple case to create an array of 10 integers.
import array as ar
# Create an array of 10 integers using range()
array_var = ar.array('i', range(10))
print("Type of array_var is:", type(array_var))
# Print the values generated by range() function
print("The array will include: ", list(range(10)))
# We first imported the array module and then used the range() function to produce ten integers.We’ve also printed the numbers that our array variable would hold.
# Python Range
# Type of array_var is: <class 'array.array'>
# The array will include: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# In the next sections, we’ll cover all actions that can be performed using arrays.
# Array Operations
# Indexing an array
# We can use indices to retrieve elements of an array. See the below example:
import array as ar
# Create an array of 10 integers using range()
array_var = ar.array('i', range(10))
# Print array values using indices
print("1st array element is {} at index 0.".format(array_var[0]))
print("2nd array element is {} at index 1.".format(array_var[1]))
print("Last array element is {} at index 9.".format(array_var[9]))
print("Second array element from the tail end is {}.".format(array_var[-2]))
# Arrays have their first element stored at the zeroth index. Also, you can see that if we use -ve index,
# then it gives us elements from the tail end.
# The output is:
# 1st array element is 0 at index 0.
# 2nd array element is 1 at index 1.
# Last array element is 9 at index 9.
# Second array element from the tail end is 8.
# Slicing arrays The slice operator “:” is commonly used to slice strings and lists.
# However, it does work for the arrays also. Let’s see with the help of examples.
from array import *
# Create an array from a list of integers
intger_list = [10, 14, 8, 34, 23, 67, 47, 22]
intger_array = array('i', intger_list)
# Slice the given array in different situations
print("Slice array from 2nd to 6th index: {}".format(intger_array[2:6]))
print("Slice last 3 elements of array: {}".format(intger_array[:-3]))
print("Slice first 3 elements from array: {}".format(intger_array[3:]))
print("Slice a copy of entire array: {}".format(intger_array[:]))
# When you execute the above script, it produces the following output:
# Slice array from 2nd to 6th index: array('i', [8, 34, 23, 67])
# Slice last 3 elements of array: array('i', [10, 14, 8, 34, 23])
# Slice first 3 elements from array: array('i', [34, 23, 67, 47, 22])
# Slice a copy of entire array: array('i', [10, 14, 8, 34, 23, 67, 47, 22])
# The following two points, you should note down:
# When you pass both the left and right operands to the slice operator, then they act as the indexes.
# If you take one of them whether the left or right one, then it represents the no.of elements. Add / Update an array
# We can make changes to an array in different ways.Some of these are as follows:
# Assignment operator to change or update an array
# Append() method to add one element
# Extend() method to add multiple items
# We’ll now understand each of these approaches with the help of examples.
from array import *
# Create an array from a list of integers
num_array = array('i', range(1, 10))
print("num_array before update: {}".format(num_array))
# Update the elements at zeroth index
index = 0
num_array[index] = -1
print("num_array after update 1: {}".format(num_array))
# Update the range of elements, say from 2-7
num_array[2:7] = array('i', range(22, 27))
print("num_array after update 2: {}".format(num_array))
# The output is:
# num_array before update: array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9])
# num_array after update 1: array('i', [-1, 2, 3, 4, 5, 6, 7, 8, 9])
# num_array after update 2: array('i', [-1, 2, 22, 23, 24, 25, 26, 8, 9])
# We’ll apply the append() and extend() methods. These work the same for lists in Python.
# Difference Between List Append() and Extend()
from array import *
# Create an array from a list of integers
num_array = array('i', range(1, 10))
print("num_array before append()/extend(): {}".format(num_array))
# Add one elements using the append() method
num_array.append(99)
print("num_array after applying append(): {}".format(num_array))
# Add multiple elements using extend() methods
num_array.extend(range(20, 25))
print("num_array after applying extend(): {}".format(num_array))
# Results:
# num_array before append() / extend(): array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9])
# num_array after applying append(): array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 99])
# num_array after applying extend(): array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 99, 20, 21, 22, 23, 24])
# The point to note is that both append() or extend() adds elements to the end.
# The next tip is an interesting one.We can join two or more arrays using the “+” operator.
# Python Operator
from array import *
# Declare two arrays using Python range()
# One contains -ve integers and 2nd +ve values.
num_array1 = array('i', range(-5, 0))
num_array2 = array('i', range(0, 5))
# Printing arrays before joining
print("num_array1 before joining: {}".format(num_array1))
print("num_array2 before joining: {}".format(num_array2))
# Now, concatenate the two arrays
num_array = num_array1 + num_array2
print("num_array after joining num_array1 and num_array2: {}".format(num_array))
# Results:
# num_array1 before joining: array('i', [-5, -4, -3, -2, -1])
# num_array2 before joining: array('i', [0, 1, 2, 3, 4])
# num_array after joining num_array1 and num_array2: array('i', [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4])
# Remove array elements
# There are multiple ways that we can follow to remove elements from an array.
# Python del operator
# Remove() method
# Pop() method
from array import *
# Declare an array of 10 floats
num_array = array('f', range(0, 10))
# Printing the array before deletion of elements
print("num_array before deletion: {}".format(num_array))
# Delete the first element of array
del num_array[0]
print("num_array after removing first element: {}".format(num_array))
# Delete the last element
del num_array[len(num_array) - 1]
print("num_array after removing the last element: {}".format(num_array))
# Remove the entire array in one go
del num_array
# Printing a deleted array would raise the NameError
# print("num_array after removing first element: {}".format(num_array))
# The output is as follows:
# num_array before deletion: array('f', [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])
# num_array after removing first element: array('f', [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])
# num_array after removing the last element: array('f', [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])
# print("num_array after removing first element: {}".format(num_array))
# -->NameError: name 'num_array' is not defined
# Try to utilize the remove() and pop() methods.The former removes the given value from the array whereas the latter deletes the item at a specified index.
from array import *
# Declare an array of 8 numbers
num_array = array('i', range(11, 19))
# Printing the array before deletion of elements
print("num_array before deletion: {}".format(num_array))
# Remove 11 from the array
num_array.remove(11)
print("Array.remove() to remove 11: {}".format(num_array))
# Delete the last element
num_array.pop(len(num_array) - 1)
print("Array.pop() to remove last element: {}".format(num_array))
# After running this code, we get the below result:
# num_array before deletion: array('i', [11, 12, 13, 14, 15, 16, 17, 18])
# Array.remove() to remove 11: array('i', [12, 13, 14, 15, 16, 17, 18])
# Array.pop() to remove last element: array('i', [12, 13, 14, 15, 16, 17])
# Reverse array
# The last but not the least is how we can reverse the elements of an array in Python.\
# There can be many approaches to this. However, we’ll take the following two:
# Slice operator in Python
# Python List comprehension
from array import *
# Declare an array of 8 numbers
num_array = array('i', range(11, 19))
# Printing the original array
print("num_array before the reverse: {}".format(num_array))
# Reverse the array using Python's slice operator
print("Reverse num_array using slice operator: {}".format(num_array[::-1]))
# Reverse the array using List comprehension
print("Reverse num_array using List comprehension: {}".format(
array('i', [num_array[n] for n in range(len(num_array) - 1, -1, -1)])))
# Results:
# num_array before the reverse: array('i', [11, 12, 13, 14, 15, 16, 17, 18])
# Reverse num_array using slice operator: array('i', [18, 17, 16, 15, 14, 13, 12, 11])
# Reverse num_array using List comprehension: array('i', [18, 17, 16, 15, 14, 13, 12, 11])
# Now, we are mentioning a bonus method to reverse the array using the reversed() call.
# This function inverts the elements and returns a “list_reverseiterator” type object.
# Python Reversed()
"""
Example:
Applying Python Reversed() on an array
"""
from array import *
def print_Result(iter, orig):
print("##########")
print("Original: ", orig)
print("Reversed: ", end="")
for it in iter:
print(it, end=' ')
print("\n##########")
def reverse_Array(in_array):
result = reversed(in_array)
print_Result(result, in_array)
# Declare an array of 8 numbers
in_array = array('i', range(11, 19))
reverse_Array(in_array)
# Output:
##########
# Original: array('i', [11, 12, 13, 14, 15, 16, 17, 18])
# Reversed: 18 17 16 15 14 13 12 11
########## |
"""1. Создать список и заполнить его элементами различных типов данных.
Реализовать скрипт проверки типа данных каждого элемента.
Использовать функцию type() для проверки типа.
Элементы списка можно не запрашивать у пользователя, а указать явно, в программе."""
my_list = [1, 2, True, 12.7, ['a', 'b', 'c'], None, 'task_1', -9, {5, 7, 8}, (8, 9, 10)]
for el in my_list:
print(type(el))
|
variable_int = 3215
variable_int_float = 351.235
variable_str = 'Вася Пупкин'
variable_list = [1, 2, 7, 'lol']
print(type(variable_list))
user_name = input('Введите ваше имя: ')
user_age = int(input("Введите ваш возраст: "))
print(f'Вас зовут {user_name}, Вам {user_age} лет!!! ')
print(variable_int + variable_int_float)
|
# Rječnici u Pythonu
osoba = {
"ime":"Marko",
"prezime":"Marković",
"god":18
}
print(osoba["ime"]) #ako želimo ispisati određeni ključ
print(osoba.get("prezime")) #2. način ako želimo ispisati određeni ključ
x = osoba.keys() #ispisuje samo ključeve pošto piše .keys, a da piše .values onda bi ispisalo samo vrijednost
print(x)
osoba["razred"] = "2.C" #ako želimo dodati novi ključ
print(osoba.get("razred"))
for x in osoba:
print(x)
for x in osoba:
print(osoba[x])
for x in osoba.values():
print(x)
|
ime = input("unesi svoje ime:")
poruka = "dobar dan"
print(poruka + " " + ime)
a = int(input("unesi broj a:"))
b = int(input("unesi broj b:"))
print(a+b) |
# -*- coding: utf-8 -*-
from functions import contain, collect_digits, make_line, make_input
from functions import make_line_remainder, make_input_remainder
class Exercise:
"""This is the base class for the individual exercises.
An exercise is characterized by a topic. A topic determines the
fields of the settings self._sett and public methods of Exercise.
The values of self._sett may vary from exercise to exercise.
"""
def __init__(self):
""" An Exercise has a title, i.e. short textual description,
set by the author for display in the Collection. """
self._title = None
""" An Exercise has a detailed textual description
set by the author. """
self._description = None
""" An Exercise is characterized by an icon set by the author. """
self._icon = None
""" An Exercise stores data on evaluation, i.e. on how often the
Exercise has been done, what errors have been made TODO """
self._eval = None
""" The settings determine the generation of calculations.
The fields of the settings are determined by self._sett['topic'];
the values of the settings are different for different Exercises.
self._sett['calclines'] determines the # of lines in a calculation."""
self._sett = None
""" Calculations are generated according to the settings. """
self._calcs = None
""" An Exercise needs the Display for updating the settings"""
self._display = None
def get_topic(self):
"""The topic is preliminarily used to identify an exercise."""
return (self._sett)['topic']
def get_setting(self):
return self._sett
def update_setting(self, sett):
""" Update the settings and generate calculations accordingly. """
self._sett = sett
self._calcs = self._generate_calcs()
def get_next_calc(self):
""" Get the next calculation from the Exercise.
TODO.WN091123: handle exception after last exercise. """
return (self._calcs).pop()
def count(self):
""" Return the number of calculations generated by
the current settings """
return len(self._calcs)
def format_addsub_simp(self, (calc, linepos)):
""" Prepare the representation of a calculation for Display
on 1 line. Used within several subclasses. """
#@print('in Display.format_addsub_simp: calc=', (calc, linepos))#@
_ccs = collect_digits(calc)
#print('in Exercise.format_addsub_simp: _ccs=',_ccs )
_l0 = make_line(_ccs, linepos)
_ip = make_input(_ccs, linepos)
#@print('in Display.format_addsub_simp: return=', ([_l0], _ip)) #@
return ([_l0], _ip)
#return ([[' ', '1', '0', ' ', '-', ' ', '7', ' ', '=', ' ', '_', ' ']], [(0, 10, '3', ' 10 - 7 = _ ', ' 10 - 7 = 3 ', [' ', '1', '0', ' ', '-', ' ', '7', ' ', '=', ' ', '3', ' '])])
#===== methods of subclasses different for topic-specific settings
def format(self, calc):
""" Prepare the representation of a calculation for Display.
This method is public for eventual use on calculations
coming through the net (TODO cooperative games, etc)"""
pass
def _generate_calcs(self):
""" Generate calculations according to topic-specific settings.
Called on each call of update_setting"""
pass
def define_buttons(self):
""" Define buttons for update settings. """
pass
def set_buttons(self, sett):
""" Display buttons according to the current setting. """
pass
|
#!/usr/bin/python3
from bs4 import BeautifulSoup
import urllib.request
from nltk.corpus import stopwords
#reading data from URL
# GOOGLE
web=urllib.request.urlopen('https://www.google.com/')
#print or store HTML taged data
##print(web.read())
webdata=web.read()
#applying soup
souped=BeautifulSoup(webdata,'html5lib')
#if you want to print souped source of HTML:
##print(souped)
#only text extraction
text_data=souped.get_text()
##print (text_data)
tokenized=[i for i in text_data.split() if i.lower not in stopwords.words('english')]
print (tokenized)
print (" ")
print ("GOOGLE SOURCE CODE LENGTH:")
print (len(tokenized))
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns; sns.set(color_codes=True)
def generate_point(num_features, num_rows):
""" Generate X with an additional column with constant 1."""
X = []
for i in range(num_rows):
x = list(np.random.rand(num_features))
x.append(1)
X.append(x)
coef =np.random.rand(num_features+1)
return np.array(X) , np.array(coef)
def linear_function(coef, x):
return np.dot(coef,x)
def binary_classifier_2D(num_features, num_rows):
""" Associates the Linear function with a classification."""
x, coef = generate_point(num_features, num_rows)
_ = list(np.random.rand(num_rows))
y = []
for i in range(x.shape[0]):
if linear_function(coef, x[i]) > _[i]:
y.append(1)
if linear_function(coef, x[i]) < _[i]:
y.append(-1)
return y ,x ,coef, _
def return_data(num_features, num_rows):
""" Run this function to return the Synthetic Data and coeficients."""
y ,x ,coef, _ = binary_classifier(num_features, num_rows)
data = pd.DataFrame(x)
data.drop(data.columns[-1],axis =1, inplace = True)
data['y'] = _
data['Labels'] = y
return data, coef
def plot(num_features, num_rows):
""" Line and scatter plots representing the data and the linear classifier.,
Return the generated data with defined classes."""
if num_features == 1:
y,x,coef,_ =binary_classifier_2D(1, 50)
data = pd.DataFrame(x)
data.drop(data.columns[-1],axis =1, inplace = True)
data['y'] = _
data['Labels'] = y
data.columns = ['x','y','Class']
to_plot = coef[0]*x + coef[1]
plt.figure(figsize = (10,6))
sns.scatterplot(
x= 'x',
y='y',
data= data,
hue='Class',
legend= "full",
style="Class"
)
plt.title('Artificial Data', fontsize = 20)
plt.plot(x,to_plot,'-r')
sns.despine()
else:
print("This function is for data with one feature only!")
return data,coef
|
###########################################################################################
# try :
# < this block of code might lead to error
# except:
# < this block will run when there is error on code
# else :
# < this block will run where there is no error in code
# finally:
# < this block will always execute no matter if there is error or not
###########################################################################################
try:
file=open("text.txt","w")
file.write("Hello..this is test line")
except TypeError: # we can capture only specific error as well
print("There was as type error")
except TimeoutError: # Specific error
print("there was time out")
except:
print('All other exceptions')
finally:
print("I always run")
#we can check default error list of python official website https://docs.python.org/3/library/exceptions.html
|
# Python does not require any object to perform file operations like VB script FileSystem object
# In Python we can directly use open() function to open file.
my_file = open("c:\\ashfaque\\PythonTest.txt")
print(my_file.read()) # returns all contents
# after every read file cursor moves to at the end of file which cause all other operations
# performed after read() to return blank. Hence we need to use seek(0) to move pointer
# to the beginning of file every time after we perform read()
my_file.seek(0)
print(my_file.readlines()) # return list with each line as individual item.
# once we performed 'open' operation on file in python we need to manually perform 'close'
# operation as well in code otherwise it will cause file in use for other operations.
my_file.close()
# To avoid this approach of closing file manually in code after open we can use below method of
# opening file which python closes automatically for us.
with open("c:\\ashfaque\\PythonTest.txt") as my_file:
print(my_file.readlines())
#File open types
# read(r) : only for reading, no writing. (Default)
# write(w) : only for writing, no reading. Overwrite existing or create new if does not exists.
# append(a) : only add contents at the end of file
# read plus (r+) : is reading and writing. Does nto create new file if does not exists.
# write plus (w+) is for writing and reading. Creates a new file if does not exists.
with open("c:\\ashfaque\\PythonTest.txt", mode='w') as my_file:
my_file.write("hello world \n. How are you") # this will overwrite existing file.
|
# Decorators are used for wrapping given function in some other code. Instead of directly changing
# existing code which is prone to introducing new error, we create a decorators which takes function
# as argument and run decorators own code before/after running function taken as argument.
# So if we have to make changes / enhance existing function we use decorator for that function
# with extra code which we want to patch to existing code of function. It helps us to implement
# changes to existing function by acting as a on/off switch. If we do not have to use new code
# around existing function then just remove decorator.
############ Basic decorator in action ##########
def my_decorator(func):
def decorator_internal_func():
print("Here goes code which we wan to run before running input function")
func() # running input function
print("Here goes code which we want to run after running inout function")
return decorator_internal_func # Here we are taking function to run as input asn returning a function which wraps
# pre and post code to input function
def func_to_decorate():
print(f"\tthis is actual function.")
func_with_decorator = my_decorator(func_to_decorate)
func_with_decorator() # Here we are running function returned from decorator
########## decorator with real use ##################
# Instead of using above approach to call decorator function, python provide easy way to apply decorator on any function.
# Please note here both functions are decorators are not accepting any arguments. If we want to apply decorator on
# function which accepts arguments then there is other script for enplaning this concept 'Decorators-withArgs.py'
@my_decorator # this single line applies decorator to next defined function, thats it...!!!
def new_func_to_decorate():
print(f"\tthis is actual new function.")
# now whenever we call actual function it will automatically use decorator
print("\n\ndecorator function call")
new_func_to_decorate() |
import argparse
from teleport.parser import InputParser
from teleport.graph import TeleportGraph
def main():
"""
Main execution function for the script.
This is done in a method to scope the variables locally (instead of polluting the module namespace)
:return:
"""
args = _get_argument_parser().parse_args()
# read the file and interpret its contents
data = InputParser.from_path(args.input_path)
# build the graph
graph = TeleportGraph.from_tuples(data.routes)
# execute queries and print results
for query in data.queries:
result = query(graph)
print(result)
def _get_argument_parser():
"""
Builds the object that handles the command line arguments
:return: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser(description="This script builds the teleportation "
"graph and executes queries against it")
# add argument(s) to the parser
parser.add_argument('--input-path',
dest='input_path',
required=True,
help="fully qualified path to the input file")
return parser
if __name__ == '__main__':
main()
|
from collections import namedtuple
from .error import DataException
Route = namedtuple('Route', ['start', 'end'])
class CityNode:
"""Represents a node in the TeleportGraph"""
def __init__(self, name):
self._name = name
self._related_cities = set()
@property
def name(self):
return self._name
@property
def related_cities(self):
return self._related_cities
def add_related_city(self, city):
self._related_cities.add(city)
def remove_related_city(self, city):
self._related_cities.remove(city)
def __repr__(self):
return f"{self.__class__.name}(name={self.name})"
class TeleportGraph:
"""Represents the graph data structure - contains an index (via a dict) to each node"""
def __init__(self):
self._city_nodes = dict()
@property
def city_nodes(self):
return self._city_nodes.values()
@classmethod
def from_tuples(cls, routes):
"""
Build a new graph based upon the provided routes
:param routes: the routes to add to the newly created graph
:return: the constructed graph
"""
instance = cls()
for city1, city2 in routes:
instance.add_route(city1, city2)
return instance
def add_route(self, city1, city2):
"""
Adds a new bi-directional route to the graph, given string representations of the cities it connects.
:param city1: A city and one endpoint of the route
:param city2: A city and one endpoint of the graph
:return: None
"""
node1 = self._get_or_create_node(city1)
node2 = self._get_or_create_node(city2)
# explicitly add the link relationship between the two cities
node1.add_related_city(node2)
node2.add_related_city(node1)
def find_city_node(self, name) -> CityNode:
"""
Locates a given CityNode in the graph based upon the provided name. If the node is not found,
an exception is raised
:param name: The name of the city to query for
:return: The requested CityNode object
"""
try:
return self._city_nodes[name]
except KeyError as e:
raise DataException(f"Could not locate a city node in the graph for city=[{city}]") from e
def _get_or_create_node(self, city):
"""
Locates the city node with the name specified by the city argument - if not found, it will create a new one
:param city: name of the city to get/create
:return: A CityNode object
"""
if city not in self._city_nodes:
self._city_nodes[city] = CityNode(city)
return self._city_nodes[city]
|
import pprint
import re
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
codes = """.- -... -.-. -.. . ..-. --. .... .. .--- -.- .-..
-- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..
.---- ..--- ...-- ....- ..... -.... --... ---.. ----. -----"""
dd = dict(zip(chars.lower(), codes.split()))
DD = dict(zip(codes.split(), chars.lower()))
# pprint.pprint(dd)
def chars2morse(char):
return dd.get(char.lower(), ' ')
def morse2chars(morse):
return DD.get(morse, ' ')
while True:
str = input()
x = str.split(' ')
ccc = ''.join(x)
if re.match('^[0-9a-zA-Z]+$', ccc):
print(' '.join(chars2morse(c) for c in ccc))
else:
cc = str.split()
print(' '.join(morse2chars(c) for c in cc))
|
#!/usr/bin/python3
# This sample shows how to access image pixels.
#
# Licensed under the MIT License (MIT)
# Copyright (c) 2016 Eder Perez
import cv2
import sys
arglist = list(sys.argv)
if len(arglist) != 2:
print('')
print('Usage: python3 4_image_access.py IMAGE_PATH')
print('')
exit()
path = arglist[1]
print(path)
# Load image
img = cv2.imread( path )
# Access image BGR pixel (slow way)
px = img[0,0]
print(px)
# Access image red pixel (slow way)
px = img[0, 0, 2]
print(px)
# Modify pixel value (slow way)
img[0, 0] = [127, 127, 127]
print(img[0, 0])
# Access image BGR pixel (better way)
b = img.item(10, 10, 0)
g = img.item(10, 10, 1)
r = img.item(10, 10, 2)
print([b, g, r])
# Image properties (height, width and channels)
print(img.shape)
# Image number of pixels
channels = 1
if len(img.shape) == 3: channels = img.shape[2]
print( int(img.size / channels) )
# Image type
print(img.dtype)
# ROI (Region Of Interest)
roi = img[10:15, 5:10] # ROI from lines 10 to 15 and columns from 5 to 10
# Split image channels
b, g, r = cv2.split(img) # Slower way
b = img[:, :, 0] # Faster way
# Set all blue and green values to zero
img[:, :, 0] = 0
img[:, :, 1] = 0
# Merge image channels
img = cv2.merge((r, g, b))
|
#!/usr/bin/python3
def uppercase(str):
for i in range(len(str)):
j = ord(str[i])
if j > 96 and j < 123:
j -= 32
print('{:c}'.format(j), end='')
print()
|
#!/usr/bin/python3
""" Defines Square class """
from models.base import Base
from models.rectangle import Rectangle
class Square(Rectangle):
""" Square """
def __init__(self, size, x=0, y=0, id=None):
"""
Args:
* size (int): size
* x (int): horizontal length
* y (int): vertical length
* id (int): instance id
"""
super().__init__(size, size, x, y, id)
def __str__(self):
""" returns string representation of instance """
s = '[Square] ({}) {}/{} - {}'
return s.format(self.id, self.x, self.y, self.width)
@property
def size(self):
""" size. must be positive int """
return self.width
@size.setter
def size(self, value):
self.width = value
self.height = value
def update(self, *args, **kwargs):
""" updates class attributes.
if an argument is not keyworded, update in the following order:
id -> size -> x -> y
"""
if len(args) == 0:
for key, value in kwargs.items():
setattr(self, key, value)
return
attrs = ('id', 'size', 'x', 'y')
for i in range(len(args)):
setattr(self, attrs[i], args[i])
def to_dictionary(self):
""" returns dictionary representation of instance """
keys = ['x', 'y', 'id', 'size']
return {key: getattr(self, key) for key in keys}
|
#!/usr/bin/python3
"""
This module defines add_integer, a function that returns the sum of 2 integers
"""
def add_integer(a, b=98):
"""Returns sum of two numbers.
- If one number is inputted, it returns the number plus 98.
- Floats are converted to integers before addition.
- Returns a Type Error if an argument is not an int or float.
"""
if type(a) in (float, int) and type(b) in (float, int):
return int(a + b)
raise TypeError('a must be an integer')
|
#!/usr/bin/python3
""" defines Rectangle class """
BaseGeometry = __import__('7-base_geometry').BaseGeometry
class Rectangle(BaseGeometry):
""" Rectangle
Args:
* width (int): initializes width
* height (int): initializes height
Attributes:
* width (int): width
* height (int): height
"""
def __init__(self, width, height):
self.integer_validator("width", width)
self.integer_validator("height", height)
self.__width = width
self.__height = height
def area(self):
""" Returns area of shape """
return self.__width * self.__height
def __str__(self):
""" Returns string representation of class """
return "[Rectangle] {:d}/{:d}".format(self.__width, self.__height)
|
#!/usr/bin/python3
""" defines City class for MySQLdb integration """
from sqlalchemy import Column, Integer, String
from sqlalchemy.sql.schema import ForeignKey
from model_state import Base
class City(Base):
"""
Representation of cities table
Args:
* id (int): represents id column
* name (str): represents name column
"""
__tablename__ = "cities"
id = Column(Integer, primary_key=True)
name = Column(String(128), nullable=False)
state_id = Column(Integer, ForeignKey('states.id'))
def __init__(self, name, id=None):
self.id = id
self.name = name
|
def listaDiff(List1,List2):
l=[]
for x in List1:
if not x in List2:
l.append(x)
return l
L1=[]
L2=['1','2','3','4','5']
for i in range(5):
L1.append(input("Inserisci valore: "))
for i in range(5):
aux=input("Inserisci il valore: ")
if aux!="":
L2.pop(i)
L2.insert(i,aux)
else:
break
print(listaDiff(L1,L2))
print(L2)
|
import tkinter as tk
from tkinter import ttk;
win = tk.Tk();
win.title("My GUI");
#This blocks the resize window function
#win.resizable(0,0);
#Configuring and creating a label instance
aLabel = ttk.Label(win, text="My cute Label *w*")
aLabel.grid(column=0, row=0);
#click event
def clickMe():
global action
global aLabel
action.configure(text="You have pressed the button o.o")
aLabel.configure(foreground="red")
aLabel.configure(text="Now I'm red ._.")
action = ttk.Button(win, text="I'm a button :3", command=clickMe)
action.grid(column=0, row=1)
win.mainloop();
|
string = input("Please enter your own String : ")
string2 = ''
for i in string:
string2 = i + string2
print("\nThe Original String = ", string)
print("The Reversed String = ", string2)
|
#File IO
with open('words_alpha.txt', 'r') as f:
words = f.read().splitlines()
#functions
def num_words():
count = 0
for word in words:
count+=1
return count
def five_letter():
count = 0
for word in words:
if len(word)==5:
count+=1
return count
def longer_seven():
count = 0
for word in words:
if len(word)>7:
count+=1
return count
def total_letters():
count = 0
for word in words:
for w in word:
count += 1
return count
def no_e():
count = 0
for word in words:
if 'e' not in word:
count+=1
return count
def first_last():
count = 0
for word in words:
if word[0] == word[-1]:
count+=1
return count
def three_a():
count = 0
for word in words:
count_a = 0
for w in word:
if w == 'a':
count_a += 1
if count_a == 3:
count += 1
return count
def q_no_u():
count = 0
for word in words:
for i in range(len(word)):
if word[i] == 'q':
if len(word[i:]) >= 2 and word[i+1] != 'u':
count += 1
break
elif len(word[i:]) < 2 :
count += 1
break
return count
#output
print(num_words())
print(five_letter())
print(longer_seven())
print(total_letters())
print(no_e())
print(first_last())
print(three_a())
print(q_no_u())
|
# Taking input from user
name = input("Enter the hindi name: \n")
# Checking for last vowels
n = len(name)
if name[n-1] in ('a', 'e', 'i', 'o', 'u'):
print(name," is a woman")
else:
print(name," might be a man, onto the next step:")
# Moving on to next classifier, sonorants
# last 3 chars of the name
nameSONO = name[::-1]
array1 = []
for i in range(0,3):
array1.append(nameSONO[i])
# reversing the sonorant string
# converting the list into a string
sono = ''.join(array1)
sonorant = sono[::-1]
print("The sonorant is ", sonorant)
# comparing the sonorant
if sono in ("mha", "nha", "lha", "vha", "rha"):
print(name," is a woman")
else:
print(name," might be a man, onto the next step:")
# checking open syllables
if sonorant in ("be", "go", "hi","aja","avi", "kha", "eha","ali","eet"):
# The above list can be increased depending upon the corpus of hindi words
print(name," is a woman")
else:
print(name," is most probably a man")
''' The decision parameters for this program was referenced from
https://medium.com/simpl-under-the-hood/classifying-gender-based-on-indian-names-in-82f34ce47f6d
using their finding for hindi first names corpus. Decision tree can also be made based on the if
statements in the above program. Its not completely accurate for men names.
'''
# https://github.com/skylanskylion/IndianFirstName_classifier link the program and screenshots
|
from sys import exit
from Classes.game import bcolors, Person, Creature
print("Hello and welcome to your journey, today we will go across a a forest path and we may encounter enemies.")
print("Keep an eye on the hints, which will affect the story as you go along. You may be attacked at random.")
print("When you enter a battle, you will be given three choices either 'fight', 'heal', 'rum'")
print("When you are in battle mode, you will not be able to exit the script. Only when making decisions will you be ")
print("able to type 'quit' as an input and exit the script. Play out the battle before attempting to quit.")
input("Press enter to continue")
player = Person(400, 40, 10, 10, 10)
enemy = Person(400, 40, 10, 5, 10)
enemy2 = Person(400, 50, 10, 5, 10)
Bear = Creature(100, 40)
def start_journey():
print("""You are walking down a forest, in the realms of Gaul. You are on the way to the Feast of Augustus,
As you approach a fork in the road, you noticed there is no signage. You pause to think, and see both
roads. The left most road seems to be wide and appealing, it seems to be the main road. But you hesitate
to take it as robbers and pillagers tend to stake them out. The right road seem harder to walk through,
the terrain in rough. And the trees are less wide apart than the right path. But you hope that as the less
busy one robbers will be less of a concern.""")
input("press enter to continue")
start_choice = input("Do you take the 'left' road or the 'right' road? Please type choice in single quotes: ")
if start_choice == "left":
print("Well the left road seems easier to walk through, you are well armed and can take care of your self")
print("You walk down the road for a couple hours, when you are attacked by a robber.")
print(bcolors.FAIL + bcolors.BOLD + "A battle ensues" + bcolors.END)
print("fight")
do_battle()
you_continue()
elif start_choice == "right":
print("You took the right most road and start on your journey. The terrain is rough and unhewm and quite eerie")
print("""But you keep pressing on ahead and come upon a river, the river seems shallow and fast. You are a
a strong person and are sure you can swim it""")
river_cross()
elif start_choice == "quit":
print("You have quit the game, you will not be able to return to this choice unless you take the same path. ")
exit()
else:
print("Response not valid")
print(bcolors.FAIL + bcolors.BOLD + "Restarting from current decision point" + bcolors.END)
start_journey()
def you_continue():
print("""Phew, that was a hard battle. It was well fought and after a day of resting and drinking healing
potions you continue on your path hoping the new day does not bring any unpleasant surprises.
at any rate. You have plenty of potions. Which though small in size, are great and powerful healers. You
continue on your path. And after several hours you come across a dead horse, Do you stop to inspect it? or
do you give it s wide berth?""")
dead_horse_choice = input("Do you 'inspect' or do you 'walk away'? ")
if dead_horse_choice == "inspect":
print("You inspected the dead horse when a bear attacks you. ")
print(bcolors.FAIL + bcolors.BOLD + "DEFEND YOURSELF" + bcolors.END)
fight_creature()
print("You decided to flay the bear and, ")
get_more_potions()
input("Press enter to continue")
print("After you harvested some potions from the bear you continued on your journey and came upon a river")
print("You crossed the bridge and come upon a fork in the road.")
fork_in_road()
elif dead_horse_choice == "walk away":
print("""You were prudent, and kept walking. God knows what could have killed the horse, so its better to keep going,
instead of facing what dreadful animal or cruel person could have done such a deed. Having to fight for your
life once is enough for one journey. Maybe it was not the best idea to take the main road. Your destination
should not be too far away though. As the forest is just a day's walk long.""")
print("""You see a river up ahead, and a small little bridge to cross it. You are feeling a bit hungry, so it
it might be a good idea to stop and fish for a bit. """)
fishing_choice = input("Do you 'fish' or 'walk across' brige? Remember to keep input to choices in quotes")
if fishing_choice == "fish":
get_more_potions()
cont_after_fishing_1()
elif dead_horse_choice == "quit":
print("You have quit the script, good bye. You will start your journey from the start when running script again")
exit()
else:
print("Response not valid")
print(bcolors.FAIL + bcolors.BOLD + "Restarting from current decision point" + bcolors.END)
you_continue()
def river_cross():
print("You start swimming across the river, it is a tough going.")
print("The current is strong and hard to stay afloat, but you are halfway across.")
print("Unfortunately you are tiring out and are near the point of drowning")
print("You keep struggling on...")
input("Press enter")
print("It is getting nearly impossible")
input("Press enter")
print("You start swallowing water")
input("Press enter")
print("You drowned")
exit()
""""
For river_crossing() i want to add other elements after this but i decided to type it like this for the time being
and close this branch of the decision tree. i want to add elements of potion taking and healing. While slowly moving
the storyline back to the bridge. Or make it across the river before continuing down the road.
"""
def fork_in_road():
print("""After a long journey, and a few scary moments. You crossed the bridge and come upon a fork in the road.
The journey so far has been tough, and you hope that you will reach your destination on time for the feast
of Augustus. In the road you notice that there are two signs. One points to the left and reads 'Lugdunum'
and it is the Destination you are heading toward, the other at the right is hard to distinguish as the words
are worn down. As you read the signs. You hear a shrill cry from the right road. You think for a second
about which path to take? """)
fork_road_choice = input("Do you take the 'left' or 'right' path? Please keep your input to 'in quotes' text: ")
if fork_road_choice == "left":
print("You ignored the cry from the right road, it is too risky. And you do not know what could happen.")
input("Press enter...")
print("After walking for a couple hours, you reach the edge of the forest. And continue on your way...")
print("""You will make it to the feast of Augustus on time. Thanks for taking this road with us, you may
restart your journey and make other choices. Good bye for now.""")
exit()
if fork_road_choice == "right":
print("You are a kind person, and you decide that honor demands that you at least go and search the right road")
print("""You walk with guarded steps, and your sword on your hand. You slowly come upon a clearing. Where there
seem to be a burned cart. And some bodies on the ground, and you start to get apprehensive. Suddenly an
enemy appears. """)
enemy.full_restore()
do_battle()
go_back_fork()
if fork_road_choice == "quit":
print("You have exited the script, you will be taken to the start of your journey when you restart the script")
print("Good bye")
exit()
else:
print("Response not valid")
print(bcolors.FAIL + bcolors.BOLD + "Restarting from current decision point" + bcolors.END)
fork_in_road()
def cont_after_fishing_1():
print("""After a long journey, and a few scary moments. You crossed the bridge and come upon a fork in the road.
The journey so far has been tough, and you hope that you will reach your destination on time for the feast
of Augustus. In the road you notice that there are two signs. One points to the left and reads 'Lugdunum'
and it is the Destination you are heading toward, the other at the right is hard to distinguish as the words
are worn down. As you read the signs. You hear a shrill cry from the right road. You think for a second
about which path to take? """)
fork_road_choice_1= input("Do you take the 'left' or 'right' path? Please keep your input to 'in quotes' text: ")
if fork_road_choice_1 == "left":
print("You ignored the cry from the right road, it is too risky. And you do not know what could happen.")
input("Press enter...")
print("After walking for a couple hours, you reach the edge of the forest. And continue on your way...")
print("""You will make it to the feast of Augustus on time. Thanks for taking this road with us, you may
restart your journey and make other choices. Good bye for now.""")
exit()
if fork_road_choice_1 == "right":
print("You are a kind person, and you decide that honor demands that you at least go and search the right road")
print("""You walk with guarded steps, and your sword on your hand. You slowly come upon a clearing. Where there
seem to be a burned cart. And some bodies on the ground, and you start to get apprehensive. Suddenly an
enemy appears. """)
enemy.full_restore()
do_battle()
go_back_fork()
if fork_road_choice_1 == "quit":
print("You have exited the script, you will be taken to the start of your journey when you restart the script")
print("Good bye")
exit()
else:
print("Response not valid")
print(bcolors.FAIL + bcolors.BOLD + "Restarting from current decision point" + bcolors.END)
fork_in_road()
def go_back_fork():
print("""My God this forest is infested with Thieves, and dangers. These are not the best times to be alive. The
nation of Gaul is facing some difficulties times. But again we have prevailed, and have managed to outwit our
foes. After looking around the battle field you conclude that there is no path to be followed from here.""")
input("Press enter to continue")
print("""You trace your steps back to the cross sign and take the left road. After a few hours you reach the end
the forest. And hope that no more scoundrels or creatures await your path.""")
input("Thank you for joining us in this journey, battles were fought and won with honor. Press enter to leave")
print("Good bye")
exit()
def do_battle():
run = True
while run:
print("=================================")
player.choose_action()
choice = input("Choose action: ")
while not choice.isnumeric():
print("not valid")
do_battle()
index = int(choice) -1
if index == 0 :
dmg = player.generate_damage()
enemy.take_damage(dmg)
print("You attacked for", dmg, "points of damage. Enemy HP:", enemy.get_hp())
enemy_choice = 0
enemy_dmg = enemy.generate_damage()
player.take_damage(enemy_dmg)
print("Enemy attacks for", enemy_dmg, "Player HP", player.get_hp())
elif index == 1:
player.take_potions()
if player.get_npotions() > 0:
heal = player.generate_hep()
player.take_heal(heal)
print("You took a healing potion for", heal, "Player HP:", player.get_hp())
print("Potions left:", player.get_npotions(), "/", player.get_max_npotions())
elif player.get_npotions() < 0:
print("You cannot take a potion at this time")
enemy_choice = 1
enemy.take_potions()
if enemy.get_npotions() > 0:
enemy_heal = enemy.generate_hep()
enemy.take_heal(enemy_heal)
print("Enemy took a healing potion for", enemy_heal, "Enemy HP:", enemy.get_hp())
print("Potions left:", enemy.get_npotions(), "/", enemy.get_max_npotions())
elif enemy.take_potions() < 0:
print("Enemy ran out of potions. He cannot take any more potions")
elif index == 2:
print("You ran away")
run = False
if enemy.get_hp() == 0:
print("Your ememy is dead, you were wounded. We recommend resting to recover hp.")
print("your total number of potions is", player.get_npotions(), "/", player.get_max_npotions())
healing_rest = input("Do you want to rest? 'yes' or 'no': ")
if healing_rest == "yes":
player.full_restore()
print("After a day of rest, you recovered your strength to continue walking.")
run = False
elif healing_rest == "no":
print("You continued your path, and died after several hours from the wounds")
exit()
elif player.get_hp() == 0:
print("You died")
exit()
def fight_creature():
run = True
while run:
print("=================================")
player.choose_crAction()
crChoice = input("Choose action: ")
while not crChoice.isnumeric():
print("not valid")
fight_creature()
index = int(crChoice) - 1
if index == 0:
dmg = player.generate_damage()
Bear.take_damage(dmg)
print("You attacked for", dmg, "points of damage. Creature HP:", Bear.get_hp())
enemy_choice = 0
creature_dmg = Bear.generate_damage()
player.take_damage(creature_dmg)
print("Enemy attacks for", creature_dmg, "Player HP", player.get_hp())
elif index == 1:
print("You ran away")
print("The bear gives chase to you, and catches you after a few minutes. It mortally wounds you...")
print("You are bleeding...")
input("Press enter")
print("You lay in agony, the bear comes around again")
input("Press enter")
print("It starts to tears you from limb to limb...")
print("You died horribly as a victim of the bear. Your family never finds your body. ")
exit()
if Bear.get_hp() == 0:
print("The creature is dead, you were wounded. We recommend resting to recover hp.")
healing_rest = input("Do you want to rest? 'yes' or 'no': ")
if healing_rest == "yes":
print("After a day of rest, you recovered your strength to continue walking.")
run = False
elif healing_rest == "no":
print("You continued your path, and died after several hours from the wounds")
exit()
elif player.get_hp() == 0:
print("You died")
exit()
def get_more_potions():
plus_potions = player.generate_npotions()
player.add_potions(plus_potions)
print("You started searching for potions and got some potions. Your new potions total is", player.get_npotions())
start_journey()
prin("Hello bitches")
|
第一遍
看答案,学数据结构,学最优解
第二遍
背
第三遍
自己写
# 28. Implement strStr()
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
for i in range(len(haystack) - len(needle) + 1):
if haystack[i:i + len(needle)] == needle:
return i
return -1
# 459. Repeated Substring Pattern
# 771. Jewels and Stones
class a(object):
def numJewelsInStones(self, J, S):
return sum(s in J for s in S)
# 242. Valid Anagram
# 写出一个函数 anagram(s, t) 判断两个字符串是否可以通过改变字母的顺序变成一样的字符串
class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return sorted(s) == sorted(t)
# 438. Find All Anagrams in a String
# return all possible index into a list
# Given a string s and a non-empty string p, find all the start indices of p's anagrams in s
from collections import Counter
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
res = []
pCounter = Counter(p)
sCounter = Counter(s[:len(p) - 1])
for i in range(len(p) - 1, len(s)):
sCounter[s[i]] += 1 # include a new char in the window
if sCounter == pCounter: # This step is O(1), since there are at most 26 English letters
res.append(i - len(p) + 1) # append the starting index
sCounter[s[i - len(p) + 1]] -= 1 # decrease the count of oldest char in the window
if sCounter[s[i - len(p) + 1]] == 0:
del sCounter[s[i - len(p) + 1]] # remove the count if it is 0
return res
class Solution:
# @param {string} s a string
# @param {string} p a non-empty string
# @return {int[]} a list of index
def findAnagrams(self, s, p):
# Write your code here
ans = []
sum = [0 for x in range(0, 30)]
plength = len(p)
slength = len(s)
for i in range(plength):
sum[ord(p[i]) - ord('a')] += 1
start = 0
end = 0
matched = 0
while end < slength:
if sum[ord(s[end]) - ord('a')] >= 1:
matched += 1
sum[ord(s[end]) - ord('a')] -= 1
end += 1
if matched == plength:
ans.append(start)
if end - start == plength:
if sum[ord(s[start]) - ord('a')] >= 0:
matched -= 1
sum[ord(s[start]) - ord('a')] += 1
start += 1
return ans
# 760. Find Anagram Mappings
class Solution(object):
def anagramMappings(self, A, B):
D = {x: i for i, x in enumerate(B)}
return [D[x] for x in A]
# 804. Unique Morse Code Words
class Solution:
def uniqueMorseRepresentations(self, words):
"""
:type words: List[str]
:rtype: int
"""
morse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
"-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
s = set()
s = {"".join(morse[ord(c) - ord('a')] for c in word)
for word in words}
return len(s)
# 3. Longest Substring Without Repeating Characters (medium)
# Given "pwwkew", the answer is "wke", with the length of 3. Note that
# the answer must be a substring, "pwke" is a subsequence and not a substring.
# 不一定从头开始的,可能是中间一节
def lengthOfLongestSubstring(self, s):
longest = []
max_length = 0
for c in s:
if c in longest:
max_length = max(max_length, len(longest))
longest = longest[longest.index(c) + 1:]
longest.append(c)
max_length = max(max_length, len(longest))
return max_length
def lengthOfLongestSubstring(self, s):
"""
"""
# runtime: 95ms
dic = {}
res, last_match = 0, -1
for i, c in enumerate(s):
if c in dic and last_match < dic[c]:
last_match = dic[c]
res = max(res, i - last_match)
dic[c] = i
return res
# 387. First Unique Character in a String
# Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
# s = "leetcode" return 0.
# s = "loveleetcode", return 2.
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
letters = 'abcdefghijklmnopqrstuvwxyz'
index = [s.index(l) for l in letters if s.count(l) == 1] # in letters not in s
return min(index) if len(index) > 0 else -1
class Solution(object):
def firstUniqChar(self, s):
return min([s.find(c) for c in string.ascii_lowercase if s.count(c) == 1] or [-1])
# 859. Buddy Strings
# Given two strings A and B of lowercase letters, return true if and
# only if we can swap two letters in A so that the result equals B
# https://leetcode.com/problems/buddy-strings/description/
def buddyStrings(self, A, B):
if len(A) != len(B): return False
if A == B and len(set(A)) < len(A): return True
dif = [(a, b) for a, b in zip(A, B) if a != b] # 这个比较两个string的方法很好
return len(dif) == 2 and dif[0] == dif[1][::-1]
# 832. Flipping an Image
class Solution(object):
def flipAndInvertImage(self, A):
for row in A:
for i in range((len(row) + 1) // 2):
row[i], row[~i] = row[~i] ^ 1, row[i] ^ 1 # has to be binary
return A
# ~i 从-1开始,-1,-2,-3, a[~i]就是倒着从最后开始.
# 1. Two Sum to target value, return index
# 千万注意这里的list不是sorted, 所以不能一前一后的查找,必须两个循环找,下面的变形题可以。
class Solution:
def twoSum(self, nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return i, j
# 变形 167. Two Sum II - Input array is sorted
# Your returned answers (both index1 and index2) are not zero-based.
class Solution:
"""
@param nums {int[]} n array of Integer
@param target {int} = nums[index1] + nums[index2]
@return {int[]} [index1 + 1, index2 + 1] (index1 < index2)
"""
def twoSum(self, nums, target):
# Write your code here
l, r = 0, len(nums) - 1
while l < r:
value = nums[l] + nums[r]
if value == target:
return [l + 1, r + 1]
elif value < target:
l += 1
else:
r -= 1
return []
# 13. Roman to integer
class Solution:
# @param {string} s
# @return {integer}
def romanToInt(self, s):
ROMAN = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
if s == "":
return 0
index = len(s) - 2
sum = ROMAN[s[-1]]
while index >= 0:
if ROMAN[s[index]] < ROMAN[s[index + 1]]:
sum -= ROMAN[s[index]]
else:
sum += ROMAN[s[index]]
index -= 1
return sum
# 12. Integer to Roman
M = ["", "M", "MM", "MMM"];
C = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"];
X = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"];
I = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];
return M[num // 1000] + C[(num % 1000) // 100] + X[(num % 100) // 10] + I[num % 10];
# 344. Reverse String
class Solution:
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
# 541. Reverse String II
# Input: s = "abcdefg", k = 2
# Output: "bacdfeg"
def reverseStr(self, s, k):
s = list(s)
for i in xrange(0, len(s), 2 * k):
s[i:i + k] = reversed(s[i:i + k])
return "".join(s)
# 151. Given an input string, reverse the string word by word.
class Solution:
# @param s : A string
# @return : A string
def reverseWords(self, s):
return ' '.join(reversed(s.strip().split()))
# 或者 return ' '.join(s.split()[::-1])
# 或者 return " ".join(word for word in reversed(s.split(' ')))
# 落单的数 · Single Number
# 给出2*n + 1 个的数字,除其中一个数字之外其他每个数字均出现两次,找到这个数字。
# 14. Longest Common Prefix
class Solution:
# @param strs: A list of strings
# @return: The longest common prefix
def longestCommonPrefix(self, strs):
# write your code here
if len(strs) <= 1:
return strs[0] if len(strs) == 1 else ""
end, minl = 0, min([len(s) for s in strs])
while end < minl:
for i in range(1, len(strs)):
if strs[i][end] != strs[i - 1][end]:
return strs[0][:end]
end = end + 1
return strs[0][:end]
# 461. Hamming Distance
class Solution(Object)
def hammingDistance(self, x, y)
return ((bin(x ^ y)[2:]).count("1"))
# 477. Total Hamming Distance
??
# 9. Palindrome Number
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
x = str(x)
return (x[::-1] == x)
# 变形Palindrome Number II 判断一个非负整数 n 的二进制表示是否为回文数
return str(bin(x)[2:])[::-1] == str(bin(x)[2:]) # didn't test
# 125. Valid Palindrome
def isPalindrome(self, s):
l, r = 0, len(s) - 1
while l < r:
while l < r and not s[l].isalnum():
l += 1
while l < r and not s[r].isalnum():
r -= 1
if s[l].lower() != s[r].lower():
return False
l += 1;
r -= 1
return True
class Solution:
# @param {string} s A string
# @return {boolean} Whether the string is a valid palindrome
def isPalindrome(self, s):
start, end = 0, len(s) - 1
while start < end:
while start < end and not s[start].isalpha() and not s[start].isdigit():
start += 1
while start < end and not s[end].isalpha() and not s[end].isdigit():
end -= 1
if start < end and s[start].lower() != s[end].lower():
return False
start += 1
end -= 1
return True
# 409. Longest Palindrome
# Given a string which consists of lowercase or uppercase letters, find the length of
# the longest palindromes that can be built with those letters.
def longestPalindrome(self, s):
odds = sum(v & 1 for v in collections.Counter(s).values())
return len(s) - odds + bool(odds)
# 7. Reverse Integer
class Solution:
# @param {int} n the integer to be reversed
# @return {int} the reversed integer
def reverseInteger(self, n):
if n == 0:
return 0
neg = 1
if n < 0:
neg, n = -1, -n
reverse = 0
while n > 0:
reverse = reverse * 10 + n % 10
n = n / 10
reverse = reverse * neg
if reverse < -(1 << 31) or reverse > (1 << 31) - 1:
return 0
return reverse
# method2
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
sign = [1, -1][x < 0]
rst = sign * int(str(abs(x))[::-1])
return rst if -(2 ** 31) - 1 < rst < 2 ** 31 else 0
# 变形 反转一个3位整数 · reverse 3 digit integer
class Solution:
"""
@param number: A 3-digit integer
@return: Reversed integer
"""
def reverseInteger(self, number):
return number % 10 * 100 + number / 10 % 10 * 10 + number / 100
# 21. Merge Two Sorted Lists
# Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
class Solution(object):
'''
题意:合并两个有序链表
'''
def mergeTwoLists(self, l1, l2):
dummy = ListNode(0)
tmp = dummy
while l1 != None and l2 != None:
if l1.val < l2.val:
tmp.next = l1
l1 = l1.next
else:
tmp.next = l2
l2 = l2.next
tmp = tmp.next
if l1 != None:
tmp.next = l1
else:
tmp.next = l2
return dummy.next
# 删除列表中节点 · Delete Node in a Linked List
# 这道题让我们删除链表的一个节点,更通常不同的是,没有给我们链表的起点,只给我们了一个要删的节点,
# 跟我们以前遇到的情况不太一样,我们之前要删除一个节点的方法是要有其前一个节点的位置,然后将其前一个
# 点的next连向要删节点的下一个,然后delete掉要删的节点即可。这道题的处理方法是先把当前节点的值用下
# 一个节点的值覆盖了,然后我们删除下一个节点即可
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val;
node.next = node.next.next;
# 203. Remove Linked List Elements
# Remove all elements from a linked list of integers that have value val.
# 206. Reverse Linked List
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
curt = None
while head != None:
temp = head.next
head.next = curt
curt = head
head = temp
return curt
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
prev = None
current = head
while current != None:
nxt = current.next
current.next = prev
prev = current
current = nxt
return prev
# 92. Reverse Linked List II
# Reverse a linked list from position m to n. Do it in one-pass.
# # 561. Array Partition I
# # https://docs.python.org/2.3/whatsnew/section-slices.html
# class Solution:
# def arrayPairSum(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# return sum(sorted(nums)[::2])
# 66 Plus one
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
end = len(digits) - 1
while end >= 0:
if digits[end] < 9:
digits[end] += 1
return digits
else:
digits[end] = 0
end -= 1
else:
return ([1] + digits)
** * # 122. Best Time to Buy and Sell Stock II, no transactional fee 可以多次买卖
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
# example [7,1,5,3,6,4]
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
profit = 0
for i in range(len(prices) - 1):
if prices[i] < prices[i + 1]:
profit = profit + prices[i + 1] - prices[i]
return profit;
# 121. Best Time to Buy and Sell Stock, 只能买卖一次, need to buy first
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
low = float('inf')
profit = 0
for i in range(len(prices)):
if prices[i] < low:
low = prices[i];
elif prices[i] - low > profit:
profit = prices[i] - low
return profit
# 169. Majority Element
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
return nums[int(len(nums) / 2)]
# 283. Move Zeroes
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
zero = 0 # records the position of "0"
for i in range(len(nums)):
if nums[i] != 0:
nums[i], nums[zero] = nums[zero], nums[i]
zero += 1
# 217. Contains Duplicate
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return len(nums) != len(set(nums)) # 不用len的时候 空list要出错
** * # 219. Contains duplicate II
# 同样元素位置相差最大是k
# Given an array of integers and an integer k, find out whether there are two
# distinct indices i and j in the array such that nums[i] = nums[j] and the
# absolute difference between i and j is at most k.
def containsNearbyDuplicate(self, nums, k):
dic = {}
for i, v in enumerate(nums):
if v in dic and i - dic[v] <= k:
return True
dic[v] = i
return False
# 26. Remove Duplicates from Sorted Array
# 给定一个排序数组,在原数组中删除重复出现的数字,使得每个元素只出现一次,并且返回新的数组的长度。
# 不要使用额外的数组空间,必须在原地没有额外空间的条件下完成。
class Solution:
"""
@param A: a list of integers
@return an integer
"""
def removeDuplicates(self, A):
# write your code here
if A == []:
return 0
index = 0
for i in range(1, len(A)):
if A[index] != A[i]:
index += 1
A[index] = A[i]
return index + 1
# 27. Remove Element in place
# Given an array nums and a value val, remove all
# instances of that value in-place and return the new length
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
st, end = 0, len(nums) - 1
while st <= end:
if nums[st] == val:
nums[st], nums[end] = nums[end], nums[st]
end -= 1
else:
st += 1
return st
# 88. merge sorted array in-place
# ou may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
while m > 0 and n > 0:
if nums1[m - 1] > nums2[n - 1]:
nums1[m + n - 1] = nums1[m - 1]
m -= 1
else:
nums1[m + n - 1] = nums2[n - 1]
n -= 1
nums1[:n] = nums2[:n]
# 104. Maximum Depth of Binary Tree
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: An integer
"""
def maxDepth(self, root):
if root is None:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
# 53. Maximum Subarray 异位动态规划
# Given an integer array nums, find the contiguous subarray (containing at least one number)
# which has the largest sum and return its sum
# [-2,1,-3,4,-1,2,1,-5,4]
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
maxSum = nums[0]
curSum = nums[0]
for i in range(1, len(nums)):
curSum = max(curSum + nums[i], nums[i]) # 注意不是比较 curSum+num[i] 和 curSum
if curSum > maxSum:
maxSum = curSum
return maxSum
class Solution:
# @param A, a list of integers
# @return an integer
# 6:57
def maxSubArray(self, A):
if not A:
return 0
curSum = maxSum = A[0]
for num in A[1:]:
curSum = max(num, curSum + num)
maxSum = max(maxSum, curSum)
return maxSum
class Solution:
def maxSubArray(self, nums):
if nums is None or len(nums) == 0:
return 0
maxSum = nums[0]
minSum = 0
sum = 0
for num in nums:
sum += num
if sum - minSum > maxSum:
maxSum = sum - minSum
if sum < minSum:
minSum = sum
return maxSum
# 643. Maximum Average Subarray I
# Given an array consisting of n integers, find the contiguous
# subarray of given length k that has the maximum average value.
# And you need to output the maximum average value.
def findMaxAverage(self, A, K): # 注意这里k是给定的,有些题里长度不一定
P = [0]
for x in A:
P.append(P[-1] + x)
ma = max(P[i + K] - P[i] for i in range(len(A) - K + 1))
return ma / float(K)
def findMaxAverage(self, nums, k):
sums = [0] + list(itertools.accumulate(nums))
return max(map(operator.sub, sums[k:], sums)) / k
def findMaxAverage(self, nums, k):
sums = np.cumsum([0] + nums)
return int(max(sums[k:] - sums[:-k])) / k
# 110. Balanced Binary Tree
class Solution(object):
def isBalanced(self, root):
def check(root):
if root is None:
return 0
left = check(root.left)
right = check(root.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return 1 + max(left, right)
return check(root) != -1
class Solution:
"""
@param root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def isBalanced(self, root):
balanced, _ = self.validate(root)
return balanced
def validate(self, root):
if root is None:
return True, 0
balanced, leftHeight = self.validate(root.left)
if not balanced:
return False, 0
balanced, rightHeight = self.validate(root.right)
if not balanced:
return False, 0
return abs(leftHeight - rightHeight) <= 1, max(leftHeight, rightHeight) + 1
# fibonacci
class Solution:
def Fibonacci(self, n):
a = 0
b = 1
for i in range(n - 1):
a, b = b, a + b
return a
# 70. Climbing Stairs 类似fabinacci DP 问题
class Solution:
"""
@param n: An integer
@return: An integer
"""
def climbStairs(self, n):
# write your code here
if n == 0:
return 1
if n <= 2:
return n
result = [1, 2]
for i in range(n - 2):
result.append(result[-2] + result[-1])
return result[-1]
# 变形 爬楼梯II, 每次可以1,2,3步
class Solution:
"""
@param {int} n a integer
@return {int} a integer
"""
def climbStairs2(self, n):
# write your code here
if n <= 1:
return 1
if n == 2:
return 2
a, b, c = 1, 1, 2
for i in range(3, n + 1):
a, b, c = b, c, a + b + c
return c
# 746. Min Cost Climbing Stairs
# On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
# Once you pay the cost, you can either climb one or two steps. You need to find minimum
# cost to reach the top of the floor, and you can either start from the step with index 0,
# or the step with index 1.
def minCostClimbingStairs(self, cost):
min_cost0, min_cost1 = cost[0], cost[1]
for c in cost[2:]:
min_cost0, min_cost1 = min_cost1, min(min_cost0, min_cost1) + c
return min(min_cost0, min_cost1)
class Solution:
def minCostClimbingStairs(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
for i in range(2, len(cost)):
cost[i] = min(cost[i] + cost[i - 1], cost[i] + cost[i - 2]);
return min(cost[-1], cost[-2]);
# 412. Fizz Buzz
class Solution:
"""
@param n: An integer as description
@return: A list of strings.
For example, if n = 7, your code should return
["1", "2", "fizz", "4", "buzz", "fizz", "7"]
"""
def fizzBuzz(self, n):
results = []
for i in range(1, n + 1):
if i % 15 == 0:
results.append("fizz buzz")
elif i % 5 == 0:
results.append("buzz")
elif i % 3 == 0:
results.append("fizz")
else:
results.append(str(i))
return results
def fizzBuzz(self, n):
return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n + 1)]
# 258. Add Digits
class Solution(object):
def addDigits(self, num):
return num if num == 0 else num % 9 or 9
# 205. Isomorphic Strings
def isIsomorphic(self, s, t):
return len(set(zip(s, t))) == len(set(s)) and len(set(zip(t, s))) == len(set(t))
def isIsomorphic1(self, s, t):
d1, d2 = {}, {}
for i, val in enumerate(s):
d1[val] = d1.get(val, []) + [i]
for i, val in enumerate(t):
d2[val] = d2.get(val, []) + [i]
return sorted(d1.values()) == sorted(d2.values())
def isIsomorphic2(self, s, t):
d1, d2 = [[] for _ in xrange(256)], [[] for _ in xrange(256)]
for i, val in enumerate(s):
d1[ord(val)].append(i)
for i, val in enumerate(t):
d2[ord(val)].append(i)
return sorted(d1) == sorted(d2)
def isIsomorphic3(self, s, t):
return len(set(zip(s, t))) == len(set(s)) == len(set(t))
def isIsomorphic4(self, s, t):
return [s.find(i) for i in s] == [t.find(j) for j in t]
def isIsomorphic5(self, s, t):
return map(s.find, s) == map(t.find, t)
def isIsomorphic(self, s, t):
d1, d2 = [0 for _ in xrange(256)], [0 for _ in xrange(256)]
for i in xrange(len(s)):
if d1[ord(s[i])] != d2[ord(t[i])]:
return False
d1[ord(s[i])] = i + 1
d2[ord(t[i])] = i + 1
return True
# 226. Invert Binary Tree (flip)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root:
invert = self.invertTree
root.left, root.right = invert(root.right), invert(root.left)
return root
# 235. Lowest Common Ancestor of a Binary Search Tree (BST 一定是左比右边小)
class Solution:
def lowestCommonAncestor(self, root, p, q):
while root:
if root.val > p.val and root.val > q.val:
root = root.left
elif root.val < p.val and root.val < q.val:
root = root.right
else:
return root
# 669. Trim a Binary Search Tree
class Solution(object):
def trimBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: TreeNode
"""
if not root:
return None
if L > root.val:
return self.trimBST(root.right, L, R)
elif R < root.val:
return self.trimBST(root.left, L, R)
root.left = self.trimBST(root.left, L, R)
root.right = self.trimBST(root.right, L, R)
return root
class Solution:
def trimBST(self, root, minimum, maximum):
dummy = prev = TreeNode(0)
while root != None:
while root != None and root.val < minimum:
root = root.right
if root != None:
prev.left = root
prev = root
root = root.left
prev.left = None
prev = dummy
root = dummy.left
while root != None:
while root != None and root.val > maximum:
root = root.left
if root != None:
prev.right = root
prev = root
root = root.right
prev.right = None
return dummy.right
# 538. Convert BST to Greater Tree
# Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key
# of the original BST is changed to the original key plus sum of all keys greater than
# the original key in BST.
class Solution:
# @param {TreeNode} root the root of binary tree
# @return {TreeNode} the new root
def convertBST(self, root):
# Write your code here
self.sum = 0
self.helper(root)
return root
def helper(self, root):
if root is None:
return
if root.right:
self.helper(root.right)
self.sum += root.val
root.val = self.sum
if root.left:
self.helper(root.left)
# 236. Lowest Common Ancestor of a 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, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root in (None, p, q): return root
left, right = (self.lowestCommonAncestor(kid, p, q)
for kid in (root.left, root.right))
return root if left and right else left or right
# 819. Most Common Word
def mostCommonWord(self, p, banned):
ban = set(banned)
words = re.sub(r'[^a-zA-Z]', ' ', p).lower().split()
return collections.Counter(w for w in words if w not in ban).most_common(1)[0][0]
# 202. Happy Number
def isHappy(self, n):
mem = set()
while n != 1:
n = sum([int(i) ** 2 for i in str(n)])
if n in mem:
return False
else:
mem.add(n)
else:
return True
def isHappy(self, n):
seen = set()
while n not in seen:
seen.add(n)
n = sum([int(x) ** 2 for x in str(n)])
return n == 1
# 20. Valid Parentheses
class Solution(object):
'''
题意:输入一个只包含括号的字符串,判断括号是否匹配
模拟堆栈,读到左括号压栈,读到右括号判断栈顶括号是否匹配
'''
def isValidParentheses(self, s):
stack = []
for ch in s:
# 压栈
if ch == '{' or ch == '[' or ch == '(':
stack.append(ch)
else:
# 栈需非空
if not stack:
return False
# 判断栈顶是否匹配
if ch == ']' and stack[-1] != '[' or ch == ')' and stack[-1] != '(' or ch == '}' and stack[-1] != '{':
return False
# 弹栈
stack.pop()
return not stack
class Solution:
# @return a boolean
def isValid(self, s):
stack = []
dict = {"]": "[", "}": "{", ")": "("}
for char in s:
if char in dict.values():
stack.append(char)
elif char in dict.keys():
if stack == [] or dict[char] != stack.pop():
return False
else:
return False
return stack == []
** * # binary search
# Binary search is a famous question in algorithm.
# For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity.
# If the target number does not exist in the array, return -1.
# Example If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.
class Solution:
# @param nums: The integer array
# @param target: Target number to find
# @return the first position of target in nums, position start from 0
def binarySearch(self, nums, target):
if len(nums) == 0:
return -1
start, end = 0, len(nums) - 1
while start + 1 < end:
mid = (start + end) / 2
if nums[mid] < target:
start = mid
else:
end = mid
if nums[start] == target:
return start
if nums[end] == target:
return end
return -1
** * # 74 search a 2D matrix
# Integers in each row are sorted from left to right.
# The first integer of each row is greater than the last integer of the previous row.
# 重点在于 下一行的第一个数大于前一行的最后一个数,其实整个matrix是个sorted
# return true or false
class Solution:
"""
@param matrix, a list of lists of integers
@param target, an integer
@return a boolean, indicate whether matrix contains target
"""
def searchMatrix(self, matrix, target):
if len(matrix) == 0:
return False
n, m = len(matrix), len(matrix[0])
start, end = 0, n * m - 1
while start + 1 < end:
mid = (start + end) / 2
x, y = mid / m, mid % m
if matrix[x][y] < target:
start = mid
else:
end = mid
x, y = start / m, start % m
if matrix[x][y] == target:
return True
x, y = end / m, end % m
if matrix[x][y] == target:
return True
return False
class Solution:
# @param matrix, a list of lists of integers
# @param target, an integer
# @return a boolean
def searchMatrix(self, matrix, target):
if not matrix or target is None:
return False
rows, cols = len(matrix), len(matrix[0])
low, high = 0, rows * cols - 1
while low <= high: # 这里必须有等于,否则结果不对
mid = (low + high) // 2 # 必须要得到整数
num = matrix[mid // cols][mid % cols]
if num == target:
return True
elif num < target:
low = mid + 1
else:
high = mid - 1
return False
# 240. Search a 2D Matrix II
# 区别是并没有完全sorted
# 而是左右,上下sorted
class Solution:
# @param {integer[][]} matrix
# @param {integer} target
# @return {boolean}
def searchMatrix(self, matrix, target):
if matrix:
row, col, width = len(matrix) - 1, 0, len(matrix[0])
while row >= 0 and col < width:
if matrix[row][col] == target:
return True
elif matrix[row][col] > target:
row = row - 1
else:
col = col + 1
return False
# 566. Reshape the Matrix
import numpy as np
class Solution(object):
def matrixReshape(self, nums, r, c):
try:
return np.reshape(nums, (r, c)).tolist()
except:
return nums
def matrixReshape(self, nums, r, c):
flat = sum(nums, [])
if len(flat) != r * c:
return nums
tuples = zip(*([iter(flat)] * c))
return map(list, tuples)
## 868. Transpose Matrix
class Solution(object):
def transpose(self, A):
return list(zip(*A)) # without list, it returns an iterator
# A = [[1,2,3],[4,5,6],[7,8,9]]
# *A 成了 [1, 2, 3] [4, 5, 6] [7, 8, 9]
# zip 就是每个list第一个元素combine起来 [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
class Solution:
def transpose(self, A):
return [[A[i][j] for i in range(len(A))] for j in range(len(A[0]))]
# 204. Count Primes Count the number of prime numbers less than a non-negative number, n.
class Solution:
# @param {integer} n
# @return {integer}
def countPrimes(self, n):
if n < 3:
return 0
primes = [True] * n
primes[0] = primes[1] = False
for i in range(2, int(n ** 0.5) + 1):
if primes[i]:
primes[i * i: n: i] = [False] * len(primes[i * i: n: i])
return sum(primes)
def countPrimes(self, n):
if n <= 2:
return 0
res = [True] * n
res[0] = res[1] = False
for i in range(2, n):
if res[i] == True:
for j in range(2, (n - 1) // i + 1):
res[i * j] = False
return sum(res)
# 172. Factorial Trailing Zeroes
def trailingZeroes(self, n):
r = 0
while n > 0:
n /= 5
r += n
return r
# 617. Merge Two Binary Trees
def mergeTrees(self, t1, t2):
if not t1 and not t2: return None
ans = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0))
ans.left = self.mergeTrees(t1 and t1.left, t2 and t2.left)
ans.right = self.mergeTrees(t1 and t1.right, t2 and t2.right)
return ans
# 530. Minimum Absolute Difference in BST
def getMinimumDifference(self, root):
def dfs(node, l=[]):
if node.left: dfs(node.left, l)
l.append(node.val)
if node.right: dfs(node.right, l)
return l
l = dfs(root)
return min([abs(a - b) for a, b in zip(l, l[1:])])
# 2. Add Two Numbers
# You are given two non-empty linked lists representing two non-negative integers.
# The digits are stored in reverse order and each of their nodes contain a single digit.
# Add the two numbers and return it as a linked list.
class Solution:
# @return a ListNode
def addTwoNumbers(self, l1, l2):
carry = 0
root = n = ListNode(0)
while l1 or l2 or carry:
v1 = v2 = 0
if l1:
v1 = l1.val
l1 = l1.next
if l2:
v2 = l2.val
l2 = l2.next
carry, val = divmod(v1 + v2 + carry, 10)
n.next = ListNode(val)
n = n.next
return root.next
# 118. Pascal's triangle
# Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
# input 5, generate all first 5 rows with correct numbers
def generate(numRows):
a = [[1] * (i + 1) for i in range(numRows)]
for i in range(2, numRows):
for j in range(1, i):
a[i][j] = a[i - 1][j - 1] + a[i - 1][j]
return a
# def generate(self, numRows):
# res = [[1]]
# for i in range(1, numRows):
# res += [map(lambda x, y: x+y, res[-1] + [0], [0] + res[-1])]
# return res[:numRows]
# 119. Pascal's Triangle II
# Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
class Solution:
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
pascal = [[1] * (i + 1) for i in range(rowIndex + 1)]
for i in range(2, rowIndex + 1):
for j in range(1, i):
pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j]
return pascal[rowIndex]
# zip没看懂
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
row = [1]
for _ in range(rowIndex):
row = [x + y for x, y in zip([0] + row, row + [0])]
return row
# 268. Missing Number
# Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
def missingNumber(self, nums):
n = len(nums)
return n * (n + 1) // 2 - sum(nums)
# 448. Find All Numbers Disappeared in an Array
# Given an array of integers where 1 ≤ a[i] ≤ n
# (n = size of array), some elements appear twice and others appear once.
Find
all
the
elements
of[1, n]
inclusive
that
do
not appear in this
array.
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# For each number i in nums,
# we mark the number that i points as negative.
# Then we filter the list, get all the indexes
# who points to a positive number
for i in range(len(nums)):
index = abs(nums[i]) - 1
nums[index] = - abs(nums[index])
return [i + 1 for i in range(len(nums)) if nums[i] > 0]
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
return list(set(range(1, len(nums) + 1)) - set(nums)) # 注意list这里是圆括号
# 69. Sqrt(x)
class Solution:
"""
@param x: An integer
@return: The sqrt of x
"""
def sqrt(self, x):
start, end = 1, x
while start + 1 < end:
mid = (start + end) / 2
if mid * mid == x:
return mid
elif mid * mid < x:
start = mid
else:
end = mid
if end * end <= x:
return end
return start
# method 2
r = x
while r * r > x:
r = (r + x // r) // 2
return r
# 697. Degree of an Array
# Given a non-empty array of non-negative integers nums, the degree
# of this array is defined as the maximum frequency of any one of its
# elements.
# Your task is to find the smallest possible length of a (contiguous)
# subarray of nums, that has the same degree as nums.
def findShortestSubArray(self, nums):
map = defaultdict(list)
for i in range(len(nums)):
map[nums[i]].append(i)
return min((-len(list), list[-1] - list[0] + 1) for list in map.values())[1]
# good methods to sort out elements in a list and their position
def findShortestSubArray(self, nums):
first, last = {}, {}
for i, v in enumerate(nums):
first.setdefault(v, i)
last[v] = i
c = collections.Counter(nums)
degree = max(c.values())
return min(last[v] - first[v] + 1 for v in c if c[v] == degree)
class Solution(object):
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
c = Counter(nums)
degree = max(c.values())
m = defaultdict(list)
for i in range(len(nums)):
m[nums[i]].append(i)
return min(m[k][-1] - m[k][0] + 1 for k in m.keys() if c[k] == degree)
def findShortestSubArray(self, nums):
map = defaultdict(list)
for i in range(len(nums)):
map[nums[i]].append(i)
return min((-len(list), list[-1] - list[0] + 1) for list in map.values())[1]
# 189. Rotate Array
class Solution:
# @param nums, a list of integer
# @param k, num of steps
# @return nothing, please modify the nums list in-place.
def rotate(self, nums, k):
n = len(nums)
# k = k % n
nums[:] = nums[n - k:] + nums[:n - k] # be careful nums[:]
# 要考虑的是k=0
# find common elements in 2 list
# 349. Intersection of Two Arrays
# Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]
# 只用找出有交集的元素
class Solution:
# @param {int[]} nums1 an integer array
# @param {int[]} nums2 an integer array
# @return {int[]} an integer array
def intersection(self, nums1, nums2):
# Write your code here
return list(set(nums1) & set(nums2))
# 350. Intersection of Two Arrays II
# Each element in the result should appear as many times as it shows in both arrays.
def intersect(self, nums1, nums2):
a, b = map(collections.Counter, (nums1, nums2))
return list((a & b).elements())
# nums1 = [1,2,2,1]
# nums2 = [2,2]
# a, b = map(collections.Counter, (nums1, nums2))
# (Counter({1: 2, 2: 2}), Counter({2: 2}))
# 682. Baseball Game
class Solution(object):
def calPoints(self, ops):
# Time: O(n)
# Space: O(n)
history = []
for op in ops:
if op == 'C':
history.pop()
elif op == 'D':
history.append(history[-1] * 2)
elif op == '+':
history.append(history[-1] + history[-2])
else:
history.append(int(op))
return sum(history)
# newton method
def dx(f, x):
return abs(0 - f(x))
def newtons_method(f, df, x0, e):
delta = dx(f, x0)
while delta > e:
x0 = x0 - f(x0) / df(x0)
delta = dx(f, x0)
print
'Root is at: ', x0
print
'f(x) at root is: ', f(x0)
|
first = 'John'
last = 'Doe'
street = 'Main Street'
number = 123
city = 'AnyCity'
state = 'AS'
zipcode = '09876'
print('{} {}\n{} {}\n{}, {} {}'.format(first, last, number, street, city, state, zipcode)) |
sentence = "Guido van Rossum heeft programmeertaal Python bedacht."
for vowels in sentence:
if vowels in 'aeiouAEIOU':
print(vowels, end=" ")
else:
print("false") |
Brown = {'Boxtel', 'Best', 'Beukenlaan', 'Eindhoven', 'Helmond \'t Hout', 'Helmond', 'Helmond Brouwhuis', 'Deurne'}
Green = {'Boxtel', 'Best', 'Beukenlaan', 'Eindhoven','Geldrop', 'Heeze', 'Weert'}
total = {'test', 'test'}
def setfunc():
total.clear()
samebrogre = Brown.intersection(Green)
diffbrown = Brown.difference(Green)
diffgreen = Green.difference(Brown)
print("Overeenkomsten tussen bruin en groen")
for a in samebrogre:
print(a, end = " ")
print()
print("Verschillen tussen bruin en groen")
for b in diffbrown:
print((b), end = " ")
for c in samebrogre:
total.add(c)
for d in diffbrown:
total.add(d)
for e in diffgreen:
total.add(e)
print()
print(total)
setfunc() |
tupleList = ('test', 'test', 'test2', 'test')
dictList = {'test': 'test', 'test2': 'test'}
setList = {'test', 'test', 'test2', 'test'}
listList = ['test', 'test', 'test2', 'test']
tableList = []
print(sorted(tupleList))
print(sorted(dictList))
print(sorted(setList))
print(sorted(listList))
|
#/usr/bin/python3
# Author = Tom van Hamersveld - V1P - 2016
##
# Creating list which is used later on
cancelList = []
###
# Open the files
##
cancelFile = open('annuleringen.txt', 'r')
trainStationsFile = open('treinritten.txt', 'r')
resultFile = open('resultTreinritten.txt', "w")
###
# Reading the lines into the variable
##
rControlLst = []
cancelLst = []
print("The journey's below are going to be canceled:")
###
# Creating a list for canceling journeys
##
for cancel in cancelFile:
cancel = cancel.strip()
station = cancel.split(': ')[1]
print(station)
cancelLst.append(station)
###
# Determining which train journey is canceled & writing to new file
##
for journey in trainStationsFile:
rControl = journey.strip()
rControlLst = rControl.split('- ')[1]
if rControlLst not in cancelLst:
resultFile.write(journey)
print("\nProcess has finished!\nPlease check the 'resultTreinritten.txt' for the results\nThe file should be created in the same directory as this script.") |
numberList = [1,2,3,4,5,6,7,8,9,0]
def som(numlist):
res = 0
for num in numlist:
res += num
print(res)
return res
print(som(numberList)) |
#coding: utf-8
u"""
暗号文
与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ.
英小文字ならば(219 - 文字コード)の文字に置換
その他の文字はそのまま出力
この関数を用い,英語のメッセージを暗号化・復号化せよ.
"""
def cipher(texts):
output = ""
for text in texts:
if text.islower():
output += chr(219 - ord(text))
else:
output += text
return output
test = "I am Mana Ihori"
print (cipher(test))
test1 = cipher(test)
print (cipher(test1))
|
# coding: utf-8
u"""
ファイル参照の抽出
記事から参照されているメディアファイルをすべて抜き出せ。
"""
import ch03_01
import re
text = ch03_01.extract('イギリス').split('\n')
pattern = r'(?:File|ファイル):(.+?)\|'
for line in text:
true = re.search(pattern, line)
if true is not None:
print(true.group(1)) |
def factorize_number(x):
factorized_numbers = []
devisor = 2
while x > 1:
if x % devisor == 0:
factorized_numbers.append(devisor)
x //= devisor
else:
devisor += 1
return factorized_numbers |
def circular_shift_right(arr:list):
length = len(arr)
if(length < 2):
return arr
last = arr[length - 1]
for i in range(length - 1, 0, -1):
arr[i] = arr[i - 1]
arr[0] = last
l = [1,2,3,4,5,6]
circular_shift_right(l)
print(l) |
#!/usr/bin/python
import sys
def hex_to_comma_list_valid(hex_mask):
if "," in hex_mask:
hex_arr = hex_mask.split(",")
hex_sum = "0x0"
for h in hex_arr:
hex_sum = hex(int(str(hex_sum)[2:], 16)+int(h, 16))
return hex_to_comma_list(hex_sum[2:])
return hex_to_comma_list(hex_mask)
def hex_to_comma_list(hex_mask):
binary = bin(int(hex_mask, 16))[2:]
reversed_binary = binary[::-1]
i = 0
output = ""
for bit in reversed_binary:
if bit == '1':
output = output + str(i) + ','
i = i + 1
return output[:-1]
def dashes_to_comas(cpus):
arr = cpus.split(",")
cpu_arr = []
i = 0
for s in arr:
if "-" in s:
for n in range(int(arr[i].split("-")[0]),int(arr[i].split("-")[1])+1):
cpu_arr.append(str(n))
else:
cpu_arr.append(s)
i += 1
return cpu_arr
def comma_list_to_hex(cpus):
if "-" in cpus:
cpu_arr = dashes_to_comas(cpus)
else:
cpu_arr = cpus.split(",")
binary_mask = 0
for cpu in cpu_arr:
binary_mask = binary_mask | (1 << int(cpu))
return format(binary_mask, '02x')
if len(sys.argv) != 2:
print("Please provide a hex CPU mask or comma separated CPU list")
sys.exit(2)
user_input = sys.argv[1]
try:
print(hex_to_comma_list_valid(user_input))
except:
print(comma_list_to_hex(user_input))
|
from data import distances, cities
def getDistance(city, otherCity):
'''Returns distances between city and otherCity
Require data package'''
return distances[city][otherCity]
def getTotalDistance(chr):
'''Return the total distance from a road (list of int)
Require data package'''
s = 0
for x in range(len(chr)):
if x == len(chr) - 1:
s += getDistance(chr[x], chr[0])
else:
s += getDistance(chr[x], chr[x + 1])
return 0 - s
def roadMaker(pattern):
pattern = list(str(pattern).replace('[', '').replace(']', ''))
while len(pattern) < len(distances):
pattern.insert(0, '0')
return pattern
|
__author__ = 'Cullin'
import PatternCount
def freq_words(text,kmer):
max_count = 0
freq_words_dict = {}
for i in range(0,len(text)-kmer + 1):
word = text[i:i+kmer]
freq = PatternCount.pattern_count(text,word)
if freq >= max_count:
max_count = freq
freq_words_dict[word] = freq
for k,v in freq_words_dict.items():
if v < max_count:
del freq_words_dict[k]
return freq_words_dict
print freq_words("Cat in Hat Hat",3) |
#!/usr/bin/python2
import cv2
# laoding image
img=cv2.imread('cat.jpg')
img1=cv2.imread('cat.jpg',0)
# Print height and width
print img.shape
# to display that image
cv2.imshow("cat",img)
cv2.imshow("catnew",img1)
# image window holder activate
cv2.waitKey(0)
# waitkey will destroy by using q button
cv2.destroyAllWindows()
|
import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_json(r'./rain.json')
print(df)
print("df.statistics:",df.describe())
df.plot(x='Month',y='Temperature')
df.plot(x='Month',y='Rainfall')
plt.show() |
#!/usr/bin/env python
from BeautifulSoup import BeautifulSoup
import urllib, json, string
# Get the content of the page
print "Fetching page from http://news.bbc.co.uk/1/hi/uk_politics/8044207.stm ..."
doc = urllib.urlopen('http://news.bbc.co.uk/1/hi/uk_politics/8044207.stm').read()
print "Done!"
# Strip non-ASCII characters - life's just easier this way...
doc = filter(lambda c: ord(c) < 128, doc)
# Parse the HTML
print "Parsing HTML with BeautifulSoup"
soup = BeautifulSoup(doc)
# Get the rows of the table
rows = soup.find('table', id='expenses_table').find('tbody').findAll('tr')
# Lets get some tuples!
print 'Extracting data from <table id="expenses_table">'
raw = list()
for r in rows:
items = r.findAll('td')
raw.append( (items[0].string if items[0].string else items[0].find('a').string,
items[1].find('span').string,
items[2].string.replace('&', '&') if items[2].string else '',
int(str(items[3].string).translate(None, '*,')),
int(str(items[4].string).translate(None, '*,')),
int(str(items[5].string).translate(None, '*,')),
int(str(items[6].string).translate(None, '*,')),
int(str(items[7].string).translate(None, '*,')),
int(str(items[8].string).translate(None, '*,')),
int(str(items[9].string).translate(None, '*,')),
int(str(items[10].string).translate(None, '*,')),
int(str(items[11].string).translate(None, '*,')),
int(str(items[12].string).translate(None, '*,')),
int(str(items[13].find('strong').string).translate(None, '*,'))) )
fields = ('MP',
'Party',
'Seat',
'2nd home allowance',
'London supplement',
'Office',
'Staffing',
'Central stationery',
'Stationery & postage',
'IT provision',
'Staff cover',
'Communications',
'Travel',
'Total')
# Print as CSV
import csv
csvwriter = csv.writer(open('mp-expenses.csv', 'w'))
csvwriter.writerow(fields)
csvwriter.writerows(raw)
print "Wrote CSV data to mp-expenses.csv"
# Print as JSON
import json
asdicts = [dict(zip(fields, values)) for values in raw]
json.dump(asdicts, open('mp-expenses.json', 'w'), indent = 1)
print "Wrote JSON data to mp-expenses.json"
|
class Customer:
def __init__(self, id, x, y, zone=-1, isDepot=False):
self.id = id
self.x = x
self.y = y
self.zone = zone
self.isDepot = isDepot
self.isDayCustomer = False
self.acceptedVehicleTypes = []
def isDummy(self):
return self.id < 0
def __repr__(self):
return str(self.id) \
# + " - x:" + str(self.x) + " - y:" + str(self.y) + " - Zone:" + str(self.zone) + \
# " - Depot:" + str(self.isDepot)
class Vehicle:
def __init__(self, type, lvCost, hvCost, minFleet, maxFleet):
self.type = type
self.lvCost = lvCost
self.hvCost = hvCost
self.minFleet = minFleet
self.maxFleet = maxFleet
|
'''
Created on 02-Oct-2018
@author: shubham
'''
class quickunion(object):
def __init__(self,filepath):
self.file=open(filepath,"r+")
array_length=int(self.file.readline().strip("\n"))
self.data=[i for i in range(array_length)]
self.initialise()
print self.data
def initialise(self):
for i in self.file:
a=int(i.strip("\n").split(" ")[0])
b=int(i.strip("\n").split(" ")[1])
self.union(a,b)
def union(self,a,b):
if self.connected(a,b):
pass
else:
a1=self.root(a)
b1=self.root(b)
self.data[b1]=a1
def connected(self,a,b):
a1=self.root(a)
b1=self.root(b)
if a1==b1:
return True
else:
return False
def root(self,a):
#print "self.data[a]",a
while a!=self.data[a]:
# print "a",a
a=self.data[a]
return a
if __name__=="__main__":
filepath="/home/shubham/Desktop/data.txt"
t1=quickunion(filepath)
|
import sqlite3
conn=sqlite3.connect('prices.db')
c = conn.cursor()
for row in c.execute('SELECT * FROM price'):
print (row)
|
n = int(input("Enter the number until which you want to find the sum : "))
sumS = 0
for x in range(1,n+1):
sumS += x
print("The sum of first %d numbers is %d." % (n, sumS))
|
class MyList:
def __init__(self, numbers=[1, 2, 3]):
self.numbers = numbers
self.output_sum = None
self.output_min_max = None
self.output_max_diff = None
self.return_sum()
self.return_min_max()
self.return_max_diff()
def return_sum(self):
""" Function returns sum of list
:param self: Attribute method to class
:raises: TypeError if list cannot be summed
:raises: ValueError if no elements in given list
:returns: sum of all elements in the list
"""
import numpy as np
import logging
logging.basicConfig(filename='sumlog.txt', level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(message)s',
datefmt='%H:%M:%S')
with open('sumlog.txt', 'w'):
pass
logging.info('Function starting')
try:
self.output_sum = np.sum(self.numbers)
except TypeError:
print('Input list should be numbers')
logging.debug('Given list does not contain summable elements')
if len(self.numbers) == 0:
raise ValueError('No elements in list to be summed')
logging.warning('No elements present to be summed')
# self.output_sum = sum(self.numbers)
# self.output_sum = 0
# for elem in self.numbers:
# self.output_sum = sum(elem)
# logging.info('Elements have been summed')
def return_min_max(self):
""" Function returns the max and min value of the input list
:param self: a list of numbers
:returns max_min: the max and min values in the list of numbers
:raises TypeError: can only input a list of numbers
:raises ValueError: can not input an empty list
"""
import numpy as np
import logging
logging.basicConfig(filename="OuroborosAssignment04log.txt",
format='%(asctime)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p')
logging.info('Started')
if np.iscomplexobj(self.numbers) is True:
logging.warning('There are imaginary numbers in your list')
try:
max(self.numbers)
except TypeError:
logging.debug('my_list is {}'.format(self.numbers))
print("You did not input a list of numbers")
except ValueError:
print("The input type is correct but inappropriate")
self.output_min_max = ((np.max(self.numbers)), (np.min(self.numbers)))
def return_max_diff(self):
"""Function will return maximum difference between adjacent numbers.
Function takes in the inputted list of values, splits it into two
arrays to calculate the difference between adjacent values, takes the
absolute values of the differences to disregard positioning, and then
outputs the maximum value.
:param self: List of numbers
:return: Maximum difference
:raises ImportError: Check if numpy is installed or
virtual env is established
:raises TypeError: Input not given as a list of values
:raises ValueError: Can occur when only 1 number is given in the list
"""
# Import pkgs
import numpy as np
import logging
# Setup log
logging.basicConfig(filename='fn3log.txt', level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p')
# Function
try:
logging.info('Start fn')
if any(self.numbers) < 0: # included to use warning
logging.warning('Negative values in list')
logging.debug('Values {}'.format(self.numbers))
input_list = np.array(self.numbers)
diffs = abs(np.diff(input_list))
self.output_max_diff = max(diffs)
logging.info('Max val: {}'.format(self.output_max_diff))
# return max_val
except ImportError: # redundancy
logging.debug('Values {}'.format(self.numbers))
logging.error('ImportError: Check if numpy is in virtualenv')
# print('Check if numpy is in virtualenv')
except TypeError:
logging.debug('Values {}'.format(self.numbers))
logging.debug(self.numbers)
logging.error('TypeError: Check if input is a list of values')
# print('Check if input is a list of values')
except ValueError:
logging.debug('Values {}'.format(self.numbers))
logging.error('ValueError: Add more numbers to the list')
# print('Add more numbers to the list')
|
import os
import string
import re
#Files to read & variables
file = open("paragraph_1.txt")
text = file.read()
#Count using split function
words = text.split(" ")
sentences = re.split("(?<=[.!?]) +", text)
#print (words)
#print (sentences)
word_counts = len(words)
sentence_counts = len(sentences)
#Compute for Average
average_words = word_counts/sentence_counts
#Solve for total of all letter counts
validLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
letterCount = {}
letterCount.update([(x,0) for x in validLetters])
with open("paragraph_1.txt", "r") as file:
for letter in file.read():
if letter in validLetters:
letterCount[letter] += 1
#print(letterCount)
total_letters =sum(letterCount.values())
#print(total_letters)
#Solve for average total letter count / word count
average_letter_count = (total_letters/word_counts)
print ("Approximate Word Count:", word_counts)
print ("Approximate Sentences:", sentence_counts)
print ("Average Letter Count in Words:", average_letter_count)
print ("Average Sentence Length in Words:", average_words)
|
#assignment 1
# print hello world
print ('Hello World')
print("by K.Kamalakannan")
#add two numbers
a=10
b=25
c=a+b
print(c)
# find maximum
a=int(input("enter numb1: "))
b=int(input("enter numb2: "))
if(a>b):
print("num1 is maximum")
else:
print("num2 is maximum")
# OR
a=int(input("enter num1:"))
b=int(input("enter num2:"))
c=max(a,b)
print("maximum value is:")
print(c)
|
#1. create a function getting two integer inputs from user & print the following
def math_funcs(num1, num2, sign):
if(sign=='+'):
print("Addition of two numbers :", num1+num2)
elif(sign=='-'):
print("Subtraction of two numbers :", num1-num2)
elif(sign=='*'):
print("Multiplication of two numbers :", num1*num2)
elif(sign=='/'):
print("Division of two numbers :", num1/num2)
a=int(input("enter the first number:"))
b=int(input("enter the second number:"))
sign=input("enter the mathematical sign + for addition, - for subtraction, * for multiplication, / for division:")
math_funcs(a, b, sign)
print()
#2. Create a function covid() & it should accept patient's name and body temperature. By default the body temperature is 98 deg
def covid(name1, temp="98 deg F"):
print("The patient name is:", name)
print("Patient's body temperature is:", temp)
name=input("Enter Patient name:")
covid(name) |
#Pandigital Fibonacci ends
#Problem 104
#The Fibonacci sequence is defined by the recurrence relation:
# Fn = Fn-1 + Fn-2, where F1 = 1 and F2 = 1.
#It turns out that F541, which contains 113 digits, is the first Fibonacci
#number for which the last nine digits are 1-9 pandigital (contain all the
#digits 1 to 9, but not necessarily in order). And F2749, which contains
#575 digits, is the first Fibonacci number for which the first nine digits are
#1-9 pandigital.
#Given that Fk is the first Fibonacci number for which the first nine digits AND
#the last nine digits are 1-9 pandigital, find k.
def pandigital(somestring):
"""Takes string length 9. Returns True if string contains all digits 1..9"""
if len(somestring) <> 9:
return False
mylist = []
for i in range(9):
mylist.append(int(somestring[i:i+1]))
mylist.sort()
for i in range(9):
if mylist[i] <> i + 1:
return False
break
return True
fibs = {0: 0, 1: 1}
def FibN(n):
"""Returns n-th Fibonacci number using Moivre-Binet"""
if n in fibs: return fibs[n]
if n % 2 == 0:
fibs[n] = ((2 * FibN((n / 2) - 1)) + FibN(n / 2)) * FibN(n / 2)
return fibs[n]
else:
fibs[n] = (FibN((n - 1) / 2) ** 2) + (FibN((n+1) / 2) ** 2)
return fibs[n]
def FirstDigitsOfFib(n, d):
""" For the fibonacci number Fib(n), return the first d digits"""
temp = n * 0.20898764024997873 - 0.3494850021680094
return int(pow(10, temp - int(temp) + d - 1 ))
for i in range(1000000):
if pandigital(str(FirstDigitsOfFib(i,9))): # first 9 digits approx
if pandigital(str(FibN(i))[-9:]): # last 9 digits from Moive-Binet
print i
break
#329468 [Finished in 66.9s]
#Congratulations, the answer you gave to problem 104 is correct. |
#Largest prime factor
#Problem 3
#The prime factors of 13195 are 5, 7, 13 and 29.
#What is the largest prime factor of the number 600851475143 ?
def primes(n):
primfac = []
d = 2
while d*d <= n:
while (n % d) == 0:
primfac.append(d)
n //= d
d += 1
if n > 1:
primfac.append(n)
return primfac
print primes(600851475143)
#6857
#Congratulations, the answer you gave to problem 3 is correct.
|
import random
options = ["snake", "water", "gun"]
user_score = 0
Computer_score = 0
print("Please Enter any one of the following\n snake \n water \n gun")
i = 1
j = 7
while i < 7:
print("You have ",j, "chances left \n")
Player = input("Enter Your choice: ")
Computer_choice = random.choice(options)
if Player == Computer_choice:
print(f" You Entered {Player} and computer Entered {Computer_choice}")
print("Tie")
elif Player == 'snake' and Computer_choice == 'water':
print(f" You Entered {Player} and computer Entered {Computer_choice}")
print("This point goes to You")
user_score = user_score + 1
elif Player == 'snake' and Computer_choice == 'gun':
print(f" You Entered {Player} and computer Entered {Computer_choice}")
print("This point goes to Computer")
Computer_score = Computer_score + 1
elif Player == 'water' and Computer_choice == 'snake':
print(f" You Entered {Player} and computer Entered {Computer_choice}")
print("This point goes to Computer")
Computer_score = Computer_score + 1
elif Player == 'water' and Computer_choice == 'gun':
print(f" You Entered {Player} and computer Entered {Computer_choice}")
print("This point goes to You")
user_score = user_score + 1
elif Player == 'gun' and Computer_choice == 'snake':
print(f" You Entered {Player} and computer Entered {Computer_choice}")
print("This point goes to You")
user_score = user_score + 1
elif Player == 'gun' and Computer_choice == 'water':
print(f" You Entered {Player} and computer Entered {Computer_choice}")
print("This point goes to Computer")
Computer_score = Computer_score + 1
else:
print("Wrong Input")
i = i + 1
j = j - 1
if user_score > Computer_score:
print("\nCongratulations You Won...... ")
print(f" Your score is: {user_score} and Computer score is {Computer_score}")
elif user_score < Computer_score:
print("\nAH! AH! You Loose....... ")
print(f" Your score is: {user_score} and Computer score is {Computer_score}")
else:
print("\nDraw....... ")
print(f" Your score is: {user_score} and Computer score is {Computer_score}")
|
a, b = 7, 5
a = a + b
b = a - b
a = a - b
print("After Swapping Numbers")
print('a =', a)
print('b =', b)
|
'''Project Euler Problem 102
Triangle Containment
April 24, 2018'''
file = "C:\\Users\\pfarrell\\Downloads\\p102_triangles.txt"
with open(file) as f:
nums = []
points = []
for line in f.readlines():
data = line.split(',')
#tris.append(data.strip())
for p in data:
nums.append(int(p))
#print(tris[:10])
#groups points by 6
for x in range(0,len(nums),6):
points.append(nums[x:x+6])
#print(points[:2])
myList = [-340, 495, -153, -910, 835, -947]
def line2pts(p1,p2):
'''Returns the slope and y-intercept of
the line between two given points'''
if p2[0]-p1[0] == 0: #vertical line
m = 1000000 #close to infinite slope
else:
m = (p2[1]-p1[1])/(p2[0]-p1[0]) #slope
b = p1[1] - m*p1[0]
return m,b
def inequalities(myList):
'''Returns True if the origin is on the same
side of each side of the triangle as the opposite
point'''
#first put the numbers into x-y points
pt1 = (myList[0],myList[1])
pt2 = (myList[2],myList[3])
pt3 = (myList[4],myList[5])
#the lines (sides) formed by joining points
lines = [line2pts(pt1,pt2),
line2pts(pt2,pt3),
line2pts(pt3,pt1)]
#put points in order of opposite sides, for
#example pt3 is opposite the line formed by
#pt1 and pt2
points = [pt3,pt1,pt2]
#create a list to store inequalities
output = []
#go through the lines and points
for i,line in enumerate(lines):
#if opposite point is under the line
if points[i][1] < line[0]*points[i][0] + line[1]:
output.append('less')
else:
output.append('greater')
origin = [] #store inequalities for the origin
for line in lines:
if 0 < line[1]: #is the origin under the line
origin.append('less')
else: #Or over the line:
origin.append('greater')
#compare the inequalities. If the origin matches the
#opposite points, it's within the triangle.
return output == origin
#helpful programs from Hacking Math Class with Python
def intersection(line1,line2):
'''returns the intersection of
y = ax + b and y = cx + d'''
a,b,c,d = line1[0],line1[1],line2[0],line2[1]
x = (d - b) / (a - c)
y = a*x + b
return (x,y)
def lineSlopePt(m,pt):
b = pt[1] - m*pt[0]
return m,b
def perpBisector(pt1,pt2):
slope2pts = (pt2[1]-pt1[1])/(pt2[0]-pt1[0])
mdpt = [(pt2[0] + pt1[0])/2.0,
(pt2[1] + pt1[1])/2.0]
m = -1.0/slope2pts
return lineSlopePt(m,mdpt)
def centroid(pt1,pt2,pt3):
pb1 = perpBisector(pt1,pt2)
pb2 = perpBisector(pt2,pt3)
return intersection(pb1,pb2)
#print(centroid((-340, 495), (-153, -910), (835, -947)))
#unfortunately the centroid can also be outside the triangle :-(
#print(inequalities([-175,41,-421,-714,574,-645]))
origins = 0
count = 0
for thing in points:
count += 1
if inequalities(thing):
origins += 1
print("origins:",origins,"count:",count)
#correct!
|
#
# @lc app=leetcode id=53 lang=python3
#
# [53] Maximum Subarray
#
# https://leetcode.com/problems/maximum-subarray/description/
#
# algorithms
# Easy (45.93%)
# Likes: 7387
# Dislikes: 341
# Total Accepted: 975.8K
# Total Submissions: 2.1M
# Testcase Example: '[-2,1,-3,4,-1,2,1,-5,4]'
#
# Given an integer array nums, find the contiguous subarray (containing at
# least one number) which has the largest sum and return its sum.
#
# Example:
#
#
# Input: [-2,1,-3,4,-1,2,1,-5,4],
# Output: 6
# Explanation: [4,-1,2,1] has the largest sum = 6.
#
#
# Follow up:
#
# If you have figured out the O(n) solution, try coding another solution using
# the divide and conquer approach, which is more subtle.
#
#
# @lc code=start
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
if not nums:
return None
max_sum = nums[0]
curr_sum = nums[0]
for num in nums[1:]:
if max_sum <= 0 and num > max_sum:
max_sum = num
curr_sum = num
else:
curr_sum += num
if curr_sum > max_sum:
max_sum = curr_sum
return max_sum
# @lc code=end
|
#
# @lc app=leetcode id=20 lang=python3
#
# [20] Valid Parentheses
#
# https://leetcode.com/problems/valid-parentheses/description/
#
# algorithms
# Easy (38.01%)
# Likes: 4056
# Dislikes: 194
# Total Accepted: 841.2K
# Total Submissions: 2.2M
# Testcase Example: '"()"'
#
# Given a string containing just the characters '(', ')', '{', '}', '[' and
# ']', determine if the input string is valid.
#
# An input string is valid if:
#
#
# Open brackets must be closed by the same type of brackets.
# Open brackets must be closed in the correct order.
#
#
# Note that an empty string is also considered valid.
#
# Example 1:
#
#
# Input: "()"
# Output: true
#
#
# Example 2:
#
#
# Input: "()[]{}"
# Output: true
#
#
# Example 3:
#
#
# Input: "(]"
# Output: false
#
#
# Example 4:
#
#
# Input: "([)]"
# Output: false
#
#
# Example 5:
#
#
# Input: "{[]}"
# Output: true
#
#
#
# @lc code=start
class Solution:
def isValid(self, s: str) -> bool:
if s == '':
return True
if len(s) % 2 != 0:
return False
start_chars = ('(', '{', '[')
stack = []
for c in s:
if c in start_chars:
stack.append(c)
else:
if len(stack) == 0:
return False
if c == ')' and stack.pop() != '(':
return False
elif c == '}' and stack.pop() != '{':
return False
elif c == ']' and stack.pop() != '[':
return False
if len(stack) == 0:
return True
# @lc code=end
|
#!/usr/bin/env python3.6
user = {"admin": True, "active": True, "name": 'Vimal'}
prefix =""
if user['admin'] and user['active']:
prefix="Active - Admin"
elif user['admin']:
prefix="Admin"
elif user['active']:
prefix="Active"
print(f"testing the input {prefix}, {user['name']}") |
import utime
class Timer:
def __init__(self):
"""Class that implements timer at microsecond clock
"""
self.start = utime.ticks_us()
def reset(self):
"""Resets the timer
"""
self.start = utime.ticks_us()
def duration(self):
"""Returns time elapsed since last reset
:return diff: The time elapsed since last reset
:type diff: Number
"""
return utime.ticks_diff(utime.ticks_us(), self.start)
|
def menorVetor(vet):
menor = vet[0]
for i in range (0,5):
if vet[i] < menor:
menor = vet[i]
return menor
vetor = []
for i in range(0, 5):
vetor.append(int(input('Informe um numero: ')))
m = menorVetor(vetor)
print(m) |
notas = dict()
notas2 = dict()
notas = {'Ana': 9.5, 'José': 8.2, 'Maria:': 9.8, 'João': 7.9}
#notas2 = {'Yuri': 9.5, 'Tiago': 8.2, 'Lucas': 9.8, 'Max': 7.9}
#get
# uma função do dicionario para procurar e devolver alguma coisa
#print(notas.get('Carla', 'Nome não encontrado'))
#utilizando in
#ele traz o valor de true ou false que existe dentro da chave, não procurando no valor
#para encontrar no valor é necessario colocar print(8.2 in notas.values()), encontrando o valor que esta dentro da chave
#print('José' in notas)
#inserindo novo elemento
#nome da chave = [uma variavel] = outra variavel
#notas['Carla'] = 8.7
#print(notas)
#deletando elemento
#del notas['Ana']
#print(notas)
#função para que se no caso ele não encontre o valor ele possa mandar uma mensagem
#print(notas.pop('Ana', 'Nome não encontrado'))
#print(notas.pop('Carlos', 'Nome não encontrado'))
#print(notas)
#Insere apenas valores diferentes que não existe no primeiro vetor
#Nome poderia ser qualquer variavel
#for nome in notas2:
#notas[nome] = notas2[nome]
#função pronta para inserir valores diferentes que não existe no primeiro vetor
#notas.update(notas2)
#print(notas)
#Inserindo uma atualização em todos os elementos do dicionario
#Está função vai percorrer o dicionario e vai adicionar +1 dentro de cada valor que esta dentro da chave
#é gerado um novo dicionario que coloca este novos valores
#nota_final = {nome: 1 + notas[nome] for nome in notas}
#print(nota_final)
|
numero = int(input('Digite um numero: '));
fatorial = 1
while numero > 0:
fatorial *= numero
numero -= 1
print(fatorial)
|
# 04-02. FUNCTIONS [Exercise]
# 06. Password Validator
def valid_pass(string):
valid_password = True
if not 6 <= len(string) <= 10:
valid_password = False
print('Password must be between 6 and 10 characters')
for char in string:
if not (char.isalpha() or char.isnumeric()):
valid_password = False
print('Password must consist only of letters and digits')
break
count_numeric = 0
for char in string:
if char.isnumeric():
count_numeric += 1
if not count_numeric >= 2:
valid_password = False
print('Password must have at least 2 digits')
if valid_password:
print('Password is valid')
valid_pass(input())
|
# 04-02. FUNCTIONS [Exercise]
# 04. Odd and Even Sum
def odd_even_sum(string):
odd_sum = 0
even_sum = 0
for char in string:
num = int(char)
if num % 2 == 0:
even_sum += num
else:
odd_sum += num
print(f'Odd sum = {odd_sum}, Even sum = {even_sum}')
odd_even_sum(input())
|
# 08-02. TEXT PROCESSING [Exercise]
# 04. Caesar Cipher
text = input()
encrypted_text = ''
for char in text:
encrypted_text += chr(ord(char) + 3)
print(encrypted_text)
|
# 03-02. LISTS BASICS [Exercise]
# 10. Bread Factory
energy = 100
coins = 100
managed = True
events = input().split('|')
for event in events:
event_type, number = event.split('-')
number = int(number)
if event_type == 'rest':
if energy < 100:
gain = min(number, 100 - energy)
energy += gain
else:
gain = 0
print(f'You gained {gain} energy.')
print(f'Current energy: {energy}.')
elif event_type == 'order':
if energy >= 30:
coins += number
energy -= 30
print(f'You earned {number} coins.')
else:
energy += 50
print('You had to rest!')
else:
if coins > number:
coins -= number
print(f'You bought {event_type}.')
else:
print(f'Closed! Cannot afford {event_type}.')
managed = False
break
if managed:
print('Day completed!')
print(f'Coins: {coins}')
print(f'Energy: {energy}')
|
# 08-02. TEXT PROCESSING [Exercise]
# 01. Valid Usernames
usernames = input().split(', ')
for username in usernames:
is_valid = True
if 3 <= len(username) <= 16:
if len(username) == len(username.strip()):
for char in username:
if char.isalpha() or char.isdigit() or char in ('-', '_'):
is_valid = True
else:
is_valid = False
break
else:
is_valid = False
else:
is_valid = False
if is_valid:
print(username)
|
# 03-02. LISTS BASICS [Exercise]
# 05. Faro Shuffle
string = list(input().split(' '))
shuffles = int(input())
half = int(len(string) / 2)
for i in range(shuffles):
string1 = string[0:half]
string2 = string[half:]
string = []
for j in range(half):
string.extend([string1[j], string2[j]])
print(string)
|
# 08-02. TEXT PROCESSING [Exercise]
# 03. Extract File
path = input()
file_name_start = path.rfind('\\') + 1
file_name_end = path.rfind('.')
file_name = path[file_name_start:file_name_end]
file_extension = path[file_name_end+1:]
print(f'File name: {file_name}')
print(f'File extension: {file_extension}')
|
# 05-01. LISTS ADVANCED [Lab]
# 04. Even Numbers
integers = input().split(', ')
integers = list(map(int, integers))
integers_even = []
for i, val in enumerate(integers):
if val % 2 == 0:
integers_even.append(i)
print(integers_even)
|
# 09-03. REGEX [More Exercises]
# 01. Race
import re
participants = input().split(', ')
race = {}
for p in participants:
race[p] = 0
while True:
string = input()
if string == 'end of race':
break
name = ''
letters = re.findall('[A-Za-z]', string)
for l in letters:
name += l
distance = 0
digits = re.findall('\\d', string)
for d in digits:
distance += int(d)
if name in race:
race[name] += distance
race = dict(sorted(race.items(), key=lambda x: -x[1]))
top_3 = [p for p in list(race)[:3]]
print(f'1st place: {top_3[0]}')
print(f'2nd place: {top_3[1]}')
print(f'3rd place: {top_3[2]}')
|
# 06-01. OBJECTS AND CLASSES [Lab]
# 05. Circle
class Circle:
__pi = 3.14
def __init__(self, diameter):
self.diameter = diameter
self.radius = diameter / 2
def calculate_circumference(self):
return Circle.__pi * self.diameter
def calculate_area(self):
return Circle.__pi * self.radius ** 2
def calculate_area_of_sector(self, angle):
return Circle.__pi * self.radius ** 2 * angle / 360
circle = Circle(10)
circle_angle = 5
print(f"{circle.calculate_circumference():.2f}")
print(f"{circle.calculate_area():.2f}")
print(f"{circle.calculate_area_of_sector(circle_angle):.2f}")
|
# 07-01. OBJECTS AND CLASSES [Lab]
# 02. Stock
stock = {}
items = input().split(' ')
for i in range(0, len(items), 2):
key = items[i]
value = items[i+1]
stock[key] = int(value)
search = input().split(' ')
for i in search:
if i in stock.keys():
print(f'We have {stock[i]} of {i} left')
else:
print(f'Sorry, we don\'t have {i}')
|
# 04-02. FUNCTIONS [Exercise]
# 01. Smallest of Three Numbers
def min_of_three(num1, num2, num3):
return min(num1, num2, num3)
a = int(input())
b = int(input())
c = int(input())
print(min_of_three(a, b, c))
|
# 04-01. FUNCTIONS [Lab]
# 04. Orders
def total(product, quantity):
if product == 'coffee':
return 1.50 * quantity
elif product == 'water':
return 1.00 * quantity
elif product == 'coke':
return 1.40 * quantity
elif product == 'snacks':
return 2.00 * quantity
order_product = input()
order_quantity = int(input())
print(f'{total(order_product, order_quantity):.2f}')
|
# 07-02. OBJECTS AND CLASSES [Exercise]
# 09. ForceBook
forcebook = {}
while True:
command = input()
if command == 'Lumpawaroo':
break
if ' | ' in command:
side, user = command.split(' | ')
all_users = []
for users in forcebook.values():
all_users += users
if user not in all_users:
if side not in forcebook:
forcebook[side] = []
forcebook[side].append(user)
elif ' -> ' in command:
user, side = command.split(' -> ')
if side not in forcebook:
forcebook[side] = []
for key in forcebook:
if user in forcebook[key]:
forcebook[key].remove(user)
forcebook[side].append(user)
print(f'{user} joins the {side} side!')
forcebook = dict(sorted(forcebook.items(), key=lambda x: (-len(x[1]), x[0])))
for side in forcebook:
if len(forcebook[side]) == 0:
continue
print(f'Side: {side}, Members: {len(forcebook[side])}')
for user in sorted(forcebook[side]):
print(f'! {user}')
|
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import paddle.fluid as fluid
import parl.layers as layers
from abc import ABCMeta, abstractmethod
from parl.framework.model_base import Network, Model
__all__ = ['Algorithm']
class Algorithm(object):
"""
Algorithm defines the way how we update the model. For example,
after defining forward network in `Network` class, you should define how to update the model here.
Before creating a customized algorithm, please do check algorithms of PARL.
Most common used algorithms like DQN/DDPG/PPO have been providing in algorithms, go and have a try.
It's easy to use them and just try pl.algorithms.DQN.
An Algorithm implements two functions:
1. define_predict() build forward process which was defined in Network
2. define_learn() computes a cost for optimization
An algorithm should be updating part of a network. The user only needs to
implement the rest of the network(forward) in the Model class.
"""
def __init__(self, model, hyperparas=None):
assert isinstance(model, Model)
self.model = model
self.hp = hyperparas
def define_predict(self, obs):
"""
describe process for building predcition program
"""
raise NotImplementedError()
def define_learn(self, obs, action, reward, next_obs, terminal):
"""define how to update the model here, you may need to do the following:
1. define a cost for optimization
2. specify your optimizer
3. optimize model defined in Model
"""
raise NotImplementedError()
def get_params(self):
""" Get parameters of self.model
Returns:
List of numpy array.
"""
return self.model.get_params()
def set_params(self, params, gpu_id):
""" Set parameters of self.model
Args:
params: List of numpy array.
gpu_id: gpu id where self.model in. (if gpu_id < 0, means in cpu.)
"""
self.model.set_params(params, gpu_id=gpu_id)
|
# ---------------------------------------------------+
# Projectiles are fired when someone (player or
# villain) fires a shot with a gun.
# A projectile is basically a moving item.
# ---------------------------------------------------+
import math
import pygame
from Functions import getMovingVector
class Projectile(pygame.sprite.Sprite):
origin = [] # A vector representing x-y-coordinates: At which position in the level was the projectile generated
speed = 5 # Speed of the projectile
max_range = 10 # Maximum range of the projectile - defined by weapon used
dmg = 0 # Damage associated with the projectile
position = [] # Current level position
angle = 0 # Shooting direction
def __init__(self, game, char):
pygame.sprite.Sprite.__init__(self) # needed for subclasses of sprites
self.origin = char.position
self.angle = char.angle
# Let the projectile start apart from char
v = getMovingVector(self)
new_x = char.position[0] + v[0] * char.image.get_rect().size[0] / game.imgMngr.texture_size[0]
new_y = char.position[1] + v[1] * char.image.get_rect().size[1] / game.imgMngr.texture_size[1]
self.position = [new_x, new_y]
current_weapon = char.get_current_weapon()
self.speed = current_weapon.speed
self.max_range = current_weapon.max_range
self.dmg = current_weapon.generate_dmg_fun()
# Get the right image for this sprite (based on level theme and weapon)
self.image = game.imgMngr.all_images[current_weapon.name + "_projectile"]
self.image = pygame.transform.rotate(self.image, -self.angle)
self.rect = self.image.get_rect()
# -------------------------------------------------+
# Move the projectile (cannot change direction)
# -------------------------------------------------+
def move_me(self):
v = (math.cos((self.angle - 90) * math.pi / 180), math.sin((self.angle - 90) * math.pi / 180))
new_pos_x = self.position[0] + v[0] * self.speed
new_pos_y = self.position[1] + v[1] * self.speed
if math.sqrt((new_pos_x - self.origin[0]) ** 2 + (new_pos_y - self.origin[1]) ** 2) < self.max_range:
self.position = [new_pos_x, new_pos_y]
else:
self.kill()
|
'''A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.'''
from math import ceil
first_num=100
max_product=0
def palindrome_checker(num):
s=str(num)
first_frag=s[0: len(s)/2]
second_frag=s[int(ceil(len(s)/2.0)):]
return first_frag == second_frag[::-1]
for x in range(100, 1000):
for y in range(100, 1000):
z=x*y
if palindrome_checker(z):
if z>max_product:
max_product=z
print max_product |
class CodingProblem2:
def __init__(self,list):
self.list = list;
def computeUsingOptimalSolution(self):
suffix_products = [] # Generate list of products suffix of element i
for num in reversed(self.list):
if suffix_products:
suffix_products.append(suffix_products[-1] * num) # Multiply each element by last index of array
else:
suffix_products.append(num) # Add first element in list
suffix_products = list(reversed(suffix_products))
# Same methodology as above, just reverse the list and reverse back the final computed list
prefix_products = [] # Generate list of products prefix of element i
for num in self.list:
if prefix_products:
prefix_products.append(prefix_products[-1] * num); # Multiply each element by last index of array
else:
prefix_products.append(num);
result = [];
for i in range(len(self.list)):
if i == 0:
result.append(suffix_products[i + 1]) # First element gets added
elif i == len(self.list) - 1:
result.append(prefix_products[i - 1]) # Last element gets added
else:
result.append(prefix_products[i - 1] * suffix_products[i + 1]) # Multiply at index of element i for products i+1 and i-1
return result
def computeEasySolution(self):
multiply_forward = []
product = 0
for num in self.list:
if multiply_forward:
product = num * product # Multiply products forward
else:
product = num # First element
multiply_forward.append(product)
#print(*multiply_forward)
#Same methodology as above. Just reverse the list and reverse it back at the end
product = 0
multiply_backward = []
for num in reversed(self.list):
if multiply_backward:
product = num * product # Multiply products backward
else:
product = num; # First element
multiply_backward.append(product)
multiply_backward = list(reversed(multiply_backward))
#print(*multiply_backward)
result = []
for index in range(len(self.list)):
result.append(int((multiply_forward[index] * multiply_backward[index])//(self.list[index] * self.list[index]))) # Multiply backward and forward elements at same index and divide by square of original element
return result;
|
# A website requires users to enter a username and password to register. Write a program to check the validity of the password entered by the user.
# Password check criteria include:
# 1. At least 1 letter is in [a-z]
# 2. At least 1 number is in [0-9]
# 3. At least 1 character in [A-Z]
# 4. At least 1 character inside [$#@]
# 5. Minimum password length: 6
# 6. Maximum password length: 12
# Input: ABd1234@1,a F1#,2w3E*,2We3345
# Output: ABd1234@1
import re
result = []
values = [x for x in input().strip().split(',')]
for e in values:
if not len(e) in range(6,13):
continue
elif not re.search('[a-z]',e):
continue
elif not re.search('[0-9]',e):
continue
elif not re.search('[A-Z]',e):
continue
elif not re.search('[$#@]',e):
continue
else:
pass
result.append(e)
print(','.join(result)
|
# Write a program that accepts a string of words entered by the user, separated by commas, and prints the words in alphabetical order, separated by commas.
# Input is: without,hello,bag,world, the output will be: bag,hello,without,world.
items = [i for i in input().split(',')]
items.sort()
print(','.join(items))
|
#defining a function
def simpleFunction():
print ("Simple funcion")
print ("Does nothing")
def addThis(x, y):
print (x+y)
return x+y
#calling funcions
simpleFunction()
x = 6
print (x)
x = simpleFunction
x()
a = addThis(2,3)
addThis(2.7,3.14)
addThis("Add"," This?")
|
#comment: Single line comment
#====
# Part-1
#====
a = 5
print (a)
a = "Allowed?"
print (a)
a, b, c = 1, 15, 9
print (b)
print (c)
a, b = 5, "Other than number"
a, b = b, a
print (a)
print (b)
x = input ("Enter a number: ")
x = int (x)
x = x + 1
print (x)
#====
# if-else
#====
if x > 0 and x < 100:
print ("x is positive")
print ("I have so much to say")
elif x == 0 or x < -100:
print ("It's zero!!")
else:
print ("Definitely negative")
print ("More things for negative")
#====
#DData Structure in 5 lines of code
#====
x = [1, 2, 3.1487, "Wow this is allowed", 9876]
print (x[0])
print (x[2])
print (x[3])
print (x.count(1))
#====
#Loops in Python
#====
#for(int i = 0; i < 10; i++)
for i in range(10):
print ("Print this a bunch of times")
for item in x:
print (item)
S= "Python is awesome"
for item in S:
print (item)
if item == 'a':
print("=======")
|
l1 = [1, 2, 3, 4, 5, 6]
ex1 = [variavel for variavel in l1]
ex2 = [v * 2 for v in l1]
ex3 = [(v, v2) for v in l1 for v2 in range(3)]
print(ex1)
print(ex2)
|
# we've keys and value
# in list, python create the index for us
# in dictionary, keys are unique, we cannot duplicate it
d1 = {'car': 'mitsubishi', 'brand': ''}
d1['nova chave'] = 'new value'
print(d1)
print(d1['nova chave'])
d2 = dict(chave1='valor da chave')
print(d2)
print('*****************')
d3 = {1: 'key', 1: 'key2', 1: 'key3'}
# key3 is the last value
print(d3)
# check if key exist
if 1 in d3:
print('exist 1')
|
import sqlite3
conexao = sqlite3.connect('basededados.db')
cursor = conexao.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS clientes ('
'id INTEGER PRIMARY KEY AUTOINCREMENT,'
'nome TEXT,'
'peso REAL'
')'
)
#cursor.execute('INSERT INTO clientes (nome, peso) VALUES ("Gabriel", 75.0)')
#conexao.commit()
cursor.execute('INSERT INTO clientes (nome, peso) VALUES (?,?)', ('Maria', 50))
conexao.commit()
cursor.execute('SELECT * FROM clientes')
for linha in cursor.fetchall():
identifier, nome, peso = linha
print(identifier, nome, peso)
cursor.close()
conexao.close()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 22:15:10 2020
@author: gabrielguimaraes
"""
numero = 2
print(numero)
vetor = [2,3,4]
import numpy as np
vetor = np.asarray(vetor)
print("maior valor", vetor.max())
print("posicao de maior valor", vetor.argmax())
print("valor minimo", vetor.min())
print("media", vetor.mean())
print("soma", vetor.sum())
vetor2 = numero * vetor
#generate random number
np.arange(1, 50, 3)
|
user = input("Create your user ")
password = input("Create your password")
qtd = len(user)
print(user, qtd)
if len(password) < 5:
print("Short Password")
else:
print("ok")
|
def daysPerMonth(year, month):
# Days per month is statis for all months except February
if(month in [1,3,5,7,8,10,12]):
return(31)
elif(month in [4,6,9,11]):
return(30)
else:
# Days per month in February will vary depending upon leap year
# Every 400 years is a leap year (starting at year 0)
# Every 100 years is NOT a leap year (starting at year 0)
# Every 4th year is a leap year (starting at year 0)
# Every other year is NOT a leap year (starting at year 0)
if(year % 400 == 0):
return(29)
elif(year % 100 == 0):
return(28)
elif(year % 4 == 0):
return(29)
else:
return(28)
def main():
month = 2
year = 2100
daysPerMonth_result = daysPerMonth(year,month)
print(daysPerMonth_result)
if __name__ == '__main__':
main()
|
class DiophanticSum:
def __init__(self, coefficients, constant):
assert all([type(c) is int for c in coefficients.values()])
assert type(constant) is int
self.coefficients = coefficients
self.constant = constant
def getConstant(self):
return self.constant
def getCoefficients(self):
return self.coefficients
def multiplyWith(self, value):
coefficients = {name : value*coeff for name, coeff in self.coefficients.items()}
constant = value * self.constant
return DiophanticSum(coefficients, constant)
def evaluateForVariableAssignment(self, assignment):
result = self.constant
for name in self.coefficients:
coeff = self.coefficients[name]
valueOfVariable = assignment[name]
result = result + coeff*valueOfVariable
return result
def __eq__(self, other):
if not isinstance(other, DiophanticSum):
return NotImplemented
return self.coefficients == other.coefficients and self.constant == other.constant
def __str__(self):
return self.__repr__()
def __repr__(self):
terms = []
for name in self.coefficients:
terms.append(str(self.coefficients[name]) + "*" + str(name))
result = str(self.constant)
if len(self.coefficients) > 0:
result = " + ".join(terms) + " + " + result
return result
|
def InsSort(arr, start, end):
for i in range(start + 1, end + 1):
elem = arr[i]
j = i - 1
while j >= start and elem < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = elem
return arr
def merge(arr, start, mid, end):
if mid == end:
return arr
first = arr[start:mid + 1]
last = arr[mid + 1:end + 1]
len1 = mid - start + 1
len2 = end - mid
ind1 = 0
ind2 = 0
ind = start
while ind1 < len1 and ind2 < len2:
if first[ind1] < last[ind2]:
arr[ind] = first[ind1]
ind1 += 1
else:
arr[ind] = last[ind2]
ind2 += 1
ind += 1
while ind1 < len1:
arr[ind] = first[ind1]
ind1 += 1
ind += 1
while ind2 < len2:
arr[ind] = last[ind2]
ind2 += 1
ind += 1
return arr
def TimSort(arr, minrun):
n = len(arr)
for start in range(0, n, minrun):
end = min(start + minrun - 1, n - 1)
arr = InsSort(arr, start, end)
curr_size = minrun
while curr_size < n:
for start in range(0, n, curr_size * 2):
mid = min(n - 1, start + curr_size - 1)
end = min(n - 1, mid + curr_size)
arr = merge(arr, start, mid, end)
curr_size *= 2
return arr
|
# -*- coding: utf-8 -*-
"""The module that initializes a CSV file
This module is needed to create a CSV file with random records via Faker
"""
from faker import Faker
import csv
def init_csv_file(source):
"""The function that initializes a CSV file
Args:
source (Faker()): the source of random names, emails etc
"""
with open('input.csv', 'w') as csv_file:
# here we specify the field names of our records
field_names = [
'name',
'success',
'email'
]
writer = csv.DictWriter(csv_file, fieldnames=field_names)
# the first row will be the names of the fields
# in order to make it clear
# what the following rows mean
writer.writerow(
{'name': 'name',
'success': 'success',
'email': 'email'}
)
# the following rows
for _ in range(100):
writer.writerow(
{
'name': source.name(),
'success': source.boolean(),
'email': source.email()
}
)
def main():
fake = Faker()
init_csv_file(fake)
if __name__ == '__main__':
main()
|
import math
def sum_digits(number):
# number_str = str(number)
# summa = 0
# for digit in number_str:
# summa += int(digit)
# return summa
s = 0
while number:
s += number % 10
number //= 10
return s
def find_result(number):
step = 9
if number % 3 == 0:
step = 3
if number % 9 == 0:
step = 1
k = 1
while True:
testing_number = k * number
if sum_digits(testing_number) == number:
return testing_number
k += step
def find_result_more_effective(number):
step = 9
if number % 3 == 0:
step = 3
if number % 9 == 0:
step = 1
testing_number = generate_min_number(number)
testing_number = testing_number - testing_number % number
k = int(testing_number / number)
while (k % 9) != 1:
k -= 1
testing_number = k * number
while True:
print(testing_number)
if sum_digits(testing_number) == number:
return testing_number
testing_number += number * step
def generate_min_number(sd):
count_nine = int(sd / 9)
search_num = "9" * count_nine
search_num = int(str(sd % 9) + search_num)
return search_num
'''
def find_next_number(number,sd):
current_sd = sum_digits(number)
number = str(number)
current_position = 0.5 # don't ask me why
for i in range(1,len(number)):
if number[-i] != 9:
current_position = -i
break
number =
'''
from sys import argv
while True:
# N = int(input("Input N: "))
N = int(argv[1])
result = find_result_more_effective(N)
# print("Result: %d" % result)
# print("\n\n")
exit()
'''
start = int(input("Input start number: "))
finish = int(input("Input final number: "))
for i in range(start,finish+1):
result = find_result_more_effective(i)
i_hope_count_digits = int(i/10)+int(i/9)+1
print("number: %3d, count digits: %3d, assumption: %3d, k : %-10d , result: %d"%(i,len(str(result)),i_hope_count_digits,int(result/i),result))
'''
|
def reverse(text):
return text[::-1]
def is_palinrome(text):
return text == reverse(text)
something = input('Введите текст: ')
something = something.lower()
forbidden = ('.','?','!',':',';','-','—',' ',)
for i in something:
if i in forbidden:
something = something.replace(i, '')
if(is_palinrome(something)):
print('Да, это палиндром')
else:
print('Нет, это не палиндром') |
def solveMeFirst(a,b):
return a+b
num1=int(raw_input("Enter The First No"))
num2=int(raw_input("Enter The Second No"))
res=solveMeFirst(num1,num2)
print(res)
|
import os
import json
print("Enter the absolute file path to the directory you need filenames for...")
print("(Ex: 'C:\Users\Vincent\Desktop')")
filenamesPath = input("Enter path: ")
print("Enter the absolute file path to the directory where you want the text file to be generated...")
outputPath = os.path.join(input("Enter path: "), "filenames.txt")
output = open(outputPath, 'w')
files = []
# first pass to grab and fix names
for file in os.listdir(filenamesPath):
# Note that these are specific to a friend's issues.
if file[2] == ".":
file = "0" + file
elif file[1] == '.':
file = "00" + file
files.append(file)
files.sort() # sort
# second pass to write to file
for file in files:
output.write("%s\n" % file)
output.close()
print("Finished! Exported to " + outputPath) |
import tkinter
win = tkinter.Tk()
win.title("jakccsm")
win.geometry("400x300+200+200")
scroll = tkinter.Scrollbar()
text = tkinter.Text(win,width=200,height=2)
scroll.pack(side=tkinter.RIGHT,fill=tkinter.Y)
text.pack(side=tkinter.LEFT,fill=tkinter.Y)
scroll.config(command=text.yview)
text.config(yscrollcommand=scroll.set)
str = '''
"helli,every body,tongith i can tell u how to spell your standard english words"
"helli,every body,tongith i can tell u how to spell your standard english words"
"helli,every body,tongith i can tell u how to spell your standard english words"
"helli,every body,tongith i can tell u how to spell your standard english words"
"helli,every body,tongith i can tell u how to spell your standard english words"
"helli,every body,tongith i can tell u how to spell your standard english words"
"helli,every body,tongith i can tell u how to spell your standard english words""helli,every body,tongith i can tell u how to spell your standard english words""helli,every body,tongith i can tell u how to spell your standard english words"
"helli,every body,tongith i can tell u how to spell your standard english words"
"helli,every body,tongith i can tell u how to spell your standard english words"
'''
text.insert(tkinter.INSERT,str)
win.mainloop() |
#!/usr/bin/env python3
#! -*- coding: utf-8 -*-
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
length = len(nums)
index = 0
count = 0
while count < length:
if(nums[index]==0):
nums.pop(index)
nums.append(0)
index -= 1
index += 1
count += 1
import unittest
class TestSolution(unittest.TestCase):
def setUp(self):
self.solution = Solution()
def test1(self):
indata = [0,1,2,3]
self.solution.moveZeroes(indata)
self.assertEqual(indata, [1,2,3,0])
def test_all_zero(self):
indata = [0,0,0,0]
self.solution.moveZeroes(indata)
self.assertEqual(indata, [0,0,0,0])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.