text
stringlengths 37
1.41M
|
---|
"""
A Python script to illustrate manipulating the data without
retrieving the orignal dataset from the web.
"""
import retrieve_data
import reformat_data_lib as reform
import csv
def main():
old_mtx = []
with open("data/project_data.csv", mode = 'r') as old_file:
reader = csv.reader(old_file)
old_mtx = [row for row in reader]
# old_mtx: list of list
# Split location into location and state (split by delim of "."
reform.split_column(old_mtx, 2, lambda x: ("City", "State"),
lambda s: (s[:-4], s[-2:]))
retrieve_data.serialize_list(old_mtx, data_fname = "project_data_states.csv")
return (old_mtx)
if __name__ == "__main__":
retval = main()
print(retval)
|
word = input('Introduce word: ')
letter = input('Introduce letter: ')
#esta función cuenta el número de letras que aparece en una palabra
def count(word, letter):
cuenta = 0
for char in word:
if char == letter:
cuenta = cuenta + 1
return cuenta
print(count(word, letter))
|
text = open('mbox-short.txt')
result = dict()
order = list()
for line in text:
lineLower = line.lower()
#print(line)
for word in lineLower.split():
for letter in word:
if letter >='a' and letter <='z':
if letter not in result:
result[letter] = 1
else:
result[letter] += 1
for value, key in result.items():
order.append((key, value))
order.sort(reverse=True)
print(order)
|
# Simple SQL tests for playing with database setups
import unittest
try:
import psycopg2
DBCONN = psycopg2.connect(database='test')
except ImportError:
import sqlite3
DBCONN = sqlite3.connect(':memory:')
class TestSQL(unittest.TestCase):
def setUp(self):
cursor = DBCONN.cursor()
try:
cursor.execute("SELECT * FROM test;")
except Exception:
DBCONN.rollback()
cursor.execute("CREATE TABLE test (id INT NOT NULL, name TEXT);")
def test_case1(self):
cursor = DBCONN.cursor()
cursor.execute("INSERT INTO test (id,name) VALUES (1, 'hello');")
self.assertEqual(cursor.rowcount, 1)
def test_case2(self):
cursor = DBCONN.cursor()
cursor.execute("INSERT INTO test (id,name) VALUES (2, 'goodbye');")
self.assertEqual(cursor.rowcount, 1)
cursor.execute("SELECT name from test where id = 2;")
rows = cursor.fetchall()
self.assertEqual(len(rows), 1)
self.assertEqual(rows[0][0], u'goodbye')
self.assertEqual(type(DBCONN), object)
|
from .piece import Piece, Position
class Rook(Piece):
# Class of the rook piece
init_position = {0: {0: Position(0, 0), 1: Position(7, 0)},
1: {0: Position(0, 7), 1: Position(7, 7)}}
init_moves = []
def __init__(self, color: int, piece_number: int):
super().__init__(color,
Rook.init_position[color][piece_number],
Rook.init_moves,
piece_type=2,
piece_number=piece_number)
|
fruits = ['mango', 'apple', 'grape', 'banana']
def list_manipulation(newItem,new_fruit_loc,action):
if(action == 1):
if(new_fruit_loc == 'e'):
fruits.append(newItem)
print(fruits)
elif(new_fruit_loc == 'b'):
fruits.insert(0,newItem)
print(fruits)
else:
print(f"Wrong text entered, {fruits} still remains the same")
elif(action == 0):
if(new_fruit_loc == 'e'):
fruits.pop()
print(fruits)
elif(new_fruit_loc == 'b'):
fruits.pop(0)
print(fruits)
else:
print(f"Wrong text entered, {fruits} still remains the same")
else:
print(f"Invalid selection")
action = int(input("Would you like to add/remove an item? enter 0 to remove and 1 to add -->"))
newFruit = input("Enter a new item to the list -->")
new_fruit_loc = input("Enter location, b or beginning, e for end -->")
list_manipulation(newFruit,new_fruit_loc,action)
# print(len(fruits)) |
def check_string(the_txt, a):
num_of_occurence = 0
for char in the_txt:
if(char == a):
num_of_occurence = num_of_occurence + 1
print(num_of_occurence)
# print (num_of_occurence)
do_the_txt = input("enter text-->")
a = input("what text? --> ")
check_string(do_the_txt, a)
# print (do_the_txt) |
# PIANO TILES BOT PYTHON SCRIPT.
# AKSHITH KANDIVANAM.
# importing the required modules.
import pyautogui
import time
import keyboard
'''
This project aimed to automate the Piano Tiles game using the PyAutoGUI module's functions.
The main idea is to simply recognize if any of the 4 pixels we took match the RGB colour code of the tile that must be clicked.
If any of the pixels match the desired tile's colour , we perform the click operation. To stop the clicking process, a while loop is set in place and will be terminated upon pressing 'q'.
Step 1. I used the IDLE IDE for Python to scope out the X & Y coordinates for 4 pixels in each of the 4 columns. I also scoped out the RGB value of the tile that is expected to be clicked.
Step 2. I wrote this Python script and worked with the PyAutoGUI's 'click()' and 'pixelMatchesColor()' functions.
WHEN I SCOPED OUT THE COORDINATES THEY CAME OUT AS:
LEFTMOST COLUMN: X-761, Y-707.
LEFT COLUMN: X-887, Y-707.
RIGHT COLUMN: X-1007, Y-707.
RIGHTMOST COLUMN: X-1136, Y-707.
THE RGB CODE OF THE TILE TO CLICK WAS (17, 17, 17)
**Note: This program works with the Piano Tiles game from the website: http://tanksw.com/piano-tiles/. To play it on another website, adjust the coordinates and find the appropriate RGB value for the tile to click.
'''
# creating the main function for the click of the mouse.
# function takes in the parameters of a pixel's X & Y coordinates in each of the 4 columns.
def click_event(x, y):
# using the module's 'click' function to click on the pixel.
pyautogui.click(x, y)
time.sleep(0)
# creating a function to perform the clicking event on the leftmost column.
def leftmost_column():
# creating an if-statement to check if the pixel (761, 707) in the leftmost column matches the RGB code of the desired tile.
if pyautogui.pixelMatchesColor(761, 707, (17, 17, 17)):
# if the pixel does match the RGB code, we call the 'click_event' function and pass the appropriate coordinates of the pixel.
click_event(761, 707)
# creating a function to perform the clicking event on the left column.
def left_column():
# creating an if-statement to check if the pixel (887, 707) in the left column matches the RGB code of the desired tile.
if pyautogui.pixelMatchesColor(887, 707, (17, 17, 17)):
# if the pixel does match the RGB code, we call the 'click_event' function and pass the appropriate coordinates of the pixel.
click_event(887, 707)
# creating a function to perform the clicking event on the right column.
def right_column():
# creating an if-statement to check if the pixel (1007, 707) in the right column matches the RGB code of the desired tile.
if pyautogui.pixelMatchesColor(1007, 707, (17, 17, 17)):
# if the pixel does match the RGB code, we call the 'click_event' function and pass the appropriate coordinates of the pixel.
click_event(1007, 707)
# creating a function to perform the clicking event on the rightmost column.
def rightmost_column():
# creating an if-statement to check if the pixel (1136, 707) in the rightmost column matches the RGB code of the desired tile.
if pyautogui.pixelMatchesColor(1136, 707, (17, 17, 17)):
# if the pixel does match the RGB code, we call the 'click_event' function and pass the appropriate coordinates of the pixel.
click_event(1136, 707)
# creating a while-loop to iterate until the key 'q' is pressed to quit the program.
while keyboard.is_pressed('q') == False:
# calling all the functions to find if the pixels in their respective columns represent the RGB code for the tile to click.
leftmost_column()
left_column()
right_column()
rightmost_column()
|
class card:
# A class to represent a single card
def __init__(self, newSuit, newValue):
self.suit = newSuit #Suit
self.value = newValue #Value, 9-A
self.trump = False
self.winPercentage = 0.0
self.color = getColor(self.suit)
class kitty:
def __init__(self):
self.cards = []
def getTop(self):
return self.cards[0]
class team:
def __init__(self, mem1, mem2):
self.score = 0
self.called = False
self.tricks = 0
self.mem1 = mem1
self.mem2 = mem2
def findLowest(cards):
allTrump = False
for card in cards:
if not card.trump:
lowest = card
break
try:
highest
except NameError:
allTrump = True
lowest = cards[0]
if not allTrump:
for card in cards:
if (card.value < lowest.value and not card.trump):
lowest = card
else:
for card in cards:
if (card.value < lowest.value):
lowest = card
return lowest
def findHighest(cards):
ledSuit = cards[0].suit
ledTrump = cards[0].trump
highest = cards[0]
for card in cards:
if card.suit is ledSuit:
if (card.value > highest.value and not highest.trump):
highest = card
elif ledTrump and (card.value > highest.value):
highest = card
elif card.trump and card.suit is not ledSuit:
if highest.trump:
if card.value > highest.value:
highest = card
else:
highest = card
return highest
def getColor(suit):
if (suit == "diamonds") or (suit == "hearts"):
return "red"
elif (suit == "clubs") or (suit == "spades"):
return "black"
else:
return "green" # For some reason |
a=8
if(a<0)
print("negative")
elif(a>0)
print("postive")
else
print("zero")
|
def merge(playlist, l, m, r):
fh = m - l + 1
lh = r - m
L = [0] * (fh)
R = [0] * (lh)
for i in range(0 , fh):
L[i] = playlist[l + i]
for j in range(0 , lh):
R[j] = playlist[m + 1 + j]
i = j = 0
k = l
while i < fh and j < lh:
#Need something here to get input from module (user) in the form of a
#choice between two songs. For testing purposes (for now), it asks the user
#for input directly
print("\n")
print(L[i])
print(R[j])
choice = int(input("Type 1 for first song or type 2 for second song: "))
if choice == 1:
playlist[k] = L[i]
i += 1
else:
playlist[k] = R[j]
j += 1
k += 1
while i < fh:
playlist[k] = L[i]
i += 1
k += 1
while j < lh:
playlist[k] = R[j]
j += 1
k += 1
def sort(playlist, l, r):
if l < r:
m = (l+(r-1))//2
sort(playlist, l, m)
sort(playlist, m+1, r)
merge(playlist, l, m, r)
#Driver code/test code
playlist = ["ABC", "Bye Bye Bye", "Gladiator", "Brother", "Sky full of starts", "Jackie and Wilson", "About Love", "Sleep on the floor"]
n = len(playlist)
print("Original:")
print("\n")
for i in playlist:
print(i)
sort(playlist, 0, n-1)
print("\n")
print("Sorted:")
print("\n")
for i in playlist:
print(i)
|
"""
From page 263
Write a program that goes to a photo-sharing site like Flickr or Imgur, searches for a category of photos, and then
downloads all the resulting images. You could write a program that works with any photo site that has a search feature.
"""
import logging
import os
import requests
import sys
import urllib
from selenium import webdriver
from selenium.common import exceptions as selenium_exceptions
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait
DELAY_SEC = 10
IMAGE_DIR = r'.\out\downloaded_images'
logger = logging.getLogger('automate_boring.image_site_downloader')
if __name__ == '__main__':
os.makedirs(IMAGE_DIR, exist_ok=True)
url = sys.argv[1]
search_term = ' '.join(sys.argv[2:])
browser = webdriver.Firefox()
browser.get('https://{}'.format(url))
search_elem = browser.find_element_by_css_selector('#search_query')
search_elem.send_keys(search_term)
search_elem.submit()
try:
element_present = expected_conditions.presence_of_element_located((By.CSS_SELECTOR, 'img.photo'))
WebDriverWait(browser, DELAY_SEC).until(element_present)
except selenium_exceptions.TimeoutException:
msg = 'Failed to find any images in {} seconds'.format(DELAY_SEC)
logger.error(msg)
raise
pic_elems = browser.find_elements_by_css_selector('img.photo')
for pic in pic_elems:
pic_url = pic.get_attribute('src')
try:
res = requests.get(pic_url)
except requests.exceptions.InvalidSchema as e:
logger.error(repr(e))
continue
res.raise_for_status()
fn = os.path.basename(urllib.parse.urlparse(pic_url).path)
with open(os.path.join(IMAGE_DIR, fn), 'wb') as f:
for chunk in res.iter_content(100000): # TODO: upgrade to python 3.6 for 100_000
f.write(chunk)
|
import csv
with open('scores.csv', 'r') as scores:
reader = csv.reader(scores, delimiter=';')
maxt = 0
for row in reader: # Row is a list
if int(row[2]) > int(maxt):
naam = row[0]
datum = row[1]
maxt = int(row[2])
print('De hoogste score is: {2} op {1} behaald door {0}'.format(naam,datum,maxt))
|
import re
def password():
print ('Enter a password\n\nThe password must be between 6 and 12 characters.\n')
while True:
password = input('Password: ... ')
if 6 <= len(password) < 12:
break
print ('The password must be between 6 and 12 characters.\n')
password_scores = {0:'Horrible', 1:'Weak', 2:'Medium', 3:'Strong'}
password_strength = dict.fromkeys(['has_upper', 'has_lower', 'has_num'], False)
if re.search(r'[A-Z]', password):
password_strength['has_upper'] = True
if re.search(r'[a-z]', password):
password_strength['has_lower'] = True
if re.search(r'[0-9]', password):
password_strength['has_num'] = True
score = len([b for b in password_strength.values() if b])
print ('Password is %s' % password_scores[score]) |
import datetime
import csv
with open('inloggers.csv', 'a', newline='') as inloggersCSV:
writer = csv.writer(inloggersCSV, delimiter=';') #csv.writer
writer.writerow(('naam', 'voorl', 'gbdatum', 'email', 'time')) # Columnnames (one tuple!), optional!
while True:
naam = input("Wat is je achternaam? ")
if naam == 'einde':
break
else:
voorl = input("Wat zijn je voorletters? ")
gbdatum = input("Wat is je geboortedatum? ")
email = input("Wat is je e-mail adres? ")
vandaag = datetime.datetime.today()
time = vandaag.strftime("%a %d %b %Y, %H:%M:%S")
writer.writerow((naam, voorl, gbdatum, email, time)) # Values, one tuple!!
|
def convert(celcius):
farenheit = (celcius * 1.8) + 32
return farenheit
print('{:^5} {:^7}'.format("F", "C"))
for celcius in range(-30, 41, 5):
farenheit = convert(celcius)
print('{:5} {:7}'.format(farenheit, celcius)) |
import numpy as np
from marketdata import get_data
class trader():
def __init__(self, name, holding_days, sd, min_deviations, max_deviations):
# Name of the bot
self.name = name
# How many days that it will hang on to
self.holding_days = holding_days
# How much will the stock have to go down so the buy function is triggered
self.sd = sd
# How many deviations will meet the criteria to allow transaction
self.min_deviations = min_deviations
# Max. amount of deviations that will authorize the transaction
self.max_deviations = max_deviations
# How much the trader has
total_profit = 0
self.total_profit = total_profit
# How much the trader has
percentage_profit = 0
self.percentage_profit = percentage_profit
def validate(self, sd, holding_on, val_data, lines, max_deviations, min_deviations, start, end, symbol):
'''
CRITERIA AND MAIN INFO:
:param holding_on: This will be for how long we keep each stock
:param filename: This will be for which file we're working with
:param lines: This holds how many lines the current file has
:param max_deviation_criteria: This will be the max standard deviation criteria
:return: Did it make any transactions, how many, average return, list with
all transactions, total increase, accuracy
'''
# List storing all 'Open' values from the data csv file
information = val_data
# Go over all days and check if they are suitable for a transaction (don't go over index)
# This variable will store the index of the days suitable for a transaction
days = []
purchases = []
accuracy = 0
percent_sum = 0
for i in range(len(information)):
if i > 1 and i <= lines - holding_on + 1:
previous_percentage = float(information[i - 1]) / float(information[i - 2]) - 1
if previous_percentage < (sd * -1 * min_deviations) and previous_percentage > (
sd * -1 * max_deviations):
days.append(i)
# Iterate over information again, and if that element is in the suitable days list make purchase
# Calculate individual percentage profit and append to transactions
for j in range(len(information)):
if j in days:
try:
percent = float(information[j + holding_on]) / float(information[j]) - 1
purchases.append(percent)
percent_sum += np.log(percent + 1)
# To calculate the accuracy
if percent >= -0: accuracy += 1
except:
pass
# Calculate the average return, total return, yearly return if using this strategy (datetime module?)
total_change = np.exp(percent_sum) - 1
try:
avg_return = np.exp(percent_sum / len(purchases)) - 1
accuracy = accuracy / len(purchases)
except:
avg_return = 0
accuracy = 0
# This variable will store how many transactions were made
transactions = len(days)
results = {
'Total Change': total_change,
'Average Return': avg_return,
'Accuracy': accuracy,
'Days': days,
'Purchases': purchases,
'Holding Days': holding_on,
'Min Deviations': min_deviations,
'Max Deviations': max_deviations,
'Transactions': transactions,
}
return results
# This Function returns the average daily percentage change
def gather_sd(data):
# TODO use yfinance instead
# This variable will store the total change, meaning how much has changed from day 1 to the last
total_change = 0
first = True
# This variable will store a list of all percentages to be used to calculate standard deviation
values = []
# CALCULATING THE AVERAGE AND TOTAL CHANGE
for i in data:
# This statement will only run if line is still the first element. This is because we can't use
# the first day to calculate change. It will 'continue' this iteration of the for loop
if first:
previous_percentage = float(i)
first = False
continue
# This variable will calculate the ln of the change. Formula: ln(price[day] / price[previous_day])
percentage = np.log(float(i) / previous_percentage)
values.append(percentage)
total_change += percentage
# This will set the current day percentage as the previous day. Needed to calculate the next day's change
previous_percentage = float(i)
# CALCULATING STANDARD DEVIATION
sd = np.exp(np.std(values)) - 1
return (sd) |
"""
Stack Data Structure.
A B C D
D
C
B
A
"""
class Stack():
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return self.items == []
def get_stack(self):
return self.items
s = Stack()
#s.push("A")
#s.push("B")
#print(s.get_stack())
#s.push("C")
#s.pop()
#print(s.get_stack())
#s.pop()
#print(s.get_stack())
print(s.is_empty())
s.push("A")
print(s.is_empty())
|
__author__ = 'Josh'
import os
import urllib
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
vowels = ['a', 'e', 'i', 'o', 'u']
consonants = [x for x in alphabet if x not in vowels]
def join_with_spaces(lst):
#joins together lists of strings into sentences
index, counter, string = len(lst), 1, lst[0]
while counter < index:
string += ' '
string += lst[counter]
counter += 1
return string
class Word(str):
def __init__(self, word):
self.word = word
self.tag = None
def __getitem__(self, i):
return self.word[i]
def __len__(self):
return len(self.word)
def set_tag(self, part):
self.tag = part
class Sentence(object):
def __init__(self, text):
self.words = [Word(elem) for elem in self.remove_punc(text)]
def __repr__(self):
return join_with_spaces(self.words)
def __str__(self):
return str(join_with_spaces(self.words))
def __contains__(self, other):
if other in [x.word for x in self.words]:
return True
else:
return False
def __len__(self):
return len(self.words)
def __getitem__(self, i):
if i < 0:
return False
elif i > len(self.words)-1:
return False
else:
return self.words[i]
def index(self, elem):
return self.words.index(elem)
def get_previous(self, i):
return self.words[i-1]
def get_next(self, i):
return self.words[i+1]
def check_tag(self, i):
if i < 0:
return False
elif i > len(self.words)-1:
return False
else:
return self.words[i].tag
def set_tag(self, i, tag):
self.words[i].set_tag(tag)
def append_tag(self, i, app):
self.words[i].set_tag(self.words[i].tag+app)
def show_tags(self):
return [(elem, elem.tag) for elem in self.words]
def is_last_word(self, i):
if i == len(self.words)-1:
return True
else:
return False
def has_comma(self, i):
if i < 0:
return False
elif i > len(self.words)-1:
return False
else:
if self.words[i][len(self.words[i])-1] == ',':
return True
else:
return False
def remove_punc(self, text):
if text[-1] == '?':
self.question = True
mod = list(text)
mod.pop()
mod = ''.join(mod)
mod = mod.lower()
return mod.split()
else:
self.question = False
mod = list(text)
mod.pop()
mod = ''.join(mod)
mod = mod.lower()
return mod.split()
class Word_Ref (object):
#used for part of speech tagging, and word look up.
def __init__(self, selection):
if selection == 'Verbs':
txt = urllib.request.urlopen('https://raw.githubusercontent.com/jweinst1/Tagineer/master/tagineer/Verbs.txt').read()
wordstring = txt.decode("utf-8")
self.reference = wordstring.split()
elif selection == 'Nouns':
txt = urllib.request.urlopen('https://raw.githubusercontent.com/jweinst1/Tagineer/master/tagineer/Nouns.txt').read()
wordstring = txt.decode("utf-8")
self.reference = wordstring.split()
elif selection == 'Adjectives':
txt = urllib.request.urlopen('https://raw.githubusercontent.com/jweinst1/Tagineer/master/tagineer/Adjectives.txt').read()
wordstring = txt.decode("utf-8")
self.reference = wordstring.split()
elif selection == 'Adverbs':
txt = urllib.request.urlopen('https://raw.githubusercontent.com/jweinst1/Tagineer/master/tagineer/Adverbs.txt').read()
wordstring = txt.decode("utf-8")
self.reference = wordstring.split()
elif selection == 'Pronouns':
self.reference = ['i', 'me', 'my', 'mine', 'myself', 'you', 'your', 'yours', 'yourself', 'he', 'she', 'it', 'him', 'her'
'his', 'hers', 'its', 'himself', 'herself', 'itself', 'we', 'us', 'our', 'ours', 'ourselves',
'they', 'them', 'their', 'theirs', 'themselves', 'that', 'this']
elif selection == 'Coord_Conjunc':
self.reference = ['for', 'and', 'nor', 'but', 'or', 'yet', 'so']
elif selection == 'Be_Verbs':
self.reference = ['is', 'was', 'are', 'were', 'could', 'should', 'would', 'be', 'can', 'cant', 'cannot'
'does', 'do', 'did', 'am', 'been', 'go']
elif selection == 'Subord_Conjunc':
self.reference = ['as', 'after', 'although', 'if', 'how', 'till', 'unless', 'until', 'since', 'where', 'when'
'whenever', 'where', 'wherever', 'while', 'though', 'who', 'because', 'once', 'whereas'
'before', 'to', 'than']
elif selection =='Prepositions':
self.reference = ['on', 'at', 'in', 'of', 'into', 'from']
else:
raise ReferenceError('Must choose a valid reference library.')
def __contains__(self, other):
if other[-1] == ',':
return other[:-1] in self.reference
else:
return other in self.reference
def tag_pronouns(statement):
#will be first process, assumes no tag is given.
pronouns = Word_Ref('Pronouns')
i = 0
while i < len(statement):
if statement[i] in pronouns:
statement.set_tag(i, 'pronoun')
i += 1
else:
i += 1
return statement
def tag_preposition(statement):
preposition = Word_Ref('Prepositions')
articles = ['the', 'an', 'a']
i = 0
while i < len(statement):
if statement[i] in preposition:
statement.set_tag(i, 'preposition')
i += 1
elif statement[i] in articles:
statement.set_tag(i, 'article')
i += 1
else:
i += 1
return statement
def tag_be_verbs(statement):
be_verbs = Word_Ref('Be_Verbs')
i = 0
while i < len(statement):
if statement[i] in be_verbs:
statement.set_tag(i, 'verb')
i += 1
else:
i += 1
return statement
def tag_subord_conj(statement):
subord_conj = Word_Ref('Subord_Conjunc')
i = 0
while i < len(statement):
if statement[i] in subord_conj:
statement.set_tag(i, 'subord_conj')
i += 1
else:
i += 1
return statement
def tag_coord_conj(statement):
coords = Word_Ref('Coord_Conjunc')
i = 0
while i < len(statement):
if statement[i] in coords:
statement.set_tag(i, 'coord_conj')
i += 1
else:
i += 1
return statement
def tag_avna(statement):
adverbs = Word_Ref('Adverbs')
verbs = Word_Ref('Verbs')
nouns = Word_Ref('Nouns')
adjectives = Word_Ref('Adjectives')
i = 0
while i < len(statement):
if statement.check_tag(i) != None:
i += 1
else:
if statement[i] in nouns:
statement.set_tag(i, 'noun')
i += 1
elif statement[i] in verbs:
statement.set_tag(i, 'verb')
i += 1
elif statement[i] in adverbs:
statement.set_tag(i, 'adverb')
i += 1
elif statement[i] in adjectives:
statement.set_tag(i, 'adjective')
i += 1
else:
i += 1
return statement
def post_processing(statement):
#corrects errors in tagging based on rule-based deduction.
be_verbs = ['is', 'was', 'are', 'were']
i = 0
while i < len(statement):
if statement.check_tag(i) == 'noun' and statement.check_tag(i-1) == 'pronoun':
statement.set_tag(i, 'verb')
i += 1
elif statement.check_tag(i) == None and statement.check_tag(i+1) == 'verb':
statement.set_tag(i, 'noun')
i += 1
elif statement.check_tag(i) == None and statement.check_tag(i-1) == 'preposition':
statement.set_tag(i, 'noun')
i += 1
elif statement.check_tag(i) == None and statement.check_tag(i+1) == 'subord_conj':
statement.set_tag(i, 'noun')
i += 1
elif statement.check_tag(i) == 'noun' and statement.check_tag(i-1) == 'noun' and statement.has_comma(i-1) == False:
statement.set_tag(i, 'verb')
i += 1
elif statement.check_tag(i) == 'noun' and statement.check_tag(i-1) == 'adjective' and statement.check_tag(i+1) == 'noun' and statement.is_last_word(i):
statement.set_tag(i, 'adjective')
elif statement.check_tag(i) == 'noun' and statement.check_tag(i-1) == 'article' and statement.check_tag(i+1) == 'noun':
statement.set_tag(i, 'adjective')
i += 1
elif statement.check_tag(i) == 'noun' and statement[i-1] in be_verbs and statement.is_last_word(i) and statement.check_tag(i-2) == 'noun':
statement.set_tag(i, 'adjective')
i += 1
elif statement.check_tag(i) == None and statement.check_tag(i-1) == 'article' and statement.check_tag(i+1) == 'noun':
statement.set_tag(i, 'adjective')
i += 1
elif statement.check_tag(i) == 'noun' and statement.check_tag(i-1) == 'adverb':
statement.set_tag(i, 'verb')
i += 1
else:
i += 1
return statement
def tag_noun_plurals(statement):
i = 0
while i < len(statement):
if statement.check_tag(i) == 'noun':
if statement[i][-1] == 's' and statement[i][-2] in consonants:
statement.append_tag(i, '-P')
i += 1
elif statement[i][-1] == 's' and statement[i][-2] == 'e' and statement[i][-3] in consonants:
statement.append_tag(i, '-P')
i += 1
else:
statement.append_tag(i, '-S')
i += 1
else:
i += 1
return statement
def tag_sentence(statement):
elem = statement
tag = tag_avna(elem)
tag = tag_pronouns(tag)
tag = tag_preposition(tag)
tag = tag_coord_conj(tag)
tag = tag_subord_conj(tag)
tag = tag_be_verbs(tag)
tag = post_processing(tag)
tag = tag_noun_plurals(tag)
return tag
def tag_text(text):
elem = Sentence(text)
tag = tag_avna(elem)
tag = tag_pronouns(tag)
tag = tag_preposition(tag)
tag = tag_coord_conj(tag)
tag = tag_subord_conj(tag)
tag = tag_be_verbs(tag)
tag = post_processing(tag)
tag = tag_noun_plurals(tag)
return tag
def package_sentence(statement):
#packages a tagged sentence into a displayable string
counter = 0
string = ""
while counter < len(statement):
if statement[counter].tag == None:
string += statement[counter].word + " " + "\n"
counter += 1
else:
string += statement[counter].word + " " + statement[counter].tag + "\n"
counter += 1
return string
#condition functions to check for nouns/subjects
#possible secondary processing arguments
def check_articles(i, statement):
articles = ['the', 'a', 'an']
if statement.get_previous(i) in articles:
return True
else:
return False
def check_simpV(i, statement):
simple = ['is', 'was', 'are', 'were', 'can', 'cannot', 'will', 'do', 'does', 'did' 'dont', 'would', 'could', 'should', 'has', 'had', 'have']
if statement.get_next(i) in simple:
return True
else:
return False
def precede_verb(i, statement):
current = statement.get_next(i)
if current[-1] == 's' and current[-2] in consonants:
return True
else:
return False
|
import numpy as np
'''
ndarray对象的内容可以通过索引或切片来访问和修改,与 Python 中 list 的切片操作一样。
ndarray 数组可以基于 0 - n 的下标进行索引,切片对象可以通过内置的 slice 函数,并设置 start, stop 及 step 参数进行,从原数组中切割出一个新数组。
'''
a = np.arange(10)
print(a)
s = slice(2, 7, 2) # 从索引 2 开始到索引 7 停止,间隔为2
print(a[s])
# 通过冒号分隔切片参数 start:stop:step 来进行切片操作
print(a[2:7:2])
print(a[2:9:3])
print(a[2:])
print(a[2:5])
# 多维数组同样适用于上述索引提取方法
a2 = np.array([[1, 2, 3], [3, 4, 5], [4, 5, 6]])
print(a2)
print("从数组索引a[1:]处开始切割")
print(a2[1:])
# 切片还可以包括省略号 …,来使选择元组的长度与数组的维度相同。 如果在行位置使用省略号,它将返回包含行中元素的 ndarray。
a3 = np.array([[1, 2, 3], [3, 4, 5], [4, 5, 6]])
print(a3[..., 1]) # 第二列元素
print(a3[1, ...]) # 第二行元素
print(a3[..., 1:]) # 第二列及剩下的所有元素
|
'''
迭代是访问集合元素的一种方式,迭代器是一个可以记住,迭代器是一个可以记住遍历位置的男人。迭代器对象从集合的第一个元素开始访问,直到所有的要素被访问结束。
特点:
迭代器只能往前不会后退。
可以被next()函数调用并不断返回下一个值的对象成为迭代器:Iterable
可迭代的是不是迭代器??? list是可迭代的,俺不是迭代器
借助函数iter(),参数为可迭代对象
生成器与迭代器
生成器是迭代器的子集,迭代器还包括元组,集合,列表,字典,字符串等可迭代对象,这些对象借助iter()函数的转换,可以变成迭代器
'''
# 可迭代对象:1.生成器 2.元组,列表,集合,字典, 字符串
# 如何判断一个对象的是否可迭代?
from collections.abc import Iterable
list1 = [1, 4, 7, 8, 9]
f = isinstance(list1, Iterable)
print(f)
f = isinstance('abc', Iterable)
print(f)
f3 = isinstance(100, Iterable)
print(f3)
g = iter(list1)
print(next(g))
print(next(g)) |
import numpy as np
'''
种类 速度 最坏情况 工作空间 稳定性
'quicksort'(快速排序) 1 O(n^2) 0 否
'mergesort'(归并排序) 2 O(n*log(n)) ~n/2 是
'heapsort'(堆排序) 3 O(n*log(n)) 0 否
'''
'''
numpy.sort()
numpy.sort() 函数返回输入数组的排序副本。函数格式如下:
numpy.sort(a, axis, kind, order)
参数说明:
a: 要排序的数组
axis: 沿着它排序数组的轴,如果没有数组会被展开,沿着最后的轴排序, axis=0 按列排序,axis=1 按行排序
kind: 默认为'quicksort'(快速排序)
order: 如果数组包含字段,则是要排序的字段
'''
print('numpy.sort()')
a = np.array([[3, 7], [9, 1]])
print('我们的数组是:')
print(a)
print('调用 sort() 函数:')
print(np.sort(a))
print('按列排序:')
print(np.sort(a, axis=0))
# 在 sort 函数中排序字段
dt = np.dtype([('name', 'S10'), ('age', int)])
a = np.array([("raju", 21), ("anil", 25),
("ravi", 17), ("amar", 27)], dtype=dt)
print('我们的数组是:')
print(a)
print('按 name 排序:')
print(np.sort(a, order='name'))
print('\n')
'''
numpy.argsort()
numpy.argsort() 函数返回的是数组值从小到大的索引值。
'''
print('argsort() 函数返回的是数组值从小到大的索引值。')
x = np.array([3, 1, 2])
print('我们的数组是:')
print(x)
print('对 x 调用 argsort() 函数:')
y = np.argsort(x)
print(y)
print('以排序后的顺序重构原数组:')
print(x[y])
print('使用循环重构原数组:')
for i in y:
print(x[i], end=" ")
print('\n')
'''
numpy.lexsort()
numpy.lexsort() 用于对多个序列进行排序。把它想象成对电子表格进行排序,每一列代表一个序列,排序时优先照顾靠后的列。
这里举一个应用场景:小升初考试,重点班录取学生按照总成绩录取。在总成绩相同时,数学成绩高的优先录取,在总成绩和数学成绩都相同时,
按照英语成绩录取…… 这里,总成绩排在电子表格的最后一列,数学成绩在倒数第二列,英语成绩在倒数第三列。
'''
print('lexsort() 用于对多个序列进行排序。')
nm = ('raju', 'anil', 'ravi', 'amar')
dv = ('f.y.', 's.y.', 's.y.', 'f.y.')
# 传入np.lexsort 的是一个tuple,排序时首先排 nm,顺序为:amar、anil、raju、ravi 。综上排序结果为 [3 1 0 2]。
ind = np.lexsort((dv, nm))
print('调用 lexsort() 函数:')
print(ind)
print('使用这个索引来获取排序后的数据:')
print([nm[i] + ", " + dv[i] for i in ind])
print('\n')
'''
msort(a) 数组按第一个轴排序,返回排序后的数组副本。np.msort(a) 相等于 np.sort(a, axis=0)。
sort_complex(a) 对复数按照先实部后虚部的顺序进行排序。
partition(a, kth[, axis, kind, order]) 指定一个数,对数组进行分区
argpartition(a, kth[, axis, kind, order]) 可以通过关键字 kind 指定算法沿着指定轴对数组进行分区
'''
print('msort(a) 数组按第一个轴排序,返回排序后的数组副本。')
x = np.array([[3, 1, 2], [6, 9, 8], [4, 9, 8]])
print(np.msort(x))
print()
print('partition(a, kth[, axis, kind, order]) 指定一个数,对数组进行分区')
# 将数组 a 中所有元素(包括重复元素)从小到大排列,3 表示的是排序数组索引为 3 的数字,比该数字小的排在该数字前面,比该数字大的排在该数字的后面
print(np.partition(np.array([3, 4, 9, 2, 1]), 3))
'''
numpy.argmax() 和 numpy.argmin()
numpy.argmax() 和 numpy.argmin()函数分别沿给定轴返回最大和最小元素的索引。
'''
print('\n')
print('argmax() 和 argmin()函数分别沿给定轴返回最大和最小元素的索引。')
a = np.array([[30, 40, 70], [80, 20, 10], [50, 90, 60]])
print('我们的数组是:')
print(a)
print(np.argmax(a))
print(np.argmin(a))
print('沿轴 0 的最大值索引:')
maxindex = np.argmax(a, axis=0)
print(maxindex)
print('沿轴 1 的最大值索引:')
maxindex = np.argmax(a, axis=1)
print(maxindex)
print('\n')
'''
numpy.nonzero()
numpy.nonzero() 函数返回输入数组中非零元素的索引。
'''
print('nonzero() 函数返回输入数组中非零元素的索引。')
a = np.array([[30, 40, 0], [0, 20, 10], [50, 0, 60]])
print('我们的数组是:')
print(a)
print(np.array(np.nonzero(a)))
'''
numpy.where()
numpy.where() 函数返回输入数组中满足给定条件的元素的索引。
'''
print('\n')
print('where() 函数返回输入数组中满足给定条件的元素的索引。')
x = np.arange(9.).reshape(3, 3)
print('我们的数组是:')
print(x)
y = np.where(x > 3)
print(y)
print('使用这些索引来获取满足条件的元素:')
print(x[y])
'''
numpy.extract()
numpy.extract() 函数根据某个条件从数组中抽取元素,返回满条件的元素。
'''
print('\n')
print('extract() 函数根据某个条件从数组中抽取元素,返回满条件的元素。')
x = np.arange(9.).reshape(3, 3)
print('我们的数组是:')
print(x)
# 定义条件, 选择偶数元素
condition = np.mod(x, 2) == 0
print(condition)
print('按条件提取元素:')
print(np.extract(condition, x))
|
# 递归的次数是入口决定的,防止死循环的关键在于是否规划好“何时退出循环”
print("\n")
print("demo1")
def sum(x):
if x == 0:
return 0
else:
return x+sum(x-1)
print(sum(10))
print("\n")
print("demo2")
def sum1(n):
if n > 100:
return 0
else:
return n + sum1(n+1)
print(sum1(1))
|
# Create a list and just append whatever you want to it!
positive_sayings = list()
positive_sayings.append("You are a unique child of this world.")
positive_sayings.append("You have as much brightness to offer the world as the next person.")
positive_sayings.append("You matter and what you have to this world also matters.")
positive_sayings.append("Trust yourself.")
positive_sayings.append("The situation you're in will work out for your highest good.")
positive_sayings.append("Wonderful things will unfold before you.")
positive_sayings.append("Draw from your inner strength and light.")
positive_sayings.append("You may not make all the right choices, but you'll grow from all of them.")
positive_sayings.append("Feel the love from those not physically around you.")
positive_sayings.append("You are too big a gift to this world to feel self-pity.")
positive_sayings.append("I love and approve of you.")
positive_sayings.append("Forgive yourself for all the mistakes you've made. They've made you better.")
positive_sayings.append("Let go of your anger so you can see things clearly.")
positive_sayings.append("Accept responsibility if your anger has hurt anyone, and work to rememedy it.")
positive_sayings.append("Replace your anger with understanding and compassion.")
positive_sayings.append("You may not understand the good in this situation, but it is there, time will tell.")
positive_sayings.append("Muster up more hope and courage from deep inside you.")
positive_sayings.append("Choose to find hopeful and optimistic ways to look at your situation.")
positive_sayings.append("It's ok to ask for help and guidance - it's not weakness, it's intelligence.")
positive_sayings.append("Refuse to give up, there's always another way.")
positive_sayings.append("Never stop loving.")
positive_sayings.append("Receive all feedback with kindness, but ultimately you make the final call.")
positive_sayings.append("Continue showing love to everyone, it will come back to you.")
positive_sayings.append("You are a better person from all the pain you've gone through.")
positive_sayings.append("Choose friends who approve and love you.")
positive_sayings.append("Surround yourself with people who treat you well.")
positive_sayings.append("Take the time to show your friends that you care about them.")
positive_sayings.append("Take great pleasure with your friends, even if you disagree or live different lives.")
positive_sayings.append("You play a huge role in your own career success.")
positive_sayings.append("What you do is meaningful and rewarding.")
positive_sayings.append("Believe in your ability to change the world with the work that you do.")
positive_sayings.append("Engage in activities that impact this world positively.")
positive_sayings.append("Peaceful sleep awaits for you in the dreamland.")
positive_sayings.append("Let go of all the false stories that you make up in your head.")
positive_sayings.append("Release your mind of throught until you wake up.")
positive_sayings.append("Embrace the peace and quiet of the night.")
positive_sayings.append("The day will bring you nothing but growth.")
positive_sayings.append("Today will be a gorgeous day to remember.")
positive_sayings.append("Your thoughts are your reality so think up a bright new day.")
positive_sayings.append("Fill up your day with hope and face it with joy.")
positive_sayings.append("Choose to fully participate in your day.")
positive_sayings.append("Let go of worries that simply drain your energy.")
positive_sayings.append("You are a smart, caluclated person.")
positive_sayings.append("You are in complete charge of planning for your future.")
positive_sayings.append("Trust in your own abilities.")
positive_sayings.append("Follow your dreams no matter what.")
positive_sayings.append("If they don't support you, don't associate with them.")
positive_sayings.append("Pursue your dream.")
positive_sayings.append("All your problems have a solution. Find it")
positive_sayings.append("You are safe and sound. All is well.")
positive_sayings.append("There is a great reason this is unfolding before me now.")
positive_sayings.append("You have the smarts and the ability to get through this.")
positive_sayings.append("Seek a new way of thinking about your situation.")
positive_sayings.append("The answer is right before you, even if you can't see it yet.")
positive_sayings.append("Believe in your ability to unlock the way and set yourself free.")
positive_sayings.append(
"You have no right to compare yourself to anyone, for you do not know their whole story, nor them, yours.")
positive_sayings.append("Compare youself only to that of your highest self.")
positive_sayings.append("Choose to see the light that you are to this world.")
positive_sayings.append("Be happy in your own skin and in your own circumstances.")
positive_sayings.append("You are a gift to everyone who interacts with you.")
positive_sayings.append("You are more than good enough and you're getting better every day.")
positive_sayings.append("Adopt the mindset to praise yourself.")
positive_sayings.append("Give up that self-critical habit.")
positive_sayings.append("See the perfection in all your flaws and all your genius.")
positive_sayings.append("You ARE a good person at all times of day and night.")
positive_sayings.append("Bad thoughts do not make you a bad person.")
positive_sayings.append("We all struggle, it's ok, you're strong. I believe in you.")
positive_sayings.append("You cannot give up until you have tried every single possible conceivable way.")
positive_sayings.append("Giving up is easy and always an option, so let's delay it for another day.")
positive_sayings.append("Press on, your path is true.")
positive_sayings.append("It is always too early to give up on your goals.")
positive_sayings.append("You've already traversed so far through the dark tunnel, don't give up just yet.")
positive_sayings.append("The past has no power over you anymore.")
positive_sayings.append("Embrace the rhythm ad the flowing of your own heart.")
positive_sayings.append("All that you need comes to you at the right time and place in this life.")
positive_sayings.append("You should be deeply fulfilled with who you are.")
|
def get_default_wheel_list():
result = []
for i in range(3):
result.append(get_default_wheel())
return result
class Wheel(object):
def __init__(self, vector_from_robot_center, wheel_spin=0, linear_velocity):
pass
|
#!/usr/bin/env python
import time
start_time = time.time()
calc = time.time()
end_time = time.time()
print (end_time - start_time)/2.0
start_time = time.clock()
calc = time.clock()
end_time = time.clock()
print (end_time - start_time)/2.0
|
class Musician(object):
def __init__(self, sounds):
self.sounds = sounds
def solo(self, length):
for i in range(length):
print(self.sounds[i % len(self.sounds)])
# The Musician class is the parent of the Bassist class
class Bassist(Musician):
def __init__(self):
# Call the __init__ method of the parent class
super(Bassist, self).__init__(["Twang", "Thrumb", "Bling"])
class Guitarist(Musician):
def __init__(self):
# Call the __init__ method of the parent class
super(Guitarist, self).__init__(["Boink", "Bow", "Boom"])
def tune(self):
print("Be with you in a moment")
print("Twoning, sproing, splang")
class Drummer(Musician):
def __init__(self):
#TODO
# Forgive me I really have no idea how to describe drum sound in English
super(Drummer, self).__init__(["Dong", "Tong", "Ting", "Hehe"])
def __count__(self):
for i in range(4):
print i
class Band(object):
def __init__(self):
self.musicians=[]
def hire_musician(self, musician):
self.musicians.append(musician)
def fire_musician(self, musician):
self.musicians.remove(musician)
def play_solo(self, length):
for musician in self.musicians:
musician.solo(length)
if(__name__ == '__main__'):
david = Guitarist()
derek= Bassist()
jorge = Drummer()
popBand = Band()
popBand.hire_musician(david)
popBand.hire_musician(derek)
popBand.hire_musician(jorge)
jorge.__count__()
length = 10
popBand.play_solo(length)
popBand.fire_musician(david)
popBand.play_solo(length)
|
import numpy as np
def sigmoid(x):
# f(x) = 1 / (1 + e^(-x)) دالة السيجمويد
return 1 / (1 + np.exp(-x))
def deriv_sigmoid(x):
# f'(x) = f(x) * (1 - f(x)) : مشتقة السيجمويد
fx = sigmoid(x)
return fx * (1 - fx)
def mse_loss(y_true, y_pred):
# بنفس الطول arrays عبارة عن y_true و y_pred
return ((y_true - y_pred) ** 2).mean()
class OurNeuralNetwork:
'''
:الشبكة العصبية لديها
- مدخلين
- (h1, h2) طبقة خفية تحتوي على عصبونين
- (o1) طبقة مخرجات تحتوي على عصبون واحد
'''
def __init__(self):
# الأوزان
self.w1 = np.random.normal()
self.w2 = np.random.normal()
self.w3 = np.random.normal()
self.w4 = np.random.normal()
self.w5 = np.random.normal()
self.w6 = np.random.normal()
# الإنحياز
self.b1 = np.random.normal()
self.b2 = np.random.normal()
self.b3 = np.random.normal()
def feedforward(self, x):
# لها عنصرين array هي x
h1 = sigmoid(self.w1 * x[0] + self.w2 * x[1] + self.b1)
h2 = sigmoid(self.w3 * x[0] + self.w4 * x[1] + self.b2)
o1 = sigmoid(self.w5 * h1 + self.w6 * h2 + self.b3)
return o1
def train(self, data, all_y_trues):
'''
تساوي عدد الأمثلة n و (n x 2) حجمها numpy array البيانات هي
عناصر n لها numpy array هي all_y_trues
تمثل البيانات all_y_trues العناصر في
'''
learn_rate = 0.1
epochs = 1000 # عدد الدورات خلال البيانات
for epoch in range(epochs):
for x, y_true in zip(data, all_y_trues):
# --- التفذية الأمامية و التي سنحتاجها لاحقاً
sum_h1 = self.w1 * x[0] + self.w2 * x[1] + self.b1
h1 = sigmoid(sum_h1)
sum_h2 = self.w3 * x[0] + self.w4 * x[1] + self.b2
h2 = sigmoid(sum_h2)
sum_o1 = self.w5 * h1 + self.w6 * h2 + self.b3
o1 = sigmoid(sum_o1)
y_pred = o1
# --- .حساب المشتقات الجزئيى
d_L_d_ypred = -2 * (y_true - y_pred)
# o1 العصبون
d_ypred_d_w5 = h1 * deriv_sigmoid(sum_o1)
d_ypred_d_w6 = h2 * deriv_sigmoid(sum_o1)
d_ypred_d_b3 = deriv_sigmoid(sum_o1)
d_ypred_d_h1 = self.w5 * deriv_sigmoid(sum_o1)
d_ypred_d_h2 = self.w6 * deriv_sigmoid(sum_o1)
# h1 العصبون
d_h1_d_w1 = x[0] * deriv_sigmoid(sum_h1)
d_h1_d_w2 = x[1] * deriv_sigmoid(sum_h1)
d_h1_d_b1 = deriv_sigmoid(sum_h1)
# h2 العصبون
d_h2_d_w3 = x[0] * deriv_sigmoid(sum_h2)
d_h2_d_w4 = x[1] * deriv_sigmoid(sum_h2)
d_h2_d_b2 = deriv_sigmoid(sum_h2)
# --- تحديث الأوزان و الإنحياز
# h1 العصبون
self.w1 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w1
self.w2 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w2
self.b1 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_b1
# h2 العصبون
self.w3 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w3
self.w4 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w4
self.b2 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_b2
# O1 العصبون
self.w5 -= learn_rate * d_L_d_ypred * d_ypred_d_w5
self.w6 -= learn_rate * d_L_d_ypred * d_ypred_d_w6
self.b3 -= learn_rate * d_L_d_ypred * d_ypred_d_b3
# --- epoch حساب الخسارة بعد كل
if epoch % 10 == 0:
y_preds = np.apply_along_axis(self.feedforward, 1, data)
loss = mse_loss(all_y_trues, y_preds)
print("Epoch %d loss: %.3f" % (epoch, loss))
# التغريف بالبيانات
data = np.array([
[-2, -1], # إيمان
[25, 6], # مدثر
[17, 4], # عبد الفتاح
[-15, -6], # أمال
])
all_y_trues = np.array([
1, # إيمان
0, # مدثر
0, # عبد الفتاح
1, # أمال
])
# تدريب الشبكة العصبية
network = OurNeuralNetwork()
network.train(data, all_y_trues)
# القيام بالتنبؤ
Hala = np.array([-7, -3]) # 65 kg, 163 cm
Khaled = np.array([20, 2]) # 92 kg, 168 cm
print("Hala: %.3f" % network.feedforward(Hala)) # 0.951 - F
print("Khaled: %.3f" % network.feedforward(Khaled)) # 0.039 - M
|
print("Q.1- Take 10 integers from user and print it on screen.")
for i in range(1,6):
x=input("enter a no")
print(x)
print("Q.3- Create a list of integer elements by user input. Make a new list which will store square of elements of previous list.")
a={}
for i in range(1,4):
a[i]=int(input("enter a no"))
for i in range(1,4):
a[i]=a[i]*a[i]
print(a[i])
print("Q 4.From a list containing ints, strings and floats, make three lists to store them separately")
mylist=[1,2,"pri",2.3]
#print(type(mylist[2]))
mylistint=[]
mylistfloat=[]
myliststr=[]
for i in range(0,len(mylist)):
if(type(mylist[i])==int):
mylistint.append(mylist[i])
elif(type(mylist[i])==float):
mylistfloat.append(mylist[i])
elif (type(mylist[i]) == str):
myliststr.append(mylist[i])
print("main list")
print(mylist)
print("integer list")
print(mylistint)
print("flloat list")
print(mylistfloat)
print("string list")
print(myliststr)
print("Q.5- Using range(1,101), make a list containing only prime numbers")
for i in range(1,101):
j=2
for j in range(2,i+1):
if(i%j==0):
break
if(i==j):
print(i)
print("Q.2- Write an infinite loop.An infinite loop never ends. Condition is always true.")
i=6
while(i>5):
print("infinite")
i=i+1
|
#Create a list with user defined inputs
mylist=[input("enter first no"),input("emter second no")]
print(mylist)
#2.Add the following list to above created list:
#[‘google’,’apple’,’facebook’,’microsoft’,’tesla’]
mylist2=["google","apple","facebook","microsoft","tesla"]
mylist.extend(mylist2)
print(mylist)
#3. Count the number of time an object occurs in a list.
mylist4=["as","wsd","ab","we","ab"]
print(mylist4.count("ab"))
#4. create a list with numbers and sort it in ascending order.
mylist3=[2,1,5,4,6,8,3]
mylist3.sort()
print(mylist3)
#5. Given are two one-dimensional arrays A and B which are sorted in ascending order. Write a program to merge them into a single sorted array C that contains every item from arrays A and B, in ascending order. [List]
mylist5=[1,2,3,4,6,7]
mylist6=[5,8,9]
mylist5.extend(mylist6)
mylist5.sort()
print(mylist5) |
from pyquery import PyQuery as pq
from lxml import etree
import urllib
#Acceso al html
#d = pq("<html></html>")
#d = pq(etree.fromstring("<html></html>"))
d = pq(url='http://www.mambiente.munimadrid.es/opencms/opencms/calaire/consulta/Gases_y_particulas/informegaseshorarios.html?__locale=es')
#d = pq(url='http://google.com/', opener=lambda url, **kw: urllib.urlopen(url).read())
#d = pq(filename='table.html')
#<span class="tabla_titulo_fecha">2016-01-24 09:00:00.0</span>
#Selection of data date
date_data=d('span[class=tabla_titulo_fecha]')
date_data=date_data.text()
#print (date_data)
#Selection of station name
station_name=d('td[class="primertd"]')
station_name=station_name.append("**")
station_name=station_name.text()
station_name=station_name.split("**")
#print(station_name)
del station_name[0] #Delete the first empty element of the list
#for x in station_name:
# print(x)
#Selection of all the N02 data
no2rawdata=d('td[headers="NO2"]')
no2data=no2rawdata.text()
no2data=no2data.replace("-","0")#Replaces no data with a 0
no2data=no2data.split(" ")
no2data = map(int, no2data) #int conversion
'''
#Info output
print("\n\nContaminacion de NO2 en Madrid-Fecha: "+date_data)
for x in no2data:
if x<20:
print(str(x)+"-ALERTA POR POLUCION")
else:
print(x)
'''
#Info output
print("\n\nContaminacion de NO2 en Madrid-Fecha: "+date_data)
for x in range(len(no2data)):
if no2data[x]>400:
print("\n")
print(station_name[x]+": "+str(no2data[x])+" microgramos/metro cubico"+"-POSIBLE ALERTA POR POLUCION")
elif no2data[x]>250:
print("\n")
print(station_name[x]+": "+str(no2data[x])+" microgramos/metro cubico"+"-POSIBLE AVISO POR POLUCION")
elif no2data[x]>200:
print("\n")
print(station_name[x]+": "+str(no2data[x])+" microgramos/metro cubico"+"-POSIBLE PREAVISO POR POLUCION")
else:
print("\n")
print(station_name[x]+": "+str(no2data[x])+" microgramos/metro cubico")
|
class Person:
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
def print_info(self):
print('姓名:', self.name, '年龄:', self.age, '性别', self.sex)
class Student(Person):
def __init__(self, name, age, sex, stuNo):
Person.__init__(self, name, age, sex)
self.stuNo = stuNo
def print_info(self):
print('姓名:', self.name, '年龄:', self.age, '性别:'
, self.sex, '学号:', self.stuNo)
p = Person('cuppar', 22, '男')
p.print_info()
s = Student('cuppar', 22, '男', 20151120237)
s.print_info()
|
title='''
6.编写程序,输入一个字符,判断该字符是大写字母、小写字母,数字还是其他字符,并作相应的显示。
提示:利用ord()函数来获得字符的ASCII。
'''
def distinguish(c: chr):
c_ascii = ord(c)
if c_ascii >= 48 and c_ascii <= 57:
print('该字符为数字')
elif c_ascii >= 65 and c_ascii <= 90:
print('该字符为大写字母')
elif c_ascii >= 97 and c_ascii <= 122:
print('该字符为小写字母')
else:
print('该字符为其他字符')
if __name__ == '__main__':
print(title)
distinguish(input('input a char: ')) |
"""
文法:
E->E+T | T
T->T*F | F
F->(E)|i
消除左递归:
E->TH
H->+TH|e(e替代空)
T->FY
Y->*FY|e
F->(E)|i
"""
# 手动构造预测分析表
dists = {
('E', 'i'): 'TH',
('E', '('): 'TH',
('H', '+'): '+TH',
('H', ')'): 'e',
('H', '#'): 'e',
('T', 'i'): 'FY',
('T', '('): 'FY',
('Y', '+'): 'e',
('Y', '*'): '*FY',
('Y', ')'): 'e',
('Y', '#'): 'e',
('F', 'i'): 'i',
('F', '('): '(E)',
}
# 构造终结符集合
Vt = ('i', '+', '*', '(', ')')
# 构造非终结符集合
Vh = ('E', 'H', 'T', 'Y', 'F')
def printstack(stack): # 获取输入栈中的内容
rtu = ''
for i in stack:
rtu += i
return rtu
def printstr(str, index): # 得到输入串剩余串
rtu = ''
for i in range(index, len(str), 1):
rtu += str[i]
return rtu
def error(): # 定义error函数
print('Error')
exit()
def masterctrl(str): # 总控程序,用列表模拟栈
stack = []
location = 0
stack.append(str[location]) # 将#号入栈
stack.append('E') # 将文法开始符入栈
location += 1
a = str[location] # 将输入串第一个字符读进a中
printstack(stack)
flag = True
count = 0
print('%d\t\t\t%s\t\t\t%s' % (count, printstack(stack), printstr(str, location)))
while flag:
if count == 0:
pass
else:
if x in Vt:
print('%d\t\t\t%s\t\t%s' % (count, printstack(stack), printstr(str, location)))
else:
print('%d\t\t\t%s\t\t%s\t\t%s->%s' % (count, printstack(stack), printstr(str, location), x, s))
x = stack.pop()
if x in Vt:
if x == str[location]:
location += 1
a = str[location]
else:
error()
elif x == '#':
if x == a:
flag = False
else:
error()
elif (x, a) in dists.keys():
s = dists[(x, a)]
for i in range(len(s) - 1, -1, -1):
if s[i] != 'e':
stack.append(s[i])
else:
error()
count += 1
def main():
str = '#i+i*i+i#'
print("步骤\t\t符号栈\t\t输入串\t\t\t所用产生式")
masterctrl(str)
if __name__ == '__main__':
main()
|
class Person:
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
def print_info(self):
print('姓名:', self.name, '年龄:', self.age, '性别', self.sex)
p = Person('cuppar', 22, '男')
p.print_info()
|
import math
title='''
3.编写程序,输入球体半径,计算出球的体积和表面积,并输出结果。
提示:球体表面积计算公式为 S=4πR²,球体体积计算公式为 V=(4/3)πR³。
'''
print(title)
r=float(input("please input the ball's radius:"))
s=4*math.pi*r**2
v=(4/3)*math.pi**3
print("This ball's surface is: ", s)
print("This ball's valume is: ", v) |
name = "Mike"
user_name = input("Please enter your name: \n").strip().title()
if name == user_name:
print("Hello Mike! The password is W@12")
else:
print("Hello ", user_name, "See you later!") |
'''
Created on Apr 19, 2018
A player will have its associated style like X or O
A player will be able to perform action to put a piece on the board
When performing an action, a piece instance will be created and placed
on the board
@author: varunjai
'''
from abc import ABC
class Player(ABC):
def __init__(self, name, style):
if(name is None or style is None):
raise ValueError('Player name and style cannot be None')
self.style = style
self.name = name
def get_player_style(self):
return self.style
def get_player_name(self):
return self.name
|
y=10 #stel een getal in
if y > 0: #is dit getal groter dan 0?
print("Y is positief")
else: #anders is het kleiner of gelijk aan 0
print("Y is negatief of 0")
|
from num2words import num2words
letters=0
for i in range(1, 1001):
numstr=num2words(i)
numstr=numstr.replace(" ", "")
numstr=numstr.replace("-", "")
letters+=len(numstr)
print numstr
print letters
|
def collatz(n, cd):
i = 0
n_orig = n
n = int(n)
while n not in cd:
i += 1
if n % 2 == 0:
n //= 2
else:
n = n*3 + 1
return cd.update({n_orig: cd[n] + i})
collatzdict = {1: 0}
max_route = 0
furthest = 1
for j in range(1, 10**6):
collatz(j, collatzdict)
if collatzdict[j] > max_route:
max_route = collatzdict[j]
furthest = j
print(furthest)
|
import unittest
def is_unique(s):
char_map = [False for _ in range(128)]
for i in range(len(s)):
ord_ch = ord(s[i])
if char_map[ord_ch]:
return False
else:
char_map[ord_ch] = True
return True
class Test(unittest.TestCase):
dataT = [('abcde'), ('12arca'), ('s4fad'), ('')]
dataF = [('hb 637jh=j ()'), ('23sd2')]
def test_unique(self):
test_string = ""
try:
for test_string in self.dataT:
actual = is_unique(test_string)
self.assertTrue(actual)
for test_string in self.dataF:
self.assertFalse(is_unique(test_string))
except AssertionError:
# print("Assertion failed with Input: {}".format(test_string))
raise Exception("One or more unit tests failed - Input: {}".format(test_string))
if __name__ == "__main__":
unittest.main()
|
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 15 15:42:34 2018
@author: David
Input: positive values for total_cost, portion_saved and annual_salary.
Output: A positive integer, the number of months needed to save for down payment.
"""
# Get user input.
annual_salary = float(input('Enter your annual salary?: '))
portion_saved = float(input('Enter the percent of your salary to save, as a decimal :'))
total_cost = float(input('Enter the cost of your dream home?: '))
portion_down_payment = 0.25
current_savings = 0
r = 0.04
monthly_salary = annual_salary/12
months_spent_saving = 0
## Iterate savings until down payment is covered.
while(current_savings < total_cost * portion_down_payment):
current_savings += monthly_salary * portion_saved + current_savings * r/12
months_spent_saving += 1
print('Number of Months: ', months_spent_saving)
|
import random
import collections
import copy
from tabulate import tabulate
NUMBER_OF_GAMES = 5
def rockPaperScissors():
print("\n"*2)
userinput = input("Choose out of the following options \n 1.rock \n 2.paper \n 3.scissors? ")
print("\n"*100)
gameOptions = ['rock','paper','scissors']
gameWinOptions = ['paper','scissors','rock']
randomIntegerGen = random.randint(0,len(gameOptions)-1)
print(f'\n The computer guessed {gameOptions[randomIntegerGen]} \n you guessed {userinput} ')
if userinput == gameOptions[randomIntegerGen]:
print("\n3 points good effort\n")
return 3
elif userinput == gameWinOptions[randomIntegerGen]:
print("\n10 points well done\n")
return 10
else:
print(f"\n 0 points unlucky, \nThe correct answer was {gameOptions[random.randint(0,len(gameOptions)-1)]}\n")
return 0
def startGame():
totalScore = 0
for num in range(0,NUMBER_OF_GAMES):
currentScore = rockPaperScissors()
totalScore = totalScore + currentScore
print(f'\n\n The total score so far is {totalScore}\n but you can still improve')
with open("newscore.txt","a") as myNewFile:
myNewFile.write(str(currentScore)+",")
with open("newscore.txt","a") as myNewFile:
myNewFile.write('\ntotalScore:' + str(totalScore)+"\n")
def getScores():
scores = []
with open('newscore.txt','r') as myNewFile:
tempDictionaryValues = {}
for lineIndex,line in enumerate(myNewFile):
if((lineIndex+1) % 2 == 0 and (lineIndex+1) % 4 != 0 ):#This extracts the name
tempDictionaryValues['name'] = line.split(';')[1].split(':')[1].replace('\n','')
if((lineIndex+1) % 2 == 0 and (lineIndex+1) % 4 != 0 ):#This extracts the age
tempDictionaryValues['age'] = line.split(';')[0].split(':')[1].replace('\n','')
if((lineIndex) % 2 == 0 and lineIndex % 4 != 0 ):
arrayOfStrings = line.split(':')[1].replace('\n',"").split(',')
score = []
for index in range(len(arrayOfStrings)-1):
score.append(int(arrayOfStrings[index]))
tempDictionaryValues['score'] = score.copy()
if((lineIndex+1) % 4 == 0 ):#This extracts the total score
scores.append((int(line.split(':')[1]),tempDictionaryValues.copy()))
# data[int(line.split(':')[1])] = tempDictionaryValues.copy()
return scores
def sortedData(data):
data.sort(key=lambda s:s[0],reverse=True)
inAData = []
for totalScore,scoreData in data:
inAData.append([scoreData['name'],scoreData['age'],scoreData['score'],totalScore])
print(tabulate(inAData, headers=['Name', 'Age','Scores','Total Score']))
def getNewUserData():
name = input("What is your name?")
print("\n"*50)
age = input("What is your age?")
print('\n'*50)
with open("newscore.txt","a") as myNewFile:
myNewFile.write("#################################\n")
myNewFile.write("age:"+ age + ";name:" + name +"\n" + "Score:")
def main():
#Menu code
howWouldYouLikeToPlay = ""
while howWouldYouLikeToPlay != "X":
howWouldYouLikeToPlay = input("Press any of the following for the appropraite actions: \n Z -> to play normally \n Y -> to view all scores \n X -> to quit the game \n").upper()
print("\n"*50)
if howWouldYouLikeToPlay == "Z":
getNewUserData()
startGame()
print("\n"*1)
elif howWouldYouLikeToPlay == "Y":
scoreData = getScores()
sortedData(scoreData)
print("\n"*1)
howWouldYouLikeToPlay = input("\nWould you like to go to the menu (X otherwise)...").upper()
print("\n"*1)
elif howWouldYouLikeToPlay == "X":
break
print("\n"*50)
main()
|
#LISTAS Y MUTABILIDAD
#Son secuencias de objetos mutables
#Cuando modificamos una lista, puede haber efectos secundarios
#Es posible iterar con ellas
#Ejemplos en consola
my_list = [1, 2, 3]
my_list[0]
my_list[1,:]
#[2, 3]
my_list.append(4)
print(my_list)
#[1, 2, 3, 4]
#agregar
my_list[0] = 'a'
print(my_list)
['a', 2, 3]
#eliminar
my_list.pop()
#iterar
for element in my_list:
print(element)
#side efects
a = [1, 2, 3]
b = a
id(a)
id(b)
c = [a, b]
a.append(5)
#Clonar listas
a = [1, 2, 3]
id(a)
b = a
#clonar con list
c = list(a)
id(a) != id(c)
#clonar con slices
d = a[::]
#List comprehension
my_list = list(range(100))
double = [i * 2 for i in my_list]
pares = [ i for i in my_list if i % 2 == 0] |
import re
numerals = {
"numbers": ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen"],
"tens": ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy",
"eighty", "ninety"],
"powers": {
100: "hundred",
1000: "thousand",
1000000: "million"}}
operations = {
"+": "plus",
"-": "minus",
"*": "multiply",
"/": "divide",
"=": "equals",
}
def convert_num_to_word(num):
if num < 20:
return numerals["numbers"][num]
elif num < 100:
high_digit = numerals["tens"][num // 10]
low_digit = "" if num % 10 == 0 else "-" + \
numerals['numbers'][num % 10]
return high_digit + low_digit
else:
highest_power = max(
[power for power in numerals['powers'].keys() if power <= num])
return convert_num_to_word(num // highest_power) + " " + numerals["powers"][highest_power] + " " \
+ ("" if num %
highest_power == 0 else convert_num_to_word(num %
highest_power))
def string_contains_error(splited_string):
max_num = max(numerals["powers"].keys())
if splited_string[0] in operations or \
splited_string[len(splited_string) - 1] in operations:
return True
for i in splited_string:
if (not i.isdigit() and i not in operations.keys()) or \
(i.isdigit() and int(i) > max_num * 10):
return True
return False
def convert_expression_to_words(string):
string = string.replace(" ", "") # remove all whitespaces
splited_string = re.findall('[0-9]+|.', string)
if string_contains_error(splited_string):
return "Invalid input"
result = []
for i in splited_string:
if i in operations.keys():
result.append(" " + operations[i] + " ")
else:
result.append(convert_num_to_word(int(i)))
return "".join(result)
|
#!/usr/bin/python3
'''
The 3-say_my_name module
This module has a funciton that says a name
'''
def say_my_name(first_name, last_name=""):
'''
The function that that prints My name is <first name> <last name>
'''
if isinstance(first_name, str) is False:
raise TypeError('first_name must be a string')
if isinstance(last_name, str) is False:
raise TypeError('last_name must be a string')
print('My name is {} {}'.format(first_name, last_name))
|
#!/usr/bin/python3
""" Module """
def append_write(filename="", text=""):
""" Append to a file """
with open(filename, 'a', encoding="utf-8") as f:
f.write(text)
f.close()
return len(text)
|
# Bekijk je fizzbuzz van vorige week.
# Nu willen we fizzbuzz voor alle getallen van 1 tot en met 100 uitvoeren
# Met input zou dit te lang duren ;)
# Schrijf dit nu met een loop, zodat dit automagisch gebeurt
#%%
for fizzbuzz in range(100):
if fizzbuzz % 3 == 0 and fizzbuzz % 5 == 0:
print("fizzbuzz")
continue
elif fizzbuzz % 3 == 0:
print("fizz")
continue
elif fizzbuzz % 5 == 0:
print("buzz")
continue
print(fizzbuzz)
# print alle even getallen vanaf 0 tot en met 42; gebruik hiervoor geen modulo!
# Schrijf een loop die een driehoek van sterretjes print, zoals
# *
# * *
# * * *
# etc.
# Doe dit tot 10 sterretjes.
#%%
def pyramid(n):
myList = []
for i in range(1,n+1):
myList.append("*"*i)
print("\n".join(myList))
n = 10
pyramid(n)
# Laat je driehoek nu ook weer terug lopen.
# *
# * *
# (.. meer sterren ..)
# * *
# *
# Hint: gebruik twee for loops
#%%
#half
def pyramid(n):
myList = []
for i in range(1,n+1):
myList.append("*"*i)
print("\n".join(myList))
n = 10
pyramid(n)
#%%
#full inverted
rows = 5
for i in range(1, rows + 1):
for j in range(1, i + 1):
print("*", end=' ')
print('')
rows = 5
b = 0
# reverse for loop from 5 to 0
for i in range(rows, 0, -1):
b += 1
for j in range(1, i + 1):
print("*", end=' ')
print('\r')
# Voor een extra uitdaging bij deze opdracht kan je de driehoek ook zo maken (doe dit pas als je de rest af hebt. Let op: is erg lastig):
# *
# * *
# * * *
#%%
#triangle
def triangle(n):
# number of spaces
k = n - 1
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number spaces
# values changing acc. to requirement
for j in range(0, k):
print(end=" ")
# decrementing k after each loop
k = k - 1
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):
# printing stars
print("* ", end="")
# ending line after each row
print("\r")
n = 5
triangle(n)
#%%
#diamond
n = 9
print("Pattern 1")
for a1 in range(1, (n+1)//2 + 1): #from row 1 to 5
for a2 in range((n+1)//2 - a1):
print(" ", end = "")
for a3 in range((a1*2)-1):
print("*", end = "")
print()
for a1 in range((n+1)//2 + 1, n + 1): #from row 6 to 9
for a2 in range(a1 - (n+1)//2):
print(" ", end = "")
for a3 in range((n+1 - a1)*2 - 1):
print("*", end = "")
print()
# Schrijf nu je eigen max algoritme; zoek het grootste getal uit onderstaande lijst
# Je mag er vanuit gaan dat het kleinste getal nul is.
#
# Stappen:
# Maak een var_max met als waarde nul
# Loop over de lijst heen
# Als de waarde groter is dan var_max maak de variabele deze waarde
#
# Check of jouw max overeenkomt met de max van de python functie max()
lijst = [1,3,4,1,123,0,5,1,32,1,1,3,5,1,12,3,101,10]
# %%
|
#!/usr/bin/env python3
from collections import Iterable
print(isinstance('abc', Iterable))
print(isinstance([1, 2, 4], Iterable))
print(isinstance(123, Iterable))
for i, value in enumerate(['A', 'B', 'C']):
print(i, value)
for x, y in [(1, 1), (3, 5), (6, 8)]:
print(x, y)
def find_max_and_min(l):
max_value = None
min_value = None
for values in l:
if max_value is None:
max_value = values
elif max_value < values:
max_value = values
if min_value is None:
min_value = values
elif values < min_value:
min_value = values
return min_value, max_value
# 测试
if find_max_and_min([]) != (None, None):
print('测试失败!')
elif find_max_and_min([7]) != (7, 7):
print('测试失败!')
elif find_max_and_min([7, 1]) != (1, 7):
print('测试失败!')
elif find_max_and_min([7, 1, 3, 9, 5]) != (1, 9):
print('测试失败!')
else:
print('测试成功!')
|
# 두 정수(a, b)를 입력받아
# a의 값이 b의 값과 서로 다르면 True 를, 같으면 False 를 출력하는 프로그램을 작성해보자.
a,b = map(int, input().split())
print(a!=b) |
# 16진수를 입력받아 8진수(octal)로 출력해보자.
# 예시
# a = input()
# n = int(a, 16) #입력된 a를 16진수로 인식해 변수 n에 저장
# print('%o' % n) #n에 저장되어있는 값을 8진수(octal) 형태 문자열로 출력
# 참고
# 8진법은 한 자리에 8개(0 1 2 3 4 5 6 7)의 문자를 사용한다.
# 8진수 10은 10진수의 8, 11은 9, 12는 10 ... 와 같다.
a = input()
n = int(a, 16)
print('%o' % n) |
import math
from queue import Queue
import numpy as np
def is_connected(A):
"""
:param A:np.array the adjacency matrix
:return:bool whether the graph is connected or not
"""
for _ in range(int(1 + math.ceil(math.log2(A.shape[0])))):
A = np.dot(A, A)
return np.min(A) > 0
def identity(A, F):
"""
:param A:np.array the adjacency matrix
:param F:np.array the nodes features
:return:F
"""
return F
def first_neighbours(A):
"""
:param A:np.array the adjacency matrix
:param F:np.array the nodes features
:return: for each node, the number of nodes reachable in 1 hop
"""
return np.sum(A > 0, axis=0)
def second_neighbours(A):
"""
:param A:np.array the adjacency matrix
:param F:np.array the nodes features
:return: for each node, the number of nodes reachable in no more than 2 hops
"""
A = A > 0.0
A = A + np.dot(A, A)
np.fill_diagonal(A, 0)
return np.sum(A > 0, axis=0)
def kth_neighbours(A, k):
"""
:param A:np.array the adjacency matrix
:param F:np.array the nodes features
:return: for each node, the number of nodes reachable in k hops
"""
A = A > 0.0
R = np.zeros(A.shape)
for _ in range(k):
R = np.dot(R, A) + A
np.fill_diagonal(R, 0)
return np.sum(R > 0, axis=0)
def map_reduce_neighbourhood(A, F, f_reduce, f_map=None, hops=1, consider_itself=False):
"""
:param A:np.array the adjacency matrix
:param F:np.array the nodes features
:return: for each node, map its neighbourhood with f_map, and reduce it with f_reduce
"""
if f_map is not None:
F = f_map(F)
A = np.array(A)
A = A > 0
R = np.zeros(A.shape)
for _ in range(hops):
R = np.dot(R, A) + A
np.fill_diagonal(R, 1 if consider_itself else 0)
R = R > 0
return np.array([f_reduce(F[R[i]]) for i in range(A.shape[0])])
def max_neighbourhood(A, F):
"""
:param A:np.array the adjacency matrix
:param F:np.array the nodes features
:return: for each node, the maximum in its neighbourhood
"""
return map_reduce_neighbourhood(A, F, np.max, consider_itself=True)
def min_neighbourhood(A, F):
"""
:param A:np.array the adjacency matrix
:param F:np.array the nodes features
:return: for each node, the minimum in its neighbourhood
"""
return map_reduce_neighbourhood(A, F, np.min, consider_itself=True)
def std_neighbourhood(A, F):
"""
:param A:np.array the adjacency matrix
:param F:np.array the nodes features
:return: for each node, the standard deviation of its neighbourhood
"""
return map_reduce_neighbourhood(A, F, np.std, consider_itself=True)
def mean_neighbourhood(A, F):
"""
:param A:np.array the adjacency matrix
:param F:np.array the nodes features
:return: for each node, the mean of its neighbourhood
"""
return map_reduce_neighbourhood(A, F, np.mean, consider_itself=True)
def local_maxima(A, F):
"""
:param A:np.array the adjacency matrix
:param F:np.array the nodes features
:return: for each node, whether it is the maximum in its neighbourhood
"""
return F == map_reduce_neighbourhood(A, F, np.max, consider_itself=True)
def graph_laplacian(A):
"""
:param A:np.array the adjacency matrix
:return: the laplacian of the adjacency matrix
"""
L = (A > 0) * -1
np.fill_diagonal(L, np.sum(A > 0, axis=0))
return L
def graph_laplacian_features(A, F):
"""
:param A:np.array the adjacency matrix
:param F:np.array the nodes features
:return: the laplacian of the adjacency matrix multiplied by the features
"""
return np.matmul(graph_laplacian(A), F)
def isomorphism(A1, A2, F1=None, F2=None):
"""
Takes two adjacency matrices (A1,A2) and (optionally) two lists of features. It uses Weisfeiler-Lehman algorithms, so false positives might arise
:param A1: adj_matrix, N*N numpy matrix
:param A2: adj_matrix, N*N numpy matrix
:param F1: node_values, numpy array of size N
:param F1: node_values, numpy array of size N
:return: isomorphic: boolean which is false when the two graphs are not isomorphic, true when they probably are.
"""
N = A1.shape[0]
if (F1 is None) ^ (F2 is None):
raise ValueError("either both or none between F1,F2 must be defined.")
if F1 is None:
# Assign same initial value to each node
F1 = np.ones(N, int)
F2 = np.ones(N, int)
else:
if not np.array_equal(np.sort(F1), np.sort(F2)):
return False
if F1.dtype() != int:
raise NotImplementedError('Still have to implement this')
p = 1000000007
def mapping(F):
return (F * 234 + 133) % 1000000007
def adjacency_hash(F):
F = np.sort(F)
b = 257
h = 0
for f in F:
h = (b * h + f) % 1000000007
return h
for i in range(N):
F1 = map_reduce_neighbourhood(A1, F1, adjacency_hash, f_map=mapping, consider_itself=True, hops=1)
F2 = map_reduce_neighbourhood(A2, F2, adjacency_hash, f_map=mapping, consider_itself=True, hops=1)
if not np.array_equal(np.sort(F1), np.sort(F2)):
return False
return True
def count_edges(A):
"""
:param A:np.array the adjacency matrix
:return: the number of edges in the graph
"""
return np.sum(A) / 2
def is_eulerian_cyclable(A):
"""
:param A:np.array the adjacency matrix
:return: whether the graph has an eulerian cycle
"""
return is_connected(A) and np.count_nonzero(first_neighbours(A) % 2 == 1) == 0
def is_eulerian_percorrible(A):
"""
:param A:np.array the adjacency matrix
:return: whether the graph has an eulerian path
"""
return is_connected(A) and np.count_nonzero(first_neighbours(A) % 2 == 1) in [0, 2]
def map_reduce_graph(A, F, f_reduce):
"""
:param A:np.array the adjacency matrix
:param F:np.array the nodes features
:return: the features of the nodes reduced by f_reduce
"""
return f_reduce(F)
def mean_graph(A, F):
"""
:param A:np.array the adjacency matrix
:param F:np.array the nodes features
:return: the mean of the features
"""
return map_reduce_graph(A, F, np.mean)
def max_graph(A, F):
"""
:param A:np.array the adjacency matrix
:param F:np.array the nodes features
:return: the maximum of the features
"""
return map_reduce_graph(A, F, np.max)
def min_graph(A, F):
"""
:param A:np.array the adjacency matrix
:param F:np.array the nodes features
:return: the minimum of the features
"""
return map_reduce_graph(A, F, np.min)
def std_graph(A, F):
"""
:param A:np.array the adjacency matrix
:param F:np.array the nodes features
:return: the standard deviation of the features
"""
return map_reduce_graph(A, F, np.std)
def has_hamiltonian_cycle(A):
"""
:param A:np.array the adjacency matrix
:return:bool whether the graph has an hamiltonian cycle
"""
A += np.transpose(A)
A = A > 0
V = A.shape[0]
def ham_cycle_loop(pos):
if pos == V:
if A[path[pos - 1]][path[0]]:
return True
else:
return False
for v in range(1, V):
if A[path[pos - 1]][v] and not used[v]:
path[pos] = v
used[v] = True
if ham_cycle_loop(pos + 1):
return True
path[pos] = -1
used[v] = False
return False
used = [False] * V
path = [-1] * V
path[0] = 0
return ham_cycle_loop(1)
def all_pairs_shortest_paths(A, inf_sub=math.inf):
"""
:param A:np.array the adjacency matrix
:param inf_sub: the placeholder value to use for pairs which are not connected
:return:np.array all pairs shortest paths
"""
A = np.array(A)
N = A.shape[0]
for i in range(N):
for j in range(N):
if A[i][j] == 0:
A[i][j] = math.inf
if i == j:
A[i][j] = 0
for k in range(N):
for i in range(N):
for j in range(N):
A[i][j] = min(A[i][j], A[i][k] + A[k][j])
A = np.where(A == math.inf, inf_sub, A)
return A
def diameter(A):
"""
:param A:np.array the adjacency matrix
:return: the diameter of the gra[h
"""
sum = np.sum(A)
apsp = all_pairs_shortest_paths(A)
apsp = np.where(apsp < sum + 1, apsp, -1)
return np.max(apsp)
def eccentricity(A):
"""
:param A:np.array the adjacency matrix
:return: the eccentricity of the gra[h
"""
sum = np.sum(A)
apsp = all_pairs_shortest_paths(A)
apsp = np.where(apsp < sum + 1, apsp, -1)
return np.max(apsp, axis=0)
def sssp_predecessor(A, F):
"""
:param A:np.array the adjacency matrix
:param F:np.array the nodes features
:return: for each node, the best next step to reach the designated source
"""
assert (np.sum(F) == 1)
assert (np.max(F) == 1)
s = np.argmax(F)
N = A.shape[0]
P = np.zeros(A.shape)
V = np.zeros(N)
bfs = Queue()
bfs.put(s)
V[s] = 1
while not bfs.empty():
u = bfs.get()
for v in range(N):
if A[u][v] > 0 and V[v] == 0:
V[v] = 1
P[v][u] = 1
bfs.put(v)
return P
def max_eigenvalue(A):
"""
:param A:np.array the adjacency matrix
:return: the maximum eigenvalue of A
since A is positive symmetric, all the eigenvalues are guaranteed to be real
"""
[W, _] = np.linalg.eig(A)
return W[np.argmax(np.absolute(W))].real
def max_eigenvalues(A, k):
"""
:param A:np.array the adjacency matrix
:param k:int the number of eigenvalues to be selected
:return: the k greatest (by absolute value) eigenvalues of A
"""
[W, _] = np.linalg.eig(A)
values = W[sorted(range(len(W)), key=lambda x: -np.absolute(W[x]))[:k]]
return values.real
def max_absolute_eigenvalues(A, k):
"""
:param A:np.array the adjacency matrix
:param k:int the number of eigenvalues to be selected
:return: the absolute value of the k greatest (by absolute value) eigenvalues of A
"""
return np.absolute(max_eigenvalues(A, k))
def max_absolute_eigenvalues_laplacian(A, n):
"""
:param A:np.array the adjacency matrix
:param k:int the number of eigenvalues to be selected
:return: the absolute value of the k greatest (by absolute value) eigenvalues of the laplacian of A
"""
A = graph_laplacian(A)
return np.absolute(max_eigenvalues(A, n))
def max_eigenvector(A):
"""
:param A:np.array the adjacency matrix
:return: the maximum (by absolute value) eigenvector of A
since A is positive symmetric, all the eigenvectors are guaranteed to be real
"""
[W, V] = np.linalg.eig(A)
return V[:, np.argmax(np.absolute(W))].real
def spectral_radius(A):
"""
:param A:np.array the adjacency matrix
:return: the maximum (by absolute value) eigenvector of A
since A is positive symmetric, all the eigenvectors are guaranteed to be real
"""
return np.abs(max_eigenvalue(A))
def page_rank(A, F=None, iter=64):
"""
:param A:np.array the adjacency matrix
:param F:np.array with initial weights. If None, uniform initialization will happen.
:param iter: log2 of length of power iteration
:return: for each node, its pagerank
"""
# normalize A rows
A = np.array(A)
A /= A.sum(axis=1)[:, np.newaxis]
# power iteration
for _ in range(iter):
A = np.matmul(A, A)
# generate prior distribution
if F is None:
F = np.ones(A.shape[-1])
else:
F = np.array(F)
# normalize prior
F /= np.sum(F)
# compute limit distribution
return np.matmul(F, A)
def tsp_length(A, F=None):
"""
:param A:np.array the adjacency matrix
:param F:np.array determining which nodes are to be visited. If None, all of them are.
:return: the length of the Traveling Salesman Problem shortest solution
"""
A = all_pairs_shortest_paths(A)
N = A.shape[0]
if F is None:
F = np.ones(N)
targets = np.nonzero(F)[0]
T = targets.shape[0]
S = (1 << T)
dp = np.zeros((S, T))
def popcount(x):
b = 0
while x > 0:
x &= x - 1
b += 1
return b
msks = np.argsort(np.vectorize(popcount)(np.arange(S)))
for i in range(T + 1):
for j in range(T):
if (1 << j) & msks[i] == 0:
dp[msks[i]][j] = math.inf
for i in range(T + 1, S):
msk = msks[i]
for u in range(T):
if (1 << u) & msk == 0:
dp[msk][u] = math.inf
continue
cost = math.inf
for v in range(T):
if v == u or (1 << v) & msk == 0:
continue
cost = min(cost, dp[msk ^ (1 << u)][v] + A[targets[v]][targets[u]])
dp[msk][u] = cost
return np.min(dp[S - 1])
def get_nodes_labels(A, F):
"""
Takes the adjacency matrix and the list of nodes features (and a list of algorithms) and returns
a set of labels for each node
:param A: adj_matrix, N*N numpy matrix
:param F: node_values, numpy array of size N
:return: labels: KxN numpy matrix where K is the number of labels for each node
"""
labels = [identity(A, F), map_reduce_neighbourhood(A, F, np.mean, consider_itself=True),
map_reduce_neighbourhood(A, F, np.max, consider_itself=True),
map_reduce_neighbourhood(A, F, np.std, consider_itself=True), first_neighbours(A), second_neighbours(A),
eccentricity(A)]
return np.swapaxes(np.stack(labels), 0, 1)
def get_graph_labels(A, F):
"""
Takes the adjacency matrix and the list of nodes features (and a list of algorithms) and returns
a set of labels for the whole graph
:param A: adj_matrix, N*N numpy matrix
:param F: node_values, numpy array of size N
:return: labels: numpy array of size K where K is the number of labels for the graph
"""
labels = [diameter(A)]
return np.asarray(labels)
|
import pandas as pd
import numpy as np
#importing the required datasets into dataframes
trainset = pd.read_csv('train.csv',index_col = 0 )
testset = pd.read_csv('test.csv',index_col = 0)
result = pd.read_csv('gender_submission.csv',index_col = 0)
#Examining the training dataset
trainset.head()
#Preparing the training dataset for machine learning by filling missing values, preprocessing etc
X_train = trainset.drop(['Name','Survived','Ticket','Cabin'],axis = 1)
mean = X_train['Age'].mean()
X_train['Age'] = X_train['Age'].fillna(mean).astype(int)
X_train['Fare'] = X_train['Fare'].fillna(0).astype(int)
Y_train = trainset['Survived']
X_train = X_train.join(pd.DataFrame(pd.get_dummies(X_train['Pclass'])))
X_train= X_train.drop('Pclass',axis = 1,)
X_train = X_train.join(pd.DataFrame(pd.get_dummies(X_train['Embarked'])))
X_train= X_train.drop('Embarked',axis = 1,)
X_train = X_train.join(pd.DataFrame(pd.get_dummies(X_train['Sex'])))
X_train= X_train.drop('Sex',axis = 1,)
print (X_train)
# Import the StandardScaler
from sklearn.preprocessing import StandardScaler
# Scale the features and set the values to a new variable
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
#Preparing the training dataset for machine learning by filling missing values, preprocessing etc
X_test = testset.drop(['Name','Ticket','Cabin'],axis = 1)
avg = X_test['Age'].mean()
X_test['Age'] = X_test['Age'].fillna(avg).astype(int)
X_test['Fare'] = X_test['Fare'].fillna(0).astype(int)
X_test = X_test.join(pd.DataFrame(pd.get_dummies(X_test['Pclass'])))
X_test= X_test.drop('Pclass',axis = 1,)
X_test = X_test.join(pd.DataFrame(pd.get_dummies(X_test['Embarked'])))
X_test= X_test.drop('Embarked',axis = 1,)
X_test = X_test.join(pd.DataFrame(pd.get_dummies(X_test['Sex'])))
X_test= X_test.drop('Sex',axis = 1,)
print (X_test)
# Import the StandardScaler
from sklearn.preprocessing import StandardScaler
# Scale the features and set the values to a new variable
scaler = StandardScaler()
X_test = scaler.fit_transform(X_test)
Y_test = result
#Applying Adaptive Boosting
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
dt = DecisionTreeClassifier(max_depth=1,random_state=10)
adb = AdaBoostClassifier(base_estimator=dt,n_estimators=100)
adb.fit(X_train,Y_train)
Y_pred = adb.predict(X_test)
#Setting a K-Fold CV so that hyperparameters of our model could be optimized afterwards
from sklearn.model_selection import KFold, cross_val_score
# Set up our K-fold cross-validation
kf = KFold(20,random_state=10)
#Generating the report matrix for Adaptive Boosting thus reflecting f1-score, recall, precision etc.
from sklearn.metrics import classification_report
rpt = classification_report(Y_test,Y_pred)
print(rpt)
#Trying XGBoost in case it can provide better results
import xgboost as xgb
xg = xgb.XGBClassifier(Objective = 'binary:logistic',n_estimators=10,seed = 123)
xg.fit(X_train,Y_train)
Y_pred_xg = xg.predict(X_test)
#Generating the report for XGBoost
report = classification_report(Y_test,Y_pred_xg)
print(report)
#Chose XGBoost as it gave a f1-score of 0.97
#A new output dataframe in desired format
tests = pd.read_csv('test.csv')
Pas = tests['PassengerId'].values
df = pd.DataFrame({'PassengerId':Pas, 'Survived':Y_pred_xg})
cols = df.columns.tolist()
df = df[cols]
df = df.set_index(['PassengerId'])
print(df.head())
#Exporting the dataframe to csv file
df.to_csv('output.csv')
|
class Node():
def __init__(self):
self.next = None
self.item = None
class Stack():
def __init__(self):
self._first = None
def push(self, item):
old_first = self._first
self._first = Node()
self._first.item = item
self._first.next = old_first
def pop(self):
if self.isEmpty():
raise "it's empty stack!"
item = self._first.item
self._first = self._first.next
return item
def isEmpty(self):
return self._first is None
def size(self):
pass
def main():
s = Stack()
s.push(5)
s.push(4)
s.push(3)
s.push(4)
while not s.isEmpty():
item = s.pop()
print(item)
if __name__ == '__main__':
main() |
import maze
import helper
import matplotlib.pyplot as plt
import question23
import random
import helper_24
# Using Threshold Probability from previous question
p0=question23.probability_threshold()
prob=[round(random.uniform(0,p0),2) for _ in range(6)] #Random Probability generated from 0 to p0
prob.sort()
# prob=[0.1,0.2,0.3,0.4,0.5,0.6]
dim=50
no_of_run=15 #No. of Runs for each probability
#List created for each Algorithm
bfs=[]
dfs=[]
bibfs=[]
euclid=[]
mann=[]
#Variables for each algorithm for calculating average
sumBfs=0
countBfs=0
sumDfs=0
countDfs=0
sumBibfs=0
countBibfs=0
sumEuclid=0
countEuclid=0
sumMann=0
countMann=0
#
# #Calculated avg length of path for each algorithm
# for p in prob:
# for k in range(no_of_run):
# a = maze.Maze(dim, p)
# bfs1 = len(a.BFS()) #Calculating length of path returned
# if bfs1 != 0:
# sumBfs += bfs1
# countBfs += 1
# dfs1 = len(a.dfs()) #Calculating length of path returned
# if dfs1!=0:
# sumDfs += dfs1
# countDfs += 1
# bibfs1 = len(a.bidirection()) #Calculating length of path returned
# if bibfs1!=0:
# sumBibfs += bibfs1
# countBibfs += 1
# euclid1 = len(a.aStarSearch(helper.euclidDistance)) #Calculating length of path returned
# if euclid1!=0:
# sumEuclid += euclid1
# countEuclid += 1
# mann1 = len(a.aStarSearch(helper.manhattanDistance)) #Calculating length of path returned
# if mann1!=0:
# sumMann += mann1
# countMann += 1
# # Calculating Avg for all the runs
# if countBfs!=0:
# bfs.append((sumBfs/countBfs))
# elif countBfs==0:
# bfs.append(countBfs)
# if countDfs != 0:
# dfs.append((sumDfs / countDfs))
# elif countDfs == 0:
# dfs.append(countDfs)
# if countBibfs != 0:
# bibfs.append((sumBibfs / countBibfs))
# elif countBibfs == 0:
# bibfs.append(countBibfs)
# if countEuclid != 0:
# euclid.append((sumEuclid / countEuclid))
# elif countEuclid == 0:
# euclid.append(countEuclid)
# if countMann != 0:
# mann.append((sumMann / countMann))
# elif countMann == 0:
# mann.append(countMann)
#
# #Plotting graph between Avg Length and Density for each graph
# plt.plot(prob, bfs,label='BFS')
# plt.plot(prob, dfs,label='DFS')
# plt.plot(prob,bibfs,label='BIBFS')
# plt.plot(prob,euclid,label='Euclid')
# plt.plot(prob,mann,label='Manhattan')
# plt.ylabel('Average')
# plt.xlabel('Density')
# plt.title('Average vs Density')
# plt.show()
def closedSet(): #Method to calculate length of closed set to compare all algorithms
totalBfs=[]
totalDfs=[]
totalEuclid=[]
totalMann=[]
totalBidirection=[]
closebfs=0
closedfs=0
closedBiBfs=0
closedEuclid=0
closedMann=0
for p in prob:
for k in range(no_of_run):
b=maze.Maze(dim,p)
closebfs+=len(b.BFS()) #Each Algorithm will return length of closed set
closedfs+=len(b.dfs())
closedBiBfs+=len(b.bidirection())
closedEuclid+=len(b.aStarSearch(helper.euclidDistance))
closedMann+=len(b.aStarSearch(helper.manhattanDistance))
totalBfs.append(closebfs/no_of_run)
totalDfs.append(closedfs/no_of_run)
totalBidirection.append(closedBiBfs/no_of_run)
totalEuclid.append((closedEuclid/no_of_run))
totalMann.append(closedMann/no_of_run)
bfsAvg=sum(totalBfs)/len(totalBfs) #Calculating Average of closed set length for BFS
dfsAvg=sum(totalDfs)/len(totalDfs) #Calculating Average of closed set length for DFS
Bidir=sum(totalBidirection)/len(totalBidirection) #Calculating Average of closed set length for BD-BFS
Eucl=sum(totalEuclid)/len(totalEuclid) #Calculating Average of closed set length for A* Euclid
Mannt=sum(totalMann)/len(totalMann) #Calculating Average pf closed set length for A* Mannhattan
print("bfs=" + str(bfsAvg))
print("dfs=" + str(dfsAvg))
print("bibfs=" + str(Bidir))
print("Euclid=" + str(Eucl))
print("Manhattan=" + str(Mannt))
plt.plot(prob, totalBfs, label='BFS')
plt.plot(prob, totalDfs, label='DFS')
plt.plot(prob, totalBidirection, label='BIBFS')
plt.plot(prob, totalEuclid, label='Euclid')
plt.plot(prob, totalMann, label='Manhattan')
plt.ylabel('Average Length')
plt.xlabel('Density')
plt.title('Average Length vs Density')
plt.legend()
plt.show()
closedSet()
|
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 29 23:05:47 2021
@author: annie
"""
import numpy as np
import pickle
def check_winner(matrix):
xpos = ''
opos = ''
allpos = ''
#horizontal win patterns
winnercombs = [b'000000111',b'000111000',b'111000000',
#vertical win patterns
b'100100100',b'010010010',b'001001001',
#diagonal win patterns
b'100010001',b'001010100']
print(matrix)
# traverse through all tictactoe squares
for i in matrix:
for j in i:
if j == 'x':
xpos += '1'
opos += '0'
allpos += '1'
elif j == 'o':
xpos += '0'
opos += '1'
allpos += '1'
else:
xpos += '0'
opos += '0'
# convert to binary string
xpos = xpos.encode('ascii')
opos = opos.encode('ascii')
allpos = allpos.encode('ascii')
for i in winnercombs:
if i and xpos == i:
print('Winner is X!')
return 1
elif i and opos == i:
print('Winner is O!')
return -1
#check if board is full
if allpos == b'111111111':
print("It's a draw!")
return 'draw'
def tictactoe():
players = int(input('How many players? Enter 1 or 2: '))
assert(players <= 2)
assert(players > 0)
board = np.zeros((3,3), dtype=str)
if players == 1:
single_player(board)
if players == 2:
two_player(board)
def single_player(board):
possible = [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)]
symbol = 'x'
#load training policy1
fr = open("policy_p1",'rb')
p1states_value = pickle.load(fr)
fr.close()
#load training policy2
fr = open("policy_p2",'rb')
p2states_value = pickle.load(fr)
fr.close()
def availablePlays(matrix):
position = []
for i in range(3):
for j in range(3):
if board[i][j] == '':
position.append((i,j))
return position
def chooseAction(positions, current_board, symbol, player):
exploration_rate = 0.3
#make a random move
if np.random.uniform(0, 1) <= exploration_rate:
pos = np.random.choice(len(positions))
action = positions[pos]
else:
value_max = -999
action = positions[0]
for p in positions:
boardcopy = current_board.copy()
boardcopy[p] = symbol
boardcopy_hash = getHash(boardcopy)
if player == 'p1':
value = 0 if p1states_value.get(boardcopy_hash) is None else p1states_value.get(boardcopy_hash)
else:
value = 0 if p2states_value.get(boardcopy_hash) is None else p2states_value.get(boardcopy_hash)
if value >= value_max:
value_max = value
action = p
return action
def getHash(matrix):
matrixHash = str(matrix.reshape(9))
return matrixHash
def updateState(matrix, position, player):
nonlocal symbol
if player == 'p1':
symbol = 'o'
matrix[position] = 'x'
else:
symbol = 'x'
matrix[position] = 'o'
def goesFirst():
order = int(input('Would you like to go first or second? Enter 1 or 2: ' ))
if order == 1:
return 1
else:
return 2
first = goesFirst()
if first == 1:
pstring = 'p2'
else:
pstring = 'p1'
boardpos = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], np.int32)
print(boardpos)
if first == 1:
while True:
#player 1 person
print('You are player 1. You will use X')
pos = int(input('Where do you want to place X? Insert a num val: '))
pos = possible[pos-1]
xx, xy = int(pos[0]), int(pos[1])
board[xx][xy] = symbol
symbol = 'x'
win = check_winner(board)
print()
if win is not None:
break
else:
#player 2 AI
positions = availablePlays(board)
p1_action = chooseAction(positions, board, symbol, pstring)
print('AI moves:')
updateState(board, p1_action, pstring)
win = check_winner(board)
if win is not None:
break
else:
while True:
#player 1 AI
positions = availablePlays(board)
p1_action = chooseAction(positions, board, symbol, pstring)
print()
print('AI moves:')
updateState(board, p1_action, pstring)
win = check_winner(board)
if win is not None:
break
else:
#player 2 person
print('You are player 2. You will use O')
pos = int(input('Where do you want to place O? Insert a num val: '))
pos = possible[pos-1]
xx, xy = int(pos[0]), int(pos[1])
board[xx][xy] = symbol
symbol = 'x'
win = check_winner(board)
if win is not None:
break
def two_player(board):
boardpos = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], np.int32)
print(boardpos)
possible = [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)]
turn = 'x'
while True:
if turn == 'x':
print('You are player 1. You will use X')
pos = int(input('Where do you want to place X? Insert a num val: '))
pos = possible[pos-1]
xx, xy = int(pos[0]), int(pos[1])
board[xx][xy] = turn
turn = 'o'
win = check_winner(board)
if win is not None:
break
else:
print('You are player 2. You will use O')
pos = int(input('Where do you want to place O? Insert a num val: '))
pos = possible[pos-1]
xx, xy = int(pos[0]), int(pos[1])
board[xx][xy] = turn
turn = 'x'
win = check_winner(board)
if win is not None:
break
#two player tic tac toe simulation
tictactoe()
|
import typing as tp
def two_sum(nums: tp.Sequence[int], target: int) -> tp.List[int]:
"""
Takes a list of integers, return indices of the two numbers
such that they add up to a specific target.
You may assume that each input would have exactly one solution,
and you may not use the same element twice.
:param nums: list of integers
:param target: specific target
:return: list of the two indices
"""
|
import random
## 09. Typoglycemia
def typoglycemia(target):
result = []
for word in target.split():
if len(word) < 4:
result.append(word)
else:
word_ran = list(word[1:-1]) #convert str to list since random.shuffle needs a list
random.shuffle(word_ran)
result.append(word[0] + ''.join(word_ran) + word[-1]) #append a string, take the first and the last alphabet add the shuffled list
return ' '.join(result) # turn the list to a string
print('09. Typoglycemia')
target = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."
print(typoglycemia(target)) |
## 16. ファイルをN分割する
import math, pandas as pd
N = int(input('N is: '))
# with open('hightemp.txt') as data_file:
# lines = data_file.readlines()
# file_len = len(lines)
# unit = math.ceil(file_len / n) #how many lines in one file
# # i is from 1, offset is from 0, and then offset + unit
# for i, offset in enumerate(range(0, file_len, unit), 1):
# with open('ht_{:02d}.txt'.format(i), mode = 'w') as out_file:
# for line in lines[offset:offset + unit]:
# out_file.write(line)
df = pd.read_csv('popular-names.txt', delimiter='\t', header=None)
unit = math.ceil(len(df) / N)
for n in range(N):
df_split = df.iloc[n * unit : (n + 1) * unit]
df_split.to_csv('popular-names' + str(n) + '.txt', sep='\t', header=False, index=False) |
"""
Greg Stewart
Your python script should take d, the number of digits, as a command line parameter.
You will need to perform r=10 runs to record the average time to multiply two d-digit
integers in decimal using the three methods above.
For each run generate a random pair of integers x and y, that are d digits long,
by using random.randint() or similar python function from the random module.
(You can generate d random digits, concatenate them and convert into int). Call
Method1, Method2 and Method3 on these inputs and record their running time on each pair.
Finally, print the average time for each method over the r=10 runs.
"""
import timeit
import matplotlib.pyplot as plt
import sys
import random
def meth1(x, y):
y_bin = "{0:b}".format(y)
product = 0
for i in range(len(y_bin)):
product += (x<<i) * int(y_bin[i])
return product
def meth2(x,y):
if (y == 0): return 0
z = meth2(x, y>>1)
if (y%2 == 0):
return z<<1
else:
return x + (z<<1)
def meth3(x,y):
x_len = x.bit_length()
y_len = y.bit_length()
n = max(x_len, y_len)%2
if (n == 0 or n == 1):
return x*y
bin_right = 2**(n>>1) - 1
bin_left = 0
for i in range(0, (n>>1)):
bin_left += 2**((n>>1)+i)
#print('num', n)
x_l = ((bin_left>>(n-x_len)) & x)>>(n>>1)
x_r = bin_right&x # int(x_bin[x_len-(n>>1)], 2)
y_l = ((bin_left>>(n-y_len))&y)>>(n>>1)
y_r = bin_right&y # int(y_bin[y_len-(n>>1)], 2)
P_1 = meth3(x_l, y_l)
P_2 = meth3(x_r, y_r)
P_3 = meth3(x_l + x_r, y_l + y_r)
return P_1 * 2**n + (P_3 - P_1 - P_2) * 2**(n>>1) + P_2
if __name__ == "__main__":
d = int(sys.argv[1])
time_1 = 0
time_2 = 0
time_3 = 0
for i in range(0, 10):
x, y = 0, 0
for j in range(0,d):
x += random.randint(0,9) * 10**j
y += random.randint(0,9) * 10**j
time_1+=timeit.timeit("meth1(%d, %d)" %(x, y), setup="from __main__ import meth1", number=1)
if (d < 300):
time_2+=timeit.timeit("meth2(%d, %d)" %(x, y), setup="from __main__ import meth2", number=1)
time_3+=timeit.timeit("meth3(%d, %d)" %(x, y), setup="from __main__ import meth3", number=1)
time_1 = time_1/10.
time_2 = time_2/10.
time_3 = time_3/10.
print("Method\tTime\n"+"="*20)
print(" 1 \t%.7f s" %time_1)
print(" 2 \t%.7f s" %time_2)
print(" 3 \t%.7f s" %time_3)
|
# filename: Salvador_e2.py
# author: Ronald Salvador
# description: This is a python program that classifies a tropical cyclone wrt its sustain winds
import sys
sustained_winds = sys.argv[1]
sustained_winds = float(sustained_winds)
if sustained_winds >= 220.0:
print("Super Typhoon")
elif sustained_winds >= 188.0:
print("Typhoon lang")
elif sustained_winds >= 89.0:
print("Severe Tropical Storm")
elif sustained_winds >= 62.0:
print("Tropical Storm")
else:
print("yehey Tropical Depression lang ") |
'''
Jesus Manuel Rodriguez Castro
12/04/2019
Assigment 8 Data Collections
*Create a class called Grade that contains the class name,
the credits and the grade point (from 0 to 4) for the grade.
*Create a second class called Student that contains the students
name and id number and a list of grade objects.
*The student class should have a methods to enter the name and id,
and a method to calculate a GPA.
*(GPAs are what is called "weighted averages." To calculate a
GPA you get a weight by multiplying the grade by the credits.
Then you divide the sum of the weights by the sum of the credits.)
*There should be a display class that allows you to enter the
information into the grade and student classes and then displays
the student name, id and the GPA.
*This is complex enough that I don't have an extra credit.
'''
class Student():
def __init__(self, student_name, id_number):
self.student_name = student_name
self.id_number = id_number
def getStuden_Name(self, student_name):
return self.student_name
def getId_Number(self, id_number):
return self.id_number
def getObject_Grade(self, object_grade):
return self.object_grade
def __str__(self):
return str(self.student_name) + ", " + str(self.id_number)
class Grade():
def __init__(self, class_name, class_credits, grade_points):
self.class_name = class_name
self.class_credits = class_credits
self.grade_points = grade_points
def ClassName(self,class_name ):
return self.class_name
def Class_Credits(self,class_credits):
return self.class_credits
def Grade_Credits(self, grade_points):
return self.grade_points
def main():
student=Student("Jesus Rodriguez", 98012345565)
c1=Grade(input("Class name: "), int(input("Credits: ")), float(input("Grades: ")))
c2=Grade(input("Class name: "), int(input("Credits: ")), float(input("Grades: ")))
c3=Grade(input("Class name: "), int(input("Credits: ")), float(input("Grades: ")))
gpa = ((c1.class_credits * c1.grade_points) + (c2.class_credits * c2.grade_points) + (c3.class_credits * c3.grade_points)) / (c1.class_credits + c2.class_credits + c3.class_credits)
print("---------------------------------")
print("The student name is: ", student.student_name)
print("The student ID is : ", student.id_number)
print("---------------------------------")
print("Course" ,"\t","\t", "Grade" ,"\t","\t", "Credits")
print(c1.class_name, "\t", "\t", c1.grade_points, "\t", "\t", c1.class_credits)
print(c2.class_name, "\t", "\t", c2.grade_points, "\t", "\t", c2.class_credits)
print(c3.class_name, "\t", "\t", c3.grade_points, "\t", "\t", c3.class_credits)
print("\t", "\t",c1.grade_points + c2.grade_points + c3.grade_points,"\t", "\t",(c1.class_credits * c1.grade_points) + (c2.class_credits * c2.grade_points) + (c3.class_credits * c3.grade_points))
print("Your GPA is : ", gpa)
main()
|
# Assignment 1 " Average"
# This program will find the average of three exam scores.
# Jesus Manuel Rodriguez Castro
# 9/23/2019
def main():
print(" This program will show you the average of the three exam scores. ")
score1 = eval(input("Enter the first score "))
score2 = eval(input("Enter the second score "))
score3 = eval(input("Enter the third score "))
average = (score1 + score2 + score3) / 3
print(" The average of the scores is:", average)
main()
|
#Jesus Manuel Rodriguez Castro
#10/20/2019
#Peer Assigment 4
#steps: 1. Get the number of values to be enter from the user.
# 2. Prompt the user for each numbre
# 3. Total the numbers.
# 4. Print the total
def main():
print("This program will total values entered by the user. ")
n=eval(input("How many values do you want to enter? "))
total=0
for i in range(n):
num = eval(input("Enter a number: "))
total += num # same as total=num + num
print("Your total is", total)
main()
|
# Assignment 1 KM to Miles.
# This program will convert kilometers to milles.
# Jesus Manuel Rodriguez Castro
# 9/23/2019
def main():
print(" Convert Kilometers to Miles ")
kilometers = int(input(" Enter Kilometer that you would like to know in Miles: "))
miles = kilometers * 0.62137119
print( kilometers,"kilometers are",miles,"miles ")
main()
|
'''
Jesus Manuel Rodriguez Castro
11/13/2019
Assignment 6
A certain college classifies students according to credits earned.
A student with less than 7 credits is a Freshman.
At least 7 credits are required to be a Sophomorem,
16 to be Junior and 26 to be classified as a Senior
Write a program that calculates class standing from
the number of credits earned.
'''
def main():
credit=int(input("Enter credits: "))
if credit ==0:
print("You are not a student of this college!")
elif credit <=6:
print("You are a Freshman!")
elif credit <=15:
print("You are Sophomore!")
elif credit <=25:
print("You are Junior!")
elif credit == 26:
print("You are Senior!")
else:
print("You are almost a teacher!")
main()
|
def NormalizeMult(data, set_range):
'''
返回归一化后的数据和最大最小值
'''
normalize = np.arange(2*data.shape[1], dtype='float64')
normalize = normalize.reshape(data.shape[1], 2)
for i in range(0, data.shape[1]):
if set_range == True:
list = data[:, i]
listlow, listhigh = np.percentile(list, [0, 100])
else:
if i == 0:
listlow = -90
listhigh = 90
else:
listlow = -180
listhigh = 180
normalize[i, 0] = listlow
normalize[i, 1] = listhigh
delta = listhigh - listlow
if delta != 0:
for j in range(0, data.shape[0]):
data[j, i] = (data[j, i] - listlow)/delta
return data, normalize
#反归一化
def FNormalizeMult(data, normalize):
data = np.array(data, dtype='float64')
#列
for i in range(0, data.shape[1]):
listlow = normalize[i, 0]
listhigh = normalize[i, 1]
delta = listhigh - listlow
#print("listlow, listhigh, delta", listlow, listhigh, delta)
#行
if delta != 0:
for j in range(0, data.shape[0]):
data[j, i] = data[j, i]*delta + listlow
return data
|
def swap_bits(x:int, i: int, j: int) -> int:
if ((x >> i & 1) != (x >> j & 1)):
# print("Bits are different")
bit_mask = (1 << i) | (1 << j)
x ^= bit_mask
return x
while True:
try:
number = int(input("Enter a decimal number: "))
print(number.bit_length())
i = int(input("Enter i: "))
if (i > number.bit_length() - 1 or i < 0):
raise ValueError("i is out of bounds")
j = int(input("Enter j: "))
if (j > number.bit_length() - 1 or j < 0):
raise ValueError("j is out of bounds")
print("Your number in binary is: " + str(bin(number)[2:]))
number = swap_bits(number, i, j)
print("Your number with bits " + str(i) + " and " + str(j) + " swapped is: " + str(bin(number)[2:]) + " or " + str(number))
break
except ValueError as error:
print(error)
|
courses = ['Python', 'SQL', 'Docker', 'Airflow', 'NoSQL']
print('Courses:', courses)
print(courses.index('SQL')) # Fetch index of item in a list
print(min(courses)) # aggregates
print('Python' in courses) # returns a boolean
print("Traditional indexing:")
for index, course in enumerate(courses):
print(f"{index}, {course}")
print("\nCustomized indexing")
for index, course in enumerate(courses, start=1):
print(f"{index}, {course}")
courses_string = ", ".join(courses)
print(courses_string)
newlist = courses_string.split(', ')
|
"""
A scenario where it would be important to use a class variable, would be when
an attribute is to have a constant value across all instances. This can then be
referenced in a class method
e.g a total number of employees (num_of_emps) which increases each time a new
employee is created.
"""
class Employee:
num_of_emps = 0
raise_amount = 1.04 # 4% increase
def __init__(self, first_name, last_name, pay):
self.first_name = first_name
self.last_name = last_name
self.pay = pay
self.email = first_name + '.' + last_name + '@company.com'
Employee.num_of_emps += 1 # have an increase of 1 at every new instance
def fullname(self):
return f'{self.first_name} {self.last_name}'
def apply_raise(self):
self.pay = self.pay * self.raise_amount
@classmethod
def count(cls):
return cls.num_of_emps
print('Employee count:', Employee.count())
print('\nCreating two employees...')
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('John', 'Smith', 60000)
print('Employee count now:', Employee.num_of_emps)
print('\nCreating one more employee...')
emp_3 = Employee('Jane', 'Jones', 50000)
print('Employee count now:', emp_1.num_of_emps)
|
# instance methods and variables
"""
--Instance variables are used to store data that is unique to each instances
--
"""
class Employee:
def __init__(self, first_name, last_name, pay):
self.first_name = first_name
self.last_name = last_name
self.pay = pay
self.email = first_name + '.' + last_name + '@company.com'
def fullname(self):
return f'{self.first_name} {self.last_name}'
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('John', 'Smith', 60000)
print(emp_1.fullname())
"""
Methods can also be run from the class name itself.
In this case the instance has to be passed into the method as an argument
It enables the class know what instance the method should be called upon
"""
print(Employee.fullname(emp_2))
|
import speech_recognition as sr
import os, sys
from actions import action
from conversation import *
r = sr.Recognizer()
m = sr.Microphone()
position = 1
try:
print("A moment of silence, please...")
with m as source: r.adjust_for_ambient_noise(source)
print("Set minimum energy threshold to {}".format(r.energy_threshold))
while True:
print("Say something!")
with m as source: audio = r.listen(source)
print("Got it! Now to recognize it...")
try:
# recognize speech using Google Speech Recognition
transcribe = r.recognize_google(audio)
convoSub_Starter = ['want to play outside', 'want to play inside', 'what time is it']
convoSub_Cont = ['how come', 'why not', 'I don\'t think', 'okay', 'what do you want to do']
commandList = ['Stand', 'Sit', 'Walk', 'Run', 'Bark', 'Shake', 'Sleep', 'stand', 'sit', 'walk', 'run', 'bark', 'shake', 'sleep', 'goodnight']
if any(x in transcribe for x in convoSub_Starter):
convoStarter(transcribe)
if any(x in transcribe for x in convoSub_Cont):
convoContinue(transcribe)
if any(x in transcribe for x in commandList):
if transcribe.find('Stand')!=-1 or transcribe.find('stand')!=-1:
print("Pupper will stand up")
action(1, position)
position = 1
elif transcribe.find('Sit')!=-1 or transcribe.find('sit')!=-1:
print("Pupper will sit down")
action(2, position)
position = 2
elif transcribe.find('Walk')!=-1 or transcribe.find('walk')!=-1:
print("Pupper will walk")
action(3, position)
position = 1
elif transcribe.find('Run')!=-1 or transcribe.find('run')!=-1:
print("Pupper will run")
action(4, position)
position = 1
elif transcribe.find('Bark')!=-1 or transcribe.find('bark')!=-1:
print("Pupper will bark")
action(5, position)
elif transcribe.find('Shake')!=-1 or transcribe.find('shake')!=-1:
print("Pupper will shake")
action(6, position)
position = 1
elif transcribe.find('Sleep')!=-1 or transcribe.find('sleep')!=-1:
os.system('omxplayer -o local /home/pi/speech_recognition/sounds/snore.wav')
print("Pupper is sleeping. Give him a few seconds")
action(1, position)
elif transcribe.find('goodnight')!=-1:
print("Pupper is going to sleep. Goodnight")
break
# we need some special handling here to correctly print unicode characters to standard output
if str is bytes: # this version of Python uses bytes for strings (Python 2)
print(u"You said '{}'\n".format(transcribe).encode("utf-8"))
else: # this version of Python uses unicode for strings (Python 3+)
print("You said '{}'\n".format(transcribe))
except sr.UnknownValueError:
print("Oops! Didn't catch that")
except sr.RequestError as e:
print("Uh oh! Couldn't request results from Google Speech Recognition service; {0}".format(e))
except KeyboardInterrupt:
pass
|
from Utils.bt_scheme import PartialSolutionWithOptimization, BacktrackingOptSolver, State, Solution
from typing import *
from random import random, seed
from time import time
def knapsack_solve(weights, values, capacity):
class KnapsackPS(PartialSolutionWithOptimization):
def __init__(self, solution=(), suma_pesos=0,
suma_valores=0): # IMPLEMENTAR: Añade los parámetros que tú consideres
self.solution = solution
self.n = len(solution)
self.suma_pesos = suma_pesos
self.suma_valores = suma_valores
def is_solution(self) -> bool: # IMPLEMENTAR
return self.n == len(values) and self.suma_pesos <= capacity
def get_solution(self) -> Solution: # IMPLEMENTAR
return self.solution
def successors(self) -> Iterable["KnapsackPS"]: # IMPLEMENTAR
if self.n >= len(values):
return []
yield KnapsackPS(self.solution + (0,), self.suma_pesos, self.suma_valores)
if self.suma_pesos + weights[self.n] <= capacity:
yield KnapsackPS(self.solution + (1,), self.suma_pesos + weights[self.n],
self.suma_valores + values[self.n])
def state(self) -> State: # IMPLEMENTAR
return self.n, self.suma_pesos
def f(self) -> Union[int, float]: # IMPLEMENTAR
return -self.suma_valores
initialPS = KnapsackPS() # IMPLEMENTAR: Añade los parámetros que tú consideres
return BacktrackingOptSolver.solve(initialPS)
def knapsack_solve2(weights, values, capacity):
class KnapsackPS(PartialSolutionWithOptimization):
def __init__(self, solution=()): # IMPLEMENTAR: Añade los parámetros que tú consideres
self.solution = solution
self.n = len(solution)
def is_solution(self) -> bool: # IMPLEMENTAR
return self.n == len(values) and suma_pesos <= capacity
def get_solution(self) -> Solution: # IMPLEMENTAR
return self.solution
def successors(self) -> Iterable["KnapsackPS"]: # IMPLEMENTAR
nonlocal suma_pesos
nonlocal suma_valores
if self.n >= len(values):
return []
if suma_pesos + weights[self.n] <= capacity:
suma_pesos += weights[self.n]
suma_valores += values[self.n]
yield KnapsackPS(self.solution + (1,))
suma_pesos -= weights[self.n]
suma_valores -= values[self.n]
yield KnapsackPS(self.solution + (0,))
def state(self) -> State: # IMPLEMENTAR
return self.n, suma_pesos
def f(self) -> Union[int, float]: # IMPLEMENTAR
return -suma_valores
suma_pesos = 0
suma_valores = 0
initialPS = KnapsackPS() # IMPLEMENTAR: Añade los parámetros que tú consideres
return BacktrackingOptSolver.solve(initialPS)
def create_knapsack_problem(num_objects: int) -> Tuple[Tuple[int, ...], Tuple[int, ...], int]:
seed(42)
weights = [int(random() * 1000 + 1) for _ in range(num_objects)]
values = [int(random() * 1000 + 1) for _ in range(num_objects)]
capacity = sum(weights) // 2
return weights, values, capacity
# Programa principal ------------------------------------------
if __name__ == "__main__":
# W, V, C = [1, 4, 2, 3], [2, 3, 4, 2], 7 # SOLUCIÓN: Weight=7, Value=9
W, V, C = create_knapsack_problem(30) # SOLUCIÓN: Weight=6313, Value=11824
start_time = time()
for sol in knapsack_solve2(W, V, C):
print("Weight: " + str(sum(v * W[i] for i, v in enumerate(sol))) + " Value: " + str(
sum(v * V[i] for i, v in enumerate(sol))))
# print(sol)
finish_time = time()
print("\n<TERMINADO> Tiempo de ejecucion: ", finish_time - start_time)
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
"""
two-pass alogrithm
"""
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
num = 0
cur = head
while(cur) :
num += 1
cur = cur.next
if num == n :
if n == 1 :
return None
else :
return head.next
idx = 1
cur = head
dif = num - n
while(idx < dif) :
cur = cur.next
idx += 1
cur.next = cur.next.next
return head
|
class Power():
def __init__(self,name,type,damage,diploma): #The name, damage, diploma defines the power
self.__name=name
self.__type=type
self.__damage=damage
self.__diploma=diploma
def set_name(name):
self.__name=name
def get_name(self):
return self.__name
def get_type(self):
return self.__type
def get_damage(self):
return self.__damage
def set_damage(damage):
self.__damage=damage
def print_detail(self):
print("Power_name:"+self.__name+"Power damage:"+self.__damage)
|
import random
class BasePlayer:
''' This class contains all logic for a player.
Note:
- do not change the names of any existing methods
To Do:
- incomingTrade()
- beginTurn() (eg. turn logic)
'''
def __init__(self, gamemaster, GBview, playerID):
''' BasePlayer.__init__() method
Args:
gamemaster:(GameMaster): gamemaster object to interact with
GBview(GameBoardView): game board view to interact with
playerID: this player's ID number
Returns:
{no return}
'''
self.GM = gamemaster
self.GBview = GBview
self.playerID = playerID
## print('Player created')
def initialPlacement(self):
''' determines initial settlement and road postions
Args:
{no args}
Returns:
true when done
'''
x,y = None, None
## pick random settlement location ##
while(True):
x = random.randint(0,len(self.GBview.vertices)-1)
y = random.randint(0,len(self.GBview.vertices[x])-1)
## check if valid and empty ##
## print(str(x) + ',' + str(y))
if self.GBview.vertices[x][y].valid and self.GBview.vertices[x][y].playerID == None:
if self.GM.buy('Settlement',[x,y]):
## find adj edges ##
adj = self.GBview.vertEdges([x,y])
self.GM.buy('Road',adj[random.randint(0,len(adj)-1)])
break
return True
def incomingTrade(self, trade_offer):
''' decides whether to accept, modify, or reject incoming trade offer
Args:
trade_offer[variant]: details of trade [[offer to player], [want from player], opp player ID]
Returns:
counter trade offer [[offer to opp], [want from opp], self player ID], or false
'''
## print(trade_offer)
## print(str(self.playerID) + ': incoming trade')
## if # of offer cards = # of want cards ##
## if len(trade_offer[0]) != len(trade_offer[1]):
## return False
## 50/50 chance of accepting ##
if not random.randint(0,1):
## print(str(self.playerID) + ': accepting trade')
return [trade_offer[1],trade_offer[0],self.playerID]
## return trade or false ##
return False
def selectTrade(self, trade_offers):
''' selects between competing counter offers to trade
Args:
trade_offer[variant]: details of trade [[offer to player], [want from player], other player ID]
Returns:
int index of selected trade in offers list
'''
## print(str(self.playerID) + ': select trade')
## select random option if #offer == #want ##
## for i in trade_offers[:]:
## if i[0] != i[1]:
## trade_offers.remove(i)
return random.randint(0,len(trade_offers)-1)
def moveRobber(self):
''' selects location to move robber and cards to steal
Args:
{no args}
Returns:
robber move [[location x,y], card seed, opp ID]
'''
## pick random opponent settlement ##
x,y,settle_player = None,None,None
while(True):
x = random.randint(0,len(self.GBview.vertices)-1)
y = random.randint(0,len(self.GBview.vertices[x])-1)
settle_player = self.GBview.vertices[x][y].playerID
if (settle_player != None) and (settle_player != self.playerID):
break
## place on random tile near opp settle ##
tiles = self.GBview.vertTiles([x,y])
location = tiles[random.randint(0,len(tiles)-1)]
## pick random card from player ##
seed = random.randint(1,20)
return [location, seed, settle_player]
def over7Cards(self):
''' selects cards to throwaway
Args:
{no args}
Returns:
str array of cards to throwaway
'''
## randomly select cards to throwaway ##
hands = self.GM.playerHand(self.playerID)
throwaway = []
num_cards = len(hands[self.playerID])
for j in range(int(num_cards/2)):
throwaway.append(hands[self.playerID][random.randint(0,num_cards-1)])
## print('Player ' + str(self.playerID))
## print(hands)
## print(throwaway)
return throwaway
def beginTurn(self):
''' main turn logic
Args:
{no args}
Returns:
return to end turn
'''
buildings = ['Settlement','City','Road','Dev']
build_cost = [['Br','Wo','Wh','Sh'],['Wh','Wh','Or','Or','Or'],['Br','Wo'],['Or','Wh','Sh']]
resCodes = ['Br','Wo','Or','Wh','Sh']
## randomly select build option ##
hand = self.GM.playerHand(self.playerID)[self.playerID]
for i in range(len(build_cost)):
hand_c = list(hand)
for j in range(len(build_cost[i])):
card_check = False
for k in range(len(hand_c)):
if hand_c[k] == build_cost[i][j]:
hand_c.pop(k)
card_check = True
break
if not card_check:
break
else:
if buildings[i] == 'Road':
if not random.randint(0,5):
self.build(buildings[i])
else:
self.build(buildings[i])
## if any res, rand chance to offer trade. offer 1 for 1 ##
hand = self.GM.playerHand(self.playerID)[self.playerID]
if len(hand):
## chance to offer trade ##
if not random.randint(0,3):
offer = hand[random.randint(0,len(hand)-1)]
want = []
while(True):
want = resCodes[random.randint(0,len(resCodes)-1)]
if want != offer:
break
## print(str(self.playerID) + ': offering trade')
self.GM.trade(offer, want)
## rand chance (~10%) to play any dev cards in hand ##
if (True): # always plays for testing purposes
dev_cards = self.GM.playerHandDev(self.playerID)[self.playerID]
## print(dev_cards)
if dev_cards:
card = dev_cards[random.randint(0,len(dev_cards)-1)]
if card == 'Kn':
self.GM.playDevCard(card) # No extras needed. positioning handled by player .moveRobber()
elif card == 'Ye':
extras = []
for i in range(2):
extras.append(resCodes[random.randint(0,len(resCodes)-1)])
self.GM.playDevCard(card, extras) # The resources to take from pile
elif card == 'Mo':
extras = resCodes[random.randint(0,len(resCodes)-1)]
self.GM.playDevCard(card, [extras]) # resource type to steal from all players
elif card == 'Ro':
extras = []
for j in range(2):
for i in range(100): # limited to prevent lockup
x = random.randint(0,len(self.GBview.edges)-1)
y = random.randint(0,len(self.GBview.edges[x])-1)
if self.GBview.edges[x][y].playerID == self.playerID:
verts = self.GBview.edgeVerts([x,y])
edges = self.GBview.vertEdges(verts[random.randint(0,len(verts)-1)])
[x1,y1] = edges[random.randint(0,len(edges)-1)]
if x1 != x and y1 != y:
if self.GBview.edges[x1][y1].playerID == None:
extras.append([x1,y1])
break
print(extras)
self.GM.playDevCard(card, extras) # two coordinates for roads to be built
elif card == 'Vi':
self.GM.playDevCard(card) # no extras required. card is only played
return
def build(self, item):
''' this is just to separate the location selection logic form the main logic
Args:
building(str): type of building to buy
Returns:
{no return}
'''
if item == 'Settlement':
for i in range(20):
x = random.randint(0,len(self.GBview.edges)-1)
y = random.randint(0,len(self.GBview.edges[x])-1)
if self.GBview.edges[x][y].playerID == self.playerID:
verts = self.GBview.edgeVerts([x,y])
[x1,y1] = verts[random.randint(0,len(verts)-1)]
if self.GBview.vertices[x1][y1].playerID == None:
self.GM.buy(item,[x,y])
return
elif item == 'City':
for i in range(20):
x = random.randint(0,len(self.GBview.vertices)-1)
y = random.randint(0,len(self.GBview.vertices[x])-1)
if self.GBview.vertices[x][y].playerID == self.playerID:
self.GM.buy(item,[x,y])
return
elif item == 'Road':
for i in range(20):
x = random.randint(0,len(self.GBview.edges)-1)
y = random.randint(0,len(self.GBview.edges[x])-1)
if self.GBview.edges[x][y].playerID == self.playerID:
verts = self.GBview.edgeVerts([x,y])
edges = self.GBview.vertEdges(verts[random.randint(0,len(verts)-1)])
[x1,y1] = edges[random.randint(0,len(edges)-1)]
if x1 != x and y1 != y:
if self.GBview.edges[x1][y1].playerID == None:
self.GM.buy(item,[x1,y1])
return
elif item == 'Dev':
self.GM.buy(item)
return
## BuildTest = BasePlayer()
|
a = 2
b = 4
print("a:{}".format(a))
print("b:{}".format(b))
print("a+b:{}".format(a+b))
|
import math
a, b, x = (int(i) for i in input().split())
t = 2 * (b/a - x/(a*a*a))
z = math.atan(b/a)
rad = math.atan(t)
if(rad <= z):
deg = math.degrees(rad)
else:
rad = math.atan((a*b*b)/(2*x))
deg = math.degrees(rad)
print(deg)
|
## TODO: define the convolutional neural network architecture
import torch
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
## TODO: Define all the layers of this CNN, the only requirements are:
## 1. This network takes in a square (same width and height), grayscale image as input
## 2. It ends with a linear layer that represents the keypoints
## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs
# As an example, you've been given a convolutional layer, which you may (but don't have to) change:
# 1 input image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel
self.conv1 = nn.Conv2d(1, 68, 3)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(68, 136, 3)
self.conv3 = nn.Conv2d(136, 272, 3)
self.conv4 = nn.Conv2d(272, 544, 3)
self.conv5 = nn.Conv2d(544, 1088, 3)
self.conv6 = nn.Conv2d(1088, 2176, 3)
self.fc1 = nn.Linear(2176*1*1, 1000)
self.fc2 = nn.Linear(1000, 1000)
self.fc1_drop = nn.Dropout(p=0.4)
self.fc3 = nn.Linear(1000, 136)
def forward(self, x):
## TODO: Define the feedforward behavior of this model
## x is the input image and, as an example, here you may choose to include a pool/conv step:
## x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = self.pool(F.relu(self.conv3(x)))
x = self.pool(F.relu(self.conv4(x)))
x = self.pool(F.relu(self.conv5(x)))
x = self.pool(F.relu(self.conv6(x)))
# a modified x, having gone through all the layers of your model, should be returned
x = x.view(x.size(0), -1)
x = F.relu(self.fc1(x))
x = self.fc1_drop(x)
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from Position import *
"""
SUCCESS : La position a était crée
ERROR : La position est incorrecte
"""
def testCreation(pos1):
return (pos1.x() == 1 and pos1.y() == 2)
"""
ERROR : La position est touchee
SUCCESS : La position est bien non touchee
"""
def testEstTouche(pos1):
return not(pos1.estTouche())
"""
SUCCESS : La position est bien touchee
ERROR : La position devrait être touchee
"""
def testSetTouche(pos1):
return pos1.estTouche()
def testPosition() :
#Instancier une position
pos1 = Position(1, 2)
if(not(testCreation(pos1))):
print("TEST creation FAIL")
return False
if(not(testEstTouche(pos1))):
print("TEST testEstTouche FAIL")
return False
pos1.setTouche()
if(not(testSetTouche(pos1))):
print("TEST setTouche FAIL")
return False
return True
print(testPosition())
|
'''
929. 独特的电子邮件地址
每封电子邮件都由一个本地名称和一个域名组成,以 @ 符号分隔。
例如,在 [email protected]中, alice 是本地名称,而 leetcode.com 是域名。
除了小写字母,这些电子邮件还可能包含 '.' 或 '+'。
如果在电子邮件地址的本地名称部分中的某些字符之间添加句点('.'),则发往那里的邮件将会转发到本地名称中没有点的同一地址。
例如,"[email protected]” 和 “[email protected]” 会转发到同一电子邮件地址。 (请注意,此规则不适用于域名。)
如果在本地名称中添加加号('+'),则会忽略第一个加号后面的所有内容。这允许过滤某些电子邮件,
例如 [email protected] 将转发到 [email protected]。 (同样,此规则不适用于域名。)
可以同时使用这两个规则。
给定电子邮件列表 emails,我们会向列表中的每个地址发送一封电子邮件。实际收到邮件的不同地址有多少?
示例:
输入:["[email protected]","[email protected]","[email protected]"]
输出:2
解释:实际收到邮件的是 "[email protected]" 和 "[email protected]"。
提示:
1 <= emails[i].length <= 100
1 <= emails.length <= 100
每封 emails[i] 都包含有且仅有一个 '@' 字符。
'''
from typing import List
class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
email_set = set()
for email in emails:
email_list = email.split("@")
email_list[0] = email_list[0].replace(".", "")
for index, value in enumerate(email_list[0]):
if value == "+":
email_list[0] = email_list[0][:index]
break
email_set.add(email_list[0] + "@" + email_list[1])
return len(email_set)
so = Solution()
print(so.numUniqueEmails(
["[email protected]", "[email protected]", "[email protected]"]) == 2)
|
'''
739. 每日温度
根据每日 气温 列表,请重新生成一个列表,对应位置的输出是需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。
例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。
提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。
'''
from typing import List
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
sort_result = []
length = len(T)
result = [0] * length
index = 0
while index < length:
if sort_result:
if T[index] > sort_result[-1][1]:
result[sort_result[-1][0]] = index - sort_result[-1][0]
sort_result.pop(-1)
else:
sort_result.append((index, T[index]))
index += 1
else:
sort_result.append((index, T[index]))
index += 1
return result
so = Solution()
print(so.dailyTemperatures()) |
'''
5398. 统计二叉树中好节点的数目
给你一棵根为 root 的二叉树,请你返回二叉树中好节点的数目。
「好节点」X 定义为:从根到该节点 X 所经过的节点中,没有任何节点的值大于 X 的值。
'''
from base import TreeNode
class Solution:
def goodNodes(self, root: TreeNode) -> int:
self.count = 0
def _find_deep(p, max_before):
if not p:
return 0
if p.val >= max_before:
self.count += 1
_find_deep(p.left, p.val)
_find_deep(p.right, p.val)
else:
_find_deep(p.left, max_before)
_find_deep(p.right, max_before)
_find_deep(root, - 10 ** 4)
return self.count
so = Solution()
print(so.goodNodes(TreeNode.create_tree([3, 1, 4, 3, None, 1, 5])) == 4)
print(so.goodNodes(TreeNode.create_tree([3, 3, None, 4, 2])) == 3)
print(so.goodNodes(TreeNode.create_tree([1])) == 1)
|
'''
414. 第三大的数
给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。
示例 1:
输入: [3, 2, 1]
输出: 1
解释: 第三大的数是 1.
示例 2:
输入: [1, 2]
输出: 2
解释: 第三大的数不存在, 所以返回最大的数 2 .
示例 3:
输入: [2, 2, 3, 1]
输出: 1
解释: 注意,要求返回第三大的数,是指第三大且唯一出现的数。
存在两个值为2的数,它们都排第二。
思路:按照找最大值的方式,找三次
'''
class Solution:
def thirdMax(self, nums) -> int:
m_value = None
for n in nums:
if m_value is None:
m_value = n
else:
if n > m_value:
m_value = n
s_value = None
for n in nums:
if n < m_value:
if s_value is None:
s_value = n
else:
if n > s_value:
s_value = n
if s_value is None:
return m_value
t_value = None
for n in nums:
if n < s_value:
if t_value is None:
t_value = n
else:
if n > t_value:
t_value = n
if t_value is None:
return m_value
return t_value
so = Solution()
print(so.thirdMax([3, 2, 1]) == 1)
print(so.thirdMax([1, 2]) == 2)
print(so.thirdMax([2, 2, 3, 1]) == 1) |
'''
443. 压缩字符串
给定一组字符,使用原地算法将其压缩。
压缩后的长度必须始终小于或等于原数组长度。
数组的每个元素应该是长度为1 的字符(不是 int 整数类型)。
在完成原地修改输入数组后,返回数组的新长度。
进阶:
你能否仅使用O(1) 空间解决问题?
示例 1:
输入:
["a","a","b","b","c","c","c"]
输出:
返回6,输入数组的前6个字符应该是:["a","2","b","2","c","3"]
说明:
"aa"被"a2"替代。"bb"被"b2"替代。"ccc"被"c3"替代。
示例 2:
输入:
["a"]
输出:
返回1,输入数组的前1个字符应该是:["a"]
说明:
没有任何字符串被替代。
示例 3:
输入:
["a","b","b","b","b","b","b","b","b","b","b","b","b"]
输出:
返回4,输入数组的前4个字符应该是:["a","b","1","2"]。
说明:
由于字符"a"不重复,所以不会被压缩。"bbbbbbbbbbbb"被“b12”替代。
注意每个数字在数组中都有它自己的位置。
'''
class Solution:
def compress(self, chars) -> int: # 双指针法
length = len(chars)
slow = 0
offset = 0
while slow < length - offset:
fast = slow + 1
count = 1
self_offset = 0
while fast < length - offset:
if chars[fast] == chars[slow]:
count += 1
fast += 1
else:
break
if count > 1:
count_list = list(str(count))
for i in range(len(count_list)):
chars[slow + i + 1] = count_list[i]
for i in range(slow + len(count_list) + 1, slow + count):
chars.pop(i - self_offset)
offset += 1
self_offset += 1
slow = fast - self_offset
return len(chars)
so = Solution()
print(so.compress(["a", "a", "b", "b", "c", "c", "c"]) == 6)
print(so.compress(["a"]) == 1)
print(so.compress(["a", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b"]) == 4)
print(so.compress(["a", "a", "a", "b", "b", "a", "a"]) == 6)
|
"""
LCP 22. 黑白方格画
小扣注意到秋日市集上有一个创作黑白方格画的摊位。摊主给每个顾客提供一个固定在墙上的白色画板,画板不能转动。
画板上有 n * n 的网格。绘画规则为,小扣可以选择任意多行以及任意多列的格子涂成黑色,所选行数、列数均可为 0。
小扣希望最终的成品上需要有 k 个黑色格子,请返回小扣共有多少种涂色方案。
注意:两个方案中任意一个相同位置的格子颜色不同,就视为不同的方案。
示例 1:
输入:n = 2, k = 2
输出:4
解释:一共有四种不同的方案:
第一种方案:涂第一列;
第二种方案:涂第二列;
第三种方案:涂第一行;
第四种方案:涂第二行。
示例 2:
输入:n = 2, k = 1
输出:0
解释:不可行,因为第一次涂色至少会涂两个黑格。
示例 3:
输入:n = 2, k = 4
输出:1
解释:共有 2*2=4 个格子,仅有一种涂色方案。
限制:
1 <= n <= 6
0 <= k <= n * n
"""
class Solution:
def paintingPlan(self, n: int, k: int) -> int:
res = 0
def fact(n):
if n == 0:
return 1
else:
return n * fact(n - 1)
def combination(x, y):
total = fact(y) // (fact(x) * fact(y - x))
return int(total)
for i in range(n):
j = (k - i * n) // (n - i)
if j == n:
return 1
if j * (n - i) == k - i * n and j >= 0 and j <= n:
res += (combination(i, n) * combination(j, n))
return res
|
"""
1518. 换酒问题
小区便利店正在促销,用 numExchange 个空酒瓶可以兑换一瓶新酒。你购入了 numBottles 瓶酒。
如果喝掉了酒瓶中的酒,那么酒瓶就会变成空的。
请你计算 最多 能喝到多少瓶酒。
示例 1:
输入:numBottles = 9, numExchange = 3
输出:13
解释:你可以用 3 个空酒瓶兑换 1 瓶酒。
所以最多能喝到 9 + 3 + 1 = 13 瓶酒。
示例 2:
输入:numBottles = 15, numExchange = 4
输出:19
解释:你可以用 4 个空酒瓶兑换 1 瓶酒。
所以最多能喝到 15 + 3 + 1 = 19 瓶酒。
示例 3:
输入:numBottles = 5, numExchange = 5
输出:6
示例 4:
输入:numBottles = 2, numExchange = 3
输出:2
提示:
1 <= numBottles <= 100
2 <= numExchange <= 100
"""
class Solution:
def numWaterBottles(self, numBottles: int, numExchange: int) -> int:
count = numBottles
while numBottles:
change = numBottles // numExchange
if not change:
break
count += change
numBottles = numBottles % numExchange + change
return count
so = Solution()
print(so.numWaterBottles(numBottles=9, numExchange=3) == 13)
print(so.numWaterBottles(numBottles=15, numExchange=4) == 19)
print(so.numWaterBottles(numBottles=5, numExchange=5) == 6)
print(so.numWaterBottles(numBottles=2, numExchange=3) == 2)
|
'''
693. 交替位二进制数
给定一个正整数,检查他是否为交替位二进制数:换句话说,就是他的二进制数相邻的两个位数永不相等。
示例 1:
输入: 5
输出: True
解释:
5的二进制数是: 101
示例 2:
输入: 7
输出: False
解释:
7的二进制数是: 111
示例 3:
输入: 11
输出: False
解释:
11的二进制数是: 1011
示例 4:
输入: 10
输出: True
解释:
10的二进制数是: 1010
通过次数13,338提交次数22,085
'''
class Solution:
def hasAlternatingBits(self, n: int) -> bool:
before = None
while n > 0:
if n % 2 == before:
return False
before = n % 2
n = n // 2
return True
so = Solution()
print(so.hasAlternatingBits(5) == True)
print(so.hasAlternatingBits(7) == False)
print(so.hasAlternatingBits(11) == False)
print(so.hasAlternatingBits(10) == True)
|
"""
1252. 奇数值单元格的数目
给你一个 n 行 m 列的矩阵,最开始的时候,每个单元格中的值都是 0。
另有一个索引数组 indices,indices[i] = [ri, ci] 中的 ri 和 ci 分别表示指定的行和列(从 0 开始编号)。
你需要将每对 [ri, ci] 指定的行和列上的所有单元格的值加 1。
请你在执行完所有 indices 指定的增量操作后,返回矩阵中 「奇数值单元格」 的数目。
示例 1:
输入:n = 2, m = 3, indices = [[0,1],[1,1]]
输出:6
解释:最开始的矩阵是 [[0,0,0],[0,0,0]]。
第一次增量操作后得到 [[1,2,1],[0,1,0]]。
最后的矩阵是 [[1,3,1],[1,3,1]],里面有 6 个奇数。
示例 2:
输入:n = 2, m = 2, indices = [[1,1],[0,0]]
输出:0
解释:最后的矩阵是 [[2,2],[2,2]],里面没有奇数。
提示:
1 <= n <= 50
1 <= m <= 50
1 <= indices.length <= 100
0 <= indices[i][0] < n
0 <= indices[i][1] < m
"""
from typing import List
class Solution:
def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
# 解题思路,统计行列数据
row_count = [0 for _ in range(n)]
col_count = [0 for _ in range(m)]
for indice in indices:
row_count[indice[0]] += 1
col_count[indice[1]] += 1
count = 0
for rc in row_count:
for cc in col_count:
if (rc + cc) % 2 == 1:
count += 1
return count
so = Solution()
print(so.oddCells(n=2, m=3, indices=[[0, 1], [1, 1]]) == 6)
print(so.oddCells(n=2, m=2, indices=[[1, 1], [0, 0]]) == 0)
|
'''
645. 错误的集合
集合 S 包含从1到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个元素复制了成了集合里面的另外一个元素的值,导致集合丢失了一个整数并且有一个元素重复。
给定一个数组 nums 代表了集合 S 发生错误后的结果。你的任务是首先寻找到重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。
示例 1:
输入: nums = [1,2,2,4]
输出: [2,3]
注意:
给定数组的长度范围是 [2, 10000]。
给定的数组是无序的。
'''
class Solution:
def findErrorNums(self, nums): # 先排序,找到重复的
result = []
count = 0
count_val = 0
nums.sort()
for index, num in enumerate(nums):
if index > 0 and num == nums[index - 1]:
result.append(num)
count_val += num
count += 1
result.append((count + 1) * count // 2 - count_val + result[0])
return result
so = Solution()
print(so.findErrorNums([1, 2, 2, 4]) == [2, 3])
|
'''
728. 自除数
自除数 是指可以被它包含的每一位数除尽的数。
例如,128 是一个自除数,因为 128 % 1 == 0,128 % 2 == 0,128 % 8 == 0。
还有,自除数不允许包含 0 。
给定上边界和下边界数字,输出一个列表,列表的元素是边界(含边界)内所有的自除数。
示例 1:
输入:
上边界left = 1, 下边界right = 22
输出: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
注意:
每个输入参数的边界满足 1 <= left <= right <= 10000。
'''
from typing import List
class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
result = []
for num in range(left, right + 1):
status = True
num_copy = num
while num_copy > 0:
mode = num_copy % 10
if mode == 0:
status = False
break
if num % mode != 0:
status = False
break
num_copy = num_copy // 10
if status:
result.append(num)
return result
so = Solution()
print(so.selfDividingNumbers(1, 22) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]) |
'''
832. 翻转图像
给定一个二进制矩阵 A,我们想先水平翻转图像,然后反转图像并返回结果。
水平翻转图片就是将图片的每一行都进行翻转,即逆序。例如,水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]。
反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。例如,反转 [0, 1, 1] 的结果是 [1, 0, 0]。
示例 1:
输入: [[1,1,0],[1,0,1],[0,0,0]]
输出: [[1,0,0],[0,1,0],[1,1,1]]
解释: 首先翻转每一行: [[0,1,1],[1,0,1],[0,0,0]];
然后反转图片: [[1,0,0],[0,1,0],[1,1,1]]
示例 2:
输入: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
输出: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
解释: 首先翻转每一行: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]];
然后反转图片: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
说明:
1 <= A.length = A[0].length <= 20
0 <= A[i][j] <= 1
'''
from typing import List
class Solution:
def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
for x, row in enumerate(A):
start = 0
end = len(row) - 1
while start <= end:
row[start], row[end] = row[end], row[start]
if start == end:
row[start] = (row[start] + 1) % 2
else:
row[start] = (row[start] + 1) % 2
row[end] = (row[end] + 1) % 2
start += 1
end -= 1
return A
so = Solution()
print(so.flipAndInvertImage([[1,1,0],[1,0,1],[0,0,0]]) == [[1,0,0],[0,1,0],[1,1,1]])
print(so.flipAndInvertImage([[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]) == [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]) |
'''
453. 最小移动次数使数组元素相等
给定一个长度为 n 的非空整数数组,找到让数组所有元素相等的最小移动次数。每次移动可以使 n - 1 个元素增加 1。
示例:
输入:
[1,2,3]
输出:
3
解释:
只需要3次移动(注意每次移动会增加两个元素的值):
[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
'''
class Solution:
def minMoves1(self, nums) -> int: # 暴力破解法
count = 0
status = True
while status:
status = False
max_index = 0
max_value = None
for index, n in enumerate(nums):
if index == 0:
max_value = n
max_index = index
else:
if n > max_value:
max_value = n
nums[max_index] += 1
status = True
else:
if n < max_value:
status = True
nums[index] += 1
if status:
count += 1
return count
def minMoves(self, nums) -> int: # 除最值外加1,相当于最大值-1
# 计算最小值
min_value = min(nums)
count = 0
for n in nums:
count += n - min_value
return count
so = Solution()
print(so.minMoves([1, 2, 3]) == 3)
print(so.minMoves([1, 2, 3, 4]) == 6)
|
'''
551. 学生出勤记录 I
给定一个字符串来代表一个学生的出勤记录,这个记录仅包含以下三个字符:
'A' : Absent,缺勤
'L' : Late,迟到
'P' : Present,到场
如果一个学生的出勤记录中不超过一个'A'(缺勤)并且不超过两个连续的'L'(迟到),那么这个学生会被奖赏。
你需要根据这个学生的出勤记录判断他是否会被奖赏。
示例 1:
输入: "PPALLP"
输出: True
示例 2:
输入: "PPALLL"
输出: False
'''
class Solution:
def checkRecord(self, s: str) -> bool:
a_count = 0
l_count = 0
for val in s:
if val == "A":
a_count += 1
if a_count == 2:
return False
l_count = 0
elif val == "L":
if l_count:
l_count += 1
if l_count == 3:
return False
else:
l_count += 1
else:
l_count = 0
return True
so = Solution()
print(so.checkRecord("PPALLP") == True)
print(so.checkRecord("PPALLL") == False) |
'''
594. 最长和谐子序列
和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。
现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。
示例 1:
输入: [1,3,2,2,5,2,3,7]
输出: 5
原因: 最长的和谐数组是:[3,2,2,2,3].
说明: 输入的数组长度最大不超过20,000.
'''
class Solution:
def findLHS(self, nums) -> int: # hash法
has_dict = dict()
for num in nums:
if num in has_dict.keys():
has_dict[num] += 1
else:
has_dict[num] = 1
max_count = 0
for num in nums:
if num + 1 in has_dict.keys():
if has_dict[num] + has_dict[num + 1] > max_count:
max_count = has_dict[num] + has_dict[num + 1]
elif num - 1 in has_dict.keys():
if has_dict[num] + has_dict[num - 1] > max_count:
max_count = has_dict[num] + has_dict[num - 1]
return max_count
so = Solution()
print(so.findLHS([1, 3, 2, 2, 5, 2, 3, 7]) == 5)
|
'''
378. 有序矩阵中第K小的元素
给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第 k 小的元素。
请注意,它是排序后的第 k 小元素,而不是第 k 个不同的元素。
示例:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
返回 13。
提示:
你可以假设 k 的值永远是有效的,1 ≤ k ≤ n2
'''
from typing import List
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
# 暴力排序法
result = []
for ma in matrix:
result += ma
result.sort()
return result[k - 1]
|
'''
633. 平方数之和
给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c。
示例1:
输入: 5
输出: True
解释: 1 * 1 + 2 * 2 = 5
示例2:
输入: 3
输出: False
'''
class Solution:
def judgeSquareSum(self, c: int) -> bool: # 穷举法
has_in = set()
a = 0
while a * a <= c:
has_in.add(a * a)
a += 1
for ss in has_in:
if c - ss in has_in:
return True
return False
so = Solution()
print(so.judgeSquareSum(5) == True)
print(so.judgeSquareSum(3) == False) |
'''
977. 有序数组的平方
给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。
示例 1:
输入:[-4,-1,0,3,10]
输出:[0,1,9,16,100]
示例 2:
输入:[-7,-3,2,3,11]
输出:[4,9,9,49,121]
提示:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A 已按非递减顺序排序。
'''
from typing import List
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
sorta = []
sortb = []
for index, val in enumerate(A):
if val < 0:
sorta = [abs(val)] + sorta
else:
sortb = A[index:]
break
# 合并两个有序数列
result = []
start1, start2 = 0, 0
len1 = len(sorta)
len2 = len(sortb)
while start1 < len1 or start2 < len2:
if start1 < len1 and start2 < len2:
if sorta[start1] <= sortb[start2]:
result.append(sorta[start1] ** 2)
start1 += 1
else:
result.append(sortb[start2] ** 2)
start2 += 1
else:
if start1 < len1:
result.append(sorta[start1] ** 2)
start1 += 1
else:
result.append(sortb[start2] ** 2)
start2 += 1
return result
so = Solution()
print(so.sortedSquares([-4, -1, 0, 3, 10]) == [0, 1, 9, 16, 100])
print(so.sortedSquares([-7, -3, 2, 3, 11]) == [4, 9, 9, 49, 121])
|
'''
5415. 圆形靶内的最大飞镖数量 显示英文描述
墙壁上挂着一个圆形的飞镖靶。现在请你蒙着眼睛向靶上投掷飞镖。
投掷到墙上的飞镖用二维平面上的点坐标数组表示。飞镖靶的半径为 r 。
请返回能够落在 任意 半径为 r 的圆形靶内或靶上的最大飞镖数。
'''
class Solution:
def numPoints(self, points, r: int) -> int:
return 0
so = Solution()
print(so.numPoints([[-2, 0], [2, 0], [0, 2], [0, -2]], 2) == 4)
print(so.numPoints([[-3, 0], [3, 0], [2, 6], [5, 4], [0, 9], [7, 8]], 5) == 5)
print(so.numPoints([[-2, 0], [2, 0], [0, 2], [0, -2]], 1) == 1)
print(so.numPoints([[1, 2], [3, 5], [1, -1], [2, 3], [4, 1], [1, 3]], 2) == 4)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.