text stringlengths 37 1.41M |
|---|
"""implemenation of factorial with recursion"""
def factorial(n: int) -> int:
"""recursive implementation of factorial. Simple example without error checking.
args:
n: positive integer for factoial input
returns:
integer of product of factorial"""
# stop recursion when we get to 1
if n == 1:
return 1
else:
return n * factorial(n-1)
if __name__=="__main__":
print(factorial(1)) |
#!/usr/bin/env python
"""
Simple iterator examples
"""
class IterateMe_2:
def __init__(self, start=0, stop=5, step=1):
self.current = start-step
self.stop = stop
self.step = step
def __iter__(self):
return IterateMe_2_iter(self.current+self.step, self.stop, self.step)
class IterateMe_2_iter:
"""
About as simple an iterator as you can get:
returns the sequence of numbers from zero to 4
( like range(4) )
"""
def __init__(self, start=0, stop=5, step=1):
self.current = start-step
self.stop = stop
self.step = step
def __iter__(self):
return self
def __next__(self):
self.current += self.step
if self.current < self.stop:
return self.current
else:
raise StopIteration
def next(self):
return self.__next__()
if __name__ == "__main__":
print("Testing the iterator")
for i in IterateMe_2():
print(i)
print("\n Test that iterator matches range() function \n")
print("iterator output")
it = IterateMe_2(2,20,2)
for i in it:
if i>10: break
print(i)
print("\n Does iterator generate new iterator in a new for loop:")
for i in it:
print(i)
print("\n If we do the same with the range() function: \n")
it = range(2,20,2)
for i in it:
if i>10: break
print(i)
print("\n Does the range() function generate new iterator in a new for loop:")
for i in it:
print(i)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 13 17:18:15 2018
@author: Karl M. Snyder
"""
# recursive function for factorials
def factorial(x):
if x == 0: return 1
return x * factorial(x-1)
if __name__ == "__main__":
for x in range(1, 11):
print("factorial for,",x, "is ", factorial(x)) |
#!/usr/bin/env python3
import pandas as pd
def make_upper_att_filter(att, value):
def att_filter(data):
return [(song, artist, attribute) for song, artist, attribute
in zip(data.name, data.artists, data[att])
if attribute > value]
return att_filter
if __name__ == '__main__':
attribute = 'energy'
min_value = 0.8
music = pd.read_csv("featuresdf.csv")
energy_filter = make_upper_att_filter(attribute, min_value)
for n in energy_filter(music):
print('Song Name: {}, performed by: {}, energy value: {}'.format(*n)) |
'''
Lesson 2 Assignment #1: Generators
'''
import numpy as np
import pandas as pd
music = pd.read_csv("featuresdf.csv")
def get_name(result):
return result[1]
results = sorted([(a,n) for a,n in zip(music.artists, music.name) if a == "Ed Sheeran"], key=get_name)
def my_generator():
for i, result in enumerate(results):
yield result
gen = my_generator()
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
|
#!/usr/bin/env python 3
def sum_of_int(max):
'''Sum of the integers 0 + 1 + 2 + 3 + 4 + 5 + ...'''
sum = 0
a = 0
while a < max:
sum += a
a += 1
yield sum
def doubler(max):
'''Each value is double the previous value: 1, 2, 4, 8, 16, 32, ...'''
a = 1
while a < max:
yield a
a *= 2
def fibo(input_number):
'''Computes fibonacci numbers'''
a = 0
b = 1
while b <= input_number:
yield b
temp = b
b = a + b
a = temp
def prime_numbers(input_number):
'''Computes prime numbers, integers divisible only by 1 and itself.'''
a = 2
while a < input_number:
for x in range(2, a):
if a % x == 0:
break
else:
yield a
a += 1
def squared(max):
'''Calculate the square of consecutive numbers'''
a = 1
while a < max:
yield a * a
a += 1
def cubed(max):
'''Calculate the cube of consecutive numbers.'''
a = 1
while a < max:
yield a * a * a
a += 1
def counting_by(stop, counting_by_number):
'''Counting by a number.'''
if counting_by_number == 0:
yield counting_by_number
if counting_by_number > 0:
a = 1
while a < stop:
yield a
a += counting_by_number
else:
a = 1
while a > stop:
yield a
a += counting_by_number
if __name__ == "__main__":
print("Sum of consecutive integers: ")
sums = sum_of_int(10)
for x in sums:
print(x)
print("----------------------")
print("Double last number: ")
dbl = doubler(20)
for x in dbl:
print(x)
print("----------------------")
print("Fibonacci numbers")
fib = fibo(30)
for x in fib:
print(x)
print("----------------------")
print("Prime numbers")
prm = prime_numbers(30)
for x in prm:
print(x)
print("----------------------")
print("Squared numbers")
sqred = squared(10)
for x in sqred:
print(x)
print("----------------------")
print("Cubed numbers")
cbd = cubed(10)
for x in cbd:
print(x)
print("----------------------")
print("Generic function that counts by a number")
print("----------------------")
print("Count by 3")
skip = counting_by(20, 3)
for x in skip:
print(x)
print("----------------------")
print("Count by 6")
skip = counting_by(20, 6)
for x in skip:
print(x)
print("----------------------")
print("Count by -7")
skip = counting_by(-40, -7)
for x in skip:
print(x)
|
#!/usr/bin/env python
"""
Regular synchronous script to see how much a given word is mentioned in the news today
https://newsapi.org
NOTE : you need to register with the web site to get a key
"""
import time
import requests
import threading
import queue
__author__ = "Wieslaw Pucilowski"
WORD = "trump"
NEWS_API_KEY = "aaf5ea8408b845678ae5bd3c7f01ad18"
base_url = 'https://newsapi.org/v1/'
def get_sources():
"""
Get all the english language sources of news
'https://newsapi.org/v1/sources?language=en'
"""
url = base_url + 'sources'
params = {"language": "en"}
resp = requests.get(url, params=params)
data = resp.json()
sources = [src['id'].strip() for src in data['sources']]
print("all the {} sources:".format(len(sources)))
print(sources)
return sources
def get_articles(source):
"""
"""
url = base_url + "articles"
params = {"source": source,
"apiKey": NEWS_API_KEY,
# "sortBy" "latest", # some sources don't support latest
"sortBy": "top",
# "sortBy": "popular",
}
print("requesting:", source)
resp = requests.get(url, params=params)
if resp.status_code != 200: # aiohttpd has "status"
print("something went wrong with {}".format(source))
print(resp)
print(resp.text)
return []
data = resp.json()
titles = [str(art['title']) + str(art['description'])
for art in data['articles']]
return titles
def count_word(word, titles):
word = word.lower()
count = 0
for title in titles:
if word in title.lower():
count += 1
return count
def get_artickles_queue(source):
titles = get_articles(source)
q.put(titles)
if __name__ == "__main__":
art_count = 0
word_count = 0
q = queue.Queue()
threads = []
start = time.time()
sources = get_sources()
start2 = time.time()
# giving the free key limitation reducing polling to 10 sources
print("\nGiving the free key limitation reducing polling to 10 sources.\n")
for i in range(len(sources[:10])):
t = threading.Thread(target=get_artickles_queue, args=(sources[i],))
t.start()
threads.append(t)
for t in threads:
t.join()
print('All threads/requests finished, time to parse titles in the queue\n')
while not q.empty():
titles = q.get()
art_count += len(titles)
word_count += count_word('trump', titles)
print(WORD, "found {} times in {} articles".format(word_count, art_count))
print("Process took {:.0f} seconds, Articles scan took {:.0f} seconds".format(time.time() - start,
time.time() - start2)
)
############# Statistics ###############
########################################
# sequential:
# 'trump' found 70 times in 563 articles
# Process took 29 seconds
########################################
# threads:
# 'trump' found 52 times in 563 articles
# Process took 7 seconds
########################################
# threads and queue
# 'trump' found 55 times in 563 articles
# Process took 2 seconds
|
# multiplier.py
"""This module provides a multiplication operator"""
class Multiplier():
"""this performs multiplication"""
@staticmethod
def calc(operand_1, operand_2):
"""Multiplication"""
return operand_1 * operand_2
|
# lesson 07 mailroom using peewee
# !/usr/bin/env python3
""" Add, Delete, and Modify Donor Database Models in Peewee"""
import logging
from mailroom_setup import *
import datetime
logger = logging.getLogger(__name__)
database = SqliteDatabase('mailroom_db.db')
def add_donation():
""" Add new donation data """
logger.info('Trying to Add New Donation')
try:
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
while True:
add_name = input("\nTo whom would you like to send a thank you?\n"
"'List' will display current donors.\n"
"'Exit' will return to main menu.\n"
">>")
if add_name.lower() == "exit":
database.close()
print("\nExiting.\n")
break
elif add_name.lower() == "list":
nameq = (Donor.select(Donor.donor_name))
for name in nameq:
print(name)
else:
donation = input("\nWhat is the donation amount?\n>>")
try:
donation = int(donation)
if donation >= (10 ** 6):
print("\nThe amount entered is too large.")
else:
logger.info('Trying to add new donation')
with database.transaction():
nameq = (Donor.select().where(Donor.donor_name == add_name))
if nameq.scalar() == None:
"""Add Donor to database if not in there"""
DONOR_NAME = 0
DONOR_TOTAL = 1
DONOR_COUNT = 2
DONOR_AVERAGE = 3
donor = (add_name, 0, 0, 0)
new_donor = Donor.create(
donor_name = donor[DONOR_NAME],
donor_total = donor[DONOR_TOTAL],
donor_count = donor[DONOR_COUNT],
donor_average = donor[DONOR_AVERAGE]
)
new_donor.save()
logger.info('Donor population successful')
"""Add Donation to database"""
todays_date = datetime.date.today()
todays_date = (f'{todays_date:%Y%m%d}')
DONATION_DONOR = 0
DONATION_AMOUNT = 1
DONATION_DATE = 2
donation = (add_name, donation, str(todays_date))
don_donor = donation[DONATION_DONOR].split()
don_id = donation[DONATION_DATE] + "_" + don_donor[0][0:2] + don_donor[1][0:2]
new_donation = Donation.create(
donation_donor = donation[DONATION_DONOR],
donation_amount = donation[DONATION_AMOUNT],
donation_date = donation[DONATION_DATE],
donation_id = don_id)
new_donation.save()
refreshq = (Donor
.select(Donor, fn.SUM(Donation.donation_amount).alias('donor_total'), fn.COUNT(Donation.donation_id).alias('donor_count'), fn.AVG(Donation.donation_amount).alias('donor_average'))
.join(Donation, JOIN.INNER)
.group_by(Donor)
.order_by(SQL('donor_total').desc())
)
for don_ref in refreshq:
don_ref.donor_total = don_ref.donor_total
don_ref.donor_count = don_ref.donor_count
don_ref.donor_average = don_ref.donor_average
don_ref.save()
print(f"\nThank you, {new_donation.donation_donor}, for your generous donation of "
f"${new_donation.donation_amount} to the Brave Heart Foundation.")
logger.info('Donation population successful')
break
except ValueError:
if donation.lower() == "exit":
print("\nExiting.")
else:
print("\nInvalid entry.")
except Exception as e:
logger.info(f'Error adding new donation')
logger.info(e)
logger.info(f'Adding of donation failed')
exit()
finally:
logger.info('Database closed')
database.close()
def update_donation():
""" Update donation data """
logger.info('TODO')
logger.info('Trying to Update Donation')
try:
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
while True:
ask_donor = input("\nFor whom would you like to update a donation?\n"
"'List' will display current donors.\n"
"'Exit' will return to main menu.\n"
">>")
nameq = Donation.select().where(Donation.donation_donor == ask_donor)
if ask_donor.lower() == "exit":
database.close()
print("\nExiting.\n")
break
elif ask_donor.lower() == "list":
nameq = Donor.select(Donor.donor_name)
for name in nameq:
print(name)
elif nameq.scalar() == None:
database.close()
print("\nDonor not found.\n")
break
else:
print("\n{:<25} {:<10} {:<12}".format("Donor", "Date", "Amount"))
donq = Donation.select().where(Donation.donation_donor == ask_donor)
for donation in donq:
print(f'{str(donation.donation_donor):<25} {donation.donation_date:^10} ${donation.donation_amount:>12,.2f}')
ask_date = input("\nWhich donation date would you like to update?\n>>")
dateq = donq.select().where(Donation.donation_date == ask_date)
if dateq.scalar() == None:
print("\nThe date was not found.")
else:
update_don = input("\nWhat is the donation amount?\n>>")
try:
if int(update_don) >= (10 ** 6):
print("\nThe amount entered is too large.")
except ValueError:
if update_don.lower()== "exit":
print("\nExiting.")
else:
print("\nInvalid entry.")
update_date = input("\nWhat is the donation date? (Format: YYYYMMDD)\n>>")
try:
int(update_date)
except ValueError:
if update_date.lower()== "exit":
print("\nExiting.")
else:
print("\nInvalid entry.")
updateq = Donation.select().where(Donation.donation_donor == ask_donor, Donation.donation_date == ask_date)
for upd in updateq:
update_don_id = 12345678
upd.donation_amount = update_don
upd.donation_date = update_date
upd.save()
refreshq = (Donor
.select(Donor, fn.SUM(Donation.donation_amount).alias('donor_total'), fn.COUNT(Donation.donation_id).alias('donor_count'), fn.AVG(Donation.donation_amount).alias('donor_average'))
.join(Donation, JOIN.INNER)
.group_by(Donor)
.order_by(SQL('donor_total').desc())
)
for don_ref in refreshq:
don_ref.donor_total = don_ref.donor_total
don_ref.donor_count = don_ref.donor_count
don_ref.donor_average = don_ref.donor_average
don_ref.save()
print(f"The donation for {upd.donation_donor} has been updated to ${upd.donation_amount} on {upd.donation_date}.")
break
except Exception as e:
logger.info(f'Error updating donation')
logger.info(e)
logger.info(f'Update of donation failed')
exit()
finally:
logger.info('Database closed')
database.close()
def delete_donation():
""" Delete donation data """
logger.info('Trying to Delete Donation')
try:
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
while True:
ask_donor = input("\nFrom whom would you like to delete a donation?\n"
"'List' will display current donors.\n"
"'Exit' will return to main menu.\n"
">>")
nameq = Donation.select().where(Donation.donation_donor == ask_donor)
if ask_donor.lower() == "exit":
database.close()
print("\nExiting.\n")
break
elif ask_donor.lower() == "list":
nameq = Donor.select(Donor.donor_name)
for name in nameq:
print(name)
elif nameq.scalar() == None:
database.close()
print("\nDonor not found.\n")
break
else:
print("\n{:<25} {:<10} {:<12}".format("Donor", "Date", "Amount"))
donq = Donation.select().where(Donation.donation_donor == ask_donor)
for donation in donq:
print(f'{str(donation.donation_donor):<25} {donation.donation_date:^10} ${donation.donation_amount:>12,.2f}')
ask_date = input("\nWhich donation date would you like to delete?\n>>")
dateq = donq.select().where(Donation.donation_date == ask_date)
if dateq.scalar() == None:
print("\nThe date was not found.")
else:
del_don = Donation.delete().where(Donation.donation_donor == ask_donor, Donation.donation_date == ask_date)
del_don.execute()
print(f"The donation record for {ask_donor} on {ask_date} was deleted.")
query = Donation.select().where(Donation.donation_donor == ask_donor)
if query.scalar() == None:
del_donor = Donor.delete().where(Donor.donor_name == ask_donor)
del_donor.execute()
print(f"The donor record for {ask_donor} was deleted.")
break
except Exception as e:
logger.info(f'Error deleting donation')
logger.info(e)
logger.info(f'Deletion of donation failed')
exit()
finally:
logger.info('Database closed')
database.close()
if __name__ == '__main__':
add_donation()
update_donation()
delete_donation()
|
"""
This module provides a Divider class
"""
class Divider:
"""
This class allows for calculator division
"""
@staticmethod
def calc(operand_1, operand_2):
"""
This method calculates, and returns, the division of the two operands
"""
return operand_1/operand_2
|
#!/usr/bin/env python3
class Locke:
def __init__(self, size):
self.size = size
def __enter__(self):
print("Stopping the pumps.")
print("Opening the doors.")
return self
def move_boats_through(self, boats):
self.boats = boats
if self.boats > self.size:
raise ValueError(f'Number of boats({self.boats}) exceeds lock size({self.size})')
else:
print(f'Moving {self.boats} boats through!')
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
print("Closing the doors.")
print("Restarting the pumps")
else:
print("Please try again with fewer boats")
if __name__ == '__main__':
small_locke = Locke(5)
large_locke = Locke(10)
boats = 8
# Too many boats through a small locke will raise an exception
with small_locke as locke:
locke.move_boats_through(boats)
# A lock with sufficient capacity can move boats without incident.
# with large_locke as locke:
# locke.move_boats_through(boats) |
"""subtractor Module
Contains a single Subtractor class that provides subtraction functionality
"""
class Subtracter(object):
"""This class performs a single static subtraction calculation"""
@staticmethod
def calc(operand_1, operand_2):
"""Performs subtraction of the two passed operands
Args:
operand_1 (float): first operand
operand_2 (float): second operand
Returns:
float: result of subtraction of the two operands
"""
return operand_1 - operand_2
|
# ----------------------------------------------------------------------------------------------------------------------
# AUTHOR: Micah Braun
# PROJECT NAME: Closures.py
# DATE CREATED: 09/13/2018
# UPDATED: N/A
# PURPOSE: PYTHON 220 Lesson 02
# DESCRIPTION: Program exemplifies aspects of Python's closures (a function defined within another function) that has
# 'memory' of variables from the outer function without having the actual variables present in RAM. For this program
# the main() function calls the outer function, closure_part_one(), which takes the .csv variable as an argument
# passed in to it. The function, filters the .csv file for music tracks over 0.8 (tempo) and then falls through
# to the nested function, closure_part_two which 'remembers' the data from the outer scope and formats/prints it.
# ------------------------------------------------------------------------------------------------------------------
# ============================================= SET UP =======================================================
import pandas as f
space = '\n' # spacing between prints
decor = "-" * 100 # line separator for printing
# ============================================ PROCESSING ====================================================
def closure_part_one(music): # outer scope with access to .csv data
print(space)
print('{:>55}'.format('HYPE SONGS')) # Header for data
print(decor)
over_point_eight = ([(artist, name, energy) for artist, name, energy
in zip(music.artists, music.name, music.energy) if energy > 0.8]) # filter/generator
def closure_part_two(): # nested function
count_next = 1
for i in over_point_eight:
if count_next <= 9: # Adjusts spaces based on single/double-digits
print(count_next, ' .) ', end='')
print('{:>20s} {:^25f} {:<5s} '.format(i[0], i[2], i[1]))
count_next += 1
else:
print(count_next, '.) ', end='')
print('{:>20s} {:^25f} {:<15s} '.format(i[0], i[2], i[1]))
count_next += 1
return closure_part_two()
def main():
music = f.read_csv("featuresdf.csv")
closure_part_one(music)
# ============================================== OUT-PUT =====================================================
if __name__ == '__main__':
main()
|
"""
Simple database example with Peewee ORM, sqlite and Python
Here we define the schema
Use logging for messages so they can be turned off
"""
import logging
from peewee import *
from pprint import *
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info('Here we define our data (the schema)')
logger.info('First name and connect to a database (sqlite here)')
logger.info('The next 3 lines of code are the only database specific code')
database = SqliteDatabase('donors.db')
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
logger.info('Enable the Peewee magic! This base class does it all')
class BaseModel(Model):
class Meta:
database = database
logger.info('By inheritance only we keep our model (almost) technology neutral')
class Donor(BaseModel):
"""
This class defines Donor.
"""
donor_name = CharField(primary_key = True, max_length=40)
donor_num = IntegerField()
class Donation(BaseModel):
"""
This class defines a donation table
"""
logger.info('The donation amount')
donation_amount = DecimalField()
logger.info('The donor')
donor_name_two = ForeignKeyField(Donor, column_name='donor_name', null=False)
def populate_donors():
"""
Add donor to database
"""
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
database = SqliteDatabase('donors.db')
logger.info('Working with Donor class')
DONOR_NAME = 0
DONOR_NUM = 1
donors = [('Andy', 1), ('Bill', 2), ('Chuck', 3)]
try:
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
for donor in donors:
with database.transaction():
new_donor = Donor.create(
donor_name=donor[DONOR_NAME],
donor_num=donor[DONOR_NUM]
)
new_donor.save()
logger.info('Database add successful')
logger.info('Print the Donor records we saved...')
for donors in Donor:
logger.info(f'{donors.donor_name} added to database.')
except Exception as e:
logger.info(f'Error creating = {donor[DONOR_NAME]}')
logger.info(e)
logger.info('See how the database protects our data')
finally:
logger.info('database closes')
database.close()
database.create_tables([Donor, Donation])
database.close()
def populate_donations():
"""
Add donations to database
"""
database = SqliteDatabase('donors.db')
DONATION_AMOUNT = 0
DONOR_NAME_TWO = 1
donations = [
(10.00, 'Andy'),
(20.00, 'Andy'),
(30.00, 'Andy'),
(40.00, 'Bill'),
(50.00, 'Bill'),
(25.00, 'Chuck'),
]
try:
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
for donation in donations:
with database.transaction():
new_gift = Donation.create(
donation_amount = donation[DONATION_AMOUNT],
donor_name_two = donation[DONOR_NAME_TWO])
new_gift.save()
logger.info('Database add successful')
logger.info('Print the Person records we saved...')
for donations in Donation:
logger.info(f'{donations.donation_amount} from {donations.donor_name_two}')
except Exception as e:
logger.info(f'Error creating = {donation[GIFT_VALUE]}')
logger.info(e)
logger.info('See how the database protects our data')
finally:
logger.info('database closes')
database.close()
if __name__ == '__main__':
populate_donors()
populate_donations()
|
import pandas as pd
# 1st ex.: Using Spotify 2017 top100 track data w/ Pandas + List Comprehensions
# m = pd.read_csv('featuresdf.csv')
m = pd.read_csv('featuresdf.csv')
print('m.head() returns:\n')
print(m.head())
print('\nm.describe() returns:\n')
print(m.describe(), '\n'*2)
a = sorted(list(zip(m.danceability, m.name, m.artists, m.loudness)),
reverse=True)
b = [track for track in a if track[0] > 0.8 and track[3] < -5.0]
print('Top 5 tracks in order by descending danceability > 0.8' +
' and loudness < -5.0:\n')
for track in b[:5]:
print(track)
|
#!/usr/bin/env python
# Lesson 1: learning generators
def intsum(i=0, count=0):
while True:
count += i
yield count
i += 1
def intsum2(i=0, count=0):
while True:
count += i
yield count
i += 1
def doubler(i=1):
while True:
yield i
i *= 2
def fib(a=1, b=1):
while True:
yield a
a, b = b, a + b
def prime(i=2):
while True:
if not [x for x in range(2, i) if i % x == 0]:
yield i
i += 1
|
#!/usr/bin/env python3
"""
Simple metaclass example that creates upper and lower case versions of
all non-dunder class attributes
"""
class NameMangler(type): # deriving from type makes it a metaclass.
def __new__(cls, clsname, bases, _dict):
uppercase_attr = {}
for name, val in _dict.items():
if not name.startswith('__'):
uppercase_attr[name.upper()] = val
uppercase_attr[name.lower()] = val
uppercase_attr[name*2] = val
else:
uppercase_attr[name] = val
return super().__new__(cls, clsname, bases, uppercase_attr)
class Foo(metaclass=NameMangler):
x = 1
Y = 2
# note that it works for methods, too!
class Bar(metaclass=NameMangler):
x = 1
def a_method(self):
print("in a_method")
if __name__ == "__main__":
f = Foo()
print(f.x)
print(f.X)
print(f.y)
print(f.Y)
print(f.xx)
print(f.YY)
b = Bar()
b.A_METHOD() |
#!/usr/bin/env python3
import sys
import re
import json
from donor_class import *
import os
# New instance of the MyDonation class
donations_list = MyDonations()
def main():
"""
Displays the main menu selection options
"""
# Menu options
options = {1: send_thank_you,
2: create_report,
3: send_letters,
4: challenge,
5: update_donor,
6: update_donation,
7: delete_donor,
8: delete_donation,
9: load_initial_donors,
10: validate_donor,
0: sys.exit}
prompt = "\nChoose an action:\n"
menu_sel = ("\n1 - Send a Thank You\n2 - Create a Report\n"
"3 - Send letters to everyone\n4 - Projections\n\n"
"5 - Update Donor\n6 - Update Donation\n\n"
"7 - Delete Donor\n8 - Delete Donation\n\n"
"9 - Load Initial Donors\n\n*10 - Donor Validation Lookup\n\n"
"0 - Quit\n\n")
# User selection
while True:
try:
user_selection = input(prompt + menu_sel)
options.get(int(user_selection))()
except ValueError:
print("\nPlease select a numeric value...")
# except TypeError as e:
# print(e)
# print("\nOption {} is invalid. Try again...".format(user_selection))
def send_thank_you():
"""
Sends a thank you email to the selected donor
"""
# Get name of donor
donor_name = name_prompt()
# Display list of donors when user types "list"
while donor_name.lower() == "list":
donations_list.get_formatted_list_of_donors()
donor_name = name_prompt()
# Get donation amount
amt_input = donation_prompt()
donations_list.add_donation(donor_name, float(amt_input))
print(send_email(donations_list.get_last_donation(donor_name)))
def create_report():
"""
Displays a summary report of the current list of donations
"""
donations_list.get_summary
def send_letters():
"""
reates a thank you letter for each donor as a
text document
"""
for value in donations_list.get_list_of_donors():
name = str(value)
if not os.path.exists('letters/'):
os.makedirs('letters/')
with open("letters/"+name+".txt", 'w') as f:
f.write(create_letter(donations_list.get_donor_summary(name)))
print("\nLetter to {} has been sent...".format(name))
def challenge():
"""
Challenges a donor's current donations for a given range
and with a given multiplier value
"""
while True:
try:
donor_name = name_prompt()
# Display list of donors when user types "list"
while donor_name.lower() == "list":
donations_list.get_formatted_list_of_donors()
donor_name = name_prompt()
# Display current list of donations
donations_list.get_formatted_list_of_donations(donor_name)
min = min_prompt()
max = max_prompt()
multiplier = multiplier_prompt()
print(donations_list.challenge(donor_name, factor=multiplier, min=min, max=max))
break
except ValueError:
print("\n>> Please enter a valid donor name <<")
except KeyError:
print("\n>> Donor not found <<")
def update_donor():
"""
Updates a donor's current name
"""
while True:
try:
# Get name of donor to be updated
donor_name = name_prompt()
# Display list of donors when user types "list"
while donor_name.lower() == "list":
donations_list.get_formatted_list_of_donors()
donor_name = name_prompt()
# Get donor's new name
new_name = new_name_prompt()
donations_list.update_donor(donor_name, new_name)
break
except ValueError:
print("\n>> Donor not found <<")
def update_donation():
"""
Updates a donor's donation
"""
while True:
try:
# Get name of donor to be deleted
donor_name = name_prompt()
# Display list of donors when the user types "list"
while donor_name.lower() == "list":
donations_list.get_formatted_list_of_donors()
donor_name = name_prompt()
# Display current list of donations
donations_list.get_formatted_list_of_donations(donor_name)
donation = donation_prompt()
new_donation = new_donation_prompt()
donations_list.update_donation(donor_name, donation, new_donation)
break
except ValueError:
print("\n>> Donor not found <<")
except DonationError:
print("\n>> Donation not found <<")
def delete_donor():
"""
Deletes the specified donor and donations from the database
"""
while True:
try:
# Get name of donor to be deleted
donor_name = name_prompt()
# Display list of donors when user types "list"
while donor_name.lower() == "list":
donations_list.get_formatted_list_of_donors()
donor_name = name_prompt()
donations_list.delete_donor(donor_name)
break
except ValueError:
print("\n>> Donor not found <<")
def delete_donation():
"""
Deletes the specified donor's donation
"""
donor_name = ""
donation = 0
while True:
try:
# Get name of donor to be deleted
donor_name = name_prompt()
# Display list of donors when the user types "list"
while donor_name.lower() == "list":
donations_list.get_formatted_list_of_donors()
donor_name = name_prompt()
# Display current list of donations
donations_list.get_formatted_list_of_donations(donor_name)
donation = donation_prompt()
donations_list.delete_donation(donor_name, donation)
break
except ValueError:
print("\n>> Donor not found <<")
except DonationError:
print("\n>> Donation not found <<")
def load_initial_donors():
"""
Loads the initial list of donors and donations
"""
donations_list.load_initial_donors()
def validate_donor():
"""
Gives the user the ability validate a donor's information
"""
donations_list.update_cache()
val_value = ''
# Get name of donor to validate
donor_name = name_prompt()
# Display list of donors when user types "list"
while donor_name.lower() == "list":
donations_list.get_formatted_list_of_donors()
donor_name = name_prompt()
while val_value.lower() != "done":
# Get name of donor to validate
val_value = lookup_prompt()
donations_list.donor_lookup(donor_name, val_value)
print("\n--Type 'done' to return to main menu.\n")
####
# Helper methods:
####
def name_prompt():
"""
Prompts the user for the name of donor to send thank you email
"""
while True:
try:
name = input("\nPlease enter the Donor's full name:\n" +
"(Type 'list' to display a list of current donors): ").strip()
if re.match("^[A-Za-z ,]*$", name) and name:
return name
break
else:
print("\n>> Please enter a valid name <<")
except ValueError:
print("\n>> Please enter a valid name <<")
def new_name_prompt():
"""
Prompts the user for the donor's updated name
"""
while True:
try:
name = input("\nPlease enter the Donor's new name:\n").strip()
if re.match("^[A-Za-z ,]*$", name) and name:
return name
break
else:
print("\n>> Please enter a valid name <<")
except ValueError:
print("\n>> Please enter a valid name <<")
def donation_prompt():
"""
Prompts the user for a donation amount
"""
while True:
try:
amount = re.sub("[, ]", "", input("\nDonation amount:\n$"))
return round(float(amount), 2)
break
except ValueError:
print("\n>> Please enter a valid donation amount <<")
def new_donation_prompt():
"""
Prompts the user for the updated donatino amount
"""
while True:
try:
amount = re.sub("[, ]", "", input("\nNew donation amount:\n$"))
return round(float(amount), 2)
break
except ValueError:
print("\n>> Please enter a valid donation amount <<")
def multiplier_prompt():
"""
Prompts the user for the donation multiplier factor
"""
while True:
try:
multiplier = re.sub("[, ]", "", input("\nMultiply donations by: "))
return int(multiplier)
break
except ValueError:
print("\n>> Please enter a valid multiplier <<")
def min_prompt():
"""
Prompts the user for the minimum projection donation
"""
while True:
try:
min = re.sub("[, ]", "", input("\nMin donation (Press enter for default value): "))
return round(float(0), 2) if not min else round(float(min), 2)
break
except ValueError:
print("\n>> Please enter a valid minimum value <<")
def max_prompt():
"""
Prompts the user for the maximum projection donation
"""
while True:
try:
max = re.sub("[, ]", "", input("\nMax donation (Press enter for default value): "))
return round(float(9999999), 2) if not max else round(float(max), 2)
break
except ValueError:
print("\n>> Please enter a valid maximum value <<")
def lookup_prompt():
"""
Prompts the user for a validation value
"""
list_of_values = ['phone', 'email', 'zip', 'last donation', 'last donation date',
'all', 'done']
while True:
try:
value = (input("\nPlease enter a lookup value:\n" +
"(phone, email, zip, last donation, last donation date, all): ")
.strip().lower())
if re.match("^[A-Za-z ,]*$", value) and value and value in list_of_values:
return value.replace(' ', '_')
break
else:
print("\n>> Please enter a valid lookup value <<")
except ValueError:
print("\n>> Please enter a valid lookup value <<")
def send_email(new_donor):
"""
Formats the email for newly added donors
"""
body = ("\nDear {donor_name},\n\n"
"I would like to personally thank you for your generours donation "
"of ${amount} to our charity organization.\nYour support allows us"
" to continue supporting more individuals in need of our services."
"\n\nSincerely,\nCharity Inc.\n").format(**new_donor)
return body
def create_letter(donations):
"""
Formats the letter for the current list of donors
"""
body = ("\nDear {donor_name},\n\n"
"I would like to personally thank you for your recent "
"donation of ${last_donation} to our charity organization. "
"You have donated a total of ${total} as of today. "
"Your support allows us to continue supporting more individuals "
"in need of our services."
"\n\nSincerely,\nCharity Inc.\n").format(**donations)
return body
if __name__ == "__main__":
main()
|
"""
This module provides an Adder class
"""
class Adder:
"""
This class allows for calculator addition
"""
@staticmethod
def calc(operand_1, operand_2):
"""
This method calculates, and returns, the addition of the two operands
"""
return operand_1 + operand_2
|
#-------------------------------------------------#
# Title: Context Managers: Lockes
# Dev: LDenney
# Date: February 11th, 2019
# ChangeLog: (Who, When, What)
# Laura Denney, 2/11/19, Started work on context Managers Assignment
# Laura Denney, 2/13/19, Finished testing
#-------------------------------------------------#
from contextlib import contextmanager
class Locke(object):
def __init__(self,boat_capacity):
self.boat_capacity=boat_capacity
def __repr__(self):
return "Locke capacity is {} boats.".format(self.boat_capacity)
def __enter__(self):
self.pump = "stop"
print("Stopping the pumps.")
self.door = "open"
print("Opening the doors.")
self.door = "close"
print("Closing the doors.")
self.pump = "start"
print("Restarting the pumps.")
return self
def __exit__(self,exc_type, exc_val, exc_tb):
if exc_type:
print("{}".format(exc_val))
self.pump = "stop"
print("Stopping the pumps.")
self.door = "open"
print("Opening the doors.")
self.door = "close"
print("Closing the doors.")
self.pump = "start"
print("Restarting the pumps.\n")
def move_boats_through(self, boats):
if boats <= self.boat_capacity:
print("Boats moving through the lockes.")
else:
raise ValueError("Too many boats, will not fit in lockes.")
def locke_spectator(locke, boats):
print(locke)
print(f"Number of boats attempting passage: {boats}")
with locke as spectacle:
try:
spectacle.move_boats_through(boats)
except ValueError as e:
print(e)
if __name__ == "__main__":
small_locke = Locke(4)
large_locke = Locke(8)
locke_spectator(small_locke, 3)
locke_spectator(small_locke, 5)
locke_spectator(large_locke, 6)
locke_spectator(large_locke, 9)
|
"""defines divider objects"""
class Divider:
"""defines basic divider object"""
@staticmethod
def calc(operand_1: float, operand_2: float):
"""performs division of two numerators with first input being numerator and
second input denomenator
args:
operand_1: numerator float input
operand_2: denomenator float input
returns:
float from division of operand_1/operand_2
"""
return operand_1/operand_2
|
import time
from math import sqrt, factorial
times = 35
def fib_recursive(n):
"""
The Fibonacci sequence as a generator:
f(n) = f(n-1) + f(n-2)
1, 1, 2, 3, 5, 8, 13, 21, 34…
"""
if n <= 1:
return n
else:
return fib_recursive(n-1) + fib_recursive(n-2)
def factorial_recursive(n):
"""
Returns the factorial of a given non-negative integer,
the product of all positive integers less than or equal to that number.
"""
if n < 0:
print(f"Please enter a non-negative integer. You entered {n}.")
return
elif n <= 1:
return 1
else:
return n * factorial(n - 1)
if __name__ == "__main__":
init = time.clock()
for i in range(times):
# Credits to Stack Overflow for this succinct version of the Fibonacci sequence.
value = ((1+sqrt(5))**i-(1-sqrt(5))**i)/(2**i*sqrt(5))
print(f"No function time for Fibonacci: {time.clock() - init}")
init = time.clock()
result = fib_recursive(times)
print(f"Function time for Fibonacci: {time.clock() - init}")
init = time.clock()
factorial(times)
print(f"No function time for factorial: {time.clock() - init}")
init = time.clock()
result = factorial_recursive(times)
print(f"Function time for factorial: {time.clock() - init}")
# Standard Python interpreter results:
# No function time for Fibonacci: 7.107942644800277e-05
# Function time for Fibonacci: 3.1865595943568525
# No function time for factorial: 3.414295593362482e-06
# Function time for factorial: 2.1727335597354624e-06
# pypy interpreter results:
# No function time for Fibonacci: 0.00536044408190833
# Function time for Fibonacci: 0.18236652897743708
# No function time for factorial: 8.473660882230005e-05
# Function time for factorial: 3.290139390169089e-05
|
"""
Learning persistence with Peewee and sqlite
delete the database to start over
(but running this program does not require it)
"""
from mailroom_db_model import *
import logging
def populate_donor_db():
"""
add person data to database
"""
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
database = SqliteDatabase('donor_list.db')
logger.info('Working with Person class')
PERSON_NAME = 0
LIVES_IN_TOWN = 1
donors = [
('Toni Orlando', 'Sumner'),
('Amanda Clark', 'Seattle'),
('Robin Hood', 'NeverLand'),
('Gina Travis', 'Coventry'),
('Mark Johnson', 'Colchester')
]
logger.info('Creating Donor records: iterate through the list of tuples')
try:
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
for person in donors:
with database.transaction():
new_person = Donor.create(
person_name=person[PERSON_NAME],
lives_in=person[LIVES_IN_TOWN])
new_person.save()
logger.info('Database add successful')
logger.info('Print the Person records we saved...')
for saved_person in Donor:
logger.info(
f'{saved_person.person_name} lives in {saved_person.lives_in}')
except Exception as e:
logger.info(f'Error creating = {person[PERSON_NAME]}')
logger.info(e)
finally:
database.close()
def populate_donations_db():
"""
add donations amount to database
"""
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
database = SqliteDatabase('donor_list.db')
logger.info('Migrating initial data into tables.')
DONOR_NAME = 0
DONATION_AMOUNT = 1
donations_list = [
('Toni Orlando', 150.00),
('Toni Orlando', 200.00),
('Toni Orlando', 100.00),
('Amanda Clark', 1800.00),
('Robin Hood', 1234.56),
('Robin Hood', 4500.34),
('Robin Hood', 765.28),
('Gina Travis', 75.00),
('Mark Johnson', 850.00),
('Mark Johnson', 20.14),
]
try:
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
for donation in donations_list:
with database.transaction():
new_donation = Donations.create(
donor_name=donation[DONOR_NAME],
donation_amount=donation[DONATION_AMOUNT])
new_donation.save()
logger.info('Reading and print all Departments rows')
for donation in Donations:
logger.info(f'{donation.donor_name} donated '
f'${donation.donation_amount}')
except Exception as e:
logger.info(f'Error creating = {donation[DONOR_NAME]}')
logger.info(e)
finally:
logger.info('database closes')
database.close()
if __name__ == '__main__':
populate_donor_db()
populate_donations_db()
|
#!/usr/bin/env python3
import pandas as pd
__author__="Wieslaw Pucilowski"
music = pd.read_csv("featuresdf.csv")
def Find_Artist(artist="Ed Sheeran"):
selection = [x for x in list(zip(music.name,
music.artists))
if x[1] == artist]
def music_gen():
for i in selection:
yield i
return music_gen
if __name__ == "__main__":
g = Find_Artist(artist="Ed Sheeran")()
while True:
try:
print("{}, {}".format(*next(g)))
except StopIteration:
print("+++ This is the end +++")
break |
"""
Simple module that provides class instances for subtraction operations
"""
class Subtracter():
"""This class has only a static calc method that
returns the result of subtraction of two operands
"""
@staticmethod
def calc(operand_1, operand_2):
"""Subtracts second operand from first operand; returns difference"""
return operand_1 - operand_2
|
"""Module for adding two numbers"""
class Adder(object):
"""Class for addition of 2 numbers."""
@staticmethod
def calc(operand_1, operand_2):
""" Perforn the addition step."""
return operand_1 + operand_2
|
import time
def memoize(f):
memo = {}
def helper(x):
if x not in memo:
memo[x] = f(x)
return memo[x]
return helper
@memoize
def fib(n):
if n <= 1:
return n
else:
return fib(n-1) + fib(n-2)
def fib1(n):
if n <= 1:
return n
else:
return fib1(n-1) + fib1(n-2)
if __name__ == '__main__':
start = time.time()
print(fib(35))
print("Memoized implemematation: " + str(time.time() - start))
start = time.time()
print(fib1(35))
print("Regualr recursive implemematation: " + str(time.time() - start))
init = time.clock()
print(fib(35))
print("Using clock: " + str(time.clock() - init))
|
import pandas as pd
music = pd.read_csv("featuresdf.csv")
song_list = [ x for x in zip(music.name, music.artists, music.danceability, music.loudness) if x[2] > 0.8 and x[3] < -5]
def danceability_sort(x):
return x[2]
for song in sorted(song_list, key=danceability_sort, reverse=True):
print(song) |
""" Write a context manager class named "Locke"
WHen locked entered:
stop pump
opens doors
closes doors
restarts pumps
When Locke exited:
stops pumps
opens doors
closes doors
restarts pumps
class initiation:
class accepts locke's capacity (num boats)
if too many boats:
error raised
Example:
small_locke = Locke(5)
large_locke = Locke(10)
boats = 8
# Too many boats through a small locke will raise an exception
with small_locke as locke:
locke.move_boats_through(boats)
# A lock with sufficient capacity can move boats without incident.
with large_locke as locke:
locke.move_boats_through(boats)
"""
class Locke:
def __init__(self, capacity):
self.capacity = capacity
def __enter__(self):
print("Stopping the pumps")
print("Opening the doors")
print("Closing the doors")
print("Restarting the pumps")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_val:
print(exc_val)
print("Stopping the pumps")
print("Opening the doors")
print("Closing the doors")
print("Restarting the pumps")
return self
def move_boats_through(self, boats):
if boats > self.capacity:
raise Exception("Too many Boats in the locke.")
else:
print("Moving {} Boats through".format(boats))
#Testing below
small_locke = Locke(5)
large_locke = Locke(10)
boats = 8
# Too many boats through a small locke will raise an exception
with small_locke as locke:
locke.move_boats_through(boats)
# A lock with sufficient capacity can move boats without incident.
with large_locke as locke:
locke.move_boats_through(boats)
|
# Ballard Locks context manager exercise
from time import sleep
class Locke(object):
"""
Creates Locke objects
"""
def __init__(self, boat_capacity):
self.boat_capacity = boat_capacity
def typical_operation(*args):
op_text = """
Stopping the pumps.
Opening the doors.
Closing the doors.
Restarting the pumps.
"""
sleep(2)
print(op_text)
def __enter__(self):
return self
def __exit__(self, *args):
print('\nLocke operation halted.')
def move_boats_through(self, boats):
try:
assert boats <= self.boat_capacity
print('Preparing to allow entry into locke.\n')
self.typical_operation()
print('\nBoats entering locke.')
print('Preparing locke for exiting.\n')
self.typical_operation()
print('\nBoats have exited locke.')
except AssertionError:
print('Number of boats exceeds locke\'s capacity.')
|
class Generator:
def sum_of_integers(self, int_list):
my_sum = 0
for num in int_list:
my_sum += num
yield my_sum
def doubler(self, start, stop):
if start < 1:
start += 1
cur_value = start
for num in range(start, stop):
yield cur_value
cur_value *= 2
@staticmethod
def sum_series(n,x=0,y=1):
"""return the nth value of fibonacci (x=0,y=1) or lucas (x=2,y=1) series"""
if x not in (0,2) or y != 1:
print("function not found for x=" + str(x) + " and y=" + str(y))
else:
if n == 0:
return x
elif n == 1:
return y
else:
return Generator.sum_series(n-2,x,y) + Generator.sum_series(n-1,x,y)
def fibonacci(self, int_list):
"""return the nth value in the fibonacci series fib(n) = fib(n-2) + fib(n-1)"""
for n in int_list:
if n >= 2:
yield Generator.sum_series(n)
else:
yield n
def prime(self,int_list):
""" return any value in a list of integers that is prime """
for n in int_list:
if n < 2:
continue
else:
prime = True
for i in range(2,n):
if n % i == 0:
prime = False
break
if prime:
yield n
|
#!/usr/bin/env python3
"""Recursive module"""
import sys
def my_func(n):
if n == 2:
return True
return my_func(n / 2)
if __name__ == '__main__':
n = int(sys.argv[1])
print(my_func(n)) |
def intsum():
x = 0
x_sum = 0
while True:
x_sum += x
yield x_sum
x += 1
def intsum2():
x = 0
x_sum = 0
while True:
x_sum += x
yield x_sum
x += 1
def doubler():
x = 1
while True:
yield x
x = x + x
def fib():
x = 1
x_1 = 0
x_2 = 0
while True:
yield x
x_2 = x_1
x_1 = x
x = x_1 + x_2
def prime():
x = 2
while True:
valid_divisors = 0
for div in range(1,x+1):
if x % div == 0:
valid_divisors += 1
if valid_divisors == 2 or x == 2:
yield x
x += 1
else:
x += 1 |
#!/usr/bin/env python3
from math import sqrt
def intsum():
x, increment = 0, 1
while True:
yield x
x += increment
increment += 1
def intsum2():
x = 0
while True:
yield x * (x + 1) / 2
x += 1
def doubler():
x = 1
while True:
yield x
x *= 2
def fib():
x, y = 0, 1
while True:
x, y = y, x + y
yield x
def prime():
x = 1
while True:
x += 1
for i in range(int(sqrt(x)), 1, -1):
if not x % i:
break
else:
yield x
def squared():
x = 1
while True:
yield x * x
x += 1
def cubed():
x = 1
while True:
yield x * x * x
x += 1
def threes():
x = 0
while True:
yield x
x += 3
def minus7():
x = 0
while True:
yield x
x -= 7
def factorial():
x, increment = 1, 1
while True:
x, increment = x * increment, increment + 1
yield x
def ten_to_xth_power():
x = 1
while True:
yield x
x *= 10 |
"""
ORIGINAL AUTHOR: INSTRUCTOR
CO-AUTHOR: Micah Braun
PROJECT NAME: adder.py
DATE CREATED: File originally created by instructor, date unknown
UPDATED: 10/18/2018
PURPOSE: Lesson 6
DESCRIPTION: Returns the calculation of divider(x / y) back
to method caller divide(), which returns the calculation
to method _do_calc().
"""
class Divider:
"""
This module provides the division operator to the
calculator class
"""
@staticmethod
def calc(operand_1, operand_2):
"""
Performs division operation on passed-in operands
:param operand_1:
:param operand_2:
"""
return operand_1/operand_2
|
#!/usr/bin/python
import sys
def my_fun(n):
if n == 2:
return True
return my_fun(n/2)
if __name__ == '__main__':
n = int(sys.argv[1])
print(my_fun(n))
# The function keeps calling itself without stopping because its termination condition was not set very clearly. It only stops by returning True
# if n equals 2 or another number that is a power of 2, e.g. 8, 16, 32, 64. Otherwise, no termination condition is implemented and as a result,
# the function keeps calling itself endlessly. The value of n keeps decreasing with each recursion of the recursive function
# since the function doesn't know when to stop and keeps calling itself.
# Below is my debugging log:
# PS C:\Users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05> python -m pdb debugging.py 15
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(2)<module>()
# -> import sys
# (Pdb) ll
# 1 #!/usr/bin/python
# 2 -> import sys
# 3
# 4 def my_fun(n):
# 5 if n == 2:
# 6 return True
# 7
# 8 return my_fun(n/2)
# 9
# 10 if __name__ == '__main__':
# 11 n = int(sys.argv[1])
# 12 print(my_fun(n))
# 13
# 14
# (Pdb) n
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(4)<module>()
# -> def my_fun(n):
# (Pdb) pp n
# *** NameError: name 'n' is not defined
# (Pdb) n
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(10)<module>()
# -> if __name__ == '__main__':
# (Pdb) n
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(11)<module>()
# -> n = int(sys.argv[1])
# (Pdb) n
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(12)<module>()
# -> print(my_fun(n))
# (Pdb) pp n
# 15
# (Pdb) s
# --Call--
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(4)my_fun()
# -> def my_fun(n):
# (Pdb) s
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(5)my_fun()
# -> if n == 2:
# (Pdb) pp n
# 15
# (Pdb) s
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(8)my_fun()
# -> return my_fun(n/2)
# (Pdb) s
# --Call--
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(4)my_fun()
# -> def my_fun(n):
# (Pdb) pp n
# 7.5
# (Pdb) s
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(5)my_fun()
# -> if n == 2:
# (Pdb) n
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(8)my_fun()
# -> return my_fun(n/2)
# (Pdb) s
# --Call--
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(4)my_fun()
# -> def my_fun(n):
# (Pdb) s
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(5)my_fun()
# -> if n == 2:
# (Pdb) pp n
# 3.75
# (Pdb) n
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(8)my_fun()
# -> return my_fun(n/2)
# (Pdb) s
# --Call--
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(4)my_fun()
# -> def my_fun(n):
# (Pdb) s
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(5)my_fun()
# -> if n == 2:
# (Pdb) pp n
# 1.875
# (Pdb) n
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(8)my_fun()
# -> return my_fun(n/2)
# (Pdb) s
# --Call--
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(4)my_fun()
# -> def my_fun(n):
# (Pdb) s
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(5)my_fun()
# -> if n == 2:
# (Pdb) pp n
# 0.9375
# (Pdb) n
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(8)my_fun()
# -> return my_fun(n/2)
# (Pdb) s
# --Call--
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(4)my_fun()
# -> def my_fun(n):
# (Pdb) s
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(5)my_fun()
# -> if n == 2:
# (Pdb) pp n
# 0.46875
# (Pdb) n
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(8)my_fun()
# -> return my_fun(n/2)
# (Pdb) s
# --Call--
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(4)my_fun()
# -> def my_fun(n):
# (Pdb) s
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(5)my_fun()
# -> if n == 2:
# (Pdb) pp n
# 0.234375
# (Pdb) n
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(8)my_fun()
# -> return my_fun(n/2)
# (Pdb) s
# --Call--
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(4)my_fun()
# -> def my_fun(n):
# (Pdb) s
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(5)my_fun()
# -> if n == 2:
# (Pdb) pp n
# 0.1171875
# (Pdb) n
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(8)my_fun()
# -> return my_fun(n/2)
# (Pdb) s
# --Call--
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(4)my_fun()
# -> def my_fun(n):
# (Pdb) s
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(5)my_fun()
# -> if n == 2:
# (Pdb) pp n
# 0.05859375
# (Pdb) n
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(8)my_fun()
# -> return my_fun(n/2)
# (Pdb) s
# --Call--
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(4)my_fun()
# -> def my_fun(n):
# (Pdb) s
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(5)my_fun()
# -> if n == 2:
# (Pdb) pp n
# 0.029296875
# (Pdb) n
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(8)my_fun()
# -> return my_fun(n/2)
# (Pdb) s
# --Call--
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(4)my_fun()
# -> def my_fun(n):
# (Pdb) s
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(5)my_fun()
# -> if n == 2:
# (Pdb) pp n
# 0.0146484375
# (Pdb) n
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(8)my_fun()
# -> return my_fun(n/2)
# (Pdb) s
# --Call--
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(4)my_fun()
# -> def my_fun(n):
# (Pdb) s
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(5)my_fun()
# -> if n == 2:
# (Pdb) pp n
# 0.00732421875
# (Pdb) n
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(8)my_fun()
# -> return my_fun(n/2)
# (Pdb) s
# --Call--
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(4)my_fun()
# -> def my_fun(n):
# (Pdb) s
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(5)my_fun()
# -> if n == 2:
# (Pdb) pp n
# 0.003662109375
# (Pdb) n
# > c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py(8)my_fun()
# -> return my_fun(n/2)
# (Pdb) n
# Traceback (most recent call last):
# File "C:\Users\elnura\AppData\Local\Programs\Python\Python36\lib\pdb.py", line 1667, in main
# pdb._runscript(mainpyfile)
# File "C:\Users\elnura\AppData\Local\Programs\Python\Python36\lib\pdb.py", line 1548, in _runscript
# self.run(statement)
# File "C:\Users\elnura\AppData\Local\Programs\Python\Python36\lib\bdb.py", line 434, in run
# exec(cmd, globals, locals)
# File "<string>", line 1, in <module>
# File "c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py", line 12, in <module>
# print(my_fun(n))
# File "c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py", line 8, in my_fun
# return my_fun(n/2)
# File "c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py", line 8, in my_fun
# return my_fun(n/2)
# File "c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py", line 8, in my_fun
# return my_fun(n/2)
# [Previous line repeated 980 more times]
# File "c:\users\elnura\documents\pythoncert\sp_online_course2_2018\students\elnurad\lesson05\debugging.py", line 4, in my_fun
# def my_fun(n):
# File "C:\Users\elnura\AppData\Local\Programs\Python\Python36\lib\bdb.py", line 53, in trace_dispatch
# return self.dispatch_call(frame, arg)
# File "C:\Users\elnura\AppData\Local\Programs\Python\Python36\lib\bdb.py", line 79, in dispatch_call
# if not (self.stop_here(frame) or self.break_anywhere(frame)):
# File "C:\Users\elnura\AppData\Local\Programs\Python\Python36\lib\bdb.py", line 176, in break_anywhere
# return self.canonic(frame.f_code.co_filename) in self.breaks
# File "C:\Users\elnura\AppData\Local\Programs\Python\Python36\lib\bdb.py", line 32, in canonic
# if filename == "<" + filename[1:-1] + ">":
# RecursionError: maximum recursion depth exceeded in comparison
# Uncaught exception. Entering post mortem debugging
# Running 'cont' or 'step' will restart the program
|
# ------------------------------------------------- #
# Title: Lesson 1, pt 2, Iterators Assignment
# Dev: Craig Morton
# Date: 11/6/2018
# Change Log: CraigM, 11/6/2018, Iterators Assignment
# ------------------------------------------------- #
# !/usr/bin/env python3
class IterateMe_1:
"""Simple iterator that returns the sequence of numbers from 0 to 4 (like range(4))"""
def __init__(self, stop=5):
self.current = -1
self.stop = stop
def __iter__(self):
return self
def __next__(self):
self.current += 1
if self.current < self.stop:
return self.current
else:
raise StopIteration
class IterateMe_2:
"""Like IterateMe_1, but similar to range()"""
def __init__(self, start, stop, step):
self.current = start - step
self.start = start
self.stop = stop
self.step = step
def __iter__(self):
self.current = self.start - self.step
return self
def __next__(self):
self.current += self.step
if self.current < self.stop:
return self.current
else:
raise StopIteration
if __name__ == "__main__":
print("\nBegin IterateMe_1 testing:")
for i in IterateMe_1():
print(i)
print("\nBegin IterateMe_2 testing:")
iterate = IterateMe_2(2, 20, 2)
for i in iterate:
if i > 10:
break
print(i)
for i in iterate:
print(i)
print("\nBegin range() testing:")
use_range = range(2, 20, 2)
for i in use_range:
if i > 10:
break
print(i)
for i in use_range:
print(i)
|
__author__="Wieslaw Pucilowski"
def intsum():
i, sum = 0, 0
while True:
sum += i
yield sum
i += 1
def intsum2():
i, sum = 0, 0
while True:
sum += i
yield sum
i += 1
def doubler():
i = 1
while True:
yield i
i = i * 2
def fib():
x, y = 0, 1
while True:
x, y = y, x + y
yield x
def prime():
i = 2
while True:
if not [x for x in range(2, i) if i % x == 0]:
yield i
i += 1 |
"""
Learning persistence with Peewee and sqlite
delete the database to start over
(but running this program does not require it)
"""
from personjobdept_model import *
from datetime import datetime
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
database = SqliteDatabase('personjobdept.db')
# function to calculate duration for time in jobs
def date_calculation(date1, date2):
date1 = datetime.strptime(''.join(date1.split('-')), '%Y%m%d')
date2 = datetime.strptime(''.join(date2.split('-')), '%Y%m%d')
return (date2 - date1).days
def populate_people():
"""Populates people table in database"""
logger.info('Working with Person class')
PERSON_NAME = 0
LIVES_IN_TOWN = 1
NICKNAME = 2
people = [
('Andrew', 'Sumner', 'Andy'),
('Peter', 'Seattle', None),
('Susan', 'Boston', 'Beannie'),
('Pam', 'Coventry', 'PJ'),
('Steven', 'Colchester', None),
]
logger.info('Creating People records')
try:
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
for person in people:
with database.transaction():
new_person = Person.create(
person_name=person[PERSON_NAME],
lives_in_town=person[LIVES_IN_TOWN],
nickname=person[NICKNAME])
new_person.save()
logger.info('Database add successful')
logger.info('Print the Person records we saved...')
for saved_person in Person:
logger.info(f'{saved_person.person_name} lives in {saved_person.lives_in_town} ' +
f'and likes to be known as {saved_person.nickname}')
except Exception as e:
logger.info(f'Error creating = {person[PERSON_NAME]}')
logger.info(e)
logger.info('See how the database protects our data')
finally:
logger.info('database closes')
database.close()
def populate_departments():
"""Populates department table in database"""
logger.info('Working with Department class')
logger.info('Creating Department records')
DEPT_NUM = 0
DEPT_NAME = 1
DEPT_MGR = 2
departments = [
('HR', 'Human Resources', 'Steven McRory'),
('ENG', 'Engineering', 'Peter Rabbit'),
('ADOP', 'Ad Operations', 'Andrew Jenson'),
('BI', 'Business Intel', 'Susan Bonnet')
]
try:
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
for dept in departments:
with database.transaction():
new_dept = Department.create(
department_number=dept[DEPT_NUM],
department_name=dept[DEPT_NAME],
department_manager=dept[DEPT_MGR])
new_dept.save()
logger.info('Database add successful')
logger.info(
'Reading and print all Department rows ...')
for dept in Department:
logger.info(f'{dept.department_number} : {dept.department_name} manager : {dept.department_manager}')
except Exception as e:
logger.info(f'Error creating = {dept[DEPT_NAME]}')
logger.info(e)
finally:
logger.info('database closes')
database.close()
def populate_jobs():
"""Populates jobs table in database"""
logger.info('Working with Job class')
logger.info('Creating Job records: just like Person. We use the foreign key')
JOB_NAME = 0
START_DATE = 1
END_DATE = 2
SALARY = 3
PERSON_EMPLOYED = 4
DEPARTMENT = 5
jobs = [
('Analyst', '2001-09-22', '2003-01-30', 65500, 'Andrew', 'BI'),
('Senior analyst', '2003-02-01', '2006-10-22', 70000, 'Andrew', 'BI'),
('Senior business analyst', '2006-10-23', '2016-12-24', 80000, 'Andrew', 'BI'),
('Admin supervisor', '2012-10-01', '2014-11-10', 45900, 'Peter', 'HR'),
('Admin manager', '2014-11-14', '2018-01-05', 45900, 'Peter', 'HR')
]
try:
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
for job in jobs:
with database.transaction():
new_job = Job.create(
job_name=job[JOB_NAME],
start_date=job[START_DATE],
end_date=job[END_DATE],
duration=date_calculation(job[START_DATE], job[END_DATE]),
salary=job[SALARY],
person_employed=job[PERSON_EMPLOYED],
job_department=job[DEPARTMENT])
new_job.save()
logger.info('Database add successful')
logger.info(
'Reading and print all Job rows (note the value of person)...')
for job in Job:
logger.info(f'{job.job_name} : {job.start_date} to {job.end_date} for {job.person_employed}')
except Exception as e:
logger.info(f'Error creating = {job[JOB_NAME]}')
logger.info(e)
finally:
logger.info('database closes')
database.close()
if __name__ == '__main__':
populate_people()
populate_departments()
populate_jobs()
|
from googleapiclient.discovery import build
import pandas as pd
import demoji
import urllib.request
import urllib
from langdetect import detect
import re # regular expression
import json
from textblob import TextBlob
key="AIzaSyAIGeU6DMwurpAb9Ndcwyr9TB2rVzzPnbk"
def can_you():
return "hello"
#* 1st step
# * this method helps us to make a connection between the google apis
def build_service():
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
return build(YOUTUBE_API_SERVICE_NAME,
YOUTUBE_API_VERSION,
developerKey=key)
# * this is the video title retriving method which was took from youtube api documentation
def get_vid_title(vidid):
# VideoID = "LAUa5RDUvO4"
params = {"format": "json", "url": "https://www.youtube.com/watch?v=%s" % vidid}
url = "https://www.youtube.com/oembed"
query_string = urllib.parse.urlencode(params)
url = url + "?" + query_string
with urllib.request.urlopen(url) as response:
response_text = response.read()
data = json.loads(response_text.decode())
# print(data['title'])
return data['title']
def main_method(videolink):
#* 2nd step
# Then we will call this connection method to build connection
service = build_service()
# videolink="https://www.youtube.com/watch?v=TXakJYHe9uQ"
#* 3rd step:
# we will pass the video link to this method
# then we are retriving the video id from the youtube link
test=(videolink.find("v="))
videoid=videolink[test+2:]
# and then we are passing this link to out query_vid_title method which will help in geting our video title
# query will be our video title
query = get_vid_title(videoid)
#* query result will be our video details
# this search is just like google search which will get all the relevent data reagrding the video title
query_results = service.search().list(part='snippet', q=query,
order='relevance',
type='video',
relevanceLanguage='en',
safeSearch='moderate').execute()
video_id = []
channel = []
video_title = []
video_desc = []
video_thumb=[]
video_pubdate=[]
# this query_result will be in the form of json
print(query_results['items'])
# result={'thumbnail': '', 'videoTitle': '', 'MainResult': '', 'description': '','publishTime':'','publishedAt':'','channelTitle':'',}
for item in query_results['items']:
video_id.append(item['id']['videoId'])
channel.append(item['snippet']['channelTitle'])
video_title.append(item['snippet']['title'])
video_desc.append(item['snippet']['description'])
video_pubdate.append(item['snippet']['publishTime'])
video_thumb.append(item['snippet']['thumbnails']['medium']['url'])
video_id = video_id[0]
channel = channel[0]
video_title = video_title[0]
video_desc = video_desc[0]
video_thumb=video_thumb[0]
video_pubdate=video_pubdate[0]
print(video_id,channel,video_title,video_desc,video_thumb)
video_id_pop = []
channel_pop = []
video_title_pop = []
video_desc_pop = []
comments_pop = []
comment_id_pop = []
reply_count_pop = []
like_count_pop = []
comments_temp = []
comment_id_temp = []
reply_count_temp = []
like_count_temp = []
# The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set.
nextPage_token = None
while 1:
response = service.commentThreads().list(
part = 'snippet',
videoId = videoid,
maxResults = 100,
order = 'relevance',
textFormat = 'plainText',
pageToken = nextPage_token
).execute()
nextPage_token = response.get('nextPageToken')
for item in response['items']:
comments_temp.append(item['snippet']['topLevelComment']['snippet']['textDisplay'])
comment_id_temp.append(item['snippet']['topLevelComment']['id'])
reply_count_temp.append(item['snippet']['totalReplyCount'])
like_count_temp.append(item['snippet']['topLevelComment']['snippet']['likeCount'])
comments_pop.extend(comments_temp)
comment_id_pop.extend(comment_id_temp)
reply_count_pop.extend(reply_count_temp)
like_count_pop.extend(like_count_temp)
video_id_pop.extend([video_id]*len(comments_temp))
channel_pop.extend([channel]*len(comments_temp))
video_title_pop.extend([video_title]*len(comments_temp))
video_desc_pop.extend([video_desc]*len(comments_temp))
# this will help us to find wheather there is another page or not
if nextPage_token is None:
break
# print(comments_pop)
output_dict = {
'Channel': channel_pop,
'Video Title': video_title_pop,
'Video Description': video_desc_pop,
'Video ID': video_id_pop,
'Comment': comments_pop,
'Comment ID': comment_id_pop,
'Replies': reply_count_pop,
'Likes': like_count_pop,
}
output_df = pd.DataFrame(output_dict, columns = output_dict.keys())
duplicates = output_df[output_df.duplicated("Comment ID")]
unique_df = output_df.drop_duplicates(subset=['Comment'])
# unique_df.to_csv("extraced_comments.csv",index = False)
# comments = pd.read_csv('extraced_comments.csv')
comments=unique_df
demoji.download_codes()
#replacing emoji with empty text
comments['clean_comments'] = comments['Comment'].apply(lambda x: demoji.replace(x,""))
comments['language'] = 0
count = 0
for i in range(0,len(comments)):
temp = comments['clean_comments'].iloc[i]
count += 1
try:
comments['language'].iloc[i] = detect(temp)
except:
comments['language'].iloc[i] = "error"
comments[comments['language']=='en']['language'].value_counts()
english_comm = comments[comments['language'] == 'en']
# english_comm.to_csv("english_comments.csv",index = False)
# en_comments = pd.read_csv('english_comments.csv',encoding='utf8',error_bad_lines=False)
en_comments=english_comm
en_comments.shape
regex = r"[^0-9A-Za-z'\t]"
copy = en_comments.copy()
copy['reg'] = copy['clean_comments'].apply(lambda x:re.findall(regex,x))
copy['regular_comments'] = copy['clean_comments'].apply(lambda x:re.sub(regex," ",x))
dataset = copy[['Video ID','Comment ID','regular_comments']].copy()
dataset = dataset.rename(columns = {"regular_comments":"comments"})
# dataset.to_csv("Dataset.csv",index = False)
# data = pd.read_csv("Dataset.csv")
data=dataset
data['polarity'] = data['comments'].apply(lambda x: TextBlob(x).sentiment.polarity)
data = data.sample(frac=1).reset_index(drop=True)
data['pol_cat'] = 0
data['pol_cat'][data.polarity > 0] = 1
data['pol_cat'][data.polarity < 0] = -1
data['pol_cat'][data.polarity == 0] = 0
data['pol_cat'].value_counts()
data.to_csv("Dataset1.csv",index = False)
size=len(data)
data_nutral=data[data['pol_cat']==0]
data_pos = data_nutral.reset_index(drop = True)
data_pos = data[data['pol_cat'] == 1]
data_pos = data_pos.reset_index(drop = True)
data_neg = data[data['pol_cat'] == -1]
data_neg = data_neg.reset_index(drop = True)
sizepos=len(data_pos)/len(data)
# 0 1 2 3 4 5 6 7 8 9 10
return len(data_pos)/len(data),len(data_neg)/len(data),len(data_nutral)/len(data),video_desc,video_title,video_thumb,channel,video_pubdate,data_pos,data_neg,data_nutral
# link=input()
# print(main_method(link)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 29 23:27:43 2018
@author: vicky
"""
# review probability
#inferential statistics
#roulette
import random
class FairRoulette():
def __init__(self):
self.pockets = []
for i in range(1,37):
self.pocekts.append(i)
self.ball = None
self.blackOdds, self.redOdds = 1.0, 1.0
def spin(self):
self.ball = random.choice(self.pockets)
def isBlack(self):
if type(self.ball) != int:
return False
if ((self.ball > 0 and self.ball <= 10)
or (self.ball > 18 and self.ball <= 28)):
return self.ball%2 == 0
else:
return self.ball%2 == 1
def isRed(self):
return type(self.ball) == int and not self.isBlack()
def betBlack(self, amt):
if self.isBlack():
return amt*self.blackOdds
else:
return -amt
def betRed(self, amt):
if self.isRed():
return amt*self.redOdds
else:
return -amt*self.redOdds
def betPocket(self, pocket, amt):
if str(pocket) == str(self.ball):
return amt*self.pocketOdds
else:
return -amt
def __str__(self):
return 'Fair Roulette'
def playRoulette(game, numSpins, toPrint = True):
luckyNumber = '2'
bet=1
totRed, totBlack, totPocket = 0.0, 0.0, 0.0
for i in range(numSpins):
game.spin()
totRed += game.betRed(bet)
totBlack += game.betBlack(bet)
totPocket += game.betPocket(luckyNumber, bet)
if toPrint:
print(numSpins, 'spins of', game)
print('Expected return betting red= ', str(100*totRed/numSpins) + '%')
print('Expected return betting black= ', str(100*totBlack/numSpins) + '%')
print('Expected return betting', luckyNumber, '=', str(100*totPocket/numSpins) + '%\n')
return (totRed/numSpins, totBlack/numSpins, totPocket/numSpins)
#types of roulette
class EuRoulette(FairRoulette):
def __init__(self):
FairRoulette.__init__(self)
self.pockets.append('0')
def __str__(self):
return 'European Roulette'
class AmRoulette(EuRoulette):
def __init__(self):
EuRoulette.__init__(self)
self.pockets.append('00')
def __str__(self):
return 'American Roulette'
def findPocketReturn(game, numTrials, trialSize, toPrint):
pocketReturns = []
for t in range(numTrials):
trialVals = playRoulette(game, trialSize, toPrint)
pocketReturns.append(trialVals[2])
return pocketReturns
def stdDevOfLengths(L):
import math
#calculate mean
sums = 0
diffsquared = []
for str in L:
sums += len(str)
mean = sums / len(L)
#calc devs squared
for str in L:
diffsquared.append((len(str) - mean)**2)
sumsquares = (sum(diffsquared))
print(math.sqrt(sumsquares/len(L)))
#tests:
L1=['mango', 'poop', 'cows']
stdDevOfLengths(L1)
#checking the empirical rule
import scipy.integrate
def gaussian(x, mu, sigma):
factor1= (1.0/(sigma*((2*pylab.pi)**0.5)))
factor2 = pylab.e**-(((x-mu)**2)/(2*sigma**2))
return factor1*factor2
def checkEmpirical(numTrials):
for t in range(numTrials):
mu = random.randint(-10,10)
sigma = random.randint(1,10)
print('For mu =', mu, 'and sigma =', sigma)
for numStd in (1, 1.96, 3):
area = scipy.integrate.quad(gaussian, mu-numStd*sigma, mu+numStd*sigma, (mu, sigma))[0]
print('Fraction within', numStd, 'std =', round(area, 4))
#Central limit theory: given a sufficiently large sample, the means of the samples in a set of samples will result in an approximately normal cure normal cruve
# the mean of the means of the sample will be roughtly the same as the mean of teh population
#the variance of teh sample means will be roughly that of the means of the population
# die with random real number 0-5, continuous
# code to check CLT:
def plotMeans(numDice, numRolls, numBins, legend, color, style):
means = []
for i in range(numRolls//numDice):
vals = 0
for j in range(numDice):
vals += 5*random.random()
means.append(vals/float(numDice))
pylab.hist(means, numBins, color = color, label = legend, weights = pylab.array(len(means)*[1])/len(means), hatch = style)
return getMeanAndStd(means)
####################
## Helper functions#
####################
def flipCoin(numFlips):
'''
Returns the result of numFlips coin flips of a biased coin.
numFlips (int): the number of times to flip the coin.
returns: a list of length numFlips, where values are either 1 or 0,
with 1 indicating Heads and 0 indicating Tails.
'''
with open('coin_flips.txt','r') as f:
all_flips = f.read()
flips = random.sample(all_flips, numFlips)
return [int(flip == 'H') for flip in flips]
def getMeanAndStd(X):
mean = sum(X)/float(len(X))
tot = 0.0
for x in X:
tot += (x - mean)**2
std = (tot/len(X))**0.5
return mean, std
#############################
## CLT Hands-on #
## #
## Fill in the missing code #
## Do not use numpy/pylab #
#############################
meanOfMeans, stdOfMeans = [], []
sampleSizes = range(10, 500, 50)
def clt():
""" Flips a coin to generate a sample.
Modifies meanOfMeans and stdOfMeans defined before the function
to get the means and stddevs based on the sample means.
Does not return anything """
for sampleSize in sampleSizes:
sampleMeans = []
for t in range(20):
sample = flipCoin(sampleSize) # flipCoin returns 1 and 0,
sampleMeans.append(getMeanAndStd(sample)[0])
meanOfMeans.append(getMeanAndStd(sampleMeans)[0])
stdOfMeans.append(getMeanAndStd(sampleMeans[1]))
#finding pi with buffon-laplace:
def throwNeedles(numNeedles):
inCircle = 0
for Needles in range(1, numNeedles+1, 1):
x = random.random()
y = random.random()
if (x*x + y*y)**0.5 <= 1.0:
inCircle += 1
return 4*(inCircle/float(numNeedles))
#this calculates ratio of needles in to out of circle
def getEst(numNeedles, numTrials):
estimates = []
for t in range(numTrials):
piGuess = throwNeedles(numNeedles)
estimates.append(piGuess)
sDev = stdDev(estimates)
curEst = sum(estimates)/len(estimates)
print('Est. = ' + str(curEst) + ', Std. dev. = ' + str(round(sDev, 6)) + ', Needles = ' + str(numNeedles))
return (curEst, sDev)
def estPi(precision, numTrials):
numNeedles = 1000
sDev = precision
while sDev >= precision/2:
curEst, sDev = getEst(numNeedles, numTrials)
numNeedles *= 2
return curEst
#general use of monte carlo - needles in / in + out of area
# pcik and enclising region, E such that the area of E is easy to calculate and R lies completely within E
# pikc a set of random points that lie within E
# let F be the fraction of the points that fall within R
# multiply the area of E by F
#e.g. monte carlo function that gives probability of 3 of same color marble in a row
def oneTrial():
balls = ['r', 'r', 'r', 'g', 'g', 'g']
chosenBalls = []
for t in range(3):
ball = random.choice(balls)
balls.remove(ball)
chosenBalls.append(ball)
if chosenBalls[0] == chosenBalls[1] == chosenBalls[2]:
return True
return False
def noReplacementSimulation(numTrials):
'''
Runs numTrials trials of a Monte Carlo simulation
of drawing 3 balls out of a bucket containing
3 red and 3 green balls. Balls are not replaced once
drawn. Returns the a decimal - the fraction of times 3
balls of the same color were drawn.
'''
numTrue = 0
for trial in range(numTrials):
if oneTrial():
numTrue += 1
return float(numTrue)/float(numTrials)
#probability sampling: each member of a population as a nonzero probability of being included in a sample
#simple random sampling : each member has an equal chance of being chosen.
# this is not always appropriate
#e.g. in sitauions in which there is a majority group and minority subgroups, smaple is subdivided into subgroups to avoid over sampling of majority group
#example
def makeHist(data, title, xlabel, ylabel, bins = 20):
pylab.hist(data, bins=bins)
pylab.title(title)
pylab.xlabel(xlabel)
pylab.ylabel(ylabel)
def getHighs():
inFiles = open('temperatures.csv')
populaton = []
for l in inFiles:
try:
tempC = float(l.split(','[1]))
population.append(tempC)
except:
continue
return population
def getMeansAndSDs(population, sample, verbose = False):
popMean = sum(population)/len(population)
sampleMean = sum(sample)/len(sample)
if verbose:
makeHist(population, 'Daily High 1961-2015, Population\n' +\
'(mean = ' + str(round(popMean, 2)) + ')', 'Degrees C', 'Number Days')
pylab.figure()
makeHist(sample, 'Daily High 1961-2015, Sample\n' +\
'(mean = ' + str(round(popMean, 2)) + ')', 'Degrees C', 'Number Days')
print('Population mean =', popMean)
print('Standard deviation of population =', numpy.std(population))
print('Sample mean=' sampleMean)
print('Standard devaiton of sample =',
numpy.std(sample))
return popMean, sampleMean, \
numpy.std(population), numpy.std(sample)
random.seed(0)
population = getHighs()
sample = random.sample(population, 100)
getMeanAndSDs(population, sample, True)
|
def get_digits(n):
r = [n % 10, n//10 % 10, n//100 % 10, n//1000 % 10, n//10000 % 10, n//100000 % 10]
return r
def increasing(digits):
result = True
N = len(digits)
for i in range(len(digits) - 1):
result = result and digits[N-1 - i] <= digits[N-1 - i-1]
return result
def adjacent(digits):
result = False
for i in range(len(digits) - 1):
result = result or digits[i] == digits[i+1]
return result
def run():
puzzle_input = (387638, 919123)
n_matching = 0
for i in range(puzzle_input[0], puzzle_input[1]):
digits = get_digits(i)
r_increasing = increasing(digits)
r_adjacent = adjacent(digits)
if r_increasing and r_adjacent:
# print("{} matches both criteria".format(i))
n_matching += 1
# if i <= puzzle_input[0] + 3:
# print(i, digits)
print("{} numbers match all criteria".format(n_matching))
if __name__ == '__main__':
run()
|
#!/usr/bin/env python
# coding: utf-8
# In[64]:
import pandas as pd
import numpy as np
import io
import warnings
warnings.filterwarnings(action='ignore')
from matplotlib import pyplot as plt
#Import the data file
#Distance (meter), Delivery Time (minute)
df = pd.read_csv('/Users/hcy/Desktop/수업자료/3학년 1학기/데이터과학/데과 과제/Lab 4/data_sets_lab4/linear_regression_data.csv',encoding='utf-8')
print(df.head())
#Change data to array
distance = df.iloc[:,0].to_numpy()
deliveryTime = df.iloc[:,1].to_numpy()
#Split data between training dataset, test dataset
trainingDis = distance[:24]
trainingTime = deliveryTime[:24]
testDis = distance[25:]
testTime = deliveryTime[25:]
# In[65]:
#Calculate linear regression
xBar = trainingDis.mean()
yBar = trainingTime.mean()
n = len(trainingDis)
B_numerator = (trainingDis * trainingTime).sum() - n * xBar * yBar
B_denominator = (trainingDis * trainingDis).sum() - n * xBar * xBar
B = B_numerator / B_denominator
A = yBar - B * xBar
print("X = {}\nY = {}".format(trainingDis, trainingTime))
print("Linear regression (y = Bx + A):")
print("B = {}, A = {}".format(B, A))
# In[66]:
#Make Linear regression to use training dataset
plt.scatter(trainingDis,trainingTime)
plt.xlabel('Distance')
plt.ylabel('Delivery Time')
px = np.array([trainingDis.min()-1, trainingTime.max()+1])
py = B * px + A
plt.plot(px, py, color = 'r')
plt.show()
# In[74]:
#Test data
resultTime = []
for i in range(len(testDis)):
resultTime.append(round(B * testDis[i] + A, 2))
print("Test Result")
print(resultTime)
print("--------------------")
print("Answer value")
print(testTime)
# In[ ]:
|
class Productos():
def __init__(self,nombre,costo,tipo):
self.nombre=nombre
self.costo=costo
self.tipo=tipo
def informe(self):
print(f""" ---INFORME DEL PRODUCTO---
Nombre: {self.nombre}
Costo: {self.costo}
Tipo: {self.tipo} """)
class Herramientas(Productos):
def garantia(self):
marca=input("Ingresar nombre de la marca: ",)
if marca == "Stanley" or marca == "STANLEY" or marca == "stanley":
garantiaP = 12
else:
garantiaP = 6
print(f"-La garantia es de {garantiaP} meses")
class Maquinas(Herramientas):
def consumo(self):
print("--Para calcular el consumo en KWH de la maquina ingrese los siguientes datos--\n")
potencia=int(input("Potencia: ",))
horas_uso=int(input("Horas de uso promedio: ",))
cons= potencia*horas_uso
print(f"\n-La consumo de KWH de la maquina es : {cons}")
class Otros(Productos):
def descripcion(self):
descrip=input("Ingrese descripcion del producto: ",)
print("\n\n",descrip)
def salir ():
desicion="p"
while desicion != "N" and desicion != "n":
desicion=input("Desea seguir ingresando datos(Y/N): ",)
if desicion == "Y" or desicion == "y":
menu()
elif desicion == "N" or desicion == "n":
print("\n\n-----Gracias por usar el programa-----\n\n")
def menuMaquina(producto,costo,tipo):
obj=Maquinas(producto,costo,tipo)
print("""\n\n
1-Ver datos del producto
2-Calcular garantia
3-Calcular consumo
4-Volver al menu
5-Salir del programa
""")
desicion=int(input())
if desicion == 1:
obj.informe()
menuMaquina(producto,costo,tipo)
elif desicion == 2:
obj.garantia()
menuMaquina(producto,costo,tipo)
elif desicion == 3:
obj.consumo()
menuMaquina(producto,costo,tipo)
elif desicion == 4:
menu()
else:
pass
def menuHerramienta(producto,costo,tipo):
obj=Herramientas(producto,costo,tipo)
print("""\n\n
1-Ver datos del producto
2-Calcular garantia
3-Volver al menu
4-Salir del programa
""")
desicion=int(input())
if desicion == 1:
obj.informe()
menuHerramienta(producto,costo,tipo)
elif desicion == 2:
obj.garantia()
menuHerramienta(producto,costo,tipo)
elif desicion == 3:
menu()
else:
pass
def menuOtro(producto,costo,tipo):
obj=Otros(producto,costo,tipo)
print("""\n\n
1-Ver datos del producto
2-Agregar una descripcion
3-Volver al menu
4-Salir del programa
""")
desicion=int(input())
if desicion == 1:
obj.informe()
menuOtro(producto,costo,tipo)
elif desicion == 2:
obj.descripcion()
menuOtro(producto,costo,tipo)
elif desicion == 3:
menu()
else:
pass
def menu():
print("\n\n************FERETERIA LA TUERCA************\n\n")
producto=input("-Ingresar nombre del producto: ",)
tipo=input("\n-Ingresar tipo de producto(maquina/herramienta/otro): ",)
costo=int(input("\n-Ingresr costo del producto: "))
if tipo == "maquina" or tipo == "Maquina":
menuMaquina(producto,costo,tipo)
elif tipo == "herramienta" or tipo == "Herramienta":
menuHerramienta(producto,costo,tipo)
elif tipo == "otro" or tipo == "Otro":
menuOtro(producto,costo,tipo)
else:
print("\n\n--DATOS MAL INGRESADOS--\n\n")
salir()
menu()
|
# Plot
import matplotlib.pyplot as plt
# Math packages
import pandas as pd
import math
import numpy as np
import itertools
class Task(object):
def __init__(self, dislikes, likes, leadership, learning, language):
self.dislikes = dislikes
self.likes = likes
self.leadership_features = leadership
self.learning_features = learning
self.language_features = language
n_students = set(
[
len(likes["value"]),
len(dislikes["value"]),
len(self.leadership_features["value"]),
len(self.learning_features["value"]),
len(self.language_features["value"]),
]
)
assert (
len(n_students) == 1
), "the input of the task is inconsistent: # students appeared in the input - {}".format(
n_students
)
self.n_students = list(n_students)[0]
self.features = {
"leadership": self.leadership_features,
"learning": self.learning_features,
"language": self.language_features,
}
self.weights = {"leadership": 1 / 3, "learning": 1 / 3, "language": 1 / 3}
def check_like(self, student1_id, student2_id):
return True if self.likes["value"][student1_id][student2_id] else False
def check_mutual_like(self, student1_id, student2_id):
return self.check_like(student1_id, student2_id) and self.check_like(
student2_id, student1_id
)
def check_dislike(self, student1_id, student2_id):
return True if self.dislikes["value"][student1_id][student2_id] else False
def check_any_dislike(self, *student_ids):
flag = False
for x, y in itertools.product(student_ids, student_ids):
if x != y and self.check_dislike(x, y):
# print(
# "group {} has a dislike pair: {} hates {}".format(
# tuple(student_ids), x, y
# )
# )
flag = True
return flag
def check_constraints_group(self, group, soft_on_number=False):
flag = True
if not soft_on_number and (len(group) > 4 or len(group) < 3):
flag = False
print(
"group {} has invalid number of people: {}".format(
tuple(group), len(group)
)
)
if self.check_any_dislike(*group):
flag = False
return flag
def check_constraints(self, assignment):
flag = True
for group in assignment:
if not self.check_constraints_group(group):
flag = False
return flag
def _diversity_objective(self, group, feature):
return (
np.array([feature["value"][student_id] for student_id in group])
.max(axis=0)
.sum()
)
def get_personal_features(self, student_id):
return {
feature_name: list(
map(
lambda x: x[0],
filter(
lambda x: x[1],
{
feature["description"][i]: feature["value"][student_id][i]
for i in range(feature["value"].shape[1])
}.items(),
),
)
)
for feature_name, feature in self.features.items()
}
def get_diversity_score_group(self, group):
return {
feature_name: self._diversity_objective(group, feature)
for feature_name, feature in self.features.items()
}
def get_diversity_score(self, assignment):
score = []
for group in assignment:
score.append(self.get_diversity_score_group(group))
return score
def get_total_score(self, assignment):
score = self.get_diversity_score(assignment)
return np.mean(
[
sum(list(map(lambda x: self.weights[x[0]] * x[1], ind_score.items())))
for ind_score in score
]
)
def print_features(self, task):
for group in task:
print(group)
for student_id in group:
print(
"{}: {}".format(student_id, self.get_personal_features(student_id))
)
print("diversity scores: {}".format(self.get_diversity_score_group(group)))
class Assignment(object):
def __init__(self, group_ids, n_groups):
self.n_groups = n_groups
self.group_ids = np.array(group_ids)
assert np.all(self.group_ids < n_groups), "invalid assignments"
self.groups = [[] for _ in range(n_groups)]
for student_id, group_id in enumerate(group_ids):
self.groups[group_id].append(student_id)
for group in self.groups:
group.sort()
def __iter__(self):
for group in self.groups:
yield group
def __repr__(self):
return "Assignment({}, {})".format(self.group_ids, self.n_groups)
class BruteForceSolver(object):
def __init__(self, task):
self.task = task
self.max_perf = None
self.best_assignment = None
def update(self, assignment):
print(assignment)
if task.check_constraints(assignment):
perf = task.get_total_score(assignment)
print(" success! - objective score: {:.3f}".format(perf))
if self.max_perf is None or perf > self.max_perf:
self.max_perf = perf
self.best_assignment = assignment
def search(
self, curr_group, groups, available_students, considering_students, n_selected
):
if n_selected == task.n_students:
group_ids = np.zeros(task.n_students, dtype=np.int64)
if len(groups[-1]) == 0:
groups_new = groups[:-1]
else:
groups_new = groups
for group_id, group in enumerate(groups_new):
for student_id in group:
group_ids[student_id] = group_id
self.update(Assignment(group_ids, len(groups_new)))
return
for index in range(len(considering_students)):
curr_group.append(considering_students[index])
if len(curr_group) == 4:
for student_id in curr_group:
available_students.pop(available_students.index(student_id))
curr_group = []
groups.append(curr_group)
considering_student_next = available_students
else:
considering_student_next = considering_students[index + 1 :]
self.search(
curr_group,
groups,
available_students,
considering_student_next,
n_selected + 1,
)
if len(curr_group) == 0:
groups.pop()
curr_group = groups[-1]
available_students.extend(curr_group)
available_students = sorted(available_students)
curr_group.pop()
def go(self):
curr_group = []
self.search(
curr_group,
[curr_group],
list(range(task.n_students)),
list(range(task.n_students)),
0,
)
def random_assignment(task):
group_ids = []
n_groups = 0
curr_num = 0
for _ in range(task.n_students):
if curr_num == 4:
curr_num = 0
n_groups += 1
group_ids.append(n_groups)
curr_num += 1
if curr_num != 0:
n_groups += 1
return Assignment(group_ids, n_groups)
limit = 12
def parse_feature(df):
return {
"value": np.array(df.values, dtype=np.bool)[:limit, :limit],
"description": list(df.columns.values),
}
languageDF = (
pd.read_excel(
"Frances_Material/MaximizingTeamDiversityData.xlsx", sheet_name="Language"
)
.drop("Languages", axis=1)
.drop("Students")
)
leaderDF = (
pd.read_excel(
"Frances_Material/MaximizingTeamDiversityData.xlsx", sheet_name="Leadership"
)
.drop("Lead. Styles", axis=1)
.drop("Students")
)
learningDF = (
pd.read_excel(
"Frances_Material/MaximizingTeamDiversityData.xlsx", sheet_name="Learning"
)
.drop("Learn. Styles", axis=1)
.drop("Students")
)
likesDF = pd.read_excel(
"Frances_Material/MaximizingTeamDiversityData.xlsx", sheet_name="Like"
)
dislikesDF = pd.read_excel(
"Frances_Material/MaximizingTeamDiversityData.xlsx", sheet_name="Dislikes"
)
dfs = {
"language": languageDF,
"leadership": leaderDF,
"learning": learningDF,
"likes": likesDF,
"dislikes": dislikesDF,
}
dfs = {
feature_name: parse_feature(feature_df) for feature_name, feature_df in dfs.items()
}
task = Task(**dfs)
solver = BruteForceSolver(task)
solver.go()
print(
"best assignment: score={:.3f}".format(task.get_total_score(solver.best_assignment))
)
task.print_features(solver.best_assignment)
# assignment = random_assignment(task)
# print(assignment)
# print(task.check_constraints(assignment))
# print(task.get_total_score(assignment))
# task.print_features(assignment)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 7 13:58:54 2019
@author: 748418
"""
num1 = int(input("Digite um numero: "))
num2 = int(input("Digite outro numero: "))
if (num1 % num2 == 0):
print("Numeros são divisíveis.")
else:
print("Os numeros não são divisíveis") |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 7 14:05:57 2019
@author: 748418
"""
lista = [0,1,2,3,4,5,6,7,9,10,11,12,13,4,15]
num = int(input("Quantos elementos você deseja que seja imprimido: "))
print(lista[:num])
#ou
for i in range(1,num):
print(i) |
# a list of strings
from builtins import print
animals = ['cat', 'dog', 'fish', 'bison']
# a list of integers
numbers = [1, 7, 34, 20, 12]
# an empty list
my_list = []
one_variable = 'touraj'
another_variable = 'vitalii'
third_variable = 'daniel'
# a list of variables we defined somewhere else
things = [
one_variable,
another_variable,
third_variable, # this trailing comma is legal in Python
]
print(animals[0]) # cat
print(numbers[1]) # 7
# This will give us an error, because the list only has four elements
# print(animals[6])
print(animals[-1]) # the last element -- bison
print(numbers[-2]) # the second-last element -- 20
# Extracting a subset of the list
print(animals[1:3]) # ['dog', 'fish']
print(animals[1:-1]) # ['dog', 'fish']
print('----------------------------')
print(animals[2:]) # ['fish', 'bison']
print(animals[:2]) # ['cat', 'dog']
print(animals[:]) # a copy of the whole list
# We can even include a third parameter to specify the step size:
print(animals[::2]) # ['cat', 'fish']
# Lists are mutable
# – we can modify elements, add elements to them or remove elements
# from them. A list will change size dynamically when we add or remove elements
# – we don’t have to manage this ourselves:
# assign a new value to an existing element
animals[3] = "hamster"
# add a new element to the end of the list
animals.append("squirrel")
# remove an element by its index
del animals[2]
print('----------------------------')
# Because lists are mutable, we can modify a list variable without assigning the variable
# a completely new value. Remember that if we assign the same list value to two variables,
# any in-place changes that we make while referring to the list by one variable name will
# also be reflected when we access the list through the other variable name:
animals = ['cat', 'dog', 'goldfish', 'canary']
pets = animals # now both variables refer to the same list object
animals.append('aardvark')
print(pets) # pets is still the same list as animals
animals = ['rat', 'gerbil', 'hamster'] # now we assign a new list value to animals
print(pets) # pets still refers to the old list
pets = animals[:] # assign a *copy* of animals to pets
animals.append('aardvark')
print(pets) # pets remains unchanged, because it refers to a copy, not the original list
# We can mix the types of values that we store in a list:
my_list = ['cat', 12, 35.8]
numbers = [34, 67, 12, 29]
my_number = 67
# How do we check whether a list contains a particular value? We use in or not in, the membership operators:
numbers = [34, 67, 12, 29]
number = 67
if number in numbers:
print("%d is in the list!" % number)
my_number = 90
if my_number not in numbers:
print("%d is not in the list!" % my_number)
print('-----------------------------------------------')
# There are many built-in functions which we can use on lists and other sequences:
# the length of a list
print(len(animals))
# the sum of a list of numbers
print(sum(numbers))
# are any of these values true?
print(any([1,0,1,0,1]))
# are all of these values true?
print(all([1,0,1,0,1]))
# List objects also have useful methods which we can call:
print('-----------------------------------------------')
numbers = [1, 2, 3, 4, 5]
# we already saw how to add an element to the end
numbers.append(5)
# count how many times a value appears in the list
numbers.count(5)
# append several values at once to the end
numbers.extend([56, 2, 12])
# find the index of a value
numbers.index(3)
# if the value appears more than once, we will get the index of the first one
numbers.index(2)
# if the value is not in the list, we will get a ValueError!
# numbers.index(42)
# insert a value at a particular index
numbers.insert(0, 45) # insert 45 at the beginning of the list
# remove an element by its index and assign it to a variable
my_number = numbers.pop(0)
# remove an element by its value
numbers.remove(12)
# if the value appears more than once, only the first one will be removed
numbers.remove(5)
# [Touraj] :: good to know following information:
# Python has a built-in array type. It’s not quite as restricting as an array in C or Java
# – you have to specify a type for the contents of the array, and you can only use it to store numeric
# values, but you can resize it dynamically, like a list. You will probably never need to use it. |
import types
class StrategyExample:
def __init__(self, func = None):
self.name = 'Strategy Example 0'
if func is not None:
self.execute = types.MethodType(func, self)
def execute(self):
print(self.name)
def execute_replacement1(self):
print(self.name + 'from execute 1')
def execute_replacement2(self):
print(self.name + 'from execute 2')
if __name__ == '__main__':
strat0 = StrategyExample()
strat1 = StrategyExample(execute_replacement1)
strat1.name = 'Strategy Example 1'
strat2 = StrategyExample(execute_replacement2)
strat2.name = 'Strategy Example 2'
strat0.execute()
strat1.execute()
strat2.execute()
# The strategy pattern is a type of behavioral pattern.
# The main goal of strategy pattern is to enable client
# to choose from different algorithms or procedures to complete
# the specified task. Different algorithms can be swapped
# in and out without any complications for the mentioned task.
#
# This pattern can be used to improve flexibility when external resources are accessed. |
def rotate(arr,n):
x = arr[n-1]
for i in range(n-1,0,-1):
arr[i] = arr[i-1]
arr[0] = x
arr = [1,4,6,8,7]
n =len(arr)
for i in range(0,n):
print(arr[i] ,end=' ')
rotate(arr,n)
print('\n')
for i in range(0,n):
print(arr[i] , end=' ')
|
def maxProfit(prices):
maxprofit = 0
for i in range(1,len(prices)):
if prices[i] > prices[i-1]:
maxprofit += prices[i] - prices[i-1]
return maxprofit
foo = [1,7,2,3,6,7,6,7]
print(maxProfit(foo))
|
def Uper(word):
word = word[0].upper() + word[1:].lower()
return word
list_of = []
n = int(input())
for i in range(n):
person = input()
list_of_rezome = person.split('.')
person = (list_of_rezome[0], Uper(list_of_rezome[1]) +' ' +list_of_rezome[2])
list_of.append(person)
list_of.sort(key=lambda x: x[0])
for latter in list_of :
print(latter[0] , latter[1]) |
# -*- coding: utf-8 -*-
# PN: 16 lesson python - try except, Created Mar, 2017
# Version 1.0
# KW: try except
# Link:
# --------------------------------------------------- lib import
while True:
# program must pass try loop to enter if loop, prevent function
try:
age = int(input("What is your age?"))
break
except:
print("Please enter a number")
if age < 15:
print("You are too young!")
else:
print("Good!") |
# -*- coding: utf-8 -*-
# PN: 16 lesson python - 9*9 chart, Created Mar, 2017
# Version 1.0
# KW: for, 9*9
# Link:
# --------------------------------------------------- python 2
for i in range(1,10,3):
for j in range(1,10):
print('%d * %d = %d ' %(i, j, i*j), end="")
print('%d * %d = %d ' %(i+1, j, (i+1)*j), end="")
print('%d * %d = %d ' %(i+2, j, (i+2)*j))
print()
# ------------------------------------------------- python 3
for i in range(1,10,3):
for j in range(1,10):
print('{}*{} = {:>2} ' .format(i, j, i*j), end="")
print('{}*{} = {:>2} ' .format(i+1, j, (i+1)*j), end="")
print('{}*{} = {:>2} ' .format(i+2, j, (i+2)*j))
print() |
# -*- coding: utf-8 -*-
# PN: 16 lesson python - earthquake, Created Mar, 2017
# Version 1.0
# KW: json, datetime
# Link:
# --------------------------------------------------- lib import
import json, datetime
# --------------------------------------------------- start
fp = open('earthquake.json', 'r')
eqs = json.load(fp)
print("過去7天全球發生重大的地震資訊: ")
print()
for eq in eqs['features']:
print("地點:{}".format(eq['properties']['place']))
print("震度:{}".format(eq['properties']['mag']))
et = float(eq['properties']['time']) / 1000.0
d = datetime.datetime.fromtimestamp(et).strftime('%Y-%m-%d %H:%M:%S')
print("時間:{}".format(d))
print() |
# -*- coding: utf-8 -*-
# PN: 16 lesson python - filter for prime, Created Mar, 2017
# Version 1.0
# KW: for, filter()
# Link:
# --------------------------------------------------- lib import
import sympy
a, b = 500, 600
numbers = range(a, b)
prime_numbers = filter(sympy.isprime, numbers) # use filter for numbers to check whether is prime number
print("Prime numbsers({}-{})".format(a, b))
for prime_number in prime_numbers:
print(prime_number, end = ",")
print() |
"""
Módulo responsável por realizar as operações de validação e execução com o DELETE.
Sintaxe para criação da table:
DELETE FROM nome_tabela
WHERE coluna = condição;
"""
# from pprint import pprint
def valida_delete(lista_query, termo_meio):
"""
pass
"""
if verifica_digito(lista_query[2]):
print("O nome da tabela não pode ser dígitos.")
return False
if termo_meio not in lista_query[3].upper():
return False
# print(lista_query)
return True
def valida_nomes(nome, tabelas):
"""
Verifica se o nome das tabela está correto.
Para ser válido, precisa retornar True.
"""
for item in tabelas:
if item['nome_tabela'] == nome:
return True
print("Tabela inexistente.")
return False
def deleta_registro(lista_query, tabelas):
"""
pass
"""
nome_tabela = lista_query[2]
coluna = lista_query[4]
chave = lista_query[6]
# print(lista_query)
for item in tabelas:
if item['nome_tabela'] == nome_tabela:
if coluna in item['coluna_nome']:
i = item['coluna_nome'].index(coluna)
# print(item['coluna_tipo'][i])
if item['coluna_tipo'][i] == 'int':
chave = int(chave)
# pprint(chave)
ind_apagar = 0
# print(i)
for indice, dado in enumerate(item['dados']):
if dado[i] == chave:
ind_apagar = indice
del item['dados'][ind_apagar]
break
break
else:
print("Coluna não encontrada.")
return tabelas
def verifica_digito(nome):
"""
Verifica se o nome da tabela não é composto apenas por dígitos.
Para ser um nome válido, precisa retornar False.
False: abc, ab2, 2ab
True: 123, 12.3
"""
return nome.isdigit()
|
"""
Módulo responsável por realizar as operações de validação e execução com o INSERT.
Sintaxe para criação da table:
INSERT INTO nome_tabela VALUES (
valor1,
valor2,
valor3,
...
);
"""
def valida_insert(lista_query, termo_meio):
"""
pass
"""
if verifica_digito(lista_query[2]):
print("O nome da tabela não pode ser dígitos.")
return False
if lista_query[3].upper() != termo_meio:
print("Faltou o termo VALUES.")
return False
return True
def valida_nomes(lista_query, tabelas):
"""
Verifica se o nome das tabela está correto.
Para ser válido, precisa retornar True.
"""
nome = lista_query[2]
for item in tabelas:
if item['nome_tabela'] == nome:
atributos = pega_conteudo_parenteses(lista_query)
if len(item['coluna_nome']) == len(atributos):
# print(atributos)
return True
else:
print("Campos insuficientes.")
# else:
# print("Tabela inexistente.")
return False
def insere(lista_query, tabelas):
"""
Insere os valores dos campos na tabela.
BUG AINDA ESTÁ INSERINDO DUPLICADO A ID
"""
# print(lista_query)
nome = lista_query[2]
for item in tabelas:
if item['nome_tabela'] == nome:
atributos = pega_conteudo_parenteses(lista_query)
# for dado in item['dados']:
# if dado[0] == atributos[0]:
# print("Valor não inserido. ID duplicado.")
item['dados'].append(atributos)
item['dados'].sort()
break
return tabelas
def verifica_digito(nome):
"""
Verifica se o nome da tabela não é composto apenas por dígitos.
Para ser um nome válido, precisa retornar False.
False: abc, ab2, 2ab
True: 123, 12.3
"""
return nome.isdigit()
def pega_conteudo_parenteses(lista_query):
"""
Separa da query todos os nomes e tipos dos campos da tabela, que ficam entre
os parênteses.
Devido a forma de criação da tabela, os itens tem um local fixo para começar e terminar.
"""
atributos = []
for item in lista_query[5:-1]:
if verifica_digito(item):
atributos.append(int(item))
else:
atributos.append(item)
return atributos
# def verifica_parenteses(abre, fecha):
# """
# Verifica se os parênteses foram entrados conforme o esperado.
# Para ser válido, precisa retornar True.
# """
# return abre == '(' and fecha == ')'
|
#!/usr/bin/python
import sys
# input comes from STDIN (stream data that goes to the program)
for line in sys.stdin:
l = line.strip().split(',')
if len(l)>30:
dist_lat = (float(l[7]) - float(l[11]))**2
dist_lon = (float(l[8]) - float(l[12]))**2
dist = (dist_lat + dist_lon)**0.5
if l[31] == '1.0':
rain = 'no'
if l[30] == '1.0':
rain = 'low'
if l[29] == '1.0':
rain = 'high'
print "%s\t%.10f" % (rain, dist)
|
import nltk
import sys
def main(grammar_file, input_file, output_file):
'''Read the sentences in a file, generate parse trees and count average amount of trees
Args: grammar_file(str): a filename for a cfg file, input_file(str): a filename of
input file containing sentences to be parsed, output_file(str): a filename where results should be writen.
Take in a grammar file and use it with NLTK tooling to create a parser. Next open the input file and for
each sentence produce a parse tree. At each point add the ammount of parse trees that can be created to a
list. Once all sentences are read calcualte the average amount of parse trees using the list
'''
grammar = nltk.data.load(grammar_file)
parser = nltk.parse.EarleyChartParser(grammar)
with open(input_file, 'r') as f:
with open(output_file, 'w') as w:
counts = [] #save the amount of parse trees in a list
for line in f:
w.write(line)
parses = 0
tokens = nltk.word_tokenize(line)
for item in parser.parse(tokens):
parses += 1
w.write(str(item)+"\n")
w.write("Number of parses: {}\n\n".format(parses))
counts.append(parses)
w.write("Average parses per sentence: {}\n".format(round(sum(counts)/len(counts),3)))
if __name__ == "__main__":
if len(sys.argv) != 4:
print("Usage: main.py <grammar file> <input sentence file> <output file name>")
exit(-1)
else:
grammar_file = sys.argv[1]
input_file = sys.argv[2]
output_file = sys.argv[3]
main(grammar_file, input_file, output_file)
|
def cal_passing_grade(midt, project, finalp):
passing_grade = midt * 0.3 + project * 0.3 + finalp * 0.4
return passing_grade
st_list = [None] * 5
for index in range(5):
print("Write student's info(name-midterm grade -project grade-final project grade)")
st = {"Name": input(), "Midterm": float(input()), "Project": float(input()), "Final Project": float(input())}
st["Passing Grade"] = cal_passing_grade(st["Midterm"], st["Project"], st["Final Project"])
st_list[index] = st
st_list.sort(key=lambda i: i["Passing Grade"], reverse=True)
for st in st_list:
print(st)
|
"""Module
"""
# import math
# import cmath
from matrix import Matrix
def main():
"""Main method
"""
_m1 = Matrix().random_int_matrix(3, 5, -9, 9)
# _m2 = Matrix().random_int_matrix(1, 8, -9, 9)
# _m3 = Matrix().random_int_matrix(5, 1, -9, 9)
# _m4 = Matrix().random_int_matrix(1, 8, -9, 9)
# _m5 = Matrix().random_int_matrix(7, 7, -9, 9)
# _m6 = Matrix().random_int_matrix(4, 4, -9, 9)
# _m_identity = Matrix.identity_matrix(5)
print(_m1)
"""
def math_6a():
_f = Matrix(4, 4)
_f.values = [[1, 1, 2, -1], [0, 1, 0, 3], [0, 0, 2, 0], [0, 0, 0, 0]]
_g = Matrix(2, 4)
_g.values = [[1, -1, 1, -1], [1, 1, -1, -1]]
_h = Matrix(3, 2)
_h.values = [[1, 0], [1, 1], [1, -1]]
_k = Matrix(4, 3)
_k.values = [[1, 1, 0], [0, 1, -1], [1, 1, 0], [1, 1, -3]]
_u = Matrix(4, 1)
_u.values = [[2], [1], [3], [-1]]
_v = Matrix(4, 1)
_v.values = [[1], [2], [3], [4]]
_w = Matrix(2, 1)
_w.values = [[1], [-1]]
print("2) --------------------")
print(_f * _u)
print("-----------------------")
print(_g * _v)
print("-----------------------")
print(_h * _w)
print("3) --------------------")
print(_g * _f)
print("-----------------------")
print(f"H * G =\n{_h * _g}")
print(f"K * H * G =\n{_k * _h * _g}")
print("-----------------------")
print(_h * _w)
def et_exercise36():
u_01 = 30
u_02 = 90j
r_1 = 100
r_2 = 200
x_l1 = 2 * math.pi * 1200 * 0.1j
x_l2 = 2 * math.pi * 1200 * 0.68j
x_c = - 1j/(2 * math.pi * 1200 * 300e-9)
print(x_l1)
print(x_l2)
print(x_c)
_d = Matrix(2, 2)
_d[0][0] = r_1 + x_l1 + x_l2
_d[0][1] = -x_l2
_d[1][0] = -x_l2
_d[1][1] = x_c + r_2 + x_l2
im1 = Matrix(2, 2)
im1[0][0] = u_01
im1[0][1] = -x_l2
im1[1][0] = -u_02
im1[1][1] = x_c + r_2 + x_l2
im2 = Matrix(2, 2)
im2[0][0] = r_1 + x_l1 + x_l2
im2[0][1] = u_01
im2[1][0] = -x_l2
im2[1][1] = -u_02
print("-------------------------------------------------")
print(im2)
print(-u_02 * (r_1 + x_l1 + x_l2))
print(x_l2 * u_01)
print(f"R1 + XL1 + XL2 = {r_1 + x_l1 + x_l2}")
print(f"Xc + R2 + XL2 = {x_c + r_2 + x_l2}")
print("-------------------------------------------------")
print(f"D = {_d.determinant():.3f}")
print(f"det Im1 = {im1.determinant():.3f}")
print(f"det Im2 = {im2.determinant():.3f}")
print("-------------------------------------------------")
_im1 = im1.determinant() / _d.determinant()
_im2 = im2.determinant() / _d.determinant()
print(f"im1 = {_im1:.5f}")
print(f"im2 = {_im2:.5f}")
print(f"im1 = {cmath.polar(_im1)}")
print(f"im2 = {cmath.polar(_im2)}")
print(f"im1 - im2 = {cmath.polar(_im1 - _im2)}")
print("-------------------------------------------------")
print(f"UL2 = {cmath.polar(_im1 * x_l1)}")
"""
if __name__ == "__main__":
main()
|
f = open("/Users/mcneillc/Dev/my-stuff/advent-of-code-2019/inputs/day6input.txt", "r")
orbits_input = f.readlines()
orbits_input = [orbit.strip('\n') for orbit in orbits_input]
f.close()
def retrieve_objects(orbit):
object1, object2 = orbit.split(')')
return [object1, object2]
def find_inner_orbits(orbits, pointer):
inner_orbits = []
orbit = orbits[pointer]
obj1, obj2 = orbit[0], orbit[1]
if obj1 == 'COM':
inner_orbits += [orbit]
else:
inner_orbits += [orbit]
while obj1 != 'COM':
for orbit in orbits:
if orbit[1] == obj1:
pointer = orbits.index(orbit)
orbit = orbits[pointer]
obj1, obj2 = orbit[0], orbit[1]
inner_orbits += [orbit]
return inner_orbits
def calculate_minimum_orbital_transfers(orbits):
orbits = [retrieve_objects(orbit) for orbit in orbits]
for orbit in orbits:
if orbit[1] == 'YOU':
you_pointer = orbits.index(orbit)
for orbit in orbits:
if orbit[1] == 'SAN':
santa_pointer = orbits.index(orbit)
you_inner_orbits = find_inner_orbits(orbits, you_pointer)
santa_inner_orbits = find_inner_orbits(orbits, santa_pointer)
for you_orbit in you_inner_orbits:
for santa_orbit in santa_inner_orbits:
if santa_orbit[0] == you_orbit[0]:
return you_inner_orbits.index(you_orbit) + santa_inner_orbits.index(santa_orbit)
def main():
print(calculate_minimum_orbital_transfers(orbits_input))
# main()
# Answer: 460
|
from nltk.corpus import stopwords
# 先token⼀把,得到⼀个word_list
# ...
# 然后filter⼀把
word_list = {'a','b','c'}
filtered_words = [word for word in word_list if word not in stopwords.words('english')] |
from util import get_input, get_int_input, char_to_int, int_to_char, invmodp
from errors import InvalidCharError, InvalidInputError
def decode_affine(ciphertext, multiply, offset):
"""
TODO: this function should return the plaintext. For example:
"SGHR HR Z SDRS." should return "THIS IS A TEST." (note that punctuation
is preserved)
"""
output = ''
try:
inverse = invmodp(multiply,26)
except ValueError:
raise InvalidInputError('%d has no inverse mod 26' % (multiply))
for char in ciphertext:
try:
integer = char_to_int(char)
integer = (integer - offset) * inverse
integer = integer % 26
char = int_to_char(integer)
output += char
except InvalidCharError:
output += char
return output
if __name__ == '__main__':
# Get the ciphertext
ciphertext = get_input()
#Get the multiplier
multiply = get_int_input()
# Get the offset to try
offset = get_int_input()
print decode_affine(ciphertext, multiply, offset)
|
from typing import Optional
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import seaborn as sns
from . import stats
def plot_bar(
df: pd.DataFrame,
ddg_cols: str,
error_cols: str,
exp_col: str = "exp",
exp_error_col: str = "dexp",
name_col: str = "edge",
title: str = "",
filename: Optional[str] = None,
):
"""
Creates a plotly barplot. It takes a pandas.Dataframe df as input and plots
horizontal bars grouping the values in the rows together. The columns which
will be used are specified by ddg_cols (DDG values),
error_cols (corresponding errors), exp_col (column with exp. values),
exp_error_col (column with exp. errors) and name_col (column which will be
used as y axis tick labels).
"""
# create color palette
colors = sns.color_palette(palette="bright")
num_edges = df.shape[0]
num_bars_per_edge = len(ddg_cols)
height = 20 * (num_bars_per_edge + 0.3) * num_edges
exp_size = height / num_edges / 2.0
alim = (
np.max(
np.fabs(df.loc[:, ddg_cols + [exp_col]].values)
+ np.fabs(df.loc[:, error_cols + [exp_error_col]].values)
)
* 1.05
)
fig = go.Figure()
# add data
for i, (col, ecol) in enumerate(zip(ddg_cols, error_cols)):
fig.add_trace(
go.Bar(
x=df.loc[:, col].values,
y=df[name_col].values,
error_x=dict(
type="data", # value of error bar given in data coordinates
array=df.loc[:, ecol].values,
visible=True,
),
name=col,
marker=dict(color=f"rgba{colors[i]}", line=None),
orientation="h",
)
)
if exp_col is not None:
fig.add_trace(
go.Scatter(
x=df.loc[:, exp_col].values,
y=df[name_col].values,
name="experiment",
mode="markers",
marker=dict(
symbol="line-ns",
color="black",
size=exp_size,
line_width=4,
),
)
)
fig.add_trace(
go.Scatter(
x=df.loc[:, exp_col].values - df.loc[:, exp_error_col].values,
y=df[name_col].values,
name="ExpErrors1",
mode="markers",
marker=dict(
symbol="line-ns",
color="black",
size=exp_size,
line_width=2,
),
showlegend=False,
)
)
fig.add_trace(
go.Scatter(
x=df.loc[:, exp_col].values + df.loc[:, exp_error_col].values,
y=df[name_col].values,
name="ExpErrors2",
mode="markers",
marker=dict(
symbol="line-ns",
color="black",
size=exp_size,
line_width=2,
),
showlegend=False,
)
)
fig.update_layout(
title=title,
xaxis=dict(
title=r"$\Delta\Delta G\, \mathrm{[kcal\,mol^{-1}]}$",
titlefont_size=16,
tickfont_size=14,
range=(-alim, alim),
),
yaxis=dict(
title="Edge",
titlefont_size=16,
tickfont_size=14,
range=(-0.5, num_edges - 0.5),
),
width=800,
height=height,
legend=dict(
x=1.0,
y=1.0,
bgcolor="rgba(255, 255, 255, 0)",
bordercolor="rgba(255, 255, 255, 0)",
font_size=16,
),
barmode="group",
bargap=0.3, # gap between bars of adjacent location coordinates.
bargroupgap=0.0, # gap between bars of the same location coordinate.
)
if filename is None:
fig.show()
elif filename.find(".html"):
fig.write_html(filename)
else:
fig.write_image(filename)
def _master_plot(
x: np.ndarray,
y: np.ndarray,
title: str = "",
xerr: Optional[np.ndarray] = None,
yerr: Optional[np.ndarray] = None,
method_name: str = "",
target_name: str = "",
plot_type: str = "",
guidelines: bool = True,
origins: bool = True,
statistics: list = ["RMSE", "MUE"],
filename: Optional[str] = None,
bootstrap_x_uncertainty: bool = False,
bootstrap_y_uncertainty: bool = False,
statistic_type: str = "mle",
):
nsamples = len(x)
ax_min = min(min(x), min(y)) - 0.5
ax_max = max(max(x), max(y)) + 0.5
fig = go.Figure()
# x = 0 and y = 0 axes through origin
if origins:
# x=0
fig.add_trace(
go.Scatter(
x=[0, 0],
y=[ax_min, ax_max],
line_color="black",
mode="lines",
showlegend=False,
)
)
# y =0
fig.add_trace(
go.Scatter(
x=[ax_min, ax_max],
y=[0, 0],
line_color="black",
mode="lines",
showlegend=False,
)
)
if guidelines:
small_dist = 0.5
fig.add_trace(
go.Scatter(
x=[ax_min, ax_max, ax_max, ax_min],
y=[
ax_min + 2.0 * small_dist,
ax_max + 2.0 * small_dist,
ax_max - 2.0 * small_dist,
ax_min - 2.0 * small_dist,
],
name="1 kcal/mol margin",
hoveron="points+fills",
hoverinfo="name",
fill="toself",
mode="lines",
line_width=0,
fillcolor="rgba(0, 0, 0, 0.2)",
showlegend=False,
)
)
fig.add_trace(
go.Scatter(
x=[ax_min, ax_max, ax_max, ax_min],
y=[
ax_min + small_dist,
ax_max + small_dist,
ax_max - small_dist,
ax_min - small_dist,
],
name=".5 kcal/mol margin",
hoveron="points+fills",
hoverinfo="name",
fill="toself",
mode="lines",
line_width=0,
fillcolor="rgba(0, 0, 0, 0.2)",
showlegend=False,
)
)
# diagonal
fig.add_trace(
go.Scatter(
x=[ax_min, ax_max],
y=[ax_min, ax_max],
line_color="black",
mode="lines",
showlegend=False,
)
)
# 2.372 kcal / mol = 4 RT
clr = np.abs(x - y) / 2.372
fig.add_trace(
go.Scatter(
x=x,
y=y,
mode="markers",
name=f"{target_name},{method_name}",
marker=dict(symbol="circle", color=clr, colorscale="BlueRed"),
error_x=dict(
type="data", # value of error bar given in data coordinates
array=xerr,
visible=True,
),
error_y=dict(
type="data", # value of error bar given in data coordinates
array=yerr,
visible=True,
),
showlegend=False,
)
)
# stats and title
string = []
if statistic_type not in ['mle', 'mean']:
raise ValueError(f"Unknown statistic type {statistic_type}")
for statistic in statistics:
bss = stats.bootstrap_statistic(x,
y,
xerr,
yerr,
statistic=statistic,
include_true_uncertainty=bootstrap_x_uncertainty,
include_pred_uncertainty=bootstrap_y_uncertainty)
string.append(
f"{statistic + ':':5s}{bss[statistic_type]:5.2f} [95%: {bss['low']:5.2f}, {bss['high']:5.2f}]"
)
stats_string = "<br>".join(string)
long_title = f"{title}<br>{target_name} (N = {nsamples})<br>{stats_string}"
# figure layout
fig.update_layout(
title=dict(
text=long_title,
font_family="monospace",
x=0.0,
y=0.95,
font_size=14,
),
xaxis=dict(
title=f"Experimental {plot_type} [kcal mol<sup>-1</sup>]",
titlefont_size=14,
tickfont_size=12,
range=(ax_min, ax_max),
),
yaxis=dict(
title=f"Calculated {plot_type} {method_name} [kcal mol<sup>-1</sup>]",
titlefont_size=14,
tickfont_size=12,
range=(ax_min, ax_max),
),
width=400,
height=400
# legend=dict(
# x=1.0,
# y=1.0,
# bgcolor='rgba(255, 255, 255, 0)',
# bordercolor='rgba(255, 255, 255, 0)',
# font_size=12
# )
)
if filename is None:
fig.show()
elif filename.find(".html") > 0:
fig.write_html(filename)
else:
fig.write_image(filename)
|
# def measure_string(myStr):
# count = 0
# if myStr == myStr[-1]:
# return count + 1
# else:
# return 1 + measure_string(myStr[1:])
# # count = 0
# # if myStr == myStr[-1]:
# # return count
# # else:
# # return measure_string(myStr[1:])
# #The line below will test your function. As written, this
# #should print 13. You may modify this to test your code.
# print(measure_string("13 characters"))
# print("--------------")
# print(measure_string("1"))
password = "Unicorn&pepsi#sugar"
print(len(password))
|
# Video 8
'''
Tirar 4 veces un dado1Eliminar el Valor menor
y Sumar el Total restante
'''
import random
'''
dado1 = random.randint(1,6)
dado2 = random.randint(1,6)
dado3 = random.randint(1,6)
dado4 = random.randint(1,6)
suma = dado1 + dado2 + dado3 + dado4
menor = min(dado1, dado2, dado3, dado4)
Fuerza = suma - menor
#print("dado1: %i - dado2: %i - dado3 %i - dado4: %i"% (dado1, dado2, dado3, dado4))
print("Fuerza: %i"% Fuerza)
dado1 = random.randint(1,6)
dado2 = random.randint(1,6)
dado3 = random.randint(1,6)
dado4 = random.randint(1,6)
suma = dado1 + dado2 + dado3 + dado4
menor = min(dado1, dado2, dado3, dado4)
Destreza = suma - menor
#print("dado1: %i - dado2: %i - dado3 %i - dado4: %i"% (dado1, dado2, dado3, dado4))
print("Destreza: %i"% Destreza)
dado1 = random.randint(1,6)
dado2 = random.randint(1,6)
dado3 = random.randint(1,6)
dado4 = random.randint(1,6)
suma = dado1 + dado2 + dado3 + dado4
menor = min(dado1, dado2, dado3, dado4)
Constitucion = suma - menor
#print("dado1: %i - dado2: %i - dado3 %i - dado4: %i"% (dado1, dado2, dado3, dado4))
print("Constitucion: %i"% Constitucion)
dado1 = random.randint(1,6)
dado2 = random.randint(1,6)
dado3 = random.randint(1,6)
dado4 = random.randint(1,6)
suma = dado1 + dado2 + dado3 + dado4
menor = min(dado1, dado2, dado3, dado4)
Inteligencia = suma - menor
#print("dado1: %i - dado2: %i - dado3 %i - dado4: %i"% (dado1, dado2, dado3, dado4))
print("Inteligencia: %i"% Inteligencia)
dado1 = random.randint(1,6)
dado2 = random.randint(1,6)
dado3 = random.randint(1,6)
dado4 = random.randint(1,6)
suma = dado1 + dado2 + dado3 + dado4
menor = min(dado1, dado2, dado3, dado4)
Sabiduria = suma - menor
#print("dado1: %i - dado2: %i - dado3 %i - dado4: %i"% (dado1, dado2, dado3, dado4))
print("Sabiduria: %i"% Sabiduria)
dado1 = random.randint(1,6)
dado2 = random.randint(1,6)
dado3 = random.randint(1,6)
dado4 = random.randint(1,6)
suma = dado1 + dado2 + dado3 + dado4
menor = min(dado1, dado2, dado3, dado4)
Carisma = suma - menor
#print("dado1: %i - dado2: %i - dado3 %i - dado4: %i"% (dado1, dado2, dado3, dado4))
print("Carisma: %i"% Carisma)
'''
mis_dados = [4,5,6,2]
print(mis_dados)
mis_dados.sort()
print(mis_dados)
print("option1___________")
dados_min = min(mis_dados)
print(dados_min)
altos = sum(mis_dados)-dados_min
print(altos)
print("option2___________")
dados_altos = mis_dados[1:]
print(dados_altos)
altos = sum(dados_altos)
print(altos)
|
import random
p = 1
r = 1
s = 1
while True:
print(f'p = {p} \t r = {r} \t s = {s}')
mylist = ['p', ] * p + ['r', ] * r + ['s', ] * s
our_combination = random.choice(mylist)
player_combination = input('input p, r, s for playing. q for finish ')
if player_combination in {'p', 'r', 's'}:
if player_combination == 'p':
s += 1
if our_combination == 'r':
print('You won!')
elif player_combination == our_combination:
print('it is a draw')
else:
print('You lost :(')
elif player_combination == 'r':
p += 1
if our_combination == 's':
print('You won!')
elif player_combination == our_combination:
print('it is a draw')
else:
print('You lost :(')
elif player_combination == 's':
r += 1
if our_combination == 'p':
print('You won!')
elif player_combination == our_combination:
print('it is a draw')
else:
print('You lost :(')
elif player_combination == 'q':
break
import random
win_variants = {
'R': ['S', ],
'S': ['P', ],
'P': ['R', 'K'],
'K': ['R', 'S'],
}
all_avail_choices = set(win_variants.keys())
stat_variants = {}
for k in win_variants.keys():
stat_variants[k] = 1
while True:
print(f'{stat_variants}')
mylist = []
for k in stat_variants:
mylist += [k] * stat_variants[k]
our_combination = random.choice(mylist)
player_combination = input('input p, r, s for playing. q for finish ')
if player_combination in all_avail_choices:
for win_key in win_variants:
if player_combination in win_variants[win_key]:
stat_variants[win_key] += 1
if our_combination in win_variants[player_combination]:
print('You won!')
elif player_combination == our_combination:
print('it is a draw')
else:
print('You lost :(')
elif player_combination == 'q':
break |
"""
Кода до 10ти строк. использование: notifier = notify(every=1000) создали нотификатор и внутри цикла дергаем его а
он каждые 1000 раз выводит "Итерация __ выполнена" (используется при генерации допустим большого файла чтоб видеть на
какой стадии процесс)
"""
def count_squares(stop):
for j in range(stop):
yield j ** 2
def write_to_file(number, filename='generator.txt'):
with open(filename, 'a') as file:
file.write(f'next_number: {number}\n')
def notify(every=1000):
counter = 0
const_every = every
while True:
yield every
if counter % every == 0 and counter > 0:
print('notify:', every)
every += const_every
counter += 1
if __name__ == '__main__':
res = count_squares(100)
n = notify(every=10)
for i in res:
next(n)
print(i)
notifier = notify()
for numb in range(10000):
write_to_file(numb)
next(notifier)
|
"""
Read about the Fibonacci search and implement it using python. Explore its complexity and compare it to sequential, binary searches.
"""
def fibonacci_search(collection, value):
fib_m_minus_2 = 0
fib_m_minus_1 = 1
fib_m = fib_m_minus_1 + fib_m_minus_2
while fib_m < len(collection):
fib_m_minus_2 = fib_m_minus_1
fib_m_minus_1 = fib_m
fib_m = fib_m_minus_1 + fib_m_minus_2
index = -1
while fib_m > 1:
i = min(index + fib_m_minus_2, (len(collection) - 1))
if collection[i] < value:
fib_m = fib_m_minus_1
fib_m_minus_1 = fib_m_minus_2
fib_m_minus_2 = fib_m - fib_m_minus_1
index = i
elif collection[i] > value:
fib_m = fib_m_minus_2
fib_m_minus_1 = fib_m_minus_1 - fib_m_minus_2
fib_m_minus_2 = fib_m - fib_m_minus_1
else:
return i
if fib_m_minus_1 and index < (len(collection) - 1) and collection[index + 1] == value:
return index + 1
return -1
|
"""Create your own implementation of an iterable, which could be used inside for-in loop. Also, add logic for
retrieving elements using square brackets syntax."""
class IterObj:
def __init__(self, *args):
self.__iter_obj = [*args]
self.__start = 0
def __iter__(self):
return self
def __next__(self):
if self.__start >= len(self.__iter_obj):
raise StopIteration
start = self.__start
self.__start += 1
return self.__iter_obj[start]
def __getitem__(self, index):
return self.__iter_obj[index]
def iter_object(obj):
index = 0
while True:
if index >= len(obj):
break
from_send = yield obj[index]
if from_send is not None:
index = from_send
else:
index += 1
if __name__ == '__main__':
obj = 'abcdefghijklmnop'
my_obj = IterObj(*obj)
print(my_obj[8])
print(my_obj[1])
print(next(my_obj))
print(next(my_obj))
print()
my_iter = iter_object('0123456789')
print(next(my_iter))
print(my_iter.send(5))
print(next(my_iter))
|
"""
Найти кратчайший маршрут на графе из одной заданной точки в другую
"""
class Node:
instances = {}
def __init__(self, name):
self.name = name
def __repr__(self):
return f'{self.name}'
def __new__(cls, *args, **kwargs):
name = args[0]
if name not in cls.instances:
cls.instances[name] = super().__new__(cls)
return cls.instances[name]
class Graph:
def __init__(self):
self._nodes = []
self._edges = {}
def add_node(self, node):
if node not in self._nodes:
self._nodes.append(node)
return self
def set_edge(self, node1, node2, distance):
key1 = (node1, node2)
self._edges[key1] = distance
key2 = (node2, node1)
self._edges[key2] = distance
return self
def _get_children(self, node):
children = set()
for n1, n2 in self._edges:
if n1 == node:
children.add(n2)
return children
def find_path(self, begin, end):
queue = [begin]
node_weight = {begin: 0, }
while queue:
current = queue.pop(0)
for ch in self._get_children(current):
dist = node_weight[current] + self._edges[(current, ch)]
if ch in node_weight:
if node_weight[ch] > dist:
node_weight[ch] = dist
queue.append(ch)
else:
node_weight[ch] = dist
queue.append(ch)
queue = [end]
way = [end]
while queue:
current = queue.pop(0)
for ch in self._get_children(current):
if node_weight[current] - self._edges[(current, ch)] == node_weight[ch]:
queue.append(ch)
way.append(ch)
return way[::-1]
if __name__ == "__main__":
g1 = Graph()
g1.add_node(Node('A')).add_node(Node('B')).add_node(Node('C')).add_node(Node('D')).add_node(Node('F'))
g1.set_edge(Node('A'), Node('B'), 2)
g1.set_edge(Node('B'), Node('C'), 5)
g1.set_edge(Node('B'), Node('D'), 3)
g1.set_edge(Node('C'), Node('D'), 1)
print(g1.find_path(Node('A'), Node('C')))
|
""" task 4
получаем в цикле
число
действие
второе число
пишем промежутчный результат
запрашиваем действие
и снова число
действие...
если вместо числа или действия введено Q выходим"""
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def get_number():
while True:
user_input = input("Enter number: ")
if user_input.isnumeric():
return int(user_input)
elif user_input == "Q":
return None
else:
print("Wrong number format.")
continue
def get_action(action):
actions = {"+": add, "-": subtract, "*": multiply}
while True:
action = input("Enter action: ")
if action in actions.keys():
return actions[action]
elif action == "Q":
return None
elif action not in actions.keys():
print("Wrong action.")
continue
if __name__ == '__main__':
total = get_number()
while True:
if total is None:
break
action = get_action()
if action is None:
break
number = get_number()
if number is None:
break
total = action(total, number)
print(f"The result is: {total}. If you want to quit enter Q.")
|
from collections import deque
from lesson_24.stack import Stack
ERROR_MSG = 'ERROR'
class InfixToPostfix:
def __init__(self, expression):
self.expression = expression
self.__operators = Stack()
self.__output = []
self.__precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3, ')': 0, '(': 0}
if self.__check_brackets():
self.__convert()
@property
def result(self):
return self.__output
def __check_brackets(self):
brackets = deque()
for element in self.expression:
if "(" in element:
brackets.appendleft("(")
elif ")" in element:
if len(brackets) > 0:
brackets.pop()
else:
return False
if len(brackets) == 0:
return True
else:
return False
def __convert(self):
for ind, char in enumerate(self.expression):
if char.isdigit():
if len(self.__output) and self.expression[ind-1].isdigit():
number = self.__output.pop() + char
self.__output.append(number)
else:
self.__output.append(char)
else:
if self.__operators.is_empty:
self.__operators.push(char)
else:
if char == '(' or self.__precedence[char] > self.__precedence[self.__operators.peek()]:
self.__operators.push(char)
else:
if char == ')':
while self.__operators.peek() != '(':
self.__output.append(self.__operators.pop())
self.__operators.pop()
else:
while len(self.__operators) and self.__precedence[char] <= self.__precedence[self.__operators.peek()]:
self.__output.append(self.__operators.pop())
self.__operators.push(char)
while len(self.__operators) > 0:
self.__output.append(self.__operators.pop())
return self.__output
class EvaluatePostfix:
def __init__(self, expression):
self.expression = expression
self.__operands = []
self.__operations = {'+': lambda a, b: a + b,
'-': lambda a, b: b - a,
'/': lambda a, b: b / a,
'*': lambda a, b: a * b,
'^': lambda a, b: b ** a,
}
self.__evaluate()
@property
def result(self):
return self.__operands[0]
def __evaluate(self):
for char in self.expression:
if char.isdigit():
self.__operands.append(int(char))
else:
new_char = self.__operations[char](self.__operands.pop(), self.__operands.pop())
self.__operands.append(new_char)
def evaluate(expression):
postfix_exp = InfixToPostfix(expression).result
try:
return str(EvaluatePostfix(postfix_exp).result)
except:
return 'ERROR'
if __name__ == '__main__':
exp = "10+5*6"
print(InfixToPostfix(exp).result)
print(evaluate(exp))
|
"""Task 4
The math quiz program
Write a program that asks the answer for a mathematical expression, checks whether the user is right or wrong,
and then responds with a message accordingly.
"""
import random
start = 0
stop = 20
while True:
number_1 = random.randint(start, stop)
number_2 = random.randint(start, stop)
operators = ["+", "-", "*", "/", "%", "//"]
operator = random.choice(operators)
try:
result = eval(str(number_1) + operator + str(number_2))
except ZeroDivisionError:
continue
else:
while True:
check_result = input(f"Please evaluate the expression: {number_1}{operator}{number_2}=?\nTo exit enter q\n")
if check_result == 'q':
exit()
elif float(check_result) == result:
print("Ok")
break
else:
print("Error")
|
# https://www.hackerrank.com/challenges/string-validators/problem
if __name__ == '__main__':
string = input()
if len(string)> 0 and len(string)<= 1000:
print(any(c.isalnum() for c in string))
print(any(c.isalpha() for c in string))
print(any(c.isdigit() for c in string))
print(any(c.islower() for c in string))
print(any(c.isupper() for c in string)) |
# https://www.hackerrank.com/challenges/python-print/problem
# The included code stub will read an integer, , from STDIN.
# Without using any string methods, try to print the following:
# Note that "" represents the consecutive values in between.
# Example n = 5
#Print the string 12345
if __name__ == '__main__':
n = int(input())
print(*range(1,n+1), sep='') |
# https://www.hackerrank.com/challenges/list-comprehensions/tutorial
if __name__ == '__main__':
x,y,z,n = map(int,input('Enter values separated by a space:').split(" "))
results = []
for x in [i for i in range(x+1)]:
for y in [j for j in range(y+1)]:
for z in [j for j in range(z+1)]:
if (x+y+z != n):
results.append([x,y,z])
print('The permutations are:\n',results) |
from selenium import webdriver
from selenium.webdriver.support.select import Select
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.get("https://rahulshettyacademy.com/angularpractice/")
driver.find_element_by_name("name").send_keys("mounika")
driver.find_element_by_css_selector("input[name = 'email']").send_keys("mounika.asula@tcs.com")
driver.find_element_by_xpath("//input[@id = 'exampleInputPassword1']").send_keys("Mounika@3109")
driver.find_element_by_id("exampleCheck1").click()
dropdown = Select(driver.find_element_by_id("exampleFormControlSelect1"))
dropdown.select_by_visible_text("Female")
dropdown.select_by_index(0)
driver.find_element_by_xpath("//input[@type = 'submit']").click()
messagr = driver.find_element_by_css_selector("[class*='alert-dismissible']").text
print(messagr)
assert "Success! The Form has been submitted successfully!." in messagr
|
# # 7-6
# age = float(input("Enter your age:"))
# grade = int(input("Enter your grade:")) # bug: 56age and 2grade will not respond
# if age >= 8 :
# if grade >=3:
# print("You can play this game.")
# else:
# print("Sorry, you can't play the game.") |
# print("Enter your name:")
# somebody = input()
# print("Hi, %s, how are you today?" % somebody)
|
# print("I am 6'2\" tall.")
#
# print('I am 6\'2" tall.')
#
# tabby_cat = "\tI'm tabbed in."
# persian_cat = "I'm split\non a line"
# backslash_cat = "I'm \\a \\ cat."
#
# fat_cat = '''
# I' ll do a list:
# \t* Cat food
# \t* Fishies
# \t* Catnip\n\t* Grass
# '''
#
# print(tabby_cat)
# print(persian_cat)
# print(backslash_cat)
# print(fat_cat)
# 1.search \
# 2. same
# 3.
name = "hawking"
print("my name is \"%s\"" % name)
# 4. something strange, when %r meet with str.
name = "hawking"
print("my name is \'%r\'" % name)
|
# test items
#1. 5 times
# for i in range(1, 6):
# print('Hi, Warren')
#2. 3 times
# for i in range(1, 6, 2):
# print('Hi, Warren')
#3. 1234567
# for i in range(1, 8):
# print(i)
#4. 01234567
# for i in range(8):
# print(i)
#5. 2-4-6-8
#6. 10-8-6-4-2
#7. continue
#8. when the condition is not adapt
# try items
# num = int(input("Which multiplication table would you like?\n"))
# print("Here's your table:")
# for i in range(1, 11):
# print(num, " x ", i, " = ", num*i)
# num = int(input("Which multiplication table would you like?\n"))
# print("Here's your table:")
# i = 1
# while i < 11 :
# print(num, " x ", i, " = ", num*i)
# i += 1
num = int(input("Which multiplication table would you like?\n"))
high = int(input("How high do you want to go?\n"))
print("Here's your table:")
i = 1
while i <= high :
print(num, " x ", i, " = ", num*i)
i += 1
|
# 测试题
apple = int(3.14)
print(apple)
# 第二题不行 先算5/9 等于零
temp = 13.2
# 第三题
print(int(temp+0.5))
# 动手试一试
cat = '12.34'
dog = float(cat)
duck = int(56.78)
ken = int(float(cat))
print(dog, " ", duck, " ", ken)
|
# test items
# 1. insert( , ) , extend([]), append(),
# 2. pop() ,remove(), del letters[3]
# 3. sorted()
# 4. 'value' in letters
# 5. ------> letters.index('d')
# 6. couple = (1,3,5)
# 7. couple = [[], []]
# 8. value = couple[0][0]
# try items
# # 1.
# print("Enter 5 names:")
# names = []
# for i in range(5):
# names.append(input())
#
# print("The names are ", end='')
# for i in range(5):
# print(names[i], end=' ')
#
# # 2.
# names.sort()
# print("The names sort out are ", end='')
# for i in range(5):
# print(names[i], end= ' ')
# print()
# # 3
# print("The third name you enterd is: %s" % names[2])
# 4.
# print("Enter 5 names:")
# names = []
# for i in range(5):
# names.append(input())
#
# print("The names are ", end='')
# for i in range(5):
# print(names[i], end=' ')
# print()
# index = int(input("Replace one name. Which one? [1-5]: "))
# new_name = input("New name:")
# names[index-1] = new_name
# print("The names are ", end='')
# for i in range(5):
# print(names[i], end=' ') |
# -*- coding: utf-8 -*-
# @Time : 2020/8/1 16:05
# @Author : sml
# @File : 7.跳台阶.py
"""
题目描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
题目解析
这是一道经典的递推题目,你可以想如果青蛙当前在第n级台阶上,那它上一步是在哪里呢?
显然,由于它可以跳1级台阶或者2级台阶,所以它上一步必定在第n-1,或者第n-2级台阶,
也就是说它跳上n级台阶的跳法数是跳上n-1和跳上n-2级台阶的跳法数之和。
"""
class Solution:
def jumpFloor(self, number):
if number ==1:
return 1
elif number==2:
return 2
else:
s=[1,2]
for i in range(2,number+1):
a=s[i-1]+s[i-2]
s.append(a)
return s[number-1]
|
# -*- coding: utf-8 -*-
# @Time : 2020/8/24 10:25
# @Author : sml
# @File : 49.把字符串转换成函数.py
"""
题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。
数值为0或者字符串不是一个合法的数值则返回0
输入描述:
输入一个字符串,包括数字字母符号,可以为空
输出描述:
如果是合法的数值表达则返回该数字,否则返回0
思路:1.先考虑第一个字符是否存在[+,-]
2.考虑字符串内是否有特殊字符,有就返回0
3.考虑字符串是否仅有[+,-]
4.考虑空字符串
"""
class Solution:
def StrToInt(self, s):
# write code here
dic1={"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9}
dic2={"+":1,"-":-1}
if not s or len(s)<1:
return 0
first=s[0]
if first in ["+","-"]:
flag=dic2[first]
if len(s)==1:
return 0
x=0
for i in s[1:]:
if i not in dic1:
return 0
x=x*10+dic1[i]
return flag*x
else:
x=0
for i in s[0:]:
if i not in dic1:
return 0
x=x*10+dic1[i]
return x
if __name__ == '__main__':
f=Solution()
print(f.StrToInt("+123")) |
# -*- coding: utf-8 -*-
# @Time : 2020/8/1 13:29
# @Author : sml
# @File : 3.从头到尾打印列表.py
#insert() 函数用于将指定对象插入列表的指定位置。
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
l = []
head = listNode
while head:
l.insert(0, head.val)
head = head.next
return l
|
x = input("Digite un numero x para compararlo con 30: ")
if int(x) < 30:
print("x es menor que 30")
elif int(x) == 30:
print("x es igual 30")
else:
print("x es mayor que 30")
y = input("Digite un numero y para verificar si esta entre 2 y 100: ")
if int(y) > 2 and int(y) <= 100:
print("y esta en el rango de 100")
else:
print("y no esta en el rango 2 a 100") |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sklearn
data=pd.read_csv("Salary_Data.csv")
X=data.iloc[:,:1].values
y=data.iloc[:,1].values
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.33)
from sklearn.linear_model import LinearRegression
lm=LinearRegression()
lm.fit(X_train,y_train)
y_pred=lm.predict(X_test)
plt.scatter(X_test,y_test,color="red")
plt.plot(X_test,y_pred,color="blue")
score=lm.score(X_test,y_test)
print "Score:",score
|
import numpy as np
from random import shuffle
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a minibatch of data.
- y: A numpy array of shape (N,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
- reg: (float) regularization strength
Returns a tuple of:
- loss as single float
- gradient with respect to weights W; an array of same shape as W
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
###############################################################################
# TODO(DONE): Compute the softmax loss and its gradient using explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
###############################################################################
# compute the loss and the gradient
num_classes = W.shape[1]
num_train = X.shape[0]
for i in range(num_train):
# compute unnormlaized log probs
unorm_log_probs = np.dot(X[i], W)
# for numerical stability
unorm_log_probs -= np.max(unorm_log_probs)
# get class probabilities
probs = np.exp(unorm_log_probs) / np.sum(np.exp(unorm_log_probs))
# compute loss
loss -= np.log(probs[y[i]])
# subtract 1 from correct class of prob
probs[y[i]] -= 1
for j in range(num_classes):
dW[:, j] += X[i, :] * probs[j]
# average out grad and loss
loss /= num_train
dW /= num_train
# add regularization contribution
loss += 0.5 * reg * np.sum(W * W)
dW += reg * W
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
def softmax_loss_vectorized(W, X, y, reg):
"""
Softmax loss function, vectorized version.
Inputs and outputs are the same as softmax_loss_naive.
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
# Compute the softmax loss and its gradient using no explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
# compute scores matrix
scores = X @ W
# get the correct class scores indicies
train_count = X.shape[0]
correct_classes_list = y.flatten().tolist()
correct_scores_indices = range(0, train_count), correct_classes_list
# get neg. correct class score for each example
correct_scores_neg = scores[correct_scores_indices] * -1
# compute the log part
sum_logs = np.log(np.sum(np.exp(scores), axis=1))
losses_vector = correct_scores_neg + sum_logs
loss = (np.sum(losses_vector) / train_count) + (reg * np.sum(W * W))
exp_scores = np.exp(scores)
# normalize them for each example
probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True)
dscores = probs
dscores[range(train_count),y] -= 1
dscores /= train_count
dW = np.dot(X.T, dscores)
dW += reg*W # don't forget the regularization gradient
return loss, dW
|
#######################################################################
# Sort paperauthors
import pandas as pd
import sys
from sets import Set
#######################################################################
#### Get the subset of authors that are found in paperauthors
# I do a few things to cut down the size of PaperAuthors because I'm
# primarily working on a wimpy laptop
PaperAuthor = pd.read_csv("PaperAuthor.csv")
PaperAuthor = PaperAuthor.drop(['Name','Affiliation'], axis=1)
PaperAuthor.to_csv("PaperAuthor2.csv")
# Now get only the authors that are in paperauthors
PaperAuthor = pd.read_csv("PaperAuthor2.csv", index_col=0)
fin = open('Author.csv', 'r')
fout = open('Author2.csv', 'w')
print >>fout, "Id,Name,Affiliation"
fin.readline()
authors = Set(PaperAuthor['AuthorId'].values)
for line in fin:
items = line.split(",")
if int(items[0]) in authors:
print >>fout, line,
fin.close()
fout.close()
########################################################################
#### AuthorsGroups - the author_groups.csv file is generated by
#### author_groups.py. It finds repeated papers duplicates and collects
#### all the authors for these papers into an "author group".
authors = pd.read_csv("Author2.csv", index_col=0)
agroups = pd.read_csv("author_groups.csv")
agrps = authors.drop(['Name', 'Affiliation'], axis=1)
agrps['agrps'] = None
# For each author, find the author groups he/she is a member of
for aid in sorted(set(agroups['authorid'].values)):
agrps['agrps'][aid] = agroups['authorgroup'][agroups['authorid']==aid].values
agrps = agrps[:][pd.notnull(agrps['agrps'])]
# Print out the dataframe, keyed on authorID and containing lists of
# author groups
agrps.to_csv("Author8a6.tsv", sep="\t")
|
# -- coding: utf-8 --
f = "%r %r %r %r"
print f % (1,2,3,4)
print f % ("one","two","three","four")
print f % (True,False,False,True)
print f %(f,f,f,f)
print f % ("I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight.")
#效果全部答应出来了
'''
习题:
手打代码,没有发生错误
对称引号不用转义,目前只了解这个情况
'''
|
l1 = list('ABCDE')
print(l1*3)
print(3*l1)
print(l1+l1)
del l1[2]
print(l1)
l1.reverse()
print(l1) |
decision=True
while decision:
import random
import time
HANGMANPICS=['''
+---+
| |
|
|
|
|
=========''','''
+---+
| |
O |
|
|
|
=========''','''
+---+
| |
O |
| |
|
|
=========''','''
+---+
| |
O |
/| |
|
|
=========''','''
+---+
| |
O |
/|\ |
|
|
=========''','''
+---+
| |
O |
/|\ |
/ |
|
=========''','''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
words='''ant baboon badger bat bear beaver camel cat clam cobra cougar
coyote crow roster deer dog donkey duck eagle ferret fox frog goat goose hawk lion
lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon
python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake
spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat
zebra'''.split()
time.sleep(3)
print(" the game start")
secret_lettr=""
def selection(wordf):
wordindex=random.randint(0,len(wordf)-1)
return wordf[wordindex]
secret_lettr=selection(words)
time.sleep(3)
def initdisplay(secretletter):
time.sleep(2)
blanks='-'*len(secretletter)
hangpictindex=len(HANGMANPICS)
print (blanks)
print("it is a %d letter word" %len(secretletter))
time.sleep(2)
print(HANGMANPICS[0])
initdisplay(secret_lettr)
def call(secretletter):
num=0
store=[]
print("enter only alphabets")
indata=input("enter the letter")
for i in range(0,len(secretletter)):
for z in range(0,1):
if secretletter[i]==indata :
store.append(str(i))
print (store)
num=num+1
else:
num=num
for j in store:
print (" the guesed element at these positions",j)
return num,indata
def guess(secretletter):
flag=True
correctentry=0
wrongentry=0
correctresult=""
while flag:
x,z=call(secret_lettr)
strsecretletter=str(secretletter)
length=len(strsecretletter)
if x >=1:
correctentry+=1
correctresult=correctresult+z
if correctresult==strsecretletter:
print (" you are winner and took and the guessed letter is ", strsecretletter)
flag=False
break
elif correctresult!=strsecretletter and len (correctresult)==len(strsecretletter):
print (" you are also awinner and took and the guessed letter is ", strsecretletter)
flag=False
break
else:
continue
elif x==0:
wrongentry=wrongentry+1
time.sleep(2)
print (" entry not matching")
hang_counter=len(HANGMANPICS)
if wrongentry < hang_counter-1:
time.sleep(1)
print(HANGMANPICS[wrongentry])
continue
elif wrongentry == hang_counter-1:
time.sleep(5)
print ("last chance, guess well")
print(HANGMANPICS[wrongentry])
continue
elif wrongentry == hang_counter:
print (" you are looser and the guessed letter is ", strsecretletter)
print ("game over")
flag=False
break
guess(secret_lettr)
print ("Do you want to play again")
print ( "press yes or y to play again and No or n to quit")
play=input('enter you interest>')
if play=='y' or play=='yes' :
decision=True
elif play=='n' or play=='no' :
decision=False
else:
print ( "wrong key pressed")
decision=False
|
# Parte de scrypt.py
# Documentacion de: https://passlib.readthedocs.io/en/stable/lib/passlib.hash.scrypt.html
# Integrantes:
# Jorge Azmitia
# Cristina Bautista
# Sebastian Maldonado
# Abril Palencia
# Cesar Rodas
from passlib.hash import scrypt
def opcion1(password):
h = scrypt.using(salt=b'salt', salt_size=1024, rounds=8, block_size=8,
parallelism=1, relaxed=True).hash(password)
return h
def opcion2(password, h):
verify = scrypt.verify(password, h)
if verify == True:
return print("Nitido, es la misma password")
else:
return print("No es la misma password, vuelve a intentarlo")
a = 0
while a != 3:
print("""
1. Ingresar password
2. Comparar password
3. Salir
""")
a = int(input("Escoja una opcion: "))
if a == 1:
password = input("Ingrese una password: ")
hpassword = opcion1(password)
elif a == 2:
password2 = input("Ingrese una password para comparar con la password de la opcion 1: ")
opcion2(password2, hpassword)
elif a == 3:
print("Hasta la proxima, amigos")
a = 3 |
print("hello,world")
print("how are you")
def learn(n):
sum = 0
for i in range(n):
sum+=i
return sum
|
#!/usr/bin/env python3
# for looping large number of data stream
from itertools import groupby
"""
Poker Hand:
Read poker_hand.txt.
Create High card number for 'T', 'J', 'Q', 'K' and 'A' as 10,11,12,13,14 and combine with range(2, 10)
and save it to card_value variable.
"""
# Card Value for cards above 10
card_value = {'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14}
# update card_value while inserting all numbers from 0 to 9
card_value.update((str(low_card), low_card) for low_card in [2,3,4,5,6,7,8,9])
# print(card_value)
def result(hand):
"""
result function will receive cards hands dealt to each player as a tuple
then we will extract the first index of it
"""
sorted_hand = sorted([c[0] for c in hand], reverse=True)
# seconds index in tuple is suits
suits = [s[1] for s in hand]
# return false if hand is not straight
straights = (sorted_hand == list(range(sorted_hand[0], sorted_hand[0]-5, -1)))
flush = all(suit == suits[0] for suit in suits)
if straights and flush: return 8, sorted_hand[1]
if flush: return 5, sorted_hand
if straights: return 4, sorted_hand[1]
three_of_kinds = []
two_of_kinds = []
for v, group in groupby(sorted_hand):
cc = sum(1 for _ in group)
if cc == 4: return 7, v, sorted_hand, print(v, sorted_hand)
elif cc == 3: three_of_kinds.append(v)
elif cc == 2: two_of_kinds.append(v)
if three_of_kinds: return (6 if two_of_kinds else 3), three_of_kinds, two_of_kinds, sorted_hand
return len(two_of_kinds), two_of_kinds, sorted_hand
player_one = 0
player_two = 0
with open("poker_hand.txt") as file:
for lines in file:
cards = [(card_value[line[0]], line[1]) for line in lines.split(' ')]
player_one += result(cards[:5]) > result(cards[5:])
player_two += result(cards[:5]) < result(cards[5:])
print(f"Player 1: {player_one}")
print(f"Player 2: {player_two}") |
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([10, 20])
print(A * B)
#1차원 배열인 배열 B가 2차원 배열 A와 똑같은 형상으로 변형된 후 원소별 연산 수행
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.