text
stringlengths 37
1.41M
|
---|
def counter(preffix, n):
some_lamb = lambda : None
for a in range(n):
yield some_lamb, a
for preffix, a in counter(preffix='buy', n=3):
print(preffix, a)
for preffix, a in counter(preffix='buy', n=3):
print(preffix, a)
|
# 3. Написать функцию, которая...
html = '''
<html>
<body>
<p>Some text..</p>
<ul id='some_list'>
<li>Ненужный элемент</li>
</ul>
<p>Some text..</p>
<ul id='menu'>
<li>Изделия</li>
<li>Функциональность</li>
<li>История</li>
<li>Конфигуратор</li>
</ul>
</body>
</html>
'''
# найдет в тексте html пункты меню и сделает список с их названиями
## +++
def find_menu( text ):
a_text = text.split()
for word in a_text:
if "li" in word and ( a_text.index( "id='menu'>" ) < a_text.index(word) > a_text.index( "</ul>" )):
print( word[4:-5] )
elif int( a_text.index( word )) > int(a_text.index( "id='menu'>" )):
break
find_menu( html )
|
# Функции
# Простая
def hello():
print('Hello!')
# Функция с аргументами
def hello(arg1, arg2, arg3):
pass # ничего не делает
hello(1, 2, 3)
# Функция с аргументами
def hello(arg1, arg2, arg3):
print('Hello:', arg1, arg2, arg3)
ret = hello(10, 20, 30)
print('ret:', ret)
# Функция с выводом
def hello(arg1, arg2, arg3):
print('Hello:', arg1, arg2, arg3)
return arg1 + arg2 + arg3
ret = hello(1, 0, 1)
print('ret:', ret)
hello(1, 2, 3, 4) # Error
hello(1, 0) # Error
# Функция с любым кол-вом аргументов
def hello(*args):
print('Hello:', args)
# args - получится кортежем (1, 2, 0)
hello(1, 2, 0)
# Распаковка args
def hello(*args):
print('Hello:', *args) # операция распаковки
hello(1, 2, 0)
def calc(a, b, operation):
if operation == '+':
return a + b
elif operation == '-':
return a - b
elif operation == '/':
# if b == 0:
# return None
return a / b
calc(100, 200, '+')
print( calc(100, 200, '-') ) # --> -100
calc(100, 0, '/') # ---> None
calc('Hello, ', 'Max!', '+')
# Проверка на тип переменной
if type(127) is str:
pass
|
a = 0
if a > 10:
a = -a
else:
a = a
a = 0
a = 'BOLSHE' if a > 10 else 'MENSHE'
print( a )
a = 20
a = a > 10 and 'BOLSHE' or 'MENSHE' # !!!
print( a )
|
# coding: utf-8
# 1. Исправить ошибки в этом программном коде
n = 0
def smart_task():
global n ## +
n += 1
print( 'start of smart_task #{}'.format(n) )
def other_task(param_1, param_2): ## ++
if param_1 == None:
return None
if param_2 == None:
return None
print("task {} start".format(other_task.__name__)) ## +
for p in param_1:
c = 0
for s in param_2:
if s == p:
c += 1
print ("{} count of {} is {}".format(p, str(c), param_2)) ## ++ str не нужно; вроде перепутаны?
print("task ", other_task.__name__," stop") ## +
smart_task()
smart_task()
other_task(('3', '4'), str(325543523))
smart_task()
|
# https://app.codility.com/demo/results/trainingVKJR3W-P6R/
def solution(A, B):
# write your code in Python 3.6
stack = []
N = len(A)
for fish in range(N):
if not stack:
stack.append(fish)
continue
prev_fish = stack[-1]
if B[fish] == B[prev_fish] or not B[prev_fish]:
stack.append(fish)
else:
while stack and B[stack[-1]]:
if A[fish] > A[stack[-1]]:
stack.pop()
else:
fish = -1
break
if fish >= 0:
stack.append(fish)
return len(stack)
|
import sqlite3
from _sqlite3 import Error
from _sqlite3 import OperationalError
import pandas as pd
from pandas import DataFrame
import os
import sys
"""
A program that can create a database if it does not already exist, creates tables with a specific format,
ability to import .csv files into tables if the formatting is the same as the created table, add single rows,
delete single rows and adjust quantities without having to use any SQL statements. Program was created as an
inventory management for supplies. Columns: Category, Product, Packaging, Volume_size, Quantity, And Expiration date
"""
def create_connection(db_file):
"""Creates connection to database
returns error if no connection is established"""
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
print(e)
return conn
def create_new_db(path):
"""Creates a new database at given location"""
conn = sqlite3.connect(path)
conn.commit()
conn.close()
def show_all_data(conn, table):
"""Displays all data in a given table, columns wrap, difficult to read"""
pd.set_option("display.max_rows", None)
pd.set_option("display.max_columns", None)
c = conn.cursor()
c.execute("""SELECT * FROM '{0}'""".format(table))
df = DataFrame(c.fetchall(), columns=['Category', 'Product', 'Packaging', 'Volume_Size', 'Quantity', 'EXP'])
return print(df)
def print_data(conn, table):
"""Displays all rows in the given table, only shows Product, Quantity, and EXP"""
pd.set_option('display.max_rows', None)
c = conn.cursor()
c.execute("""SELECT Product, QUANTITY, EXP FROM '{0}'""".format(table))
df = DataFrame(c.fetchall(), columns=["Product", "Quantity", "EXP"])
return print(df)
def show_tables(conn):
"""Displays all tables in the database"""
c = conn.cursor()
c.execute("""SELECT name FROM sqlite_master
WHERE type='table'
ORDER BY name""")
df = DataFrame(c.fetchall(), columns=["name"])
return print(df)
def check_tables(conn, table):
"""Checks to see if a table is in the database, if not returns error"""
c = conn.cursor()
c.execute("""SELECT name FROM "main".sqlite_master where name = '{0}'""".format(table))
if len(c.fetchall()) > 0:
return True
else:
raise ValueError
def make_table(conn, table_name):
"""Creates a new table with the columns predefined for the inventory management"""
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS {0} (
"Category" TEXT NOT NULL,
"Product" TEXT NOT NULL,
"Packaging" TEXT,
"Volume_Size" TEXT,
"Quantity" INTEGER,
"EXP" INTEGER)
""".format(table_name))
conn.commit()
print_data(conn, table_name)
def drop_table(conn, table):
"""Drops a selected table"""
c = conn.cursor()
c.execute("""DROP TABLE {0}""".format(table))
conn.commit()
show_tables(conn)
def csv_insert(conn, file, table):
"""Fills a table from a .csv file"""
c = conn.cursor()
read_clients = pd.read_csv(r"{}".format(file)) # CSV FIle
read_clients.to_sql('{}'.format(table), conn, if_exists='append', index=False)
c.execute("""INSERT INTO {0} (CATEGORY, PRODUCT, PACKAGING, VOLUME_SIZE, QUANTITY, EXP)
SELECT CATEGORY, PRODUCT, PACKAGING, VOLUME_SIZE, QUANTITY, EXP
FROM {1}""".format(table, table))
conn.commit()
print_data(conn, table)
def add_item(conn, table):
"""Adds a single item into a given table"""
c = conn.cursor()
category = input('Category? ')
product = input('Product? ')
packaging = input('Packaging? ')
volume_size = input('Volume or size? ')
quantity = input('Quantity? ')
exp = input('Expiration date in Year, Month, Day? ')
c.execute("""Insert into '{0}' (CATEGORY, PRODUCT, PACKAGING, VOLUME_SIZE, QUANTITY, EXP)
VALUES ('{1}', '{2}', '{3}', '{4}', '{5}', '{6}')""".format(table, category, product, packaging,
volume_size, quantity, exp))
conn.commit()
print_data(conn, table)
def remove_item(conn, table, item):
"""Removes a single item from a table, using the Product column"""
c = conn.cursor()
c.execute("""DELETE FROM '{0}' WHERE PRODUCT = '{1}'""".format(table, item))
conn.commit()
print_data(conn, table)
def adjust_quantity(conn, table, item, quantity):
"""Updates the Quantity of a given product in a given table"""
c = conn.cursor()
c.execute("""UPDATE {0} SET Quantity = '{1}' WHERE Product = '{2}' """.format(table, quantity, item))
conn.commit()
print_data(conn, table)
def find_db():
"""First scans directory where the program resides, if none is found asks for another location. If no
other database is present one is able to be created"""
db = None
while not db:
try:
with os.scandir(os.getcwd()) as it:
for entry in it:
if entry.name.endswith('.db'):
db = os.path.join(os.getcwd(), entry.name)
return db
else:
raise FileExistsError
except FileExistsError:
print("No database found here")
new_db = input("Is there another location for \n"
"existing database? (Yes, No)\n"
"or exit\n").lower()
if "no" in new_db:
create_db = input("Database path and name?\n"
"ex: /Users/user/Desktop/test.db\n")
create_new_db(create_db)
db = create_connection(create_db)
return db
elif "yes" in new_db:
existing_db = input("Path of existing Database?\n")
if existing_db.endswith(".db") and os.path.exists(existing_db):
db = existing_db
return db
elif "exit" in new_db:
sys.exit()
break
def __main__():
database = None
while not database:
database = find_db()
if database:
break
session = True
conn = create_connection(database)
while session:
try:
print("You are working in {} Database!".format(database.rsplit('/', 1)[1])) # if working in windows change to .rsplit('\\'...)
process = input("What would you like to do?\n"
"* Note, phrases must be typed exactly *\n\n"
"Make a new table?\n"
"Insert file into table?\n"
"Insert single item?\n"
"Adjust Quantity?\n"
"Remove item?\n"
"Show all tables?\n"
"Print table contents?\n"
"Remove table?\n"
"or exit?\n").lower()
if process == "make a new table":
table_loop = True
while table_loop:
try:
print("Current Tables:")
show_tables(conn)
new_table = input("What is the name of the new table?\n")
make_table(conn, new_table)
table_loop = input("Finished adding tables?\n").lower()
if "yes" in table_loop:
break
except OperationalError:
print("Something went wrong, lets try that again!")
if process == "remove table":
remove_table_loop = True
while remove_table_loop:
try:
show_tables(conn)
rmv_table = input("What table are we removing?\n")
if check_tables(conn, rmv_table):
drop_table(conn, rmv_table)
remove_table_loop = input("Finished removing tables?\n").lower()
if "yes" in remove_table_loop:
break
except OperationalError:
print("Something went wrong, lets try that again!")
if process == "insert file into table":
insert_loop = True
while insert_loop:
try:
file_loc = input("What is the path of the .csv file?\n")
if (file_loc.endswith(".csv") and os.path.exists(file_loc)):
show_tables(conn)
tbl = input("Which table do you want to import file to?\n")
if check_tables(conn, tbl):
csv_insert(conn, file_loc, tbl)
insert_loop = input("Finished importing files?\n").lower()
if "yes" in insert_loop:
break
else:
raise FileNotFoundError
except FileNotFoundError:
print("File not found or not .csv\n"
"Please try again!\n")
except OperationalError:
print("Table not found in Database, please try again!")
if process == "insert single item":
single_add_loop = True
while single_add_loop:
try:
show_tables(conn)
insert_item_table = input("What Table would you like to add to?\n")
if check_tables(conn, insert_item_table):
add_item(conn, insert_item_table)
single_add_loop = input("Finished add items?\n").lower()
if "yes" in single_add_loop:
break
except OperationalError:
print("Table not found in Database, or value incorrect type.\n"
"Please try again!")
except ValueError:
print("Table not in database")
if process == "adjust quantity":
adjust_loop = True
while adjust_loop:
try:
show_tables(conn)
adj_table = input("What table is the product in?\n")
print_data(conn, adj_table)
adj_item = input("What item are we adjusting?\n")
adj_quantity = input("What is the new quantity?\n")
if check_tables(conn, adj_table):
adjust_quantity(conn, adj_table, adj_item, adj_quantity)
adjust_loop = input("Finished adjusting items?\n").lower()
if 'yes' in adjust_loop:
adjust_loop = False
break
except OperationalError:
print("Something went wrong, please try again!")
if process == "remove item":
rmv_itm_loop = True
while rmv_itm_loop:
try:
show_tables(conn)
rmv_itm_table = input("What table is the item in?\n")
print_data(conn, rmv_itm_table)
item = input("What item are we removing?\n"
"* (If item is not in list no error will show) *\n")
if check_tables(conn, rmv_itm_table):
remove_item(conn, rmv_itm_table, item)
rmv_itm_loop = input("Finished deleting items?\n")
if "yes" in rmv_itm_loop:
break
except OperationalError:
print("Table not found in Database, or value incorrect type.\n"
"Please try again!")
except ValueError:
print("Item not in table")
if process == "show all tables":
show_tables(conn)
if process == "print table contents":
show_tables(conn)
print_table = input("What table do you want to see?\n")
show_all_data(conn, print_table)
if process == "exit":
conn.close()
sys.exit()
session = input("Are you finished with Database {}?\n".format(database.rsplit('/', 1)[1]))
if 'yes' in session:
break
except (FileNotFoundError, FileExistsError):
print("Something went wrong, please try again!")
if __name__ == "__main__":
__main__()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 13 22:48:56 2017
@author: christophergreen
Square digit chains
Problem 92
A number chain is created by continuously adding the square of the digits in a number to form a
new number until it has been seen before.
For example,
44 → 32 → 13 → 10 → 1 → 1
85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89
Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most
amazing is that EVERY starting number will eventually arrive at 1 or 89.
How many starting numbers below ten million will arrive at 89?
"""
#import math
def process(x):
count=0
output=0
for i in str(x):
output+=int(i)**2
count+=1
return output
def untilHits(m):
x=m
counter=0
while x!=1:
x=process(x)
counter+=1
if x==89:
#print(m,"became 89 after",counter,"loops")
return m
#print(m,"became 1 after",counter,"loops")
def main(maximum):
outcount=0
j=1
while j<maximum:
if j%100000==0:
print("passing through j being",j,"so there's another hundred thousand")
if untilHits(j)==j:
outcount+=1
j+=1
print("number of ints below",maximum,"that work out to 89 is",outcount)
return outcount
main(10**7) #--> 8581146 CORRECT
|
# 2_CharStrCount.py
# by Prometheus111
# for a given string, calculate the number of occurrences of a character in it
# that is read from the keyboard
s = 'Here is your own text!' #we have the string s
print(s) #output the string s
a = input('Input the character: ')
n = 0
for i in s: #checking each character in a string
if i == a: #if the character is in the string
n += 1 #count it
else: #if the character isn't in the string
pass #do nothing
if n >= 1: #if found
print('The character "%s" occurs in the string %d times' % (a, n))
else: #if not found
print('The character "%s" in the string does not occur' %a)
# Enjoy learning new things!
# https://github.com/Prometheus111
|
def add(x, y):
#code
output = (x + y)
return output
def subtract(x, y):
#code
output = (x - y)
return output
def multiply(x, y):
#code
def divide(x, y):
#code
def power(x, y):
#code
output = (x ** y)
return output
#User input
#Calculator logic
#Output
|
# This program will implement an FSA to accept the string "ABACCB".
word = input("Enter a string: ") #Asks the user to input a string
state = 1
for c in (word):
if state == 1 and c == 'C':
state = 1
elif state == 1 and c == 'A':
state = 2
elif state == 2 and c == 'B':
state = 3
elif state == 2 and c == 'A':
state = 1
elif state == 3 and c == 'A':
state = 4
elif state == 4 and c == 'A':
state = 4
elif state == 4 and c == 'B':
state = 3
elif state == 4 and c == 'C':
state = 5
elif state == 5 and c == 'C':
state = 6
elif state == 6 and c == 'A':
state = 5
elif state == 6 and c == 'B':
state = 7
elif state == 6 and c == 'C':
state = 6
elif state == 7 and c == 'C':
state = 5
elif state == 7 and c != 'C':
state = 8
else:
state = 8
if state == 7:
print ("True.")
print ("Goodbye.")
else:
print ("False.")
print ("Goodbye.")
|
def two_to_one(two_tuple, width) -> int:
"""map 2-space to 1-space
"""
x, y = two_tuple
return width * x + y + 1
def one_to_two(n, width) -> (int, int):
"""map 1-space to 2-space
"""
return (n//width - int(n % width == 0), (n - 1) % width)
def find_neighbors(index, width, height, pixels, reach) -> list:
"""find all neighbors
1) map point in 1-space to 2-space
2) add all possible combinations of offsets <= reach
to compute a pixels "neighborhood"
3) map the neighborhood back to 1-space and find the pixel value
at each index.
"""
x, y = one_to_two(index, width)
neighborhood = set() # lazy way to filter duplicates
# generate neighborhood - set of all neighbors.
for i in range(0, reach+1):
for j in range(0, reach+1):
neighborhood.add((x-i, y+j))
neighborhood.add((x+i, y-j))
neighborhood.add((x-i, y-j))
neighborhood.add((x+i, y+j))
# filter impossible neighbors
neighborhood = [(i,j) for i,j in neighborhood if 0 <= i < height and 0 <= j < width]
# map 2-tuples back to integers, subtract 1 to create valid indicies.
neighborhood = [two_to_one((i,j), width) - 1 for i,j in neighborhood]
# find pixel value of each neighbor
return [pixels[i] for i in neighborhood]
def median(arr):
"""sort array with mergesort, then calculate the median
improvements:
1) for len(arr) <= 20 insertion sort might be faster; idk worth testing.
for instance the reach parameter in denoise is greter than 2 maybe stick
with merge.
2) the code given in the assignment arr[len(arr)//2] only computes the median
for lists with odd lengths. The following function correctly
calculates the median for even and odd length lists.
"""
merge_sort(arr)
return (arr[len(arr)//2] + arr[len(arr)//2 - int(len(arr) % 2 == 0)])/2
def merge_sort(arr):
if len(arr) > 1:
# Finding middle of input list
m = len(arr)//2
# Bifurcate input list
L, R = arr[:m], arr[m:]
# Sort each half recursively
merge_sort(L)
merge_sort(R)
i, j, k = 0, 0, 0
# Copy elements from arr to L & R
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Final while loops check for leftover elements.
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
def denoise_image(pixels, width, height, reach = 2, beta = 0.2):
"""if abs(original - median) / (original + 0.1) > beta, replace pixel
***
this function assumes pixels has been transformed prior to invokation
[i,i,i ...] -> [i, ...]
remove redundancy in pixel list.
"""
from copy import deepcopy
new_pixels = deepcopy(pixels)
for i in range(len(pixels)):
neighbors = find_neighbors(i, width, height, pixels, reach)
med = median(neighbors)
if abs(pixels[i] - med)/ (pixels[i]+ 0.1) > beta:
new_pixels[i] = med
return new_pixels
def create_pixels(read_this):
"""
improvements:
- when opening a file use the with keyword.
adds error handling & auto closes file.
- no need to read all 3 integers from each line,
because image in black & white the rgb channels
all have the same value. Reading all 3 values
triples your memory requirement.
"""
f = open(read_this, 'r')
p3 = f.readline()
pixel_list = []
while True:
line = f.readline()
if line == '':
break
line_list = line.split()
for pix_str in line_list:
pixel_list.append(int(pix_str))
f.close()
return pixel_list
def test():
name = "cat.ppm"
data = create_pixels(name)
width, height, maxval = data[0:3]
pixels = data[3:]
# reduce the pixel list, we only need 1 channel.
r_pixels = [pixels[i] for i in range(0, len(pixels), 3)]
print(width, height, maxval)
new_pixels = denoise_image(r_pixels, width, height)
print("new: ",new_pixels)
if __name__ == "__main__": test()
|
#!/usr/bin/env python
# -*-coding:utf-8-*-
#time : 2020-02-21
#@Author : limeng
#@Email : [email protected]
#@Note : 类似黑客帝国的代码雨效果
#导入系统文件库
import pygame
import random
from pygame.locals import *
from random import randint
#定义窗体参数及加载字体文件
SCREEN_WIDTH = 900 #窗体宽度
SCREEN_HEIGHT = 600 #窗体高度
LOW_SPEED = 4 #字体移动最低速度
HIGH_SPEED = 10 #字体移动最快速度
FONT_COLOR =(00,150,00)#字体颜色
FONT_SIZE = 5 #字体尺寸
FONT_NUM = 20 #显示字体数量
FONT_NAME = "calibrii.ttf" #注意字体的文件名必须和真实文件完全相同(注意大小写,文件名不能是中文)
FREQUENCE = 10 #时间频度
times = 0 #初始化时间
#定义随机参数
def randomspeed():
return randint(LOW_SPEED,HIGH_SPEED)
def randomposition():
return randint(0,SCREEN_WIDTH),randint(0,SCREEN_HEIGHT)
def randomname():
return randint(0,10000)
def randomvalue():
return randint(0,100)
class Word(pygame.sprite.Sprite):
def __init__(self,bornposition):
pygame.sprite.Sprite.__init__(self)
self.value = randomvalue()
self.font = pygame.font.Font(FONT_NAME,FONT_SIZE)
self.image = self.font.render(str(self.value),True,FONT_COLOR)
self.speed = randomspeed()
self.rect = self.image.get_rect()
self.rect.topleft = bornposition
def update(self):
self.rect = self.rect.move(0,self.speed)
if self.rect.top > SCREEN_HEIGHT:
self.kill()
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
pygame.display.set_caption('ViatorSun CodeRain')
clock = pygame.time.Clock()
group = pygame.sprite.Group()
group_count = int(SCREEN_WIDTH / FONT_NUM)
#mainloop
while True:
time = clock.tick(FREQUENCE)
for even in pygame.event.get():
if even.type == QUIT :
pygame.quit()
exit()
screen.fill((0,0,0))
for i in range(0,group_count):
group.add(Word((i*FONT_NUM,-FONT_NUM)))
group.update()
group.draw(screen)
pygame.display.update()
|
import time
class Solution:
#n = input('please write your number:')
def happynumber(self,n:int):
unhappy = set()
while n not in unhappy and n != 1:
unhappy.add(n)
n = self.GetSqureSum(n)
print(unhappy)
#return n == 1
def GetSqureSum(self,n:int):
sum1 = 0
while n > 0:
#获取尾数,/和int()都能用来获取整数位
r = n - (int(n/10)*10)
#获取第一个数字,这个n最后带入r中,int(5/10)=0
n = int(n/10)
sum1 += r*r
#print(sum1)
return sum1
#GetSqureSum(52)
m = input('please write number:')
m = int(m)
start_time = time.time()
print('程序开始时间:{}'.format(start_time))
sol = Solution()
sol.happynumber(m)
end_time = time.time()
print('程序结束时间:{}'.format(end_time))
total_time = end_time-start_time
print('程序运行时间:{}'.format(total_time))
|
import csv
import math
# from operator import add
'''
readAllSamples is a user defined function. It is used to read all the sample of CSV file. It takes filename as an argument as well as test row count to make a test set from the file. This function returns a train set and a test set.
'''
def readAllSamples(fileName, test_row_count, Del_colm):
ff1 = csv.reader(fileName)
b = []
a = []
g = []
headers = []
for row in ff1:
b.append(row)
# print(b)
# print(len(b))
for i in range(Del_colm, len(b[0])):
headers.append(b[0][i])
# print(h)
for i in range(1, len(b)):
g.append(b[i])
# print(g)
for i in range(len(g)):
a.append(g[i][Del_colm:(len(g) - 1)])
# print("\n",a)
# print(len(a))
trainSet = []
testSet = []
for i in range(0, (len(a) - test_row_count)):
trainSet.append(a[i])
for i in range((len(a) - test_row_count), len(a)):
testSet.append(a[i])
return trainSet, testSet, headers
f1 = open("Book1.csv", newline='')
test_row = int(input("please provide how many rows you want as test set\n"))
Del_colm = int(input(
"is there any column you want to exclude during gain calculation? if any, please provide column number, otherwise please provide Zero(0) \n"))
train_set, test_set, headers = readAllSamples(f1, test_row, Del_colm)
'''
This is entropy function. It takes table as input and finds out entropy.
'''
def entropy(table):
decision_attribute = []
for i in range(len(table)):
decision_attribute.append(table[i][len(table[0]) - 1])
set_decision_attribute = list(set(decision_attribute))
decision_attribute_count = []
for i in range(len(set_decision_attribute)):
decision_attribute_count.append(decision_attribute.count(set_decision_attribute[i]))
entropy = 0
for i in range(len(set_decision_attribute)):
if (len(set_decision_attribute)) == 1:
entropy = 0
else:
entropy += (-1) * (decision_attribute_count[i] / sum(decision_attribute_count)) * math.log2(
(decision_attribute_count[i] / sum(decision_attribute_count)))
return entropy
'''
informationGain is an user defined function. it takes table, the attribute for which we want to find out entropy and total entropy of the table as input. It returns gain of the attribute.
'''
def informationGain(table, attribute, total_entropy):
table_len = len(table)
att = []
decision_attribute = []
for i in range(len(table)):
decision_attribute.append(table[i][len(table[i]) - 1])
att.append(table[i][attribute])
set_att = list(set(att))
att_count = []
for i in range(0, len(set_att)):
att_count.append(att.count(set_att[i]))
merge_att = []
merge_att_dec = []
header_count = len(set_att) + 1
header = [[] for i in range(1, header_count)]
for j in range(len(set_att)):
for i in range((len(att))):
if att[i] == set_att[j]:
merge_att.append(att[i])
merge_att_dec.append(decision_attribute[i])
new = [[a, merge_att_dec[ind]] for ind, a in enumerate(merge_att)]
entropy_list_attr = []
for j in range(len(set_att)):
for i in range((len(new))):
if new[i][0] == set_att[j]:
header[j].append(new[i])
entropy_list_attr.append(entropy(header[j]))
entropy_att = 0
for i in range(len(set_att)):
entropy_att += ((att_count[i] * entropy_list_attr[i]) / sum(att_count))
gain = total_entropy - entropy_att
return gain
# Finding out column of maximum gain
def gainMatrix(train_set, total_entropy):
gain = []
for i in range(len(train_set[0]) - 1):
gain.append(informationGain(train_set, i, total_entropy))
max_gain_column = gain.index(max(gain))
# print(gain)
# print(train_set)
return max_gain_column
# This function split data and create tree.
def splitData(train_set, max_gain_column, headers, counter):
set_max_gain_column = []
for i in range(len(train_set)):
set_max_gain_column.append(train_set[i][max_gain_column])
set_max_gain_column = list(set(set_max_gain_column))
# print(set_max_gain_column)
new_train_set = []
child_root_gain = []
child = [[] for i in range(len(set_max_gain_column))]
for j in range(len(set_max_gain_column)):
for i in range(len(train_set)):
if (train_set[i][max_gain_column] == set_max_gain_column[j]):
child[j].append(train_set[i])
# print(child)
# print(child)
k = counter
ent = []
for i in range(len(child)):
ent.append(entropy(child[i]))
# print(ent)
child, ent = zip(*sorted(zip(child, ent)))
# print(child)
# print(ent)
# qq=sorted(set(child), key=child.index)
# print(qq)
# k=k+1
for i in range(len(child)):
root_child_entropy = entropy(child[i])
max_gain_column = gainMatrix(child[i], root_child_entropy)
if root_child_entropy == 0:
# print("root _child node will be col", set_max_gain_column, "& element count will be", len(child[i]) )
# max_gain_column=gainMatrix(child[i], root_child_entropy)
# print(child[i])
# print(max_gain_column)
print(
"For {} {}, decision will be {}".format(headers[k], child[i][0][k], child[i][0][len(child[i][0]) - 1]))
else:
k = gainMatrix(child[i], root_child_entropy)
# print("k",k)
print("child_root will be {} ".format(headers[max_gain_column]))
# print(child[i])
splitData(child[i], max_gain_column, headers, k)
# pass
# print(child[i])
# for i in range(len(child[i][0][max_gain_column])):
# splitData(child[i], max_gain_column,headers,k)
# splitData.counter+=1
# print(splitData.counter)
# print(k)
return child
total_entropy = entropy(train_set)
# print('Total entropy\n',total_entropy)
xx = gainMatrix(train_set, total_entropy)
print("root will be {}".format(headers[xx]))
counter = 0
pp = splitData(train_set, xx, headers, counter)
# the end
|
import turtle
class TurtleInstance(turtle.Turtle):
def __init__(self, name="", color="black"):
turtle.Turtle.__init__(self)
self.setName(name)
self.setColor(color)
self.speed(0)
self.penup()
pass
def setName(self,name):
self.name = name
def setColor(self,color):
self.pencolor(color)
if __name__ == '__main__':
t = TurtleInstance()
t.forward(50)
turtle.mainloop()
|
a = 3
b = 5
b = a + b
print(b)
x = 4
y = 5
z = x / y #use the / to get the output in floating point
print(z)
print(5 // 4) #use the // to get the output in int
print(2 ** 3)
print(7 % 2)
print(x + 3j) #Complex data type which means real + imaginary numbers
print("Dividing 4 by 3 using Integer division(4//3): ", 4 // 3)
print("Dividing 4 by 3 using Floating division:(4/3): ", 4 / 3)
|
print("Hello!")
i = 10
f = 0.10
s = "Hi There"
i1 = 99999999999999999999999999999
f1 = -0.00000000000000000000000000111111111
c = 'j1'
print(c)
print(f1, i1)
name = input("Enter your name: ")
print(name)
age = (int)(input("Enter the age: "))
print(age)
investment = (float)(input("Enter the amount to be invested: "))
print(investment)
print(type(age))
print(type(f1))
print("data type of variable i1: ", type(i1))
print("data type of variable i: ", type(i))
print("data type of variable f: ", type(f))
print("data type of variable c: ", type(c))
keyboard = input("Enter the type of the keyboard: ")
print(keyboard)
|
# URL: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
# Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
# (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
# Find the minimum element.
# You may assume no duplicate exists in the array.
# Example 1:
# Input: [3,4,5,1,2]
# Output: 1
# Example 2:
# Input: [4,5,6,7,0,1,2]
# Output: 0
def find_min(nums):
min_res = nums[0]
for i,val in enumerate(nums, start=1):
if val < min_res:
min_res = val
return min_res
def find_min_bst(nums):
start = 0
end = len(nums)
min_res = None
while start <= end:
midpt = int((start + end) / 2)
cur_val = nums[midpt]
# print('start: {} end: {} midpt: {} cur_val: {}'.format(start, end, midpt, cur_val))
if midpt in (0, len(nums) - 1): # [4,2] (0,2) [2,3,4,5,6]
return cur_val
prev_val = nums[midpt - 1]
after_val = nums[midpt + 1]
if after_val < cur_val:
return after_val
if prev_val > cur_val:
return cur_val
if nums[0] < cur_val:
# Check left
end = midpt
else:
# Check right
start = midpt + 1
# arr = [5,6,7,3,4]
arr = [1,2,3,4,5]
min_res = find_min_bst(arr)
print(min_res)
|
day = (input("Enter the day the call started at:"))
time = float(input("Enter the time the call started at (hhmm):"))
minutes = float(input("Enter the duration of the call (in minutes):"))
if day == "mon" or \
day == "tue" or \
day == "wed" or \
day == "thu" or \
day == "fri" or \
day == "Mon" or \
day == "Tue" or \
day == "Wed" or \
day == "Thu" or \
day == "Fri":
weekday = 1
if weekday == 1 and \
800 <= time <= 1800:
rate = 0.4
output = rate * minutes
output = "{:,.2f}".format(output)
print("This call will cost $", output, sep="")
else:
rate = 0.25
output = rate * minutes
output = "{:,.2f}".format(output)
print("This call will cost $", output, sep="")
# For Weekdays Saturday and Sunday
if day == "sat" or\
day == "sun" or \
day == "Sat" or \
day == "Sun":
rate = 0.15
output = rate * minutes
output = "{:,.2f}".format(output)
print("This call will cost $", output, sep="")
|
print("Please enter the amount of money to convert: ")
dollar = int(input("# of Dollars: ")) * 100
cents = int(input("# of cents: "))
total = (dollar + cents) / 100
quarters = total // .25
r1 = (total - (quarters * .25))
dimes = r1 // 0.1
r2 = (r1 - (dimes * 0.1))
nickels = (r2 // .05)
r3 = (r2 - (nickels * .05))
pennies = r3 * 100
p = "{:.1f}".format(pennies)
print("the coins are", quarters, "Quarters,", dimes, "Dimes,",
nickels, "Nickels and", p, " pennies")
|
class MinimaxAgent(MultiAgentSearchAgent):
"""
Your minimax agent (question 1)
"""
def getAction(self, game_state):
"""
Returns the best minimax action from the current game_state using
self.depth and self.evaluationFunction.
Here are some method calls that are useful when implementing minimax.
game_state.getLegalActions(agent):
Returns a list of legal actions for an agent
agent=0 means Pacman, ghosts are >= 1
game_state.generateSuccessor(agent, action):
Returns the successor game state after an agent takes an action
game_state.getNumAgents():
Returns the total number of agents in the game
game_state.isWin(): Returns True if this is a terminal winning state
game_state.isLose(): Returns True if this is a terminal losing state
"""
"*** YOUR CODE HERE ***"
v = - sys.maxint #low minimax value
best_action = 'None' #low action
for action in game_state.getLegalActions(0): #loop thru actoion find minimax for right node
suc = self.value(game_state.generateSuccessor(0, action), 1, 1)
if suc > v:
v = suc
best_action = action
return best_action
def value(self, game_state, agent, current_depth):
# type: (object, object, object) -> object
""" Returns the minimax value of any state"""
"*** YOUR CODE HERE ***"
#updates current depth
if game_state.isWin() or game_state.isLose() or current_depth > self.depth : #checks for terminal state or non
return self.evaluationFunction(game_state)
if agent == 0: #checks if agent is pacman to use minimax
return self.max_value(game_state, current_depth)
else: #else uses min agent
return self.min_value(game_state, agent, current_depth)
def max_value(self, game_state, current_depth):
# type: (object, object) -> object
"""Returns the minimax value of a state under Pacman's control (max)"""
"*** YOUR CODE HERE ***"
v = -sys.maxint
actions = game_state.getLegalActions(0)
for action in actions: #loops thru actions to find minimax of root for pacman
v = max(v, self.value(game_state.generateSuccessor(0, action), 1, current_depth))
return v
def min_value(self, game_state, agent, current_depth):
"""Returns the minimax value of a state under a ghost's control (min)"""
"*** YOUR CODE HERE ***"
v = sys.maxint
next_agent = (agent + 1)% game_state.getNumAgents()
if next_agent == 0:
current_depth += 1
actions = game_state.getLegalActions(agent)
for action in actions:#loops thru actions to find mini of root for ghosts
v = min(v, self.value(game_state.generateSuccessor(agent, action), next_agent, current_depth))
return v
class AlphaBetaAgent(MultiAgentSearchAgent):
"""
Your minimax agent with alpha-beta pruning (question 2)
"""
def getAction(self, gameState):
"""
Returns the best minimax action from the current game_state using
self.depth and self.evaluationFunction.
"""
"*** YOUR CODE HERE ***"
v = -sys.maxint
best_action = 'None'
alpha = -sys.maxint #updates alpha
beta = sys.maxint
for action in gameState.getLegalActions(0): #loops thru actions finds best action related to sucessor
suc = self.value(gameState.generateSuccessor(0, action), 1, 1, alpha, beta)
if suc > v:
alpha = -sys.maxint
v = suc
best_action = action
return best_action
def value(self, game_state, agent, current_depth, alpha, beta):
""" Returns the minimax value of any state"""
"*** YOUR CODE HERE ***"
if game_state.isWin() or game_state.isLose() or current_depth > self.depth: #checks if it exceed depths
return self.evaluationFunction(game_state)
if agent == 0:
return self.max_value(game_state, current_depth, alpha, beta)
else:
return self.min_value(game_state, agent, current_depth, alpha, beta)
def max_value(self, game_state, current_depth, alpha, beta):
"""Returns the minimax value of a state under Pacman's control (max)"""
"*** YOUR CODE HERE ***"
v = -sys.maxint
actions = game_state.getLegalActions(0)
for action in actions: #uses alpha and beta to use pruning
v = max(v, self.value(game_state.generateSuccessor(0, action), 1, current_depth, alpha, beta))
if v >= beta:
return v
alpha = max(alpha, v)
return v
def min_value(self, game_state, agent, current_depth, alpha, beta):
"""Returns the minimax value of a state under a ghost's control (min)"""
"*** YOUR CODE HERE ***"
v = sys.maxint
next_agent = (agent + 1) % game_state.getNumAgents()
if next_agent == 0:
current_depth += 1
actions = game_state.getLegalActions(agent)
for action in actions:
v = min(v, self.value(game_state.generateSuccessor(agent, action), next_agent, current_depth, alpha, beta))
if v <= alpha:
return v
beta = min(beta, v)
return v
|
# snehal shilvant
# a_55
# tuple
Weights = (70, 80, 45, 50)
print(Weights)
# tuple "Weights" Cant be be modified because tuples are immutable.
Weights_New = (70,80, 48, 50)
print(Weights_New)
Maximum_variable = max(Weights_New)
Minimum_variable = min(Weights_New)
print("Maximum variable is:", Maximum_variable)
print("Minimum Variable is:", Minimum_variable)
sum = sum(Weights_New)
No_of_elements = len(Weights_New)
print("sum is:", sum)
Mean = sum/No_of_elements
print("Mean is:", Mean)
|
# snehal Shilvant
# A-55
# day 4 Problem stmt 3
list = [1, 2, 3,1, (1,3), [1,3], {1,3}, {1,3}, [1,3], [1,3], (1,3), {1,3}, (1,3), {1,3},[1,3],{1,3}]
print(list)
print("list of 1 is :", list.count(1))
print("list of 2 is :", list.count(2))
print("list of 3 is:", list.count(3))
print("list of list is :", list.count([1,3]))
print("list of dictionary is:", list.count({1,3}))
print("list of tuple is:", list.count((1,3)))
|
fruit = {"apple" : 5, "pear" : 3, "banana" : 4, "pineapple" : 1, "cherry" : 20}
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' }
dict.update(dict2)
print ("Value : %s" % dict)
|
import math
import sys
# variável para determinar em qual menu o usuário estará
comando = 0
# mensagem inicial de boas vindas
print('Bem-vindo ao Sistema de Mercadinho!\n')
# função para exibir o menu inicial
def mostrar_menu():
print('1. Inciar uma nova compra')
print('2. Adicionar produto ao catálogo')
print('3. Remover produto do catálogo')
print('4. Sair do programa')
# pega o input do usuário com o valor desejado
comando = int(input('\nSelecione uma opção digitando um número: '))
# envia o valor para a função valida_input
valida_input(comando)
# função para terminar a aplicação
def sair():
print('\nDeseja sair da aplicação?')
comando = int(input("Digite '0' para sair ou '1' para cancelar e voltar ao menu: "))
if (comando == 0):
sys.exit() # termina a aplicação
else:
mostrar_menu()
# função que verifica qual o input dado pelo usuário e exibe o menu correspondente
def valida_input(valor):
import compra
import catalogo
if (valor == 0):
mostrar_menu()
elif (valor == 1):
compra.compra()
elif (valor == 2):
catalogo.adicionar_produto()
elif (valor == 3):
catalogo.remover_produto()
elif (valor == 4):
sair()
# exibe inicialmente o menu
mostrar_menu()
|
import file_handler
class Dictionary:
@staticmethod
def word_search(word_dict, word_search):
for key, value in word_dict.items():
if word_search == key:
print(value)
def main():
'''
Creates a Dictionary object, calls load_data to populate dictionary from
a file. Allows user to search for words and returns their definition.
'''
jdict_ = Dictionary()
print(f"Enter the name of the file you would like to open")
file_path = input(">")
jdict_ = file_handler.FileHandler.load_data(file_path)
search_word = ""
print(f"Enter a word you would like to search the definition for, enter quitprogram to quit")
while search_word != 'quitprogram':
search_word = input(">")
Dictionary.word_search(jdict_, search_word.lower())
if search_word.lower not in jdict_:
Dictionary.word_search(jdict_, search_word.upper())
else:
print("Sorry we don't have that definition")
if __name__ == '__main__':
main()
|
from card import *
from wallet import *
def main():
'''
main controller class. Runs user through main menu and allows them to call
wallet methods to modify the wallet
:return:
'''
cards_ = generate_card_slots()
wallet = Wallet(cards_)
user_input = None;
while user_input != "q":
print("Welcome to your wallet!")
print(f"Enter 'add' to add a card to your wallet")
print(f"Enter 'remove' to remove a card from your wallet")
print(f"Enter 'display' to view your wallet")
print(f"Enter 'search' to search your wallet for a specific card")
print(f"Enter 'save' to save your wallet to a file")
print(f"Enter 'q' to exit")
user_input = input('>')
user_input = user_input.casefold()
if user_input == 'add':
wallet.add_card()
elif user_input == 'remove':
user_query = None
print("Please enter the nickname of the card you would like to remove")
user_query = input('>')
wallet.remove_card(user_query)
elif user_input == 'display':
print(f"Enter 'Credit' to view all Credit Cards")
print(f"Enter 'Debit' to view all Debit Cards")
print(f"Enter 'Loyalty' to view all Loyalty Cards")
print(f"Enter 'Business' to view all Business Cards")
print(f"Enter 'ID' to view personal ID cards")
print(f"Enter 'Other' to view all other cards")
print(f"Leave blank if you just want to see the entire wallet")
user_input = input(">")
user_input = user_input.casefold()
if user_input == 'credit':
wallet.display_wallet_by_type(CreditCard)
input("\nPress Enter to continue.")
elif user_input == 'debit':
wallet.display_wallet_by_type(DebitCard)
input("\nPress Enter to continue.")
elif user_input == 'loyalty':
wallet.display_wallet_by_type(LoyaltyCard)
input("\nPress Enter to continue.")
elif user_input == 'business':
wallet.display_wallet_by_type(BusinessCard)
input("\nPress Enter to continue.")
elif user_input == 'id':
wallet.display_wallet_by_type(PersonalIdentificationCard)
input("\nPress Enter to continue.")
elif user_input == 'other':
wallet.display_wallet_by_type(OtherCard)
input("\nPress Enter to continue.")
else:
wallet.display_wallet()
input("\nPress Enter to continue.")
elif user_input == 'search':
print("would you like to search by Card Name or Number?")
user_input = input(">")
user_input = user_input.casefold()
if user_input == 'name' or user_input == 'card name':
user_query = "";
print("enter the card name")
user_input = user_input.casefold()
user_query = input('>')
wallet.search_wallet_by_name(user_query)
elif user_input == 'number' or user_input == 'card number':
user_query = None;
print("enter the card number")
user_query = input('>')
wallet.search_wallet_by_number(user_query)
else:
continue
elif user_input == 'save':
print("Enter a name for your textfile")
path = input(">")
print("Saving to file..")
wallet.write_to_file(path+'txt')
print(f"Saved to: {path+'txt'}")
elif user_input == 'q':
print("Have a nice day! :)")
else:
print('Sorry that is an invalid option, press enter to be returned to the main menu')
input()
if __name__ == '__main__':
main()
|
import re;
a = "My name is Bibash. My name will always be Bibash.";
print(a);
print(re.sub("Bibash","Biplov",a));
b=r"I am\r\r!"
print(b);
|
from graphics import *
window = GraphWin("DDA line diagram",400,400)
def dda(x1,y1,x2,y2):
dx = x2 - x1
dy = y2 - y1
if abs(dx) > abs(dy):
stepsize = dx
elif abs(dx) < abs(dy):
stepsize = dy
x_inc = dx/stepsize
y_inc = dy/stepsize
x_new = x1
y_new = y1
for i in range(1,stepsize+1):
x_old = x_new
y_old = y_new
x_new = x_new + x_inc
y_new = y_new + y_inc
print(x_new,y_new)
Line(Point(x_old,y_old),Point(x_new,y_new)).draw(window)
i+=1
dda(10,10,10,380)
dda(10,380,380,380)
dda(40,170,150,130)
dda(150,130,240,135)
dda(240,135,330,165)
window.getMouse()
window.close()
|
import re;
pattern = r"(.+) \1";
if re.match(pattern,"spam spam"):
print("Match1");
if re.match(pattern,"$5 $5"):
print("Match2");
if re.match(pattern,"aa dd"):
print("Match3");
else:
print("No Match");
pattern =r"\D+\d";
# \d = didgits
# \s = whitespace'
# \w = word characters
#big letters are opposite to small \D = non digits
#\b matches empty string
#\A begining of string
# \Z end of string
|
import re;
if re.match("spam","aspamspamspam"):
print("Match");
else:
print("No Match");
if re.search("spam","aaaspamaaspamaaaspam"):
print("Match");
print(re.search("spam","aaaspamaaspamaaaspam").group());
print(re.search("spam","aaaspamaaspamaaaspam").start());
print(re.search("spam","aaaspamaaspamaaaspam").end());
print(re.search("spam","aaaspamaaspamaaaspam").span());
else:
print("No Match");
print(re.findall("spam","aspamaaspamaaaspam"));
|
class Animal:
def __init__(self,name,color):
self.name=name;
self.color=color;
class Cat(Animal):
def pur(self):
print("Meow");
class Dog(Animal):
def bark(self):
print("Bark");
def main():
a=Dog("Ema","Red");
print(a.color);
a.bark();
main();
|
++++++++++++++
class Vector:
def __init__(self,x,y):
self.x=x;
self.y=y;
def __add__(self,z):
return Vector(self.x+z.x , self.y+z.y);
def main():
a= Vector(1,2);
b= Vector(3,4);
result=a+b;
print("("+str(result.x)+","+str(result.y)+")");
main();
|
from graphics import *
win = GraphWin("Shapes", 1000, 1000)
win.setBackground("pink")
#rectangle
rec = Rectangle(Point(100,100), Point(450,350))
rec.draw(win)
rec.setWidth(5)
rec.setFill("green")
rec.setOutline("brown")
center = rec.getCenter() #returns center
corner1 = rec.getP1() #returns first point to construct rec
corner2 = rec.getP2() #returns second point to construct rec
#oval
oval = Oval(Point(100,200), Point(450,650)) #boundind box
oval.draw(win)
oval.setWidth(3)
center = oval.getCenter() #returns center
corner1 = oval.getP1() #returns first point to construct rec
corner2 = oval.getP2() #returns second point to construct rec
#polygon
poly = Polygon(Point(100,2), Point(700,8), Point(150,355)) #points can be increased to increase sides
poly.draw(win)
poly.setWidth(5)
point = poly.getPoints() #return all points
win.getMouse()
win.close()
|
a = [4,5,6,1,8,4,7,8]
key = int(input("Enter the integer to search: "))
b = 0
for i in range(len(a)):
if a[i] == key:
print("Found")
b = 1
if b == 0:
print("NotFound")
|
from tkinter import *
class Application(Frame):
def __init__(self, cord):
super(Application, self).__init__(cord)
self.grid()
self.create_widget()
def create_widget(self):
#creating label
self.lbl = Label(self, text = "What do you want to eat?").grid(row=0, column=0, sticky=W)
self.lbl2 = Label(self, text = "Select all that apply.")
self.lbl2.grid(row=1, column=0, sticky=W)
#creating the choices -> check button
self.chkbtn1 = BooleanVar() #only true or false
Checkbutton(self,
text = "Veg Momo",
variable = self.chkbtn1,
command = self.update
).grid(row=2, column=0, sticky=W)
self.chkbtn2 = BooleanVar() #only true or false
Checkbutton(self,
text = "Buff Momo",
variable = self.chkbtn2,
command = self.update
).grid(row=3, column=0, sticky=W)
self.chkbtn3 = BooleanVar() #only true or false
Checkbutton(self,
text = "Chicken Momo",
variable = self.chkbtn3,
command = self.update
).grid(row=4, column=0, sticky=W)
#creating textfield
self.txt = Text(self, width=40, height=5, wrap=WORD)
self.txt.grid(row=5, column=0, columnspan=3)
def update(self):
a=""
if self.chkbtn1.get():
a+= "Good "
if self.chkbtn2.get():
a+= "excellent "
if self.chkbtn3.get():
a+= "Nice "
self.txt.delete(0.0,END)
self.txt.insert(0.0,a)
win = Tk()
win.title("Check Button")
win.geometry("250x250")
a = Application(win)
win.mainloop()
|
#!/usr/bin/python3
__author__ = 'Alan Au'
__date__ = '2020-02-24'
'''
Problem: Given an input string, code a function that prints all the permutations of the string.
This problem will return n! results, so for testing purposes, keep it small.
Also, repeat characters will generate repeat permutations.
This solution is O(n!) because solution set is n! and I have to visit each permutation once.
'''
def find_permutations(my_input):
my_list = list(my_input)
output = []
if len(my_input) == 1:
return my_list[0]
for i in range(len(my_list)):
results = find_permutations(''.join(my_list[:i]+my_list[i+1:]))
for result in results:
output.append(my_list[i]+result)
return(output)
if __name__ == "__main__":
my_input = "abc"
print("Input:",my_input,"\nOutput:",find_permutations(my_input))
|
#coding:utf-8
import random
def solve_0(string = "stressed"):
print string[::-1]
def solve_1(string = u"パタトクカシーー"):
print string[::2]
def solve_2(str1 = u"パトカー", str2 = u"タクシー"):
print ''.join([a+b for a,b in zip(str1,str2)])
def solve_3(string = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."):
string = string.replace(',','')
string = string.replace('.','')
string = string.split()
print [len(i) for i in string]
def solve_4(string = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."):
string = string.replace('.','')
string = string.replace(',','')
string = string.split()
TARGET = [0,4,5,6,7,8,14,17,18]
dict = {}
for (i,word) in enumerate(string):
if i not in TARGET:
dict[word[:2]] = i
else:
dict[word[:1]] = i
#for k,v in sorted(dict.iteritems(),key=lambda x:x[1]):
# print k,v
def solve_5(string = "I am an NLPer", n = 2 ):
if isinstance(string,str):
string = string.replace('.', '')
string = string.replace(',', '')
string = string.split()
if isinstance(string,list):
pass
print [string[i:i+n] for i in range(len(string)) if len(string)-i >= n]
def solve_6(str1 = 'paraparaparadise', str2 = 'paragraph',n=2):
bigram1 = [str1[i:i+n] for i in range(len(str1)) if len(str1)-i >= n]
bigram2 = [str2[i:i+n] for i in range(len(str2)) if len(str2)-i >= n]
print "和集合:",list(set(bigram1).union(bigram2))
print "積集合:",list(set(bigram1).intersection(bigram2))
print "差集合:",list(set(bigram1).difference(bigram2))
def solve_7(x=12,y='気温',z='22.4'):
print "{}時の{}は{}".format(x,y,z)
def cipher(string):
res = ''
for char in string:
if char.islower():
code = chr(219-ord(char))
else:
code = char
res+=code
return res
def solve_8(string='Mypassword'):
print cipher(string)
print cipher(cipher(string))
def shuffle_char(string):
if len(string) <= 4:
return string
else:
_ = list(string[1:])
random.shuffle(_)
return string[0]+''.join(_)
def solve_9(string = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."):
string = string.split()
for word in string:
print shuffle_char(word),
|
"""
prompts before redirecting to google
can open apps from the search menu
"""
# imports
import speech_recognition as sr
import wolframalpha
import wikipedia
import requests
import webbrowser
import time
import pyttsx3
import http.client as http
import pyautogui
# necessities
appId = '' # get the wolfram alpha app id
client = wolframalpha.Client(appId)
speaker = pyttsx3.init()
voices = speaker.getProperty('voices') # getting details of current voice
speaker.setProperty('voice', voices[1].id)
rate = speaker.getProperty('rate') # getting details of current speaking rate: 200
speaker.setProperty('rate', 170) # setting up new voice rate
speech = sr.Recognizer()
print('checking connection...\n')
def prompt(param):
print('we could not find an answer to your question \n do you want to be redirected to google?')
loop = True
while loop:
ask = input('y/n ')
if ask == 'Y' or ask == 'y':
print('you are being redirected')
time.sleep(3)
webbrowser.open(f'https://google.com/search?q={param}')
loop = False
elif ask == 'N' or ask == 'n':
print('okay')
loop = False
return None
else:
print('Wrong input')
continue
def search(param):
pyautogui.hotkey('win', 's')
pyautogui.typewrite(param, interval=0.5)
pyautogui.typewrite(['enter'])
# main class
class Main:
def __init__(self):
self.loop = True
"""main thing begins here"""
self.connection = http.HTTPConnection("www.google.com", timeout=5)
try:
self.connection.request("HEAD", "/")
self.connection.close()
print("say 'end' to quit...;\nto open a file or application, say 'open <filename>';\n"
"the listener only works for 5 seconds but it can be adjusted.")
print('...')
while self.loop:
try:
print('listening...')
with sr.Microphone() as source:
speech.adjust_for_ambient_noise(source)
audio = speech.listen(source)
command = speech.recognize_google(audio)
print(command)
haystack = command
count = haystack.find('open')
if command == 'end':
self.loop = False
print('process has been ended')
elif count == 0:
param = command.replace('open ', '')
search(param)
print(f'opening {param}')
Play(f'opening {param}').__()
time.sleep(3)
else:
print('processing...')
answer = Personalised(command)
answer = answer.__()
if answer is None:
answer = Wolfram(command).__()
if answer is None:
wiki = Wiki(command).__()
if wiki is None:
continue
else:
print(wiki)
Play(wiki).__()
print('inna')
else:
print(answer)
Play(answer).__()
image = Image(command).__()
if image is None:
pass
else:
print(image)
else:
print(answer)
Play(answer).__()
# restart question
print('do you wanna go again? ')
loop = True
while loop:
question = input('y/n ')
if question == 'Y' or question == 'y':
loop = False
continue
elif question == 'N' or question == 'n':
print('thank you for your time')
loop = False
self.loop = False
else:
print('Wrong input')
continue
except Exception as e:
if e:
print('didn\'t catch that, could you come again?, or the problem was ' + str(e))
time.sleep(1)
else:
print('didnt catch that... come again')
except Exception as e:
print('there is no internet connection, or ' + str(e))
self.connection.close()
# other classes
class Wiki:
def __init__(self, variable):
self.variable = variable
def __(self):
results = wikipedia.search(self.variable)
# If there is no result, print no result
if not results:
prompt(self.variable)
try:
page = wikipedia.page(results[0])
except (wikipedia.DisambiguationError, error):
page = wikipedia.page(error.options[0])
wiki = str(page.summary)
return wiki
class Wolfram:
def __init__(self, variable):
self.variable = variable
def __(self):
res = client.query(self.variable)
if res['@success'] == 'false':
prompt(self.variable)
else:
# pod[0] is the question
# pod0 = res['pod'][0]
# pod[1] may contain the answer
pod1 = res['pod'][1]
if (('definition' in pod1['@title'].lower()) or ('result' in pod1['@title'].lower()) or (
pod1.get('@primary', 'false') == 'true')):
# extracting result from pod1
result = FixQuestion(pod1['subpod'])
return result.fix()
else:
return None
class Image:
def __init__(self, variable):
self.variable = variable
def __(self):
url = 'http://en.wikipedia.org/w/api.php'
data = {'action': 'query', 'prop': 'pageimages', 'format': 'json', 'piprop': 'original',
'titles': self.variable}
try:
keys = ''
res = requests.get(url, params=data)
key = res.json()['query']['pages'].keys()
for i in key:
keys = i
if keys == "-1":
pass
else:
image_url = res.json()['query']['pages'][keys]['original']['source']
return image_url
except Exception as e:
print('there was an exception processing the image ' + str(e))
class Personalised:
def __init__(self, variable):
self.variable = variable
def __(self):
if self.variable == "what is your name":
return 'My name is Athena, thanks for asking.'
elif self.variable == "what would you like to call yourself":
return 'I would like to be called "The greatest dopest finest virtual beauty there is" but' \
' Lord psarris says its too much'
elif self.variable == "when were you created":
return 'I have no idea. You can ask Lord psarris about that.'
elif self.variable == "who is lord psarris":
return 'Lord is my creator, he\'s a really awesome guy'
elif self.variable == "who is jesus":
return 'Jesus is the Son of God, who died to redeem us from the curse of the law.'
else:
return None
# helper classes
class FixQuestion:
def __init__(self, question):
self.question = question
def fix(self):
if isinstance(self.question, list):
return self.question[0]['plaintext']
else:
return self.question['plaintext']
def fix_(self):
tried = self.question.split('(')[0]
return tried
class Play:
def __init__(self, variable):
self.variable = variable
def __(self):
speaker.say(self.variable)
speaker.runAndWait()
speaker.stop()
if __name__ == "__main__":
Main()
|
from queue import PriorityQueue
def contains(lista,valor,key=lambda x: x[1]):
for i in range(len(lista)):
if key(lista[i])==valor:
return i
return -1
class BacktrackingFinder:
def __init__(self,context):
self.context=context
self.contador=0
def find(self,origen,destino,camino):
self.recursive_find(origen,destino,[],camino)
print(self.contador)
def recursive_find(self,origen,destino,camino,solucion):
if len(camino)>0 and self.context.calcular_distancia(camino[-1],destino)==0:
if len(solucion)==0 or (len(solucion)!=0 and len(solucion)>len(camino)):
solucion.clear()
for paso in camino:
solucion.append(paso)
return
if(len(camino)==0):
posicion=origen
else:
posicion=camino[-1]
vecinos=self.context.obtener_vecinos(posicion)
self.contador+=len(vecinos)
for vecino in vecinos:
if vecino not in camino:
camino.append(vecino)
self.recursive_find(origen,destino,camino.copy(),solucion)
camino.pop()
class DijkstraFinder:
def __init__(self,context,early_stop=False):
self.context=context
self.contador=0
self.early_stop=early_stop
def find(self,origen,destino,camino):
Q=[]
S=[]
Q.append([0,origen,-1])
while len(Q)!=0:
u=min(Q, key=lambda x: x[0])
p=contains(Q,u[1])
S.append(Q.pop(p))
if self.early_stop and u[1]==destino:
break
vecinos=self.context.obtener_vecinos(u[1])
self.contador+=len(vecinos)
for vecino in vecinos:
d=u[0]+self.context.calcular_distancia(u[1],vecino)
p=contains(Q,vecino)
if p==-1:
if contains(S,vecino)==-1:
Q.append([d,vecino,u[1]])
else:
if Q[p][0]>d:
Q[p]=[d,vecino,u[1]]
p=contains(S,destino)
while(p!=-1):
camino.append(S[p][1])
anterior=S[p][2]
p=contains(S,anterior)
camino.reverse()
camino.pop(0)
print(self.contador)
class AstarFinder:
def __init__(self,context):
self.context=context
self.contador=0
def find(self,origen,destino,camino):
Q=[]
S=[]
Q.append([0,origen,-1,0])
while len(Q)!=0:
u=min(Q, key=lambda x: x[0])
p=contains(Q,u[1])
S.append(Q.pop(p))
if u[1]==destino:
break
vecinos=self.context.obtener_vecinos(u[1])
self.contador+=len(vecinos)
for vecino in vecinos:
d=u[0]+self.context.calcular_distancia(u[1],vecino)
f=d+self.context.calcular_distancia(vecino,destino)
p=contains(Q,vecino)
if p==-1:
if contains(S,vecino)==-1:
Q.append([f,vecino,u[1],d])
else:
if Q[p][3]>d:
Q[p]=[f,vecino,u[1],d]
p=contains(S,destino)
while(p!=-1):
camino.append(S[p][1])
anterior=S[p][2]
p=contains(S,anterior)
camino.reverse()
camino.pop(0)
print(self.contador)
|
import math
def max_list_iter(int_list):
"""finds the max of a list of numbers and returns the value (not the index)
If int_list is empty, returns None. If list is None, raises ValueError"""
if int_list == None:
raise ValueError
if not int_list:
return None
m = int_list[0]
for i in range(1, len(int_list)):
if int_list[i] > m:
m = int_list[i]
return m
def reverse_rec(int_list, i = 0):
"""recursively reverses a list of numbers and returns the reversed list
If list is None, raises ValueError"""
if int_list == None:
raise ValueError
if not int_list:
return int_list
if i == (len(int_list)//2):
return int_list
temp = int_list[i]
int_list[i] = int_list[len(int_list)-1-i]
int_list[len(int_list)-1-i] = temp
return reverse_rec(int_list, i + 1)
def bin_search(target, low, high, int_list):
"""searches for target in int_list[low..high] and returns index if found
If target is not found returns None. If list is None, raises ValueError"""
if int_list == None:
raise ValueError
if not int_list:
return None
if int_list[(high+low)//2] == target:
return (high+low)//2
elif high == low or high-1 == low:
if int_list[high] == target:
return target
return None
elif int_list[(high+low)//2] > target:
return bin_search(target, low, (high+low)//2, int_list)
else:
return bin_search(target, (high+low)//2, high, int_list)
|
'''
Lista de Exercícios 5
'''
# Exercício 1
nome=input('Qual o seu nome completo?')
print(nome.upper())
print(nome.lower())
palavras=nome.split()
print(''.join(palavras))
nome1=''.join(nome.split())
print(len(nome1))
print(len(palavras[0]))
# Exercício 2
num = input('Digite um numero entre 0 e 999')
num1 = int(num)
if num1>999:
print('Invalido')
elif num1<0:
print('Invalido')
else:
print('Numero:' + num)
if num1>99:
print('Unidade:'+ num[2])
print('Dezena:'+ num[1])
print('Centena:'+ num[0])
elif 9<num1<99:
print('Dezena:' + num[1])
print('Unidade:' + num[0])
else:
print('Unidade:' + num[0])
# Exercício 3
cidade = input('Qual o nome da sua cidade?')
cidade=cidade.upper()
print('SAO' in cidade)
# Exercício 4
nome1 = input('Qual o seu nome?')
nome1=nome1.upper()
print('SILVA' in nome1)
# Exercício 5
frase = input('Digite uma frase')
frase = frase.lower()
print(frase.count('a'))
print(frase.find('a')
print(frase.rfind('a'))
|
'''
Aula 12
'''
#como mudar a cor, da fonte e do fundo, utilizando o padrao ANSI
print('\033[0;32;41mTeste de cor\033[m')
print('\033[2;35;43mTeste de cor\033[m')
print('\033[1;31;45mTeste de cor\033[m')
n = 10
print('O numero é: \033[1;31m{}\033[m'.format(n))
print('O numero é: {}{}{}'.format('\033[31m',n,'\033[m'))
|
'''
Curso de python
Aula 09: Utilizacao de modulos, bibliotecas e funcoes
'''
import math
import emoji
num = int(input('Digite um numero '))
raiz = math.sqrt(num)
print('Numero {} - Raiz {:.2f}'.format(num,raiz))
print('Numero {} - Raiz {:.2f}'.format(num,math.ceil(raiz)))
print('Numero {} - Raiz {:.2f}'.format(num,math.floor(raiz)))
print('Numero {} - Pot. {:.2f}'.format(num,math.pow(2,3)))
print(emoji.emojize('Tudo bem :smile:', use_aliases=True))
|
import random
#variables
y = 0
tries_message = "you tried %s times"
#get the number
number = int(random.randint(0, 1000))
# screen message
print("A random number will be generated")
print("Guess the Random number and you win!")
# collect user input
user_value = int(input('enter in a guess: '))
while (user_value != number):
if(user_value > number):
print('that number is too high')
y = y + 1
user_value = int(input('enter in a guess: '))
elif(user_value < number):
print('that number is too low')
y = y + 1
user_value = int(input('enter in a guess: '))
y = y + 1
print("you win!")
print(tries_message % y)
|
def maxSubArray(nums):
a = c = nums[0]
end = 0
begin = 0
for i in range(1, len(nums)):
if a+nums[i] >= nums[i]:
a = a + nums[i]
else:
a = nums[i]
begin = i
if a >= c:
c = a
end = i
else:
c = c
result = nums[begin:end+1]
return result
if __name__ == '__main__':
print(maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))
|
'''
219. 存在重复元素 II
给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的 绝对值 至多为 k。
示例 1:
输入: nums = [1,2,3,1], k = 3
输出: true
示例 2:
输入: nums = [1,0,1,1], k = 1
输出: true
示例 3:
输入: nums = [1,2,3,1,2,3], k = 2
输出: false
'''
# 下面代码会报超出时间限制
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
for i in range(len(nums)):
for m in range(k):
if i+m+1 < len(nums):
if nums[i] == nums[i+m+1]:
return True
return False
# 下面的代码通过,for循环使用的少可以减少运行时间
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
dict1 = {}
for i in range(len(nums)):
if nums[i] in dict1:
if i-dict1[nums[i]] <= k:
return True
dict1[nums[i]] = i
return False
|
# coding:utf-8
'''
551. 学生出勤记录 I
给定一个字符串来代表一个学生的出勤记录,这个记录仅包含以下三个字符:
'A' : Absent,缺勤
'L' : Late,迟到
'P' : Present,到场
如果一个学生的出勤记录中不超过一个'A'(缺勤)并且不超过两个连续的'L'(迟到),那么这个学生会被奖赏。
你需要根据这个学生的出勤记录判断他是否会被奖赏。
示例 1:
输入: "PPALLP"
输出: True
示例 2:
输入: "PPALLL"
输出: False
'''
class Solution:
def checkRecord(self, s: str) -> bool:
if s.count('A') > 1:
return False
if s.find('LLL') != -1:
return False
else:
return True
|
# coding:utf-8
'''
572. 另一个树的子树
给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。
示例 1:
给定的树 s:
3
/ \
4 5
/ \
1 2
给定的树 t:
4
/ \
1 2
返回 true,因为 t 与 s 的一个子树拥有相同的结构和节点值。
示例 2:
给定的树 s:
3
/ \
4 5
/ \
1 2
/
0
给定的树 t:
4
/ \
1 2
返回 false。
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
s_1 = "".join(self.postorder(s))
t_1 = "".join(self.postorder(t))
print(s_1)
print(t_1)
if t_1.find(s_1) != -1:
return True
else:
return False
def postorder(self, root, ans=[]):
if root.left and root.left !='null':
self.postorder(root.left, ans)
if root.right and root.right !='null':
self.postorder(root.right, ans)
ans.append(str(root.val))
return ans
# 别人的解法
class Solution:
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
return str(s).find(str(t)) != -1
|
'''
21. 合并两个有序链表
将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
22
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
result_node = ListNode(0)
node = result_node
head1 = l1
head2 = l2
while (head1 and head2):
if head1.val < head2.val:
node.next = head1
head1 = head1.next
node = node.next
else:
node.next = head2
head2 = head2.next
node = node.next
while head1:
node.next = head1
head1 = head1.next
node = node.next
while head2:
node.next = head2
head2 = head2.next
node = node.next
return result_node.next
|
#coding:utf-8
'''
637. 二叉树的层平均值
给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.
示例 1:
输入:
3
/ \
9 20
/ \
15 7
输出: [3, 14.5, 11]
解释:
第0层的平均值是 3, 第1层是 14.5, 第2层是 11. 因此返回 [3, 14.5, 11].
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def averageOfLevels(self, root: TreeNode) -> List[float]:
if not root:
return []
res = []
stack = [root]
while stack:
sum_1 = 0.0
linshi_node = []
for node in stack:
sum_1 += node.val
if node.left:
linshi_node.append(node.left)
if node.right:
linshi_node.append(node.right)
res.append(sum_1/float(len(stack)))
stack = linshi_node
return res
|
'''
1410. HTML 实体解析器
「HTML 实体解析器」 是一种特殊的解析器,它将 HTML 代码作为输入,并用字符本身替换掉所有这些特殊的字符实体。
HTML 里这些特殊字符和它们对应的字符实体包括:
双引号:字符实体为 " ,对应的字符是 " 。
单引号:字符实体为 ' ,对应的字符是 ' 。
与符号:字符实体为 & ,对应对的字符是 & 。
大于号:字符实体为 > ,对应的字符是 > 。
小于号:字符实体为 < ,对应的字符是 < 。
斜线号:字符实体为 ⁄ ,对应的字符是 / 。
给你输入字符串 text ,请你实现一个 HTML 实体解析器,返回解析器解析后的结果。
示例 1:
输入:text = "& is an HTML entity but &ambassador; is not."
输出:"& is an HTML entity but &ambassador; is not."
解释:解析器把字符实体 & 用 & 替换
示例 2:
输入:text = "and I quote: "...""
输出:"and I quote: \"...\""
示例 3:
输入:text = "Stay home! Practice on Leetcode :)"
输出:"Stay home! Practice on Leetcode :)"
示例 4:
输入:text = "x > y && x < y is always false"
输出:"x > y && x < y is always false"
示例 5:
输入:text = "leetcode.com⁄problemset⁄all"
输出:"leetcode.com/problemset/all"
'''
class Solution:
def entityParser(self, text: str) -> str:
dict1 = {'"': '\"', ''': "\'", '>': '>', '<': '<', '⁄': '/', '&': '&'}
for key in dict1:
text = text.replace(key, dict1[key])
return text
|
import calendar
import itertools
import operator
import random
import string
months = calendar.month_name[1:]
#enumerate
print list(enumerate("abcdefg"))
print list(enumerate("abcdefg", start=2))
cardinal_directions = ['north', 'south', 'east', 'west']
for idx, direction in enumerate(cardinal_directions):
print idx, direction
#range and xrange
#xrange renamed to range in python 3
#to gen a list with range in python 3: list(range(n))
print range(10, 0, -2)
print type(xrange(10, 0, -2))
for i in xrange(10, 0, -2):
print i
#zip- from PSF- returns list of tuples where the i-th tuple contains
#the i-th element from each of the argument sequences or iterables.
#The returned list is truncated in length to the length of the shortest argument sequence.
#in python 3, zip returns an iterator instead of a list
#https://en.wikipedia.org/wiki/Convolution_(computer_science)
list_a = ['a', 'b', 'c']
list_b = [0, 1, 2]
zipped = zip(list_a, list_b)
print list_a, "and", list_b, "zipped:", zipped
#see itertools.izip
print "to dictionary:", dict(zip(list_a, list_b))
print "unzipped:", zip(*zipped)
#iterate over multiple lists
for item_a, item_b in zip(list_a, list_b):
print item_a, item_b
#truncated to shortest
#see itertools.izip_longest for fillvalue with uneven iterables
list_a = ['a', 'b', 'c']
list_b = [0, 1, 2, 3, 4, 5, 6]
print list_a, "and", list_b, "zipped:", zip(list_a, list_b)
#from PSF- The left-to-right evaluation order of the iterables is guaranteed.
#This makes possible an idiom for clustering a data series into n-length groups
#using zip(*[iter(s)]*n).
# the key here is that it is the **same** iterator repeated. neat!
n = 3
iters = [iter(string.ascii_lowercase)]*n
print zip(*iters)
mtrx = [[1, 2, 3], [4, 5, 6]]
print "matrix:", mtrx, "transposed:", zip(*mtrx)
#swap keys and values. see comprehensions.py for better solution
#values and keys correspond: https://docs.python.org/2.7/library/stdtypes.html#dict.items
a_dict = {'a': 0, 'b': 1, 'c': 2}
print "keys and vals swapped:", dict(zip(a_dict.values(), a_dict.keys()))
#next- optional default returned instead of raising StopIteration
#when iterator exhausted
i = iter([42, 2112])
print next(i, 'default')
print next(i, 'default')
print next(i, 'default')
#iter- with two args returns callable-iterator. first arg is callable, second is a sentinel value.
#when next() called on iterator, callable is called. If val returned by callable does not equal
#sentinel it is returned. if it does equal sentinel StopIteration is raised.
#https://www.python.org/dev/peps/pep-0234/
for i in iter(lambda: random.randint(1, 7), 3):
print i, "is not equal to sentinel val of 3"
#sum, min, max
list_a = [1, 2, 3]
list_b = [4, 5, 6]
print sum(itertools.chain(list_a, list_b))
print sum(itertools.chain(list_a, list_b), 10)
lst = ['100', '2', '33']
print min(lst)
#min and max have opt key arg- one arg ordering function
print min(lst, key=int)
print max(2001, 42, 2112)
prices = {'MSFT': 57.18, 'AAPL': 105.63, 'FB': 124.24,
'AMZN': 762.96, 'GOOG': 772.58, 'IBM': 160.93}
print min(prices.keys(), key=prices.get)
print min(prices.iteritems(), key=operator.itemgetter(1))
print max(prices.keys(), key=prices.get)
print max(prices.iteritems(), key=operator.itemgetter(1))
print sorted(prices.keys(), key=prices.get)
print sorted(prices.iteritems(), key=operator.itemgetter(1))
#all- return True if all items of iterable are true
print all(x[-1] == 'r' for x in months)
#all short circuits (returning False) after it sees a false value
i = iter([True, False, 'blah'])
print all(i)
print i.next()
#any- return True if any item of iterable is true
print any(x[-1] == 'r' for x in months)
#use any to check if all items are false
print not any([False, False, False])
#any short circuits (returning True) after it sees a true value
i = iter([False, True, 'blah'])
print any(i)
print i.next()
#can use short circuit behavior with iterators to check only one true value
i = iter([False, False, True, False])
print any(i) and not any(i)
#only one false value
i = iter([False, False, True, False])
print not all(i) and all(i)
#sorted(iterable[, cmp[, key[, reverse]]]) return sorted list from iterable
#key is a one arg function that specifies element's comparison key
#cmp specifies a two arg custom comparison function that returns +n, 0, -n
#cmp removed in python 3
#https://www.youtube.com/watch?v=OSGv2VnC0go&t=10m05s
lod = [{'a': 1}, {'a': 0}, {'a': -1}]
print "list:", lod, "sorted via 'a' key:", sorted(lod, key=operator.itemgetter('a'))
print "reverse sorted:", sorted(lod, key=operator.itemgetter('a'), reverse=True)
lst = ['a', 'ab', 'c', 'abcd', 'abc', 'a']
print "list:", lst, "sorted by element length:", sorted(lst, key=len)
#with keys sorted
a_dict = {'d': 3, 'a': 0, 'c': 2, 'b': 1}
for key, val in sorted(a_dict.iteritems()):
print key, val
#loop backwards
lst = ['first', 'second', 'third']
for item in reversed(lst):
print item
#map- apply function to every item of iterable and return list
def double(x):
return x*2
numbers = [9, 4, 17]
print map(double, numbers)
print map(lambda x: x*2, numbers)
#filter- return list of items of iterable where function returns true
def ends_in_r(x):
return x[-1] == 'r'
print filter(ends_in_r, months)
print filter(lambda x: x[-1] == 'r', months)
#if function is None then return list of elements that are true
#see itertools.iterfalse to return false elements
print filter(None, [True, 0, 1, [0], {}, (9,)])
#reduce- reduce items of iterable to single val with function with 2 args
print range(1, 6), "((((1*2)*3)*4)*5) =", reduce(operator.mul, range(1, 6))
|
import operator
import time
# https://www.python.org/dev/peps/pep-0318/
def log_args(func):
def new_func(*args, **kwargs):
print 'arguments: {} {}'.format(args, kwargs)
return func(*args, **kwargs)
return new_func
def double_args(func):
def new_func(*args, **kwargs):
doubled_args = tuple(a*2 for a in args)
doubled_kwargs = {k: v*2 for k, v in kwargs.iteritems()}
return func(*doubled_args, **doubled_kwargs)
return new_func
def fancy_output(txt='*', n=3):
def wrap(func):
def wrapped_func(*args, **kwargs):
return '{0} {1} {0}'.format(txt*n, func(*args, **kwargs))
return wrapped_func
return wrap
def time_dec(func):
def new_func(*args, **kwargs):
t1 = time.time()
ret = func(*args, **kwargs)
t2 = time.time()
print t2 - t1, "seconds executing", func.func_name
return ret
return new_func
# pie-decorator syntax
# two decorators below equivalent to:
# add_these = double_args(log_args(add_these))
@double_args
@log_args
def add_these(*args, **kwargs):
return sum(args) + sum(kwargs.values())
@fancy_output('-*-', 2)
def multiply_these(*args):
return reduce(operator.mul, args)
@time_dec
def snooze(n=3.14):
print 'sleeping for', n, 'seconds'
time.sleep(n)
print add_these(9, 13, 11, 9, x=999, z=2112)
print multiply_these(6, 7)
snooze()
|
if not 0:
print "zero value ints are False"
if not 0.0:
print "zero value floats are False"
if not None:
print "None is False. Use is/is not to check for None."
if not False:
print "False is False"
if not '':
print "empty strings are False"
if not []:
print "empty lists are False"
if not ():
print "empty tuples are False"
if not {}:
print "dicts with no keys are False"
if not set([]):
print "empty sets are False"
num = 4
#while num > 0:
while num:
print num
num -= 1
|
#!/usr/bin/env python
# coding: utf-8
# # <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 2</font>
#
# ## Download: http://github.com/dsacademybr
# ## Exercícios Cap02
# In[2]:
# Exercício 1 - Imprima na tela os números de 1 a 10. Use uma lista para armazenar os números.
lista1 = [1,2,3,4,5,6,7,8,9,10]
print(lista1)
# In[3]:
# Exercício 2 - Crie uma lista de 5 objetos e imprima na tela
lista_animal = ['cachorro','cavalo','pato','ganso']
print(lista_animal)
# In[6]:
# Exercício 3 - Crie duas strings e concatene as duas em uma terceira string
frase1 ='Enquanto houver '
frase2 = 'amor, haverá esperança.'
frase3 = frase1 + frase2
print(frase3)
# In[11]:
# Exercício 4 - Crie uma tupla com os seguintes elementos: 1, 2, 2, 3, 4, 4, 4, 5 e depois utilize a função count do
# objeto tupla para verificar quantas vezes o número 4 aparece na tupla
tupla1 = (1, 2, 2, 3, 4, 4, 4, 5)
print(tupla1)
tupla1.count (4)
# In[12]:
# Exercício 5 - Crie um dicionário vazio e imprima na tela
dic_vazio = {}
print(dic_vazio)
# In[15]:
# Exercício 6 - Crie um dicionário com 3 chaves e 3 valores e imprima na tela
dic_chaves = {'Ana' : '35', 'Beatriz' : '38', 'Andre' : '45', 'Ricardo' : '28'}
print(dic_chaves)
# In[16]:
# Exercício 7 - Adicione mais um elemento ao dicionário criado no exercício anterior e imprima na tela
dic_chaves = {'Ana' : '35', 'Beatriz' : '38', 'Andre' : '45', 'Ricardo' : '28' , 'Gustavo' : '18'}
print(dic_chaves)
# In[18]:
# Exercício 8 - Crie um dicionário com 3 chaves e 3 valores. Um dos valores deve ser uma lista de 2 elementos numéricos.
# Imprima o dicionário na tela.
dic_mescla = {'valor1' : '23', 'valor2' : '47', 'valor3': [23, 24, 33]}
print(dic_mescla)
# In[20]:
# Exercício 9 - Crie uma lista de 4 elementos. O primeiro elemento deve ser uma string,
# o segundo uma tupla de 2 elementos, o terceiro um dcionário com 2 chaves e 2 valores e
# o quarto elemento um valor do tipo float.
# Imprima a lista na tela.
lista_div = ['carambola', (12, 340), {'amora' : '3', 'framboesa' : '27'}, 99.338]
print(lista_div)
# In[21]:
# Exercício 10 - Considere a string abaixo. Imprima na tela apenas os caracteres da posição 1 a 18.
frase = 'Cientista de Dados é o profissional mais sexy do século XXI'
frase[0:18]
# # Fim
# ### Obrigado - Data Science Academy - <a href="http://facebook.com/dsacademybr">facebook.com/dsacademybr</a>
|
#!/usr/bin/env python3
def parse_instructions(input_list):
return [instruction.split(' ') for instruction in input_list]
def execute(instruction_list):
program_count = 0
accumulator = 0
instructions_executed = set()
while True:
if program_count in instructions_executed:
return accumulator
instructions_executed.add(program_count)
program_count, accumulator = execute_instruction(instruction_list[program_count],
program_count,
accumulator)
def execute_instruction(instruction, program_count, accumulator):
operator, operand = instruction
if operator == 'nop':
return program_count+1, accumulator
if operator == 'acc':
return program_count+1, accumulator+int(operand)
if operator == 'jmp':
return program_count+int(operand), accumulator
def nop_and_jmp_instruction_indices(instruction_list):
return [i for i,[instruction, _] in enumerate(instruction_list)
if instruction in ['nop', 'jmp']]
def execute_part_2(instruction_list):
program_count = 0
max_program_count = len(instruction_list)
accumulator = 0
instructions_executed = set()
while True:
if program_count in instructions_executed:
return accumulator, False
if program_count >= max_program_count:
return accumulator, True
instructions_executed.add(program_count)
program_count, accumulator = execute_instruction(instruction_list[program_count],
program_count,
accumulator)
def accumulator_after_fixing_program(instruction_list):
indices = nop_and_jmp_instruction_indices(instruction_list)
for i in indices:
previous_instruction = instruction_list[i][0]
instruction_list[i][0] = 'nop' if previous_instruction == 'jmp' else 'jmp'
accumulator, ended = execute_part_2(instruction_list)
if ended:
return accumulator
instruction_list[i][0] = previous_instruction
def part1():
with open('./input.txt') as f:
input_str = f.read().strip().split('\n')
instruction_list = parse_instructions(input_str)
print(execute(instruction_list))
def part2():
with open('./input.txt') as f:
input_str = f.read().strip().split('\n')
instruction_list = parse_instructions(input_str)
print(accumulator_after_fixing_program(instruction_list))
if __name__ == '__main__':
part2()
|
a=int(input("Enter number a:"))
b=int(input("Enter number b:"))
c=int(input("Enter number c:"))
p=b**2-4*a*c
m=2*a
if p<0:
print("Roots are imaginary")
else:
print(“First root is:”, ((-b+ p)/m)), ”Second root is:”, ((-b-p)/m))
|
global score
score = 0 #this is to keep track of the score
def scorend(): #this function is the printing out of the final score for the user
if score<11:
print "You got ",score," out of 18 you get an F"
if 14>score>11:
print "You got ",score," out of 18 you get a C"
if 16>score>14:
print "You got ",score," out of 18 you get a B"
if 17>score>15:
print "You got ",score," out of 18 you get a B+"
if 18>score>17:
print "You got ",score," out of 18 you get a A-"
if score==18:
print "You got ",score," out of 18 you get a A"
def game(): # this is the whole function of the actual game
global score
while True: #using while statements for the questions, this is the starting question if you want to play or not
print """ ___________.__ ________ .__
\__ ___/| |__ ____ \_____ \ __ __ |__|________
| | | | \ _/ __ \ / / \ \ | | \| |\___ /
| | | Y \\ ___/ / \_/. \| | /| | / /
|____| |___| / \___ > \_____\ \_/|____/ |__|/_____/
\/ \/ \__> """
startquiz = raw_input("""This is a multiple choice quiz. It has a bunch of fun facts, just put True or False and at the end of the 18 questions, you will get your score!
Do you want to take the quiz? (yes or no)""")
if startquiz.lower() == "yes":
print "Alright! Lets go to the first question"
break
elif startquiz.lower() == "no":
print "Aw man :("
exit()
else:
print "please say yes or no"
while True: #for every question it is a while loop
firstq = raw_input("True or false :Bananas are curved because they grow towards the sun")
if firstq.lower() == "true": #put .lower() so that it is easy to read for the code at "true" or "false"
print "Correct! Nice one lets move to the next question!"
score += 1
break
elif firstq.lower() == "false":
print "Wrong! Lets move to the next question!"
break
else:
print "please say 'true' or 'false' "
while True:
secondq = raw_input("True or false : There is a species of spider called the Hobo Spider")
if secondq.lower() == "true":
print "Correct! Nice one lets move to the next question!"
score += 1
break
elif secondq.lower() == "false":
print "Wrong! Lets move to the next question!"
break
else:
print "please say 'true' or 'false' "
while True:
thirdq = raw_input("True or false : beans, corn and peppers don't make you fart")#false
if thirdq.lower() == "false":
print "Correct! Nice one lets move to the next question!"
score += 1
break
elif thirdq.lower()== "true":
print "Wrong! Lets move to the next question!"
break
else:
print "please say 'true' or 'false' "
while True:
fourthq = raw_input("True or false : Billy goats urinate on their own heads to smell more attractive to females")#true
if fourthq.lower() == "true":
print "Correct! Nice one lets move to the next question!"
score =+1
break
elif fourthq.lower()== "false":
print "Wrong! Lets move to the next question!"
break
else:
print "please say 'true' or 'false' "
while True:
fithq = raw_input("True or false : An eagle can kill a young deer and fly away with it ")#true
if fithq.lower() == "true":
print "Correct! Nice one lets move to the next question!"
score += 1
break
elif fithq.lower()== "false":
print "Wrong! Lets move to the next question!"
break
else:
print "please say 'true' or 'false' "
while True:
sixthq = raw_input("True or false : Regular water has a higher boiling point than Human saliva")#false
if sixthq.lower() == "false":
print "Correct! Nice one lets move to the next question!"
score += 1
break
elif sixthq.lower()== "true":
print "Wrong! Lets move to the next question!"
break
else:
print "please say 'true' or 'false' "
while True:
seventhq = raw_input("True or false : During your lifetime you will produce enough saliva to fill two swimming pools ")#true
if seventhq.lower() == "true":
print "Correct! Nice one lets move to the next question!"
score += 1
break
elif seventhq.lower()== "false":
print "Wrong! Lets move to the next question!"
break
else:
print "please say 'true' or 'false' "
while True:
eighthq = raw_input("True or false : More people died in 2015 by shark attacks than taking a selfie")#false
if eighthq.lower() == "false":
print "Correct! Nice one lets move to the next question!"
score += 1
break
elif eighthq.lower()== "true":
print "Wrong! Lets move to the next question!"
break
else:
print "please say 'true' or 'false' "
while True:
ninthq = raw_input("True or false : A lions roar can be heard from 7 miles away")#false, it is only 5 miles away
if ninthq.lower() == "false":
print "Correct! Nice one lets move to the next question!"
score += 1
break
elif ninthq.lower()== "true":
print "Wrong! Lets move to the next question!"
break
else:
print "please say 'true' or 'false' "
while True:
tenthq = raw_input("True or false : Recycling one glass jar saves enough energy to watch tv for 3 hours")#true
if tenthq.lower() == "true":
print "Correct! Nice one lets move to the next question!"
score += 1
break
elif tenthq.lower()== "false":
print "Wrong! Lets move to the next question!"
break
else:
print "please say 'true' or 'false' "
while True:
eleventhq = raw_input("True or false : A small child could swim through the veins of a blue whale")#true
if eleventhq.lower() == "true":
print "Correct! Nice one lets move to the next question!"
score += 1
break
elif eleventhq.lower()== "false":
print "Wrong! Lets move to the next question!"
break
else:
print "please say 'true' or 'false' "
while True:
twelthq = raw_input("True or false : The Twitter bird is named Larry")#true
if twelthq.lower() == "true":
print "Correct! Nice one lets move to the next question!"
score += 1
break
elif twelthq.lower()== "false":
print "Wrong! Lets move to the next question!"
break
else:
print "please say 'true' or 'false' "
while True:
thirteenthq = raw_input("True or false : If you consistently fart for 6 years and 9 months, enough gas is produced to create the energy of an atomic bomb")#true
if thirteenthq.lower() == "true":
print "Correct! Nice one lets move to the next question!"
score += 1
break
elif thirteenthq.lower()== "false":
print "Wrong! Lets move to the next question!"
break
else:
print "please say 'true' or 'false' "
while True:
fourteenthq = raw_input("True or false : The average person walks the equivalent of twice around the world in a lifetime ")#true
if fourteenthq.lower() == "true":
print "Correct! Nice one lets move to the next question!"
score += 1
break
elif fourteenthq.lower()== "false":
print "Wrong! Lets move to the next question!"
break
else:
print "please say 'true' or 'false' "
while True:
fifteenthq = raw_input("True or false : There are more than 75,000 toilet related injuries in the United States every year")#false its 40,000
if fifteenthq.lower() == "false":
print "Correct! It is actually 40,000. Nice one lets move to the next question!"
score += 1
break
elif fifteenthq.lower()== "true":
print "Wrong! It is actually 40,000. Lets move to the next question!"
break
else:
print "please say 'true' or 'false' "
while True:
sixteenthq = raw_input("True of false : Samuel L.Jackson requested to have a purple light saver in StarWars in order for him to accept the part as Mace Windu")#true
if sixteenthq.lower() == "true":
print "Correct! Nice one lets move to the next question!"
score += 1
break
elif sixteenthq.lower()== "false":
print "Wrong! Lets move to the next question!"
break
else:
print "please say 'true' or 'false' "
while True:
seventeenthq = raw_input("True or false : A crocodile can poke its tongue out")#false
if seventeenthq.lower() == "false":
print "Correct! Nice one lets move to the next question!"
score += 1
break
elif seventeenthq.lower()== "true":
print "Wrong! Lets move to the next question!"
break
else:
print "please say 'true' or 'false' "
while True:
eighteenthq = raw_input("True or false : 95% of people text things they could never say in person ")#true
if eighteenthq.lower() == "true":
print "Correct! Nice one lets move to the next question!"
score +=1
break
elif eighteenthq.lower()== "false":
print "Wrong! Lets move to the next question!"
break
else:
print "please say 'true' or 'false' "
game() #calling the game function to work
scorend() #calling the scorend function to work
tryagain = raw_input("Do you want to try again!") #this is the try again function to see if the user wants to play again
while True:
if tryagain.lower()=="yes":
game()
elif tryagain.lower() == "no":
print "OK bye"
exit()
else:
print"please say yes or no"
f = open("score.txt", "w") #my attempt at making a text file
f.write(score)
f.close()
f=open("score.txt", "r") #attempting to read the score.txt file
if f.mode == 'r':
contents =f.read()
|
import linkedlist
def SumLists(l1, l2):
return ConvertListToNumber(l1) + ConvertListToNumber(l2)
def ConvertListToNumber(l):
base = 10
multiplier = 1
number = 0
current = l.head
while current:
number += current.value * multiplier
multiplier *= base
current = current.next
return number
def SumLists2(l1, l2):
base = 10
quotient = 0
modulo = 0
curr1 = l1.head
curr2 = l2.head
result = linkedlist.LinkedList()
while curr1 and curr2:
sum_pos = curr1.value + curr2.value + quotient
quotient = sum_pos / base
modulo = sum_pos % base
result.add(modulo)
curr1 = curr1.next
curr2 = curr2.next
curr_longer_list = curr1 or curr2
while curr_longer_list:
result.add(curr_longer_list.value + quotient)
modulo = 0
curr_longer_list = curr_longer_list.next
if quotient:
result.add(quotient)
return result
def AddListsRecursively(n1, n2, modulo):
if n1 == None and n2 == None and modulo == 0:
return None
base = 10
value = modulo
if n1:
value += n1.value
if n2:
value += n2.value
result = linkedlist.Node(value % base)
if n1 != None or n2 != None:
digit = AddListsRecursively(None if n1 == None else n1.next,
None if n2 == None else n2.next,
value / base)
result.setNextNode(digit)
return result
l1 = linkedlist.CreateList([7, 1, 6])
l2 = linkedlist.CreateList([5, 9, 2])
l3 = linkedlist.CreateList([1, 5, 6])
l4 = linkedlist.CreateList([2, 3, 6, 7])
l5 = linkedlist.CreateList([9, 7, 8])
l6 = linkedlist.CreateList([6, 8, 5])
print SumLists(l1, l2), SumLists(l3, l4), SumLists(l5, l6)
print SumLists2(l1, l2), SumLists2(l3, l4), SumLists2(l5, l6)
res = AddListsRecursively(l1.head, l2.head, 0)
res_list = linkedlist.LinkedList()
res_list.setHead(res)
print res_list
res = AddListsRecursively(l3.head, l4.head, 0)
res_list.setHead(res)
print res_list
res = AddListsRecursively(l5.head, l6.head, 0)
res_list.setHead(res)
print res_list
|
class Remove: # Heuristic class is defined here
def __init__(self,scoreremove,weightremove,numberofremoves):
# scores and weight are defined here
self.scoreremove = scoreremove # 8
self.weightremove = weightremove # 8
self.numberofremoves = numberofremoves # number of iterations used
def printinfo(self):
print("""scoreremove:{}-weightremove: {}-numberofremoves:{}""".format(self.scoreremove, self.weightremove, self.numberofremoves))
def adduncoveredjob(self,Solutions,component):
self.Solutions[0].uncoveredjob.append(component)
def randomremove(self,N,Solutions):
import random
# print("removal 1 starts")
nurseno = random.randint(0, N-1) # determine the nurse first
while (len(Solutions[int(nurseno)].routing)==1): # if selected nurse is not a free nurse
nurseno = random.randint(0, N-1) # determine the nurse first
if (len(Solutions[nurseno].routing)>1): # if selected nurse is not a free nurse
counter = 0
jobno = random.randint(0, int(len(Solutions[int(nurseno)].routing))) # determine the job second
while jobno==0 or len(Solutions[nurseno].routing)==jobno or int(Solutions[int(nurseno)].routing[int(jobno)]) >= (N+N) and counter <=N+N:#
jobno = random.randint(0, int(len(Solutions[int(nurseno)].routing))) # determine the job second
counter += 1
if int(Solutions[int(nurseno)].routing[int(jobno)]) < (N+N):
if Solutions[0].uncoveredjob==['-1']:
Solutions[0].uncoveredjob=[str(int(Solutions[int(nurseno)].routing[jobno]))]
elif (Solutions[0].uncoveredjob)!=['-1']:
Solutions[0].uncoveredjob.append(str((Solutions[int(nurseno)].routing[jobno])))
del Solutions[int(nurseno)].routing[jobno]
Solutions[int(nurseno)].change=1
def randomremove2(self,N,Solutions): # n number of jobs removed randomly
import random
# print("removal2 1")
jobnumbers=random.randint(round(0.1*N), round(0.4*N))
i=1
while i<jobnumbers:# or jobnumbers > len(Solutions[int(0)].uncoveredjob):
self.randomremove(N, Solutions)
i=i+1
def randomremove3(self,N,Solutions,Dmatris):
# print("******Randomremove3")
import random
Array = []
Ratio=[]
Name=[]
numbers=0
for i in Solutions:
if len(i.routing) >1:
Array.append(i.obj)
Name.append(i.routing[0])
numbers+=1
hold = 0
for i in Array:
hold+=(float(i/sum(Array)))
Ratio.append(hold)
proportion = random.random() # determine random number
nurseno=0
for i in range(0, numbers-1): # roulette wheel selection
if Ratio[i]<proportion:
nurseno=i+1
jobnumber = random.randint(round(0.1 * N), round(0.4 * N))
# burada worst remove n kez çalistirilacak
i = 0
while i<=jobnumber:
self.worstremove2(N,Solutions,Dmatris,int(Name[nurseno]))
i = i + 1
def worstremove2(self, N,Solutions,Dmatris,nurseno):
big = 0
job1 = 0
for j in range(0, len(Solutions[nurseno].routing)> - 1):
if (j + 2 < len(Solutions[nurseno].routing)):
dist = int(Dmatris[int(Solutions[nurseno].routing[j])][int(Solutions[nurseno].routing[j + 1])])
dist += int(Dmatris[int(Solutions[nurseno].routing[j+1])][int(Solutions[nurseno].routing[j + 2])])
if big < dist:
job1 = j
big = dist
if job1 == 0 and big != 0:
job1 = 1
if (int(Solutions[nurseno].routing[job1]) >= N and int(Solutions[nurseno].routing[job1])< N + N): # if selected nurse is not a free nurse
i = job1 # assign
if Solutions[0].uncoveredjob == ['-1']:
Solutions[0].uncoveredjob = [str(int(Solutions[int(nurseno)].routing[job1]))]
elif (Solutions[0].uncoveredjob) != ['-1']:
Solutions[0].uncoveredjob.append(str((Solutions[int(nurseno)].routing[job1])))
del Solutions[int(nurseno)].routing[job1]
Solutions[int(nurseno)].change = 1
def worstremove(self,N,Solutions,Dmatris):
# print("Worst removal 1")
big=0
job1=0
for i in Solutions:
if len(i.routing) > 2:
for j in range(0, len(i.routing)):
if (j+2<len(i.routing)):
dist = int(Dmatris[int(i.routing[j])][int(i.routing[j + 1])])
dist+= int(Dmatris[int(i.routing[j+1])][int(i.routing[j + 2])])
if big < dist:
nurseno=int(i.routing[0])
job1=j
big=dist
if job1 == 0 and big != 0:
job1 = 1
if (job1!= 0 and int(Solutions[nurseno].routing[job1]) < N+N): # if selected nurse is not a free nurse
i =job1 #assign
if Solutions[0].uncoveredjob == ['-1']:
Solutions[0].uncoveredjob = [str(int(Solutions[int(nurseno)].routing[job1]))]
elif (Solutions[0].uncoveredjob) != ['-1']:
Solutions[0].uncoveredjob.append(str((Solutions[int(nurseno)].routing[job1])))
del Solutions[int(nurseno)].routing[job1]
Solutions[int(nurseno)].change = 1
def randomEVremove(self,N,Solutions):
import random
nurseno = random.randint(0, (N-1)) # determine the nurse first
while len(Solutions[nurseno].routing)<2: # if selected nurse is not a free nurse
nurseno = random.randint(0, (N-1)) # determine the nurse first
i = 0
while int(len(Solutions[nurseno].routing)) != 1:
if Solutions[0].uncoveredjob == ['-1'] and int(Solutions[int(nurseno)].routing[len(Solutions[nurseno].routing)-1])<N+N :
Solutions[0].uncoveredjob = [str(int(Solutions[int(nurseno)].routing[len(Solutions[nurseno].routing)-1]))]
elif (Solutions[0].uncoveredjob) != ['-1'] and int(Solutions[int(nurseno)].routing[len(Solutions[nurseno].routing)-1]) < N+N :
Solutions[0].uncoveredjob.append(str((Solutions[int(nurseno)].routing[len(Solutions[nurseno].routing)-1])))
Solutions[int(nurseno)].routing.pop()
Solutions[int(nurseno)].change = 1
i+=1
def worsttimeremove(self,N,Solutions,Dmatris):
# print("Worsttime removal 1")
big = 0
job1 = 0
for i in Solutions:
if len(i.routing) > 1 and (len(i.routing)+1)*4==len(i.scheduling):
for j in range(1, len(i.routing)):
if( float(i.scheduling[4*j]) == float(i.scheduling[4*j+1]) ): # calculate the idle time
time=float(i.scheduling[4*j])-float(i.scheduling[(4*(j-1)+2)])
time +=float(int(Dmatris[int(i.routing[j-1])][int(i.routing[j])])/50*60)
if big < time:
nurseno = int(i.routing[0])
job1 = j
big = time
if (job1 != 0 and int(Solutions[nurseno].routing[job1]) < N + N): # if selected nurse is not a free nurse
i = job1
if Solutions[0].uncoveredjob == ['-1']:
Solutions[0].uncoveredjob = [str(int(Solutions[int(nurseno)].routing[job1]))]
elif (Solutions[0].uncoveredjob) != ['-1']:
Solutions[0].uncoveredjob.append(str((Solutions[int(nurseno)].routing[job1])))
del Solutions[int(nurseno)].routing[job1]
Solutions[int(nurseno)].change = 1
def assignzeros(self, N, vector): # N zero vector
i = 0
while i < N:
vector.append(0)
i = i + 1
return vector
def stationremove(self,N,Solutions):
import random
Visit = 0
EVvisit = []
self.assignzeros(N, EVvisit)
k=0
for i in Solutions:
if len(i.routing) > 1:
for j in range(1, len(i.routing)):
if int(i.routing[j]) >= N + N:
Visit = 1
EVvisit[k] = 1
k+=1
if Visit != 0:
nurseno = random.randint(0, (N - 1)) # determine the nurse first
while EVvisit[nurseno] == 0:
nurseno = random.randint(0, (N - 1))
job1 = 0
if len(Solutions[nurseno].routing)>1: # if selected nurse is not a free nurse
for j in range(1, len(Solutions[nurseno].routing)):
if (int(Solutions[nurseno].routing[j]) >= N + N):
job1 = j
if (job1 != 0):
Solutions[nurseno].routing.remove(Solutions[nurseno].routing[job1])
Solutions[int(nurseno)].change = 1
def chargetechremove(self,N,Solutions):
import random
Visit = 0
EVvisit = []
self.assignzeros(N, EVvisit)
k = 0
for i in Solutions:
if len(i.routing) > 1:
for j in range(1, len(i.routing)):
if int(i.routing[j]) >= N + N:
Visit = 1
EVvisit[k] = 1
k += 1
if Visit != 0:
nurseno = random.randint(0, (N - 1)) # determine the nurse first
while EVvisit[nurseno] == 0:
nurseno = random.randint(0, (N - 1))
job1 = 0
if len(Solutions[nurseno].routing) > 1: # if selected nurse is not a free nurse
for j in range(1, len(Solutions[nurseno].routing)):
if (int(Solutions[nurseno].routing[j]) >= N + N):
Solutions[nurseno].chargetechnology = [str(0)]
Solutions[int(nurseno)].change = 1
#!!!!!!!!!!!!!! more than one visits may be considered and check incase the infeasible!!!!!!!
|
import numpy as np
def nullspace_basis(A):
"""
Uses singular value decomposition to find a basis of the nullsapce of A.
"""
V = np.linalg.svd(A)[2].T
rank = np.linalg.matrix_rank(A)
Z = V[:,rank:]
return Z
|
def word_count(fpath):
fopen = open(fpath)
fstr = fopen.read()
for i in fstr:
if not ((i >= 'a' and i <= 'z') or (i >= 'A' and i <= 'Z') or i == ' '):
fstr = fstr.replace(i, ' ')
fresult = fstr.split()
fopen.close()
#return len(fresult)
return fresult
fpath = raw_input("Please input the file path:\n")
#print word_count(fpath)
final = word_count(fpath)
for item in final:
print item
|
"""
Implementing a Random Tree (RT) learner
@Name : Nidhi Nirmal Menon
@UserID : nmenon34
"""
import pandas as pd
import numpy as np
class RTLearner(object):
def __init__(self,leaf_size,verbose=False):
self.leaf_size=leaf_size
self.verbose=verbose
self.learner=[]
def author(self):
"""
@summary Returning the author user ID
"""
return 'nmenon34'
def build_tree(self, data):
tree=np.array([])
flag=0
if(data.shape[0]<=self.leaf_size):
tree = np.array([['leaf', data[0][-1],'-1','-1']])
return tree
X_attr = int(np.random.randint(data.shape[1]-1))
#if values of Xattribute are the same
if(np.all(data[:,X_attr] == data[0][X_attr])):
return np.array([['leaf', np.mean(data[:, -1]), '-1', '-1']])
data = data[np.argsort(data[:, X_attr])]
splitVal = np.median(data[0:, X_attr])
if max(data[:,X_attr])==splitVal:
return np.array([['leaf', np.mean(data[:, -1]), '-1', '-1']])
#building left and right sub-trees
leftTree=self.build_tree(data[data[:,X_attr]<=splitVal])
rightTree=self.build_tree(data[data[:,X_attr]>splitVal])
root=[X_attr,splitVal, 1, leftTree.shape[0]+1]
tree= np.vstack((root,leftTree,rightTree))
return tree
def addEvidence(self, Xtrain, Ytrain):
data=[]
tree=[]
data=np.concatenate(([Xtrain,Ytrain[:,None]]),axis=1)
tree=self.build_tree(data)
self.learner = np.array(tree)
def query(self, trainX):
row=0
predY=np.array([])
for data in trainX:
while(self.learner[row][0]!='leaf'):
X_attr=self.learner[row][0]
X_attr = int(float(X_attr))
if(float(data[X_attr]) <= float(self.learner[row][1])):
row=row+int(float(self.learner[row][2]))
else:
row=row+int(float(self.learner[row][3]))
row=int(float(row))
if(self.learner[row][0]=='leaf'):
predY=np.append(predY, float(self.learner[row][1]))
row=0
return predY
|
from abc import ABC, abstractmethod
class Stmt:
class Visitor(ABC):
@abstractmethod
def visit_expression_stmt(self, stmt): pass
@abstractmethod
def visit_block_stmt(self, stmt): pass
@abstractmethod
def visit_print_stmt(self, stmt): pass
@abstractmethod
def visit_let_stmt(self, stmt): pass
@abstractmethod
def visit_if_stmt(self, stmt): pass
@abstractmethod
def visit_while_stmt(self, stmt): pass
@abstractmethod
def visit_fn_stmt(self, stmt): pass
@abstractmethod
def visit_return_stmt(self, expr): pass
class Expression:
def __init__(self, expression):
self.expression = expression
def accept(self, visitor):
return visitor.visit_expression_stmt(self)
class Block:
def __init__(self, statements):
self.statements = statements
def accept(self, visitor):
return visitor.visit_block_stmt(self)
class Print:
def __init__(self, expression):
self.expression = expression
def accept(self, visitor):
return visitor.visit_print_stmt(self)
class Return:
def __init__(self, keyword, value):
self.keyword = keyword
self.value = value
def accept(self, visitor):
return visitor.visit_return_stmt(self)
class Let:
def __init__(self, name, initializer):
self.name = name
self.initializer = initializer
def accept(self, visitor):
return visitor.visit_let_stmt(self)
class Fn:
def __init__(self, name, params, body):
self.name = name
self.body = body
self.params = params
def accept(self, visitor):
return visitor.visit_fn_stmt(self)
class If:
def __init__(self, condition, then_branch, else_branch):
self.condition = condition
self.then_branch = then_branch
self.else_branch = else_branch
def accept(self, visitor):
return visitor.visit_if_stmt(self)
class While:
def __init__(self, condition, body):
self.condition = condition
self.body = body
def accept(self, visitor):
return visitor.visit_while_stmt(self)
|
import csv
import random
import math
import operator
#Load the IRIS dataset csv file and convert the data into a list of lists (2D array) , make sure the data file is in the current working directory
#Randomly split dataset to training and testing data
def loadDataset(filename, split, trainingSet=[], testSet=[]):
with open(filename, 'rt') as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)
for x in range(len(dataset) - 1):
for y in range(4):#coverting string format to float format
dataset[x][y] = float(dataset[x][y])
if random.random() < split:
trainingSet.append(dataset[x])
else:
testSet.append(dataset[x])
#this function calculates the euclidian distance between 2 points to give a measure of dissimilarity between the 2
def euclideanDistance(point1, point2, length):
distance = 0
for x in range(length):
distance += pow((point1[x] - point2[x]), 2)
return math.sqrt(distance)
#a straight forward process of calculating the distance for all instances and selecting a subset with the smallest distance values.
# function that returns k most similar neighbors from the training set for a given test instance (using the already defined euclideanDistance function)
def getNeighbors(trainingSet, testInstance, k):
distances = []
length = len(testInstance) - 1
for x in range(len(trainingSet)):
dist = euclideanDistance(testInstance, trainingSet[x], length)
distances.append((trainingSet[x], dist))
distances.sort(key=operator.itemgetter(1))#operator is in built module provides a set of convenient operators also, assumes input is an iterable (tuple and fetches the nth object out of it)
neighbors = []
for x in range(k):
neighbors.append(distances[x][0])
return neighbors
#Once we have located the most similar neighbors for a test instance, the next task is to devise a predicted response based on those neighbors.
#We can do this by allowing each neighbor to vote for their class attribute, and take the majority vote as the prediction.
#Below provides a function for getting the majority voted response from a number of neighbors. It assumes the class is the last attribute for each neighbor.
def getResponse(neighbors):
classVotes = {}
for x in range(len(neighbors)):
response = neighbors[x][-1]
if response in classVotes:
classVotes[response] += 1
else:
classVotes[response] = 1
sortedVotes = sorted(classVotes.items(), key=operator.itemgetter(1), reverse=True)
return sortedVotes[0][0]
# the getAccuracy function that sums the total correct predictions and returns the accuracy as a percentage of correct classifications.
def getAccuracy(testSet, predictions):
correct = 0
for x in range(len(testSet)):
if testSet[x][-1] == predictions[x]:
correct += 1
return (correct / float(len(testSet))) * 100.0
def main():
# prepare data
trainingSet = []
testSet = []
split = 0.67
loadDataset('iris.data.csv', split, trainingSet, testSet)
'Train set: ' + repr(len(trainingSet))
'Test set: ' + repr(len(testSet))
# generate predictions
predictions = []
k = 3
for x in range(len(testSet)):
neighbors = getNeighbors(trainingSet, testSet[x], k)
result = getResponse(neighbors)
predictions.append(result)
print('> predicted=' + repr(result) + ', actual=' + repr(testSet[x][-1]))
accuracy = getAccuracy(testSet, predictions)
print('Accuracy: ' + repr(accuracy) + '%')
main()
|
from functools import wraps
from time import time
def timer(fn):
@wraps(fn)
def wrap(*args, **kw):
time_start = time()
result = fn(*args,**kw)
time_end = time()
print('function:{}\took:{} \n args:{} \n kwargs:{}'\
.format(fn.__name__,time_end-time_start,args,kw))
return result
return wrap
|
# import the libraries to access data
from sklearn import datasets, neighbors
# load in the data into a variable 'digits'
digits = datasets.load_digits()
# separate the loaded data into the feature vectors x and their corresponding labels y
x_digits = digits.data
y_digits = digits.target
# find the number of instances in our dataset
n_samples = len(x_digits)
print ('Number of examples: %d' % n_samples)
# Look at the input (x) and label (y) for a particular jth instance
j = 0
print('Input #%d:' % j, x_digits[j])
print('Label #%d:' % j, y_digits[j])
# set aside the first 90% of the data for the training and the remaining 10% for testing.
x_train = x_digits[0:int(.9 * n_samples)]
y_train = y_digits[0:int(.9 * n_samples)]
x_test = x_digits[int(.9 * n_samples):]
y_test = y_digits[int(.9 * n_samples):]
print('Number of training examples: %d' % len(y_train))
print('Number of testing examples: %d' % len(y_test))
# create an instance of the learner
knn = neighbors.KNeighborsClassifier()
# learn an h from the training data
knn.fit(x_train, y_train)
# evaluate h over the testing data and print its accuracy. We'll save its performance to show we did some work in class!
Q05 = knn.score(x_test,y_test)
print('KNN score: %f' % Q05)
|
#!/usr/bin/env python
def merge(a, b):
s = []
i = 0
j = 0
for k in xrange(len(a) + len(b)):
try:
a[i]
except IndexError: # reached end of a
return s + b[j:]
try:
b[j]
except IndexError: # reached end of b
return s + a[i:]
if a[i] < b[j]:
s.append(a[i])
i += 1
else:
s.append(b[j])
j += 1
return s
def main():
a = [3,4,5,6,19,22,29,31]
b = [1,2,8,9,17,24,27]
li = merge(a, b)
print li
if __name__ == '__main__':
main()
|
import time
def bubble_sort(a_list):
n = len(a_list)
if n <= 1:
return a_list
for i in range(n - 2):
if a_list[i] > a_list[i + 1]:
a_list[i], a_list[i + 1] = a_list[i + 1], a_list[i]
return a_list
if __name__ == '__main__':
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
start_time = time.time()
sorted_alist = bubble_sort(a_list)
end_time = time.time()
print("times:" , (end_time - start_time))
print(sorted_alist)
|
import sys
import time
#I changed this
a = 2
b = 0.2 # slower time between characters getting spaced out
c = 0.08 # quicker time between characters getting printed
def intro():
print("\n")
time.sleep(a)
string_1 = '"Very well, remember to answer truthfully... Or don\'t, either way you\'ll provide valuable data"\n'
for character in string_1:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(b)
time.sleep(1)
print("With that the voice leaves you and the lights turn off for a moment\nWhen they turn on again you find a table has appeared")
time.sleep(a)
print("On the table you see a key on end of the table and a hammer on the other\nThe voice chimes in again")
s = '"Please choose the item that has most value to you..."\n'
for character in s:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(b)
time.sleep(1)
print()
first_path = input("which item do you pick? (key = 1 / hammer = 2): ")
if first_path == '1':
print()
path1()
elif first_path == '2':
print()
path2()
else:
print("Unknown path detected")
def path1():
time.sleep(a)
print("\nDespite how strange and unnerving the situation is, you decided that perhaps the key might be important for something down the line.")
time.sleep(a)
print("You rationalize that there has to be some kind of logic as to why you're here and what's the meaning behind all this.")
time.sleep(a)
print("After picking up the key the lights turn off and the voice speaks up.")
s = '"Interesting choice, you have no idea where you are or if that key even fits anywhere yet you still chose it?"'
for character in s:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(c)
time.sleep(1)
print()
s2 = '"Let us find out whether your choice will be the key to freedom or the key to your death."'
for character in s2:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(b)
time.sleep(1)
print()
print("When the lights turn on again the table is gone, but now the room includes two doors.\n")
time.sleep(a)
print("The first door appears to have seen better days, mots of its color has faded while several cracks could be seen in the wood.")
time.sleep(a)
print("The second door leaves you stunned, you recognize the door as the same one on the front of your home!")
door_choice = input("\nWhich door do you use the key on? (1/2): ")
if door_choice == "1":
print()
path1_1()
elif door_choice == '2':
print()
path1_2()
def path1_1():
print("\nWhile the familiar door is calling out to you, you realize that such an obvious choice must be a trap. So going against all your instincts for survival you hesitantely unlock the worn down door and head inside.")
time.sleep(a)
print("After exiting the concrete prison you find yourself somewhere damp, dark, and cold. Using your hands to feel around you deduce that you must be in some sort of cave.")
time.sleep(a)
print("Realizing that the door is no longer behind you and left with no other options you decide to feel your way to what is hopefully an exit.")
time.sleep(a)
print("After wandering around in the dark you notice small beams of light that eventually lead to an opening in the cave, and before you know you're outside in a forest.")
time.sleep(a)
print("Out in the distance you notice smoke from a what could be a campfire but at the same time you have no idea if you've actually escaped or not.")
time.sleep(a)
print("Armed with the determination to survive, you venture towards the smoke.")
def path1_2():
print("\nNot wanting to spend another moment in the room you rush over to the familiar door and check to see if they key works.")
time.sleep(a)
print("By some miracle the key fits and you're able to open the door\nRushing through the door you find yourself in your own living room, and breathing a sigh of relief.")
time.sleep(a)
print("Things however, are not as they seem. You begin to notice that your home is eerily quiet, with no traces of your family anywhere.")
time.sleep(a)
print("As you search through your home your fears and only confirmed, none of your family members are anywhere!\nDesperate for answers you go back through the front door but are shocked by the result.")
time.sleep(a)
print("Instead of making it back to the isolated room your find yourself in your neighborhood, only there's no neighbors in sight. Moreover the normally busy interstate freeway you live next to is unusually quiet.")
time.sleep(a)
print("While trying to process what's happening you realize that if the door was in fact the one to your home how did they key you picked up unlock it if you've never seen a key like it?")
time.sleep(a)
print("Trying to remain optimistic, you figure there has to be someone around. And so you you go off in search of survivors that don't exist, forever wandering the hollow shell of the world you once knew.")
def path2():
time.sleep(a)
print("\nGiven the situation you're in, you can't rule out the possibility that this is all some kind of twisted game. Thus you reason that it's in your best interest to have some kind of weapon.")
time.sleep(a)
print("Besides, who knows if the key is meant to throw you off from choosing a multi-purpose tool? Not to mention you could theoretically open any lock using the hammer if you're smart about it.")
time.sleep(a)
print("Feeling satisfied you pick up the hammer, soon after the lights turn off and the voice could be heard again.\n")
s = '"What an interesting choice, while it\'s clever to be cautious in your position choosing what could be considered a weapon does seem rather barbaric. Though that\'s nothing new to humans."'
for character in s:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(c)
time.sleep(1)
print()
s2 = '"You made a bold choice, let\'s find out whether you have the dexterity to justify such an option."'
for character in s2:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(c)
time.sleep(1)
print()
print("Soon the lights turn on and you notice the table and key is gone but you're not interested in that. What has your attention now is the 500 pound apex preadator that occupies the room with.")
time.sleep(a)
print("With a low growl, the spontaneous bear is sizng you up. It's at this moment when your adrenaline kicks in and you're given a few breif seconds to form a plan of attack.")
time.sleep(a)
print("You narrow down to your options to two choices: 1) Use your adrenaline to take on the bear in a battle to the death or 2) Throw the hammer towards the one lightbulb in the room and use the darkness to hide and wait it out.")
bear_choice = input("\nHow do you go about dealing with the bear? (1/2): ")
if bear_choice == '1':
print()
path2_1()
else:
print()
path2_2()
def path2_1():
print("\nDespite feeling panicked and afraid for your life you decide to muster up all the courage you have and challenge the bear for the right to live.")
time.sleep(a)
print("With a war cry you rush the bear ad the bear responds with a roar of its own and stands on two feet in order to strike you down.")
time.sleep(a)
print("Seeing this you fling yourself to the right in order to dodge the potentially fatal blow and as the bear crashes its paws down and turns to face you, you get in a lucky swing and manage to strike the bear near it's eye.")
time.sleep(a)
print("With a roar of pain the bear backs off. You can't believe it, you just might be able to pull this off! Is what you were thinking before you realized that you didn't completely dodge the first attack.")
time.sleep(a)
print("Looking down you realize you see an unsightly slash on the left side of your abdomen and while attempting to stop the bleeding the last of your adrenaline fades as the bear recovers.")
time.sleep(a)
print("Your last thoughts as you see the bear closing in for the finishing move were about how people who don't consider bears as apex predators have never fought one.")
def path2_2():
print("\nUnderstanding the fact that under the laws of nature no human could ever beat a grown bear with just a hammer in an enclosed space you decide to use your higher level intelligence to your advantage.")
time.sleep(a)
print("As the bear prepares to attack your quickly throw your hammer at the dim lightbulb hanging from the ceiling, shattering it and engulfing the room in darkness.")
time.sleep(a)
print("At first your gamble seems to pay off as the bear's roars turn from aggressive to confused at the lack of vision.\nAs you hide in the corner of the now dark room a terrifying thought hits you.")
time.sleep(a)
print("Not only are you in a small room but bears don't exactly have to rely on sight alone. Sure enough, the bear begins to compose itself and soon begins sniffing the air.")
time.sleep(a)
print("You could only cower in horror and wait for your inevitable death as you curse your own lack of foresight")
print()
print()
print(" #######################")
print(" # #")
print(" # Title Card #")
print(" # #")
print(" #######################")
print()
print()
time.sleep(a)
print("You find yourself in a dim, concrete room with only a single lightbulb hanging from the ceiling")
time.sleep(a)
print("Before you are able to asses your surroundings a monotone voice could be heard")
time.sleep(a)
print()
start_game = input("Would you like to start the game? (Y/N): ")
if start_game == 'n' or start_game == 'N':
print("Understood, subject #[REDACTED] does not wish to participate in the experiment. Bringing in the next subject...")
elif start_game == 'y' or start_game == 'Y':
intro()
else:
print("Answer does not compute, try again")
|
'''
tarea # 6 de programacion 3 Alexander Cerrud 8-850-2381
'''
import unittest
class registro:
try:
def registro(self,usuario,edad):
usuario=input("escribe tu nombre")
edad=input("escribe tu edad")
return {"usuario:":usuario,"apellido":usuario+"Baso","edad:":edad}
except Exception:
print("ERROR")
class NotificationsTestCase(unittest.TestCase):
try:
def test_user_repository(self):
users=registro()
user=users.registro("lex","18")
self.assertEquals("lexbaso",user['apellido'])
except Exception:
print("ERROR")
if __name__ == '__main__':
unittest.main()
|
'''
An interpreter for #if/#elif conditional expressions.
The interpreter evaluates the conditional expression and returns its truth value.
'''
import re
def toInt(numAsStr):
'Convert a C-style number literal to a Python integer.'
if (not type(numAsStr) is str):
return numAsStr # Forward everything that is not a string (re.sub requires a string)
# Remove the trailing literal modifiers, e.g., "u", "ul", "s"
s = re.sub(r'[a-zA-Z]*$', '', numAsStr)
return int(s) # Convert to int
class ExprInterpreter:
def __init__(self, symdb):
self.symdb = symdb
self.visitorMap = {
'symbol' : self.v_symbol,
'number' : self.v_number,
'defined' : self.v_defined,
'binOp' : self.v_binOp,
'unaOp' : self.v_unaOp
}
def evaluate(self, rootNode):
visitor = self.visitorMap[rootNode.typ]
return visitor(rootNode)
def v_symbol(self, node):
return toInt(self.symdb.getValue(node.value))
def v_number(self, node):
return toInt(node.value)
def v_defined(self, node):
return self.symdb.defined(node.value)
def v_equality(self, node):
lhs = self.evaluate(node.lhs)
rhs = self.evaluate(node.rhs)
return lhs == rhs
def v_inequality(self, node):
return not self.v_equality(node)
def v_binOp(self, node):
lhs = self.evaluate(node.lhs)
rhs = self.evaluate(node.rhs)
return node.op(lhs, rhs)
def v_unaOp(self, node):
value = self.evaluate(node.value)
return node.op(value, self.symdb)
|
## the main function is one which will always be called and takes
## the users initial input and decides what to do with it
def main():
og = input().split()
go = ""
command = og[0]
og = og[1:]
for x in range(0, len(og)):
go = go + og[x]
if command == "solve":
solve(go)
## solve simply decides what order to call functions in order
## when the user wishes to solve an equation
def solve(uflist):
ufx = bracketCheck(interpart2(interpreter(uflist)))
print(ufx)
## interpreter takes the initial input and does some basic parsing which
## is essential in order for the later, more complicated parsing
def interpreter(inputlist):
intermediate = []
skip = [-1]
# this for loop identifies certain seperators and non number characters
# and decides whether or not to flag them
for x in range(0, len(inputlist)):
try:
int(inputlist[x])
intermediate.append(inputlist[x])
except ValueError:
if (
inputlist[x] == "." or inputlist[x] == "(" or \
inputlist[x] == ")" or inputlist[x] == "e" or \
inputlist[x] == "pi" or inputlist[x] == "x" or \
inputlist[x] == "y" or inputlist[x] == "z"
):
intermediate.append(inputlist[x])
else:
skip.append(x)
intermediate.append(inputlist[x])
skip.append(len(intermediate))
intermediate.append("")
outputlist = []
# this for loop conjoins related numbers and seperates them from operators
# e.g. '4, 1, *, 8' would be joint to '41, *, 8'
# this allows for the program to properly understand the users intention
for x in range(0, len(skip)-1):
glue = ""
for i in range(skip[x]+1, skip[x+1]):
glue = glue + intermediate[i]
outputlist.append(glue)
outputlist.append(intermediate[skip[x+1]])
outputlist = outputlist[:len(outputlist)-1]
return outputlist
## interpart2 deals with bracketed equations, at this point simply expressing
## them in an easier to deal with format, which can be utilised more later
def interpart2(checkee):
backside=-1
refurb=[]
for x in range(0, len(checkee)):
stack = ""
if x > backside:
if "(" in checkee[x]:
if ")" not in checkee[x]:
for y in range(x+1, len(checkee)):
if ")" in checkee[y]:
for z in range(x,y+1):
stack = stack + checkee[z]
refurb.append(stack)
backside = y
break
else:
refurb.append(checkee[x])
return refurb
## bracketCheck identifies the use of brackets and then transforms the input
## into a more readable format, that can be evaluated
def bracketCheck(sequence):
factor = ""
internal = ""
modi = 0
neosequence = []
for x in range(0, len(sequence)):
if "(" in sequence[x]:
modi = x
scan = list(sequence[x])
for y in range(0,len(scan)):
if scan[y] == "(":
operation = y
break
for y in range(0, operation):
factor = factor + scan[y]
internal = sequence[x][operation:]
break
if factor == "":
neosequence = sequence
else:
for x in range(0,modi):
neosequence.append(sequence[x])
neosequence.append(factor)
neosequence.append("*")
neosequence.append(internal)
for x in range(modi+1, len(sequence)):
neosequence.append(sequence[x])
return neosequence
## resolve takes any bracketed function and simplifies it down so that it can
## be manipulated further
def resolve(materia):
pass
## classify simply takes each part of the equation and identifies
## its type i.e. integers, decimals, operators, etc.
def classify(unknown):
identity = ""
try:
int(unknown)
identity = "integer"
except ValueError:
try:
float(unknown)
identity = "decimal"
except ValueError:
if unknown == "pi" or unknown == "e":
identity = "constant"
elif unknown == "x" or unknown == "y" or unknown == "z":
identity = "variable"
elif unknown == "+" or unknown == "-" or unknown == "*" or unknown == "/" or unknown == "^":
identity = "operator"
return identity
## TODO:
## start simplifying the equations given and actually doing some maths
## get interpreter to remove any spaces
main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 18 18:24:09 2019
@author: vikram
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 24 09:41:13 2019
@author: vikram
for regular regular expression basics
https://www.geeksforgeeks.org/regular-expression-python-examples-set-1/
"""
import pandas as pd
import re
import nltk
#nltk.download('stopwords')
nltk.download('punkt')
#from nltk.corpus import stopwords
essay = pd.read_csv('training_set_rel3.tsv', sep='\t', header=0,encoding="latin-1")
essay=essay[['essay_id','essay_set','essay','domain1_score']]
essay=essay.dropna(axis=0)
essay.head()
essay.info()
#tokens = nltk.word_tokenize(essay['essay'][0])
###########features extract##############
from nltk.tokenize import sent_tokenize, word_tokenize
features=pd.DataFrame()
def char_count(essay):
p=re.compile('\w')
char_count=p.findall(essay)
return len(char_count)
def word_count(essay):
p=re.compile('\w+')
char_count=p.findall(essay)
return len(char_count)
def sent_count(essay):
s=sent_tokenize(essay)
return len(s)
def avg_word_le(essay):
words =re.findall('\w+',essay)
return sum(len(word) for word in words)/len(words)
def extract_features(essay):
features['char_count']=essay['essay'].apply(char_count)
features['word_count']=essay['essay'].apply(word_count)
features['sent_count']=essay['essay'].apply(sent_count)
features['avg_word_le']=essay['essay'].apply(avg_word_le)
features['domain1_score']=essay['domain1_score']
return features
# extracting features from essay set 1
features_set = extract_features(essay[essay['essay_set'] == 1])
print(features_set)
#########vectorization by using TF-IDF###########
#Word Frequencies with TfidfVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
def get_count_vectors(essays):
# create the transform
print(essays[0])
vectorizer = TfidfVectorizer(max_features = 10000,min_df=0,max_df=1000, ngram_range=(1, 3), stop_words='english')
# tokenize and build vocab
vectorizer.fit(essays)
feature_names = vectorizer.get_feature_names()
#tf_cv = count_vectors.toarray()
# encode document
vector = vectorizer.transform(essays)
# summarize encoded vector
print(vector.shape)
#print(vector.toarray())
#count_vectors = vector.toarray()
return feature_names,vector
#####vectorization by bow###############
"""
from sklearn.feature_extraction.text import CountVectorizer
def get_count_vectors(essays):
vectorizer = CountVectorizer(max_features = 10000, ngram_range=(1, 3), stop_words='english')
count_vectors = vectorizer.fit_transform(essays)
feature_names = vectorizer.get_feature_names()
return feature_names, count_vectors
"""
feature_names_cv, count_vectors=get_count_vectors(essay[essay['essay_set'] == 1]['essay'])
X_cv = count_vectors.toarray()
##############features bow+extract features concatenate#########
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import LinearRegression #, Ridge, Lasso
#from sklearn.svm import SVR
#from sklearn import ensemble
#from sklearn.model_selection import GridSearchCV
from sklearn.metrics import cohen_kappa_score
X = np.concatenate((features_set.iloc[:, 0:4].as_matrix(), X_cv), axis = 1)
y = features_set['domain1_score'].as_matrix()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3)
linear_regressor = LinearRegression()
linear_regressor.fit(X_train, y_train)
y_pred = linear_regressor.predict(X_test)
# The coefficients
print('Coefficients: \n', linear_regressor.coef_)
# The mean squared error
print("Mean squared error: %.2f" % mean_squared_error(y_test, y_pred))
# Explained variance score: 1 is perfect prediction
print('Variance score: %.2f' % linear_regressor.score(X_test, y_test))
# Cohen’s kappa score: 1 is complete agreement
print('Cohen\'s kappa score: %.2f' % cohen_kappa_score(np.rint(y_pred), y_test))
################svm############
from sklearn.svm import SVC
classifier = SVC(kernel = 'poly', random_state = 0)
classifier.fit(X_train, y_train)
# Predicting the Test set results
labels_pred = classifier.predict(X_test)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, labels_pred)
# Model Score
score = classifier.score(X_test,y_test)
print('Cohen\'s kappa score: %.2f' % cohen_kappa_score(np.rint(labels_pred), y_test))
"""
from sklearn.model_selection import GridSearchCV
svr = SVC()
parameters = {'kernel':['linear', 'rbf'], 'C':[1, 100], 'gamma':[0.1, 0.001]}
grid = GridSearchCV(svr, parameters)
grid.fit(X_train, y_train)
y_pred = grid.predict(X_test)
# summarize the results of the grid search
print(grid.best_score_)
print(grid.best_estimator_)
# Explained variance score: 1 is perfect prediction
print('Variance score: %.2f' % grid.score(X_test, y_test))
# Cohen’s kappa score: 1 is complete agreement
print('Cohen\'s kappa score: %.2f' % cohen_kappa_score(np.rint(y_pred), y_test))
"""
# Exploratory Data Analysis (EDA) on the data
#import matplotlib as plot
features_set.plot.scatter(x = 'char_count', y = 'domain1_score', s=10)
features_set.plot.scatter(x = 'word_count', y = 'domain1_score', s=10)
features_set.plot.scatter(x = 'sent_count', y = 'domain1_score', s=10)
features_set.plot.scatter(x = 'avg_word_le', y = 'domain1_score', s=10)
#features_set1.plot.scatter(x = 'lemma_count', y = 'domain1_score', s=10)
#features_set1.plot.scatter(x = 'spell_err_count', y = 'domain1_score', s=10)
#features_set1.plot.scatter(x = 'noun_count', y = 'domain1_score', s=10)
#features_set1.plot.scatter(x = 'adj_count', y = 'domain1_score', s=10)
#features_set1.plot.scatter(x = 'verb_count', y = 'domain1_score', s=10)
#features_set1.plot.scatter(x = 'adv_count', y = 'domain1_score', s=10)
#Word Frequencies with TfidfVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
#list of text documents
text = ["The quick brown fox jumped over the lazy dog.",
"The dog.",
"The fox"]
# create the transform
vectorizer = TfidfVectorizer()
# tokenize and build vocab
count_vectors = vectorizer.fit(text)
feature_names = vectorizer.get_feature_names()
#tf_cv = count_vectors.toarray()
# encode document
vector = vectorizer.transform(text)
# summarize encoded vector
print(vector.shape)
print(vector.toarray())
|
# https://medium.com/python-features/using-locks-to-prevent-data-races-in-threads-in-python-b03dfcfbadd6
import threading
# Accumulate total count of all processed items
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
# By using a lock, we can have the Counter class protect
# its current value against simultaneous access from multiple threads.
class LockingCounter:
def __init__(self):
self.lock = threading.Lock()
self.count = 0
def increment(self):
# here we use with statement to acquire and release the lock
# this make it easier to see which code is executing while the lock is held
with self.lock:
self.count += 1
# Each sensors has its own worker thread for processing items
def worker(sensor_idx, items, counter):
for _ in range(items):
# Read from the sensor
# ...
# increment counter
counter.increment()
# Starts worker for each sensor and waits for them all to finish
def run_threads(func, items, counter):
threads = []
for i in range(5):
args = (i, items, counter)
thread = threading.Thread(target=func, args=args)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
def main():
# Running five threads in parallel
items = 100000
counter = Counter()
run_threads(worker, items, counter)
print('Counter should be {}, found {}'.format(5*items, counter.count))
# The Lock resolves the problem.
locked_counter = LockingCounter()
run_threads(worker, items, locked_counter)
print('Locked counter should be {}, found {}'.format(5*items, locked_counter.count))
if __name__ == '__main__':
main()
|
matrizA = [[0,0,0], [0,0,0], [0,0,0]]
matrizB = [[0,0,0], [0,0,0], [0,0,0]]
soma = [[0,0,0], [0,0,0], [0,0,0]]
for linha in range(0, 3):
for colunas in range(0, 3):
matrizA[linha][colunas] = int(input(f'Digite um valor para a Matriz A: '))
print('**' * 30)
for linha in range(0, 3):
for colunas in range(0, 3):
matrizB[linha][colunas] = int(input(f'Digite um valor para a Matriz B: '))
print('**' * 30)
for linha in range(0, 3):
for colunas in range(0,3):
soma[linha][colunas] = matrizA[linha][colunas] + matrizB[linha][colunas]
print(soma)
|
from random import randint
numeros = (randint(1,10),randint(1,10),randint(1,10),randint(1,10),randint(1,10))
print(f'Os valores sorteados foram:', end=' ')
for n in numeros:
print(f'{n}',end=' ')
print('\n'f'O maior valor foi {max(numeros)}.')
print(f'O menor valor foi {min(numeros)}.')
|
x = int(input("Digite um número inteiro: "))
print("""Escolha a base para conversão:
[ 1 ] Binário
[ 2 ] Octal
[ 3 ] Hexadecimal""")
opcao = int(input("Sua opção: "))
if opcao == 1:
print("{} convertido para Binário é igual {}".format(x, bin(x)[2:]))
elif opcao == 2:
print("{} convertido para Octal é igual {}".format(x, oct(x)[2:]))
elif opcao == 3:
print("{} convertido para Hexadecimal é igual {}".format(x, hex(x)[2:]))
else:
print("Opção inválida")
|
n = int(input("Digite um número: "))
n2 = int(input("Digite outro número: "))
soma = n+n2
print("A soma de {} mais {} é {}".format(n,n2,soma))
|
print("="*40)
print(" 10 TERMOS DE UMA PROGRESSÃO ARITMÉTICA")
print("="*40)
t = int(input("Digite o primeiro termo: "))
r = int(input("Digite a razão: "))
for c in range(0,10):
print(t,end=" ")
t = t + r
print("ACABOU")
|
l = int(input("Qual a largura da parede: "))
a = int(input("Qual a altura da parede: "))
a = l*a
tinta = a/2
print("Para pintar essa parede, você precisará de {:.0f} latas de tinta".format(tinta))
|
salario = int(input("Informe o valor do seu salário: R$ "))
salario10 = salario + (salario * 0.10)
salario15 = salario + (salario * 0.15)
if salario >= 1250:
print("O seu salário reajustado será R${:.2f}\n".format(salario10))
else:
print("O seu salário reajustado será R${:.2f}\n".format(salario15))
|
x = int(input("Digite o valor correspondente ao lado de um quadrado: "))
X = x*4
Y = x**2
print("perímetro:", X, "- área:", Y)
|
a = 3
b = a
print(f'A variável B = {b} recebe o valor da variável A = {a}')
print('***' *30)
a = 6
print(f'Alteramos o valor da variável A para {a}, o valor da variável B permanece sendo o valor da variável A do começo do código = {b}')
print('***' *30)
a = [3,4,5]
b = a
print(a,b)
b[1] = 8
print(a,b)
print('***' *30)
def g(x):
x = 5
return x
a = 3
print(f'valor de A na variável = {a}')
g(a)
print(f'valor de A dentro da função g(a) = {g(a)}')
print('***' *30)
def h(lst):
lst[0] = 5
return lst
myList = [3,6,9,12]
print(f'Minha lista no começo do código = {myList}')
h(myList)
print(f'Valor da minha lista dentro da função h(lst) alternando o valor da 1 posição na lista = {h(myList)}')
|
lista = ['Joe', 'Sue', 'Hani', 'Sofia']
nome = input('Digite seu nome: ')
if nome in lista:
print('Login:', nome)
print('Você está logado!')
else:
print('Login:', nome)
print('Acesso negado! ')
|
numero = int(input("Digite um número inteiro "))
unidade = numero % 10
numero = (numero - unidade) // 10
dezena = numero % 10
print("O dígito das dezenas é", dezena)
|
n = int(input('Digite o valor de n: '))
conta = 0
impar = 1
while conta < n:
print(impar)
conta += 1
impar += 2
|
def media(x,y):
return (x+y)/2
nota1 = eval(input('Digite o valor da nota 1: '))
nota2 = eval(input('Digite o valor da nota 2: '))
resultado = media(nota1,nota2)
print(resultado)
|
n = int(input("Digite um número: "))
contador = 0
for c in range(1,n+1):
if n == 2 or n == 5 or n == 9 or n % 2 != 0:
print("{} é primo.".format(c))
else:
print("{} não é primo.".format(c))
|
def fat(n):
if n == 0:
print(1)
else:
res = n * fat(n-1)
print(res)
n = input('Digite o valor de n: ')
fat(n)
|
def upper_first_char(s):
return s[0].upper() + s[1:]
def camel_case(s):
# remove punctuation, lower case, split by spaces
split = s.replace('.', ' ').lower().split()
# capitalize first letter of preceding words
for idx, word in enumerate(split):
if (idx > 0):
split[idx] = upper_first_char(split[idx])
return ''.join(split)
def snake_case(s):
# remove punctuation, lower case, split by spaces
split = s.replace('.', ' ').lower().split()
return '_'.join(split)
def filename(s):
return s.replace(' ', '').replace('&', '').replace('_', '').lower()
|
#Test scoreboard notice
import leaderboard
import turtle
import random
import math
playerName = input('What is your name')
Colours = ['Pink', 'lightblue', 'white']
colour = random.choice(Colours)
shape = 'circle'
size = 4
timer = 5
timerFinished = False
counter_interval = 1000
font = ('Courier New', 20, 'bold')
score = 10
pointsToAdd = 1
runner = turtle.Turtle()
runner.fillcolor(colour)
runner.shape(shape)
runner.shapesize(size)
runner.speed(8)
runner.penup()
runner.onclick(lambda x, y: addPoints())
def getNewCords():
newX = random.randint(-400, 400)
newY = random.randint(-300, 300)
return newX, newY
def moveToNewLocation():
global timerFinished
if not timerFinished:
runner.showturtle()
newX, newY = getNewCords()
runner.goto(newX, newY)
else:
return
scoreWritter = turtle.Turtle()
scoreWritter.hideturtle()
scoreWritter.penup()
scoreWritter.goto(-80, 250)
def addPoints():
global score, pointsToAdd
if runner.isvisible():
turtle.hideturtle()
score += pointsToAdd
scoreWritter.clear()
scoreWritter.write('Score: ' + str(score) , font = font)
moveToNewLocation()
def findHeading(x1, y1, x2, y2):
#I had to restudy geometry for this T~T
y = y2 -y1
x = x2 - x1
degrees = math.degrees(math.atan2(y,x))
print('Degress: ' + str(degrees))
return degrees - 90
def findDistance(x1, y1, x2, y2):
unroot = ((x2 - x1)**2) + ((y2 - y1)**2)
distance = math.sqrt(unroot)
print('Distance:' + str(distance))
return distance / 2
def moveInArc():
currentX, currentY = runner.xcor(), runner.ycor()
newX, newY = getNewCords()
runner.showturtle()
runner.setheading(findHeading(currentX, currentY, newX, newY))
runner.circle(findDistance(currentX, currentY, newX, newY), 180)
runner.hideturtle()
counter = turtle.Turtle()
counter.hideturtle()
counter.penup()
counter.goto(-80, 350)
def countdown():
global timer, timerFinished
counter.clear()
if timer <= 0:
counter.write('Times Up', font = font)
timerFinished = True
else:
counter.write("Timer: " + str(timer), font = font)
timer -= 1
counter.getscreen().ontimer(countdown, counter_interval)
window = turtle.Screen()
window.bgcolor('gray')
window.ontimer(countdown, counter_interval)
while not timerFinished:
moveInArc()
moveToNewLocation()
leaderboardTurtle = turtle.Turtle()
leaderboardTurtle.hideturtle()
leaderboardTurtle.penup()
leaderboardTurtle.goto(leaderboardTurtle.xcor() - 75, leaderboardTurtle.ycor())
if(timerFinished):
runner.hideturtle()
leaderboard.addItemToLeaderboard(playerName, score)
topThreeList = leaderboard.getTopX(3)
for player in ltopThreeList:
leaderboardTurtle.write(player, font = font)
leaderboardTurtle.goto(leaderboardTurtle.xcor(), leaderboardTurtle.ycor() - 30)
if (playerName + ' - ' + str(score) in topThreeList):
print('You made the leaderboard')
window.mainloop()
|
class Solution:
def isValid(self, s: str) -> bool:
stack = []
mapping = { ')':'(' , '}':'{', ']':'[' }
for bracket in s:
if bracket in mapping:
top_element = stack.pop() if stack else '#'
if top_element != mapping[bracket]:
return False
else:
stack.append(bracket)
return not stack
|
class Solution:
def isUgly(self, num: int) -> bool:
rem2 = 0
rem3 = 0
rem5 = 0
if num == 0:
return False
else:
while num%2 == 0:
rem2 = num%2
num = num/2
while num%3 == 0:
rem3 = num % 3
num = num / 3
while num%5 == 0:
rem5 = num % 5
num = num / 5
if num !=1:
return False
else:
return True
A=Solution()
A.isUgly(0)
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
'''
1. create a head
'''
curr = ListNode()
curr.next = head
first = curr
second = curr
for i in range (1, n+2):
first = first.next
while first != None:
first = first.next
second = second.next
second.next = second.next.next
return curr.next
|
import string
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
for i in paragraph:
if i in string.punctuation:
paragraph = paragraph.replace(i, ' ')
listOfWordsinParagraph = paragraph.lower().split()
freqOfWords = collections.Counter(listOfWordsinParagraph)
sortedfreq = sorted(freqOfWords.items(), key = lambda x : x[1], reverse = True)
#return sortedfreq
for i in sortedfreq:
if i[0] not in banned:
return i[0]
#return freqOfWords
|
d = {"a": 1, "b": 2, "c": 3}
a = d["a"]
b = d["b"]
sumlist = a + b
print(sumlist)
print(d["a"] + d["b"])
|
a=[1,2,3]
for index, item in enumerate(a):
print("Item %s has index %s" % (item,index))
for index, item in enumerate(a):
print("%s %s" % (index,item))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.