text stringlengths 37 1.41M |
|---|
"""Module for making player choices for game simulations."""
from __future__ import annotations
import logging
import cashflowsim.player as cfs_player
import cashflowsim.strategy as cfs_strategy
import cashflowsim.assets as cfs_assets
import cashflowsim.loans as cfs_loans
log: logging.Logger = logging.getLogger(__name__)
def choose_small_or_big_deal_card(*, a_player: cfs_player.Player) -> str:
"""Choose between Small or Big Deal Card."""
if a_player.strategy.manual:
while True:
small_or_big_card = input("Pick '(s)mall' or '(b)ig' Deal Card? ")
if small_or_big_card.lower() in ["small", "s"]:
log.info(f"Small Deal Card chosen with input: {small_or_big_card}")
return "small"
if small_or_big_card.lower() in ["big", "b"]:
log.info(f"Big Deal Card chosen with input: {small_or_big_card}")
return "big"
print(f"Entry not understood, please try again\n")
log.info(
f"Entry not understood, please try again with input: {small_or_big_card}"
)
else:
if a_player.savings > a_player.strategy.big_deal_small_deal_threshold:
return "big"
return "small"
def choose_to_donate_to_charity(*, a_strategy: cfs_strategy.Strategy) -> bool:
"""Decide whether to donate to charity manually or by strategy."""
if a_strategy.manual:
while True:
charity_choice: str = input(
f"Do you want to donate 10% of your income"
f" to have the option of rolling 1 or 2"
f" dice for the next 3 turns?"
).lower()[0]
log.info(f"charity_choice: {charity_choice}")
match charity_choice:
case "n":
print(f"OK, no charity chosen")
return False
case "y":
return True
case _:
print(f"Entry not understood, please try again\n")
else:
if a_strategy.charitable:
log.info(f"Choosing to be charitible in non-manual mode")
return True
log.info(f"Choosing not to be charitible in non-manual mode")
return False
def choose_no_die(
*,
no_die_choice_list: list[int],
a_strategy: cfs_strategy.Strategy,
) -> int:
"""Choose number of dice to roll."""
if a_strategy.manual:
while True:
print(f"Please choose number of die to use.")
try:
no_die_choice: int = int(input(f"Choices: {str(no_die_choice_list)}"))
except ValueError:
err_msg = f"No numeric input. please choose number of die"
log.info(err_msg)
print(err_msg)
continue
if no_die_choice in no_die_choice_list:
if no_die_choice == 1:
print(f"1 die chosen")
else:
print(f"{no_die_choice} dice chosen")
break
print(f"Entry not in list, please try again\n")
log.info(f"Entry not in list, please try again\n")
else:
no_die_choice = max(no_die_choice_list)
log.info(f"Choosing {no_die_choice} as max in options in non-manual mode")
return no_die_choice
def choose_to_buy_stock_asset(
*, a_player: cfs_player.Player, new_stock: cfs_assets.Stock
) -> bool:
"""Choose whether and how much stock to buy."""
if a_player.strategy.manual:
while True:
try:
print(f"Stock for sale: {new_stock}")
number_of_shares = int(
input(f"How many shares would you like to buy (or 0 to decline)?")
)
if number_of_shares >= 0:
break
except ValueError:
pass
print(f"Valid number not entered, please try again")
if number_of_shares >= 1:
log.info(f"Buying {number_of_shares} shares")
new_stock.shares = number_of_shares
return True
log.info(f"Small Deal Action to buy Stock declined")
return False
# Non Manual
log.info(
f"new_stock.roi: {new_stock.roi}, player roi_threshold: {a_player.strategy.roi_threshold}"
)
if new_stock.roi > a_player.strategy.roi_threshold or (
(
new_stock.cost_per_share
< (
(new_stock.price_range_high - new_stock.price_range_low)
* a_player.strategy.price_ratio_threshold
+ new_stock.price_range_low
)
)
and new_stock.name not in ["CD"]
):
log.info(f"Meets ROI (income) or Cost Ratio (Value) criteria")
if new_stock.cost_per_share < a_player.savings:
# Buy maximum your can with cash
# print(f"new_stock: {new_stock}")
number_of_shares = int(
float(a_player.savings) / float(new_stock.cost_per_share)
)
new_stock.shares = number_of_shares
else:
log.info(f"Not enough savings to buy even one share, please drive through")
return False
log.info(f"Choosing to buy {new_stock.shares} shares of {new_stock.name}")
return True
log.info(f"Choosing not to buy asset due to low roi: {new_stock.name}")
return False
def choose_to_buy_asset(
*,
a_player: cfs_player.Player,
asset: cfs_assets.Asset,
price: int = 0,
) -> bool:
"""Decide whether to buy an asset."""
if price == 0:
price = asset.cost
if a_player.strategy.manual:
while True:
print(f"Asset for sale: {asset}")
to_buy = input(f"Do you want to buy for {asset.cost}?").lower()[0]
if to_buy == "n":
print("OK, no sale")
return False
if to_buy == "y":
return True
print(f"Entry not understood, please try again\n")
else:
log.info(
f"In choosing to buy asset not-manual: {asset.name}.\nasset.roi: {asset.roi}. "
f"a_player.strategy.roi_threshold: {a_player.strategy.roi_threshold}, "
f"asset.cost: {asset.cost}, asset.price_range_low: "
f"{asset.price_range_low}, asset.price_range_high: {asset.price_range_high}"
)
if asset.roi >= a_player.strategy.roi_threshold or (
asset.cost
<= (
asset.price_range_low
+ (asset.price_range_high - asset.price_range_low)
* a_player.strategy.price_ratio_threshold
)
):
log.info(f"Choosing to buy asset: {asset.name}")
# Buy if high ROI or price below midpoint of range if not gold
return True
log.info(f"Choosing not to buy asset: {asset.name}")
return False
def choose_to_sell_asset(
*,
a_player: cfs_player.Player,
asset: cfs_assets.Asset,
price: int = 0,
delta_price: int = 0,
) -> bool:
"""Decide whether to sell assets."""
log.info(f"In choose_to_sell_asset: {asset.name}")
if asset.asset_type == "Stock":
orig_price: int = asset.total_cost # type: ignore
else:
orig_price = asset.cost
if delta_price > 0:
price = orig_price + delta_price
if a_player.strategy.manual:
while True:
print(f"Asset: {asset} has an offer of {price}")
to_sell = input("Do you want to sell?").lower()[0]
if to_sell == "n":
print("OK, no sale")
return False
if to_sell == "y":
return True
print(f"Entry not understood, please try again\n")
else:
log.info(f"price: {price}")
log.info(f"orig_price: {orig_price}")
if price > asset.loan_amount:
roi_of_sale = (
float(asset.cash_flow) * 12 / (float(price) - asset.loan_amount)
)
else:
roi_of_sale = 0
log.info(f"roi_of_sale: {roi_of_sale}")
log.info(f"a_player.strategy.roi_threshold: {a_player.strategy.roi_threshold}")
# Default is to Sell if price is higher than basis & less than ROI
# threshold on sale price
if price > orig_price and roi_of_sale < a_player.strategy.roi_threshold:
log.info(f"Choosing to sell asset: {asset.name}")
return True
log.info(f"Choosing not to sell asset: {asset.name}")
return False
def choose_to_get_loan_to_buy_asset(
*,
a_player: cfs_player.Player,
asset: cfs_assets.Asset,
loan_amount: int,
) -> bool:
"""Decice whether to take loan to buy asset."""
expected_loan_payment = int(loan_amount / 10)
log.info(
f"Loan to buy asset attempt amount: {loan_amount}"
f" with payment of {expected_loan_payment}."
)
if a_player.strategy.manual:
while True:
print(
f"Asset for sale: {asset} for {asset.cost}"
f"\nYou only have {a_player.savings}"
)
to_buy_entry: str = input(
f"Do you want to take a loan for {loan_amount} ?"
).lower()[0]
if to_buy_entry == "n":
print("OK, no sale")
return False
if to_buy_entry == "y":
print("OK, let's get it")
return True
print("Entry not understood, please try again\n")
else:
log.info(f"Player Strategy:\n{a_player.strategy}")
if a_player.strategy.take_downpayment_loans:
if expected_loan_payment <= a_player.monthly_cash_flow:
log.info("Still enough cash flow for loan, let's buy!")
return True
log.info("Can't buy, not enough cash flow to get loan")
return False
log.info("Not taking downpayment loan due to strategy")
return False
def choose_to_pay_off_loan(*, a_player: cfs_player.Player) -> bool:
"""Decide wheter to payoff loan and make payment or pay it off"""
if len(a_player.loan_list) == 0 or a_player.strategy.loan_payback == "Never":
return False
loan_payoff_strategy_to_use = a_player.strategy.loan_payback
log.info(f"loan_payoff_strategy_to_use: {loan_payoff_strategy_to_use}")
loan_to_payoff: cfs_loans.Loan = cfs_loans.Loan(
name="Dummy Loan",
balance=1000,
monthly_payment=100,
partial_payment_allowed=True,
)
match loan_payoff_strategy_to_use:
case "Manual":
while True:
for loan_no, loan in enumerate(a_player.loan_list):
print(f"{loan_no + 1}: {loan}")
log.info(f"{loan_no + 1}: {loan}")
try:
loan_no_to_payoff: int = int(
input(
f"Which Loan Do you want to payoff (enter number or 0 for none):"
)
)
except ValueError:
print(f"Invalid loan number (non number). Please try again")
log.info(f"Invalid loan number (non number). Please try again")
continue
if loan_no_to_payoff == 0:
print(f"OK, not paying off any loans")
log.info(f"OK, not paying off any loans")
return False
loan_no_to_payoff -= 1 # Change to 0 based
if loan_no_to_payoff not in range(len(a_player.loan_list)):
print(f"Invalid loan number (bad number). Please try again")
log.info(f"Invalid loan number (bad number). Please try again")
continue
log.info(f"Chose to payoff loan number {loan_no_to_payoff+1}")
break
while True:
try:
payment = int(input("How Much to payoff? (increments of 1,000):"))
except ValueError:
err_msg = "Invalid payoff amount (non number). Please try again"
log.info(err_msg)
print(err_msg)
continue
if (
payment < 1000
or payment > a_player.loan_list[loan_no_to_payoff].balance
or payment % 1_000 != 0
):
err_msg = "Invalid payoff amount (bad number). Please try again"
log.info(err_msg)
print(err_msg)
continue
break
if (
a_player.loan_list[loan_no_to_payoff].partial_payment_allowed
and payment < a_player.loan_list[loan_no_to_payoff].balance
):
log.info(f"Evaluating partial payment")
log.info(f"Choose to make partial payment of {payment}")
a_player.loan_list[loan_no_to_payoff].make_payment(payment=payment)
a_player.make_payment(payment=payment)
info_msg = f"Loan paydown made"
log.info(info_msg)
print(info_msg)
return True
else:
log.info(f"Evaluating full payoff")
if payment != a_player.loan_list[loan_no_to_payoff].balance:
info_msg = f"Partial payment not allowed and payment chosen was not for full loan amount. Loan paydown not made"
log.info(info_msg)
print(info_msg)
return False
if payment > a_player.savings:
info_msg = (
f"Not enough savings to make requested payment to pay-off loan."
)
log.info(info_msg)
print(info_msg)
return False
log.info(f"Player has enough savings to pay-off loan")
a_player.payoff_loan(loan_number=loan_no_to_payoff)
info_msg = f"Loan paid-off"
log.info(info_msg)
print(info_msg)
return True
case "Smallest":
log.info("Evaluating whether to pay-off loan using 'Smallest' method")
# loan_paid = False
while True:
loan_to_payoff_value: int = 1000000
loan_to_payoff_no: int = 1
loan_to_pay: bool = False
for loan_no, a_loan in enumerate(a_player.loan_list):
if (
a_loan.partial_payment_allowed
and a_player.savings >= 1000
and loan_to_payoff_value > 1000
): # Is it the first loan found that a payment can be made against?
loan_to_payoff_value: int = 1000
loan_to_payoff: cfs_loans.Loan = a_loan
loan_to_payoff_no: int = loan_no
loan_to_pay: bool = True
if (
a_player.savings >= a_loan.balance
and a_loan.balance < loan_to_payoff_value
): # Is it the smallest loan that a payment can be made against?
loan_to_payoff_value: int = a_loan.balance
loan_to_payoff: cfs_loans.Loan = a_loan
loan_to_payoff_no: int = loan_no
loan_to_pay: bool = True
if loan_to_pay:
if loan_to_payoff_value == loan_to_payoff.balance:
a_player.payoff_loan(loan_number=loan_to_payoff_no)
log.info(f"Loan {loan_to_payoff_no} has been paid-off")
else:
loan_to_payoff.make_payment(payment=1000)
log.info(f"Loan {loan_to_payoff_no} has been paid down")
return True # loan_paid = True
log.info(f"No loans have been paid-off")
return False
case "Largest":
log.info(f"Evaluating whether to pay-off loan using 'Largest' method")
# loan_paid = False
while True:
loan_to_payoff_value = 1
loan_to_payoff_no = 1
loan_to_pay = False
for loan_no, a_loan in enumerate(a_player.loan_list):
log.info(
f"Partial Payment allowed: {a_loan.partial_payment_allowed}"
)
log.info(
f"a_player.savings: {a_player.savings}, loan_to_payoff_value: {loan_to_payoff_value}"
)
if (
a_loan.partial_payment_allowed
and a_player.savings >= 1_000
and loan_to_payoff_value < 1_000
# should only be true for fist loan if partial_payments_allowed
):
log.info(f"Patial payment allowed and first loan")
loan_to_payoff_value = 1000
# largestLoan = aLoan
loan_to_payoff_no = loan_no
loan_to_payoff = a_loan
loan_to_pay = True
else:
log.info(f"No partial payment allowed or not first loan?")
if (
a_loan.balance > loan_to_payoff_value
and a_player.savings >= a_loan.balance
):
loan_to_payoff_value = a_loan.balance
# largestLoan = aLoan
loan_to_payoff_no = loan_no
loan_to_payoff = a_loan
loan_to_pay = True
if loan_to_pay:
if loan_to_payoff_value == loan_to_payoff.balance:
a_player.payoff_loan(loan_number=loan_to_payoff_no)
log.info(f"Loan {loan_to_payoff_no} has been paid-off")
else:
loan_to_payoff.make_payment(payment=1000)
log.info(f"Loan {loan_to_payoff_no} has been paid down")
return True # Loan Paid
log.info(f"No loans have been paid-off")
return False
case "Highest Interest":
log.info(
f"Evaluating whether to pay-off loan using 'Highest Interest' method"
)
# loan_paid = False
while True:
log.info("Searching through the list of loans")
largest_interest_rate: float = 0.0
loan_to_payoff_value: int = 1
loan_to_payoff_no: int = 1
loan_to_pay: bool = False
for loan_no, a_loan in enumerate(a_player.loan_list):
this_loan_interest_rate = float(a_loan.monthly_payment) / float(
a_loan.balance
)
if (
a_loan.partial_payment_allowed
and a_player.savings >= 1000
and this_loan_interest_rate > largest_interest_rate
):
loan_to_payoff_value = 1000
loan_to_payoff_no = loan_no
loan_to_payoff = a_loan
loan_to_pay = True
log.info(
f"Found a loan to be paritally repaid {loan_to_payoff_no}\n{a_loan}"
)
if (
a_player.savings >= a_loan.balance
and this_loan_interest_rate > largest_interest_rate
):
log.info("Found a loan to be fully repaid")
loan_to_payoff_value = a_loan.balance
loan_to_payoff_no = loan_no
loan_to_payoff = a_loan
loan_to_pay = True
if loan_to_pay:
if loan_to_payoff_value == loan_to_payoff.balance:
a_player.payoff_loan(loan_number=loan_to_payoff_no)
log.info(f"Loan {loan_to_payoff_no} has been paid-off")
else:
log.info(
f"Partially paying loan. Balance before: "
f"{a_player.loan_list[loan_to_payoff_no].balance}"
)
# new_balance, new_payment = (
loan_payment_result = loan_to_payoff.make_payment(payment=1000)
log.info(
f"Balance after: {loan_to_payoff.balance}"
# new_balance, new_payment)
f"\n{loan_payment_result}"
)
return True # loan paid
log.info(f"No loans have been paid-off")
return False
case _:
err_msg = (
f"Incorrect loan_payoff_strategy_to_use: {loan_payoff_strategy_to_use}"
)
log.error(err_msg)
raise ValueError(err_msg)
|
"""Functions related to rolling a die."""
import random
def roll_die(strategy="Manual", no_of_dice=1, verbose=False):
"""Roll a die."""
if strategy == "Manual":
verbose = True
if no_of_dice == 1:
input("Hit 'Enter' to roll die ")
else:
input("Hit 'Enter' to roll " + str(no_of_dice) + " dice")
total_die_roll = 0
for _ in range(no_of_dice):
total_die_roll += random.choice([1, 2, 3, 4, 5, 6])
if verbose:
print("Total Dice: ", str(total_die_roll))
return total_die_roll
if __name__ == '__main__': # test die rolling
import statistics
print("\n100 Automatic Rolls in verbose mode")
for roll in range(100): # Try 100 automatic rolls in verbose
die_result = roll_die("Automatic", 1, True)
print("\n100 Automatic Rolls in non-verbose mode")
die_rolls = []
for roll in range(100): # Try 100 automatic rolls in quiet
die_result = roll_die("Automatic", 1, False)
die_rolls.append(die_result)
mean_die_roll = statistics.mean(die_rolls)
std_dev_die_roll = statistics.stdev(die_rolls)
print("For 100 Automatic Die Rolls: Mean =", str(mean_die_roll),
"Std. Dev. =", str(std_dev_die_roll))
print("\n10 Manual Rolls in verbose mode")
for roll in range(10):
die_result = roll_die("Manual", 1, True)
print("\n10 Manual Rolls of two dice in non-verbose mode")
die_rolls = []
for roll in range(10):
die_result = roll_die("Manual", 2, False)
die_rolls.append(die_result)
mean_die_roll = statistics.mean(die_rolls)
std_dev_die_roll = statistics.stdev(die_rolls)
print("For 10 Manual Rolls of 2 Dice: Mean =", str(mean_die_roll),
"Std. Dev. =", str(std_dev_die_roll
))
|
def string_reverser(our_string):
"""
Reverse the input string
Args:
our_string(string): String to be reversed
Returns:
string: The reversed string
"""
# TODO: Write your solution here
string = "" # O(1)
for i in range(len(our_string)): # O(n)
string += our_string[len(our_string) - 1 - i] # O(1)
return string # O(1)
|
# sıralama
def bubbleSort(array):
for j in range(len(array)):
for i in range(len(array)-1):
if array[i+1] < array[i]:
temp = array[i]
array[i] = array[i+1]
array[i+1] = temp
result = []
for i in range(len(array)):
result.append(array[i])
return result
# ortalama bulma
def mean(array):
sum = 0
for i in range(len(array)):
sum = sum + array[i]
result = sum/len(array)
return result
# ortanca bulma
def median(array):
array = bubbleSort(array)
result = 0
if len(array) % 2 == 0:
medianorder = (int)(len(array)/2-1)
result = (array[medianorder] + array[medianorder+1])/2
else:
medianorder = (int)((len(array)+1)/2-1)
result = array[medianorder]
return result
# En çok tekrar edeni bulma
def mode(array):
most = 0
returnvalue = 0
for i in range(len(array)):
count = 0
for j in range(len(array)):
if array[i] == array[j]:
count = count + 1
if count > most:
returnvalue = array[i]
most = count
return returnvalue
|
from collections import defaultdict
class Pmf(defaultdict):
def __init__(self, prob_dict):
defaultdict.__init__(self, int, prob_dict)
if not self.is_a_probability():
print "ERROR, NOT A PROBABILITY"
def is_a_probability(self, tol = 0.001):
total_p = reduce(lambda x, v: x + v, self.itervalues(), 0)
return (abs(total_p - 1) < tol)
def __add__(self, other):
if type(other) == type(self):
X1 = self
X2 = other
X3 = defaultdict(int)
for x1 in X1:
for x2 in X2:
X3[x1+x2] += X1[x1] * X2[x2]
return Pmf(X3)
if type(other) == int or type(other) == float:
X = self
X2 = {x + other : X[x] for x in X}
return Pmf(X2)
def __mul__(self, other):
if type(other) == type(self):
X1 = self
X2 = other
X3 = defaultdict(int)
for x1 in X1:
for x2 in X2:
X3[x1 * x2] += X1[x1] * X2[x2]
return Pmf(X3)
if type(other) == int or type(other) == float:
X = self
X2 = {x * other : X[x] for x in X}
return Pmf(X2)
def sales_pmf(appt1, appt2, deluxe_sale, std_cost, deluxe_cost):
'''INPUT:
appt1: probability of making a sale at appointment one
appt2: probability of making a sale at appointment two
deluxe_sale: given a sale, probability of selling a deluxe model
std_cost: cost of a standard model
deluxe_cost: cost of a deluxe model
OUTPUT:
sales_pmf: dictionary showing probabilities of all possible sales totals
'''
sales=defaultdict(int)
sales[0] = (appt1 - 1) * (appt2 -1)
sales[std_cost] += (
appt1 * (1 - deluxe_sale) * (1 - appt2) +
appt2 * (1 - deluxe_sale) * (1 - appt1) )
sales[deluxe_cost] += (
appt1 * deluxe_sale * (1 - appt2) +
appt2 * deluxe_sale * (1 - appt1) )
sales[2 * std_cost] += appt1 * appt2 * (1 - deluxe_sale) ** 2
sales[std_cost + deluxe_cost] += (
appt1 * (1 - deluxe_sale) * appt2 * deluxe_sale +
appt2 * (1 - deluxe_sale) * appt1 * deluxe_sale )
sales[2 * deluxe_cost] += appt1 * appt2 * deluxe_sale ** 2
return sales
def sales_pmf2(appt1, appt2, deluxe_sale, std_cost, deluxe_cost):
s1 = Pmf({0: 1-appt1, std_cost: appt1*(1-deluxe_sale), deluxe_cost: appt1*deluxe_sale})
s2 = Pmf({0: 1-appt2, std_cost: appt2*(1-deluxe_sale), deluxe_cost: appt2*deluxe_sale})
s3 = s1 + s2
return s3
import numpy as np
from scipy.stats import binom
def probability_rain(simulation_size=100000):
'''
choose the simulation_size
returns
-------
probability that it will rain for at least two days in the next five days,
knowing that the forecast says that in the next five days the chance of rain
for each day is 25%
'''
tests= binom.rvs(5, 0.25, size = simulation_size)
total = reduce(lambda t, x: t + (x >= 2), tests, 0)
return float(total)/simulation_size
import numpy as np
from scipy.stats import geom
def probability_coin(p=0.8):
'''
INPUT:
p: probability of tails on a single flip of the coin (default 0.8)
returns
-------
a dictionary showing the probability of first seeing a head on the kth flip,
for k in range 1 to 15,
knowing that you have an unfair coin,
with an p chance of getting tails.
'''
return {k: geom.pmf(k, p) for k in range(1, 16)}
if __name__ == '__main__':
#print sales_pmf(0.3,0.6,0.5,500,1000)
#print sales_pmf2(0.3,0.6,0.5,500,1000)
#print probability_rain()
print probability_coin()
|
MIN_LENGTH = 1
MAX_LENGTH = 140
def is_valid_tweet(tweet):
""" (str) -> bool
Return True if and only if tweet is no less than 1 and no more
than 140 characters long.
>>> is_valid_tweet('To me programming is more than an important ' \
+ 'practical art. It is also a gigantic undertaking in the ' \
+ 'foundations of knowledge. - Grace Hopper')
True
>>> is_valid_tweet('The best programs are written so that computing ' \
+ 'machines can perform them quickly and so that human beings can ' \
+ 'understand them clearly. - Donald Knuth')
False
"""
return len(tweet) >= 1 and len(tweet) <= 140
def contains_hash_symbol(tweet):
"""(str) -> bool
Return True if and only if the tweet contains a hash symbol.
>>> contains_hash_symbol('To me programming is more than an important ' \
+ 'practical art. It is also a gigantic undertaking in the ' \
+ '# knowledge. - Grace Hopper')
True
>>> contains_hash_symbol('The best programs written so that computing ' \
+ 'machines can perform them quickly and so that human beings can ' \
+ 'understand. - Donald Knuth')
False
"""
return '#' in (tweet)
def is_mentioned(tweet, username):
"""(str, str) -> bool
Return True if and only if the tweet mentions that username preceded by @.
>>> is_mentioned('To me programming is more than an important ' \
+ 'practical art. It is also a gigantic undertaking in the ' \
+ 'foundations of @gracehopper', 'gracehopper')
True
>>> is_mentioned('The best programs are written so that computing ' \
+ 'machines can perform them quickly and so that human beings can ' \
+ 'understand.', 'Donald Knuth')
False
"""
return '@' + username in tweet
def report_shortest(tweet1, tweet2):
"""(str, str) -> str
Return 'Tweet 1' if the first tweet is shorter than the second,
'Tweet 2' if the second tweet is shorter than the first, and
'Same length' if the tweets have the same length.
>>> report_shortest('To me programming is more than an important ' \
+ 'practical art. It is also a gigantic undertaking in the ' \
+ 'foundations of knowledge.',
'The best programs are written so that computing ' \
+ 'machines can perform them quickly and so that human beings can ' \
+ 'understand them clearly.')
Tweet 1
>>> report_shortest('To me programming is more than an important ' \
+ 'practical art. It is also a gigantic undertaking in the ' \
+ 'foundations of knowledge. - Grace Hopper',
'The best programs are written so that computing ' \
+ 'machines can perform them quickly and so that human beings can ' \
+ 'understand them clearly.')
Tweet 2
>>> report_shortest('To me programming is more than an important ' \
+ 'practical art. It is also a gigantic undertaking in the ' \
+ 'foundations of knowledge. - Grace Hopper',
'The best programs are written so that computing ' \
+ 'machines can perform them quickly and so that human beings can ' \
+ 'understand them clearly.Knuth')
Same Length
"""
tweet1 = len(tweet1)
tweet2 = len(tweet2)
min(tweet1, tweet2)
if tweet1 < tweet2:
return("Tweet 1")
elif tweet1 > tweet2:
return("Tweet 2")
else:
return("Same Length")
def is_reply(reply):
"""(str) -> bool
Return True if and only if this tweet is a reply
>>> is_reply('@cssu Where is your office?')
True
>>> is_reply('Meet the @cssu executive!')
False
"""
return ('@') in reply[0]
def format_reply_to(username, tweet):
"""(str, str) -> str
Prepare a reply tweet to the given username.
If tweet is over 140 characters give an error
message with how many characters over
>>> format_reply_to('@cssu', 'Where is your office?')
@cssu Where is your office?
>>> format_reply_to('@cssu', 'Tprogramming is more than an important ' \
+ 'practical art. It is also way to gigantic undertaking in the ' \
+ 'foundations of knowledge. - Grace Hopper')
5 characters too long
"""
if len(username) + len(tweet) <= 140:
return(username + ' ' + tweet)
elif len(username) + len(tweet) > 140:
extra_characters = ((len(username) + len(tweet)) % 140)
return(str(extra_characters) + ' ' + 'characters too long')
import tweet
import builtins
# Get the initial value of the constant
constants_before = [tweet.MIN_LENGTH, tweet.MAX_LENGTH]
# Type check tweet.is_valid_tweet
result = tweet.is_valid_tweet('Test 123')
assert isinstance(result, bool), \
'''tweet.is_valid_tweet should return a bool, but returned {0}
.'''.format(type(result))
# Type check tweet.contains_hash_symbol
result = tweet.contains_hash_symbol('Test 123')
assert isinstance(result, bool), \
'''tweet.contains_hash_symbol should return a bool, but returned {0}.''' \
.format(type(result))
# Type check tweet.is_mentioned
result = tweet.is_mentioned('Test 123', 'abc')
assert isinstance(result, bool), \
'''tweet.is_mentioned should return an bool, but returned {0}.''' \
.format(type(result))
# Type check tweet.report_shortest
result = tweet.report_shortest('abc', 'def')
assert isinstance(result, str), \
'''tweet.report_shortest should return an str, but returned {0}.''' \
.format(type(result))
# Type check tweet.is_reply
result = tweet.is_reply('abcd')
assert isinstance(result, bool), \
'''tweet.is_reply should return an bool, but returned {0}.''' \
.format(type(result))
# Type check tweet.format_reply_to
result = tweet.format_reply_to('abcd', 'def')
assert isinstance(result, str), \
'''tweet.format_reply_to should return an str, but returned {0}.''' \
.format(type(result))
# Get the final values of the constants
constants_after = [tweet.MIN_LENGTH, tweet.MAX_LENGTH]
# Check whether the constants are unchanged.
assert constants_before == constants_after, \
'''Your function(s) modified the value of constant MIN_LENGTH or
MAX_LENGTH. Edit your code so that the values of constants are not
changed by your functions.'''
|
from game_view import *
from generic_game_state import *
import random
import math
import time
class Player:
""" """
def __init__(self):
""" (Player) -> NoneType
Initialize a blank player to be overwritten once a game has been
started, unless the game
>>> p = Player()
>>> p
'Player'
"""
def __str__(self):
""" (Player) -> str
Return a str representation of a player.
>>> p = Player()
>>> p.__str__()
'Player'
"""
return 'Player'
def __eq__(self, other):
""" (GameState, list of players) -> NoneType
Return if two generated players are the same.
>>> p1 = Player()
>>> p2 = Player()
>>> p1.__eq__(p2)
False
"""
return self == other
def __repr__(self):
""" (Player) -> str
Return a str representation of a player that can be used.
"""
return 'Player'
class SubtractSquaresPlayer(Player):
""" """
def __init__(self, game):
""" (SubtractSquaresPlayer) -> NoneType
Initialize a player and store their name for a subtract squares game.
>>> p = SubtractSquaresPlayer(SubtractSquaresGame)
What is your name?
>>> p.player_name
'Axel'
"""
print('What is your name?')
self.player_name = input()
self.game = game
def __str__(self):
""" (SubtractSquaresPlayer) -> str
Return the name of the player as a str.
>>> p = SubtractSquaresPlayer(SubtractSquaresGame)
What is your name?
>>> p.player_name
'Axel'
"""
return '{}'.format(self.player_name)
def make_move(self):
""" (SubtractSquaresPlayer) -> int
Ask the player for an input the satisfies the legal moves.
>>> self.game.make_move()
The current number is 100
Please choose a square less than the current number
(user input)
"""
print('The current number is {}'.format(self.game.current_value))
print('Please choose a square less than the current number')
self.player_move = input()
return self.player_move
class SubtractSquaresComputer(Player):
""" """
def __init__(self, game):
""" (SubtractSquaresComputer) -> NoneType
Initialize a computer player to play against the user.
>>> p = SubtractSquaresComputer(SubtractSquaresGame)
>>> p
"""
self.game = game
def __str__(self):
""" (SubtractSquaresComputer) -> str
Return a str representation of a player.
>>> p = Player()
>>> p.__str__()
'Player'
"""
return 'Computer'
def make_move(self):
""" (SubtractSquaresComputer) -> int
Have the computer choose a random int between 0 and the current value.
Place a 2 second delay for a real time effect.
>>> SubtractSquaresComputer.make_move()
It is the computers turn
...
The computer entered (computers random int)
"""
print("""It is the computers turn
...""")
time.sleep(2)
self.computer_move = random.randint(1, int(math.sqrt(self.game.current_value)))
print("""The computer entered {}
""".format(self.computer_move))
return self.computer_move
|
MIN_LENGTH = 1
MAX_LENGTH = 140
def is_valid_tweet(tweet):
""" (str) -> bool
Return True if and only if tweet is no less than 1 and no more
than 140 characters long.
>>> is_valid_tweet('To me programming is more than an important ' \
+ 'practical art. It is also a gigantic undertaking in the ' \
+ 'foundations of knowledge. - Grace Hopper')
True
>>> is_valid_tweet('The best programs are written so that computing ' \
+ 'machines can perform them quickly and so that human beings can ' \
+ 'understand them clearly. - Donald Knuth')
False
"""
return len(tweet) >= 1 and len(tweet) <= 140
def contains_hash_symbol(tweet):
"""(str) -> bool
Return True if and only if the tweet contains a hash symbol.
>>> contains_hash_symbol('To me programming is more than an important ' \
+ 'practical art. It is also a gigantic undertaking in the ' \
+ '# knowledge. - Grace Hopper')
True
>>> contains_hash_symbol('The best programs written so that computing ' \
+ 'machines can perform them quickly and so that human beings can ' \
+ 'understand. - Donald Knuth')
False
"""
return '#' in (tweet)
def is_mentioned(tweet, username):
"""(str, str) -> bool
Return True if and only if the tweet mentions that username preceded by @.
>>> is_mentioned('To me programming is more than an important ' \
+ 'practical art. It is also a gigantic undertaking in the ' \
+ 'foundations of @gracehopper', 'gracehopper')
True
>>> is_mentioned('The best programs are written so that computing ' \
+ 'machines can perform them quickly and so that human beings can ' \
+ 'understand.', 'Donald Knuth')
False
"""
return '@' + username in tweet
def report_shortest(tweet1, tweet2):
"""(str, str) -> str
Return 'Tweet 1' if the first tweet is shorter than the second,
'Tweet 2' if the second tweet is shorter than the first, and
'Same length' if the tweets have the same length.
>>> report_shortest('To me programming is more than an important ' \
+ 'practical art. It is also a gigantic undertaking in the ' \
+ 'foundations of knowledge.',
'The best programs are written so that computing ' \
+ 'machines can perform them quickly and so that human beings can ' \
+ 'understand them clearly.')
Tweet 1
>>> report_shortest('To me programming is more than an important ' \
+ 'practical art. It is also a gigantic undertaking in the ' \
+ 'foundations of knowledge. - Grace Hopper',
'The best programs are written so that computing ' \
+ 'machines can perform them quickly and so that human beings can ' \
+ 'understand them clearly.')
Tweet 2
>>> report_shortest('To me programming is more than an important ' \
+ 'practical art. It is also a gigantic undertaking in the ' \
+ 'foundations of knowledge. - Grace Hopper',
'The best programs are written so that computing ' \
+ 'machines can perform them quickly and so that human beings can ' \
+ 'understand them clearly.Knuth')
Same Length
"""
tweet1 = len(tweet1)
tweet2 = len(tweet2)
min(tweet1, tweet2)
if tweet1 < tweet2:
return("Tweet 1")
elif tweet1 > tweet2:
return("Tweet 2")
else:
return("Same Length")
def is_reply(reply):
"""(str) -> bool
Return True if and only if this tweet is a reply
>>> is_reply('@cssu Where is your office?')
True
>>> is_reply('Meet the @cssu executive!')
False
"""
return ('@') in reply[0]
def format_reply_to(username, tweet):
"""(str, str) -> str
Prepare a reply tweet to the given username.
If tweet is over 140 characters give an error
message with how many characters over
>>> format_reply_to('@cssu', 'Where is your office?')
@cssu Where is your office?
>>> format_reply_to('@cssu', 'Tprogramming is more than an important ' \
+ 'practical art. It is also way to gigantic undertaking in the ' \
+ 'foundations of knowledge. - Grace Hopper')
5 characters too long
"""
if len(username) + len(tweet) <= 140:
return(username + ' ' + tweet)
elif len(username) + len(tweet) > 140:
extra_characters = ((len(username) + len(tweet)) % 140)
return(str(extra_characters) + ' ' + 'characters too long') |
def check_password(passwd):
""" (str) -> bool
A strong password has a length greater than or equal to 6, contains at
least one lowercase letter, at least one uppercase letter, and at least
one digit. Return True iff passwd is considered strong.
>>> check_password('I<3csc108')
True
"""
if len(passwd) < 6:
return False
#contains at least one lowercase letter
i = 0
while i < len(passwd) and not passwd[i].islower():
i = i + 1
if i == len(passwd):
return False
#at least one uppercase letter
i = 0
while i < len(passwd) and not passwd[i].isupper():
i = i + 1
if i == len(passwd):
return False
#and at least one digit
i = 0
while i < len(passwd) and not passwd[i].isdigit():
i = i + 1
if i == len(passwd):
return False
return True
if __name__ == '__main__':
print(check_password('dE6ghi'))
|
def swap_name(name_list):
""" (list of str) -> NoneType
name_list contains a single person's name. Modify name_list so that the first name and last name are swapped.
>>> name = ['John', 'Smith']
>>> swap_name(name)
>>> name
['Smith', 'John']
>>> name = ['John', 'Andrew', 'Gleeson', 'Smith']
>>> swap_name(name)
>>> name
['Smith', 'Andrew', 'Gleeson', 'John']
"""
if len(name_list) == 2:
name = name_list[0], name_list[-1] = name_list[-1], name_list[0]
else:
name_list[0], name_list[-1] = name_list[-1], name_list[0]
#first_item = L[0]
# for i in range(1, len(L)):
# L[i - 1] = L[i]
# L[-1] = first_item
""" if __name__ == "__main__"
name = ['John', 'Smith']
swap_name(name)
name """ |
def count_uppercase(s):
""" (str) -> int
Return the number of uppercase letters in s.
>>> count_uppercase('Computer Science')
"""
num_upper = 0
for ch in s:
if ch.isupper():
num_upper = num_upper + 1
return num_upper
|
def only_evens(lst):
""" (list of list of int) -> list of list of int
Return a list of the lists in lst that contain only even integers.
>>> only_evens([[1, 2, 4], [4, 0, 6], [22, 4, 3], [2]])
[[4, 0, 6], [2]]
"""
even_lists = []
for sublist in lst:
result = True
i = 0
while i < len(sublist):
if sublist[i] % 2 == 1:
result = False
i += 1
if result == True:
even_lists.append(sublist)
return even_lists
if __name__ == "__main__":
only_evens([[1, 2, 4], [4, 0, 6], [22, 4, 3], [2]]) |
def format_name(last, first):
""" (str, str) -> str
Print first and last name given.
>>> format_name('steingrimsson', 'axel')
'steingrimsson, axel'
"""
return last + ', ' + first
def to_listing(last, first, phone):
""" (str, str, str) -> str
return a string contains a listing
>>>to_listing('Steingrimsson', 'Axel', '4165714525')
'Steingrimsson, Axel: 4165714525'
"""
return to_listing(last, first) + ': ' + phone
#return last + ', ' + first + ': ' + phone
|
def build_placements(shoes):
""" (list of str) -> dict of {str: list of int}
>>> build_placements(['Saucony', 'Asics', 'Asics', 'NB', 'Saucony', 'Nike', 'Asics', 'Adidas', 'Saucony', 'Asics'])
{'Saucony': [1, 5, 9], 'NB': [4], 'Adidas': [8], 'Asics': [2, 3, 7, 10], 'Nike': [6]}
"""
result = {}
i = 1
for shoe in shoes:
if shoe not in result:
result[shoe] = [i]
elif shoe in result:
result[shoe].append(i)
i += 1
return result
|
def reverse_lookup_dictionary(phone_num, phone_to_name):
""" (str, dict of {str: str}) -> str
This function receives a phone number phone_num, and a dictionary
phone_to_name in which each key is a phone number and each value
is the name associated with that phone number.
Return the name associated with phone_num in phone_to_name, or
an empty string if there is no match.
>>> reverse_lookup_dictionary("416-555-3498", {"416-555-3498": \
"John A. Macdonald", "647-555-9812": "Louis Riel", "416-555-6543": \
"Canoe Head", "905-555-6681":"Tim Horton"})
'John A. Macdonald'
"""
if phone_num in phone_to_name.keys():
return phone_to_name[phone_num]
return ''
|
#! /usr/bin/python3
# 程序的入口
# 每一次启动名片管理系统都通过main这个文件启动
import card_tool
while True: # 进行一个无限循环,由用户决定什么时候退出循环
# 显示功能菜单
card_tool.show_menu()
# 用户输入
action_str = input("请选择希望执行的操作: ")
print("您选择的操作是【%s】"%action_str)
# 1,2,3针对名片的操作
if action_str in ["1", "2", "3"]:
# 输入为1进行新增名片的操作
if action_str == "1":
card_tool.new_card()
# 输入为2进行显示全部的操作
elif action_str == "2":
card_tool.show_all_card()
# 输入为3进行查询名片的操作
else:
card_tool.search_card()
pass
# 0 退出系统
elif action_str == "0":
print("欢迎再次使用【名片管理系统】")
break
# 其他内容输入错误,需要提示用户
else:
print("您的输入错误, 请输入数字1, 2, 3其中的一个") |
#ЗАДАЧА Begin17◦
#a = int(input("ведите координату первой точки:"))
#b = int(input("ведите координату второй точки:"))
#c = int(input("ведите координату третьей точки:"))
#x = abs(c - a)
#y = abs(c - b)
#z = x + y
#print("длинна отрезка ac:" + str(x) + "длинна отрезка bc:" + str(y) + "сумма отрезков равна :" + str(z) )
#ЗАДАЧА Begin29◦
#p = 3.14
#a = int(input("ведите градус (0<a<360):"))
#n = p * a / 180
#print("Значение угла в радианах" + str(n))
#ЗАДАЧА Integer 6◦
#i = int(input("ведите двузначное число:"))
#x = i // 10
#z = i % 10
#print("Левая цифра числа:" + str(x))
#print("Правая цифра числа:" + str(z))
#ЗАДАЧА Integer 7◦
#i = int(input("ведите двузначное число:"))
#x = i // 10
#z = i % 10
#print("сумма цифр числа:" + str(z + x))
#print("произведение цифр числа:" + str(z * x))
|
# functions
def print_separator():
print('--------')
print('here')
# intructions
print("Hello World")
# variables
name = 'Wes'
age = 31
total = 99.78
found = False
print(name)
print(age)
print(total)
print(age + 13)
print_separator()
# if statements
user_age = 79
if(user_age < 80):
print('You are still young')
elif(user_age ==80):
print("You are on the border")
else:
print("sorry, you are getting OLD :/") |
#El enunciado es confuso en cuanto a lo que pasarìa si introduzco 30, por lo que usarè if X else X if X -- Sin usar if elif
num = int(input("Ingrese un numero: "))
if num % 2 == 0:
print("Es Multiplo de 2")
else:
print("No es multiplo de 2")
if num % 3 == 0:
print("Es Multiplo de 3")
else:
print("No es multiplo de 3")
if num % 5 == 0:
print ("Es multiplo de 5")
else:
print ("No es multiplo de 5") |
def calcularValorPalabra(cadena):
total = 0
for letra in cadena:
if letra in diccionario[1]:
total = total + 1
elif letra in diccionario[2]:
total = total + 2
elif letra in diccionario[3]:
total = total + 3
elif letra in diccionario[4]:
total = total + 4
elif letra in diccionario[5]:
total = total + 5
elif letra in diccionario[8]:
total = total + 8
return total
diccionario = {1: ('a','e','i','o','u','l','n','r','s','t'),
2: ('d','g'),
3: ('b','c','m','p'),
4: ('f','h','v','w','y'),
5: ('k'),
8: ('j','x'),
10: ('q','z')}
cadena = input("Ingresa una palabra, yo te daré su valor según Scrabble")
print(f"Tu puntaje fue de: {calcularValorPalabra(cadena)}") |
r=float(input("enter a value of radius:"))
a = 3.14*r*r
print(a) |
"""Demonstrate `for`."""
from typing import List
def test_for_string() -> None:
"""Iterate over a string."""
alpha = "ababa"
num_of_as = 0
for letter in alpha:
if letter == "a":
num_of_as += 1
assert num_of_as == 3
def test_for_list() -> None:
"""Iterate over a list."""
words: List[str] = ["cat", "window", "defenestrate"]
char_count: List[int] = []
for word in words:
char_count.append(len(word))
assert char_count == [3, 6, 12]
def test_for_modify() -> None:
"""Modifying a list in a `for` loop.
If you need to modify the sequence you are iterating over while inside the loop
(for example to duplicate selected items), it is recommended that you first make a
copy.
"""
words: List[str] = ["cat", "window", "defenestrate"]
for word in words[:]: # copy of words
if len(word) > 5:
words.insert(0, word)
assert words == ["defenestrate", "window", "cat", "window", "defenestrate"]
def test_for_modify_no_copy() -> None:
"""Modifying a list in a `for` loop without first making a copy of the list.
Not a good idea.
"""
words: List[str] = ["cat", "window", "defenestrate"]
for word in words:
if len(word) > 5 and len(words) < 7:
words.insert(0, word)
assert words == [
"window",
"window",
"window",
"window",
"cat",
"window",
"defenestrate",
]
|
"""Demonstrate default arguments and keyword arguments."""
from typing import List, Optional, Union, Tuple
import pytest
def test_default_args() -> None:
"""Default arguments."""
def default_args(value: Union[int, str], multiplier: int = 2) -> Union[int, str]:
"""If `multiplier` is not provided, the default value will be used.
Throw `ValueError` if `value` is same as `multiplier`.
"""
if value == multiplier:
raise ValueError(f"Value {value} is the same as multiplier {multiplier}")
return value * multiplier
assert default_args(5) == 10
assert default_args("a", 3) == "aaa"
with pytest.raises(ValueError) as ex_info:
default_args(5, 5)
assert "Value 5 is the same as multiplier 5" in str(ex_info.value)
def test_default_value_accumulation() -> None:
"""Default value is evaluated only once.
With a mutable object, it accumulates arguments passed to it on subsequent calls.
"""
def mutable_default_value_shared(
value: int, container: List[int] = []
) -> List[int]:
"""`container` default value is a mutable object - AVOID."""
container.append(value)
return container
def mutable_default_value_not_shared(
value: int, container: Optional[List[int]] = None
) -> List[int]:
"""Avoids the default mutable object problem."""
if container is None:
container = []
container.append(value)
return container
assert mutable_default_value_shared(1) == [1]
assert mutable_default_value_shared(2) == [1, 2]
assert mutable_default_value_not_shared(1) == [1]
assert mutable_default_value_not_shared(2) == [2]
def test_keyword_arguments() -> None:
"""Keyword arguments are arguments of the form `kwarg=value`."""
def keyword_arguments(
first: int, second: int = 2, third: int = 3
) -> Tuple[int, int, int]:
"""Accept 1 required argument and 2 optional arguments."""
return (first, second, third)
# 1 positional argument
assert keyword_arguments(10) == (10, 2, 3)
# 1 keyword argument
assert keyword_arguments(first=10) == (10, 2, 3)
# 2 keyword arguments, order unimportant
assert keyword_arguments(second=20, first=10) == (10, 20, 3)
# 1 positional argument, 1 keyword argument
assert keyword_arguments(10, third=30) == (10, 2, 30)
# Positional argument cannot follow a keyword argument
# keyword_arguments(second=20, 10)
|
"""Manual string formatting."""
from typing import List
def test_rjust() -> None:
"""Right-justifying a string."""
squares: List[str] = [
str(x).rjust(2) + " " + str(x * x).rjust(3) for x in range(1, 5)
]
assert squares[0] == " 1 1"
assert squares[1] == " 2 4"
assert squares[2] == " 3 9"
assert squares[3] == " 4 16"
def test_zfill() -> None:
"""Zero-fill a string."""
assert "3.14".zfill(6) == "003.14"
assert "-3.14".zfill(6) == "-03.14"
|
"""Looping Techniques."""
import math
from typing import Dict, List, Tuple
def test_dict_items() -> None:
"""Looping through a dictionary using `items()`."""
knights_dict: Dict[str, str] = {"gallahad": "pure", "robin": "brave"}
knights: List[str] = [
name.title() + " the " + value.title() for name, value in knights_dict.items()
]
assert knights == ["Gallahad the Pure", "Robin the Brave"]
def test_seq_enumerate() -> None:
"""Looping through a sequence using `enumerate()`."""
tic_tac_toe: Dict[int, str] = {}
for index, value in enumerate(["tic", "tac", "toe"], start=1):
tic_tac_toe[index] = value
assert tic_tac_toe == {1: "tic", 2: "tac", 3: "toe"}
def test_seqs_zip() -> None:
"""Looping over 2 or more sequences using `zip()`."""
attrs: List[str] = ["name", "quest", "drink"]
values: List[str] = ["lancelot", "the holy grail"]
props: Dict[str, str] = {}
for attr, value in zip(attrs, values):
props[attr] = value
assert props == {"name": "lancelot", "quest": "the holy grail"}
def test_seq_reversed() -> None:
"""Loop over a sequence in reverse using `reversed()`."""
fruits: List[str] = [
fruit.upper() for fruit in reversed(["banana", "cherry", "durian"])
]
assert fruits == ["DURIAN", "CHERRY", "BANANA"]
def test_seq_sorted() -> None:
"""Loop over a sequence in sorted order using `sorted()`."""
fruits_amount: List[Tuple[str, int]] = [("cherry", 4), ("banana", 5), ("durian", 2)]
assert [
fruit_name[0]
for fruit_name in sorted(fruits_amount, key=lambda fruit: fruit[1])
] == ["durian", "cherry", "banana",]
def test_changing_list() -> None:
"""Changing a list - often simpler and safer to create a new list."""
raw_data: List[float] = [56.2, float("NaN"), 51.7, float("NaN"), 47.8]
filtered_data: List[float] = []
for value in raw_data:
if not math.isnan(value):
filtered_data.append(value)
assert filtered_data == [56.2, 51.7, 47.8]
filtered_data_listcomp: List[float] = [
data for data in raw_data if not math.isnan(data)
]
assert filtered_data_listcomp == filtered_data
|
"""Output formatting using `reprlib`."""
import reprlib
def test_reprlib_string() -> None:
"""Limit the number of characters in a string representation."""
test_str = "thequickbrownfoxjumpsoverthelazydog"
assert (reprlib_str := reprlib.repr(test_str)) == "'thequickbrow...verthelazydog'"
assert len(reprlib_str) == 30
(short_repr := reprlib.Repr()).maxstring = 15
assert (short_reprlib_str := short_repr.repr(test_str)) == "'thequ...zydog'"
assert len(short_reprlib_str) == 15
def test_reprlib_dict() -> None:
"""Limit the number of entries in a dictionary representation."""
test_dict = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6}
assert reprlib.repr(test_dict) == "{'a': 1, 'b': 2, 'c': 3, 'd': 4, ...}"
(short_repr := reprlib.Repr()).maxdict = 2
assert short_repr.repr(test_dict) == "{'a': 1, 'b': 2, ...}"
|
from pynput.keyboard import Key, Listener
from threading import Thread
class KeyboardListener:
def on_enter(self,fn):
'''
fn will be called each time the enter key is pressed.
'''
#start a thread to listen to the enter key event.
#This is to prevent this method from blocking.
thread = Thread(target=self.process_callback,args=[fn])
thread.start()
def process_callback(self,fn):
'''
setup the listener to listen to the enter event.
'''
self.fn = fn
with Listener(on_press=self._on_enter) as listener:
listener.join()
def _on_enter(self,key):
'''
call the provided callback if the enter is pressed.
'''
if key == Key.enter:
self.fn()
|
def rotate(text, key):
chars = "abcdefghijklmnopqrstuvwxyz"
newchars = chars[key:] + chars[:key]
trans = str.maketrans(chars + chars.upper(), newchars + newchars.upper())
return text.translate(trans)
|
import random
import time
def binarysearch(no,arr,left,right):
if left<=right:
mid = (left+right)/2
if no >arr[mid] and no<arr[mid+1]:
return mid+1
elif no<arr[mid]:
return binarysearch(no,arr,left,mid-1)
elif no>arr[mid]:
return binarysearch(no,arr,mid+1,right)
else:
return -1
def getrank(no,arr):
if no<arr[0]:
rank=0
elif no>arr[len(arr)-1]:
rank=len(arr)
else:
rank=binarysearch(no,arr,0,len(arr)-1)
return rank
#smartmerge
#takes in two sorted arrs => arr1 and arr2 and merges them
def smartmerge(arr1,arr2):
mergedict={}
print arr1
for index,i1 in enumerate(arr1):
print index, i1
#print '\n'+str(i1)
#print 'index = '+str(index)
foreignrank=getrank(i1,arr2)
#print 'foreign = '+str(foreignrank)
rank= index+foreignrank
#print rank
#print 'rank = '+str(rank)
mergedict[rank]=i1
#print
for index,i2 in enumerate(arr2):
#print '\n' + str(i2)
#print 'index = ' + str(index)
foreignrank = getrank(i2, arr1)
#print 'foreign = ' + str(foreignrank)
#print i1, foreignrank
rank = index + foreignrank
#print rank
#print 'rank = '+str(rank)
mergedict[rank] = i2
mergelist=[]
#time.sleep(0.1)
for e in range(len(arr1)+len(arr2)):
mergelist.append(mergedict[e])
return mergelist
'''
#edit the size of range to edit the size of arr created to be sorted
def create_unsortedarr(size = None):
arr=[]
for i in range(size):
rno = random.randint(1,5*size)
while rno in arr:
rno = random.randint(1,5*size)
arr.append(rno)
return arr
arr=create_unsortedarr(10)
arr1=arr[:len(arr)/2]
arr2=arr[len(arr)/2:]
arr1.sort()
arr2.sort()
'''
#arr1=[7, 15, 22, 34, 37]
#arr2=[10, 23, 25, 28, 39]
'''
print arr1
print arr2
time.sleep(0.3)
print smartmerge(arr1,arr2)
''' |
#------code by @Hrishikesh Waikar@ -----#
def decimaltobinary(no):
#returns the binary representation of the decimal no in the form of a list
b=[] #b will hold the binary no as it forms
print('in decimal to binary , no'+str(no))
while no!=0:
remainder = no%2
#print remainder
b.append(remainder)
no=no//2
print('b'+str(b))
b.reverse()
return b
def binarytodecimal(no):
#returns decimal of no
no.reverse()
sum=0
for i,bit in enumerate(no):
if bit==1:
sum=sum+2**i
return sum
def twoscomplement(bin_no): #for negative nos
#twos complement helps represent a negative binary number
#eg. -3 can be represented as twos complement of 3
# 3=>011 , 2's complement of 3 => 101
binary_no=list(bin_no)
change=False
for i,digit in reversed(list(enumerate(binary_no))):
#print 'index'+str(i)
if change==True:
if digit==1:
binary_no[i]=0
else:
binary_no[i]=1
if digit==1:
change=True
return binary_no
def add(no1,no2) :
# add two binary nos, assuming the two nos. are of same length
#for booths it is important that the sum of two numbers have the same length as the input nos
no=[] #the new addition will be in this list
carry=0
for i,digit in reversed(list(enumerate(no1))):
sum=no1[i]+no2[i]+carry
if sum==2:
sum=0
carry=1
elif sum==3:
sum=1
carry=1
else:
carry=0
no.append(sum)
no.reverse()
return no
def asr(no): #arithmetic shift right
#shift the bits of the binary no to right by 1 digit
#the left most new bit being the same as previous left most bit
shiftedno=[]
shiftedno.append(no[0]) #add the first leftmost bit same as previous
#then copy the rest of the string - last element which will be garbaged
for i in range(0,len(no)-1):
shiftedno.append(no[i])
return shiftedno
def extendlarger(no):
no.reverse()
no.append(0)
no.append(0)
no.reverse()
return no
def extendsmaller(no,by):
no.reverse()
for i in range(by):
no.append(0)
no.reverse()
return no
#MAIN FUNCTION TO CALCULATE THE BOOTHS MULTIPLICATION OF TWO NUMBERS
def boothmultiplication(mdecimal,rdecimal):
mdecimal= int(mdecimal)
rdecimal = int(rdecimal)
#print(mdecimal)
#print(rdecimal)
m=decimaltobinary(abs(mdecimal))
r=decimaltobinary(abs(rdecimal))
#print(m)
#print(r)
original_m=list(m)
original_r=list(r)
if len(r)>len(m):
r=extendlarger(r)
m =extendsmaller(m,len(r)-len(m))
elif len(m)>len(r):
m=extendlarger(m)
r=extendsmaller(r,len(m)-len(r))
else:
m=extendlarger(m)
r=extendlarger(r)
if mdecimal<0:
m=twoscomplement(m)
if rdecimal<0:
r=twoscomplement(r)
#print " m "+str(m)
#print " r "+str(r)
#now we have got m and r
# -m
minusm=twoscomplement(m)
#There are three components in booths : A, S, P
# A = m 00..len(m) 0
# S = -m 00...len(-m) 0
# P = 00...len(r) r 0
#let e be empty list of length(m)+1 size
e=[]
for i in range(len(m)+1):
e.append(0)
A = m+e
S = minusm+e
e.pop()
P = e+r
P.append(0)
print("A "+str(A))
print("S "+str(S))
print ("P "+str(P))
x=len(m)
#print "last two bits "+str(A[len(A)-2:])
lasttwo=[]
originalP=list(P)
# NOW THE ORIGINAL BOOTHS ALGORITHM
steplist=[]
messagelist=[]
step=''
for i in range(x):
lasttwo=P[len(P)-2:]
if lasttwo[0]==lasttwo[1]: # if last two bits are 00 or 11
#only arithmetic shift right =asr
P = asr(P)
step='Step ' + str(i+1) + ' Only Arithmetic Shift Right'
messagelist.append(step)
elif lasttwo[0]==0:
#basically last two bits are 01 , now P=P+A then asr
P=add(P,A)
P=asr(P)
step='Step '+str(i+1)+' Add P and A followed by Arithmetic Shift Right'
messagelist.append(step)
else:
#last two bits are 10 , P=P+S , then asr
P=add(P,S)
P=asr(P)
step = 'Step ' + str(i+1) + ' Add P and S followed by Arithmetic Shift Right'
messagelist.append(step)
steplist.append(list(P))
#print "\n"+str(i+1)+" P "+str(P)
L=P
L.pop()
finalbinaryans=L
#print("\nfinalbinaryans "+str(finalbinaryans))
# ------code by @Hrishikesh Waikar@ -----#
if not ((mdecimal>0 and rdecimal>0) or (mdecimal<0 and rdecimal<0)) :
finalbinaryans = twoscomplement(finalbinaryans)
ans = binarytodecimal(finalbinaryans)
ans=ans*(-1)
else:
k =list(finalbinaryans)
ans = binarytodecimal(k)
print(ans)
for i in range(len(steplist)):
print(messagelist[i])
print(steplist[i])
print('\n')
contextdata={
'm':original_m,
'r':original_r,
'P':originalP,
'A':A,
'S':S,
'messagelist':messagelist,
'steplist':steplist,
'finalbinans':finalbinaryans,
'ans':ans
}
return contextdata
#boothmultiplication(3,4)
#------code by @Hrishikesh Waikar@ -----#
|
import streamlit as st
from api_call import api_call
import pandas as pd
import numpy as np
import plotly.express as px
def run():
st.header("Check the emotion in the Text.")
selected_model = st.selectbox(
"Algorithm you would like to use?", ("Logistic Regression", "Naive Bayes")
)
input_text = st.text_input(
"Enter the statment to predict the emotion type", "Enter your text here"
)
if st.button("Predict"):
response = api_call(selected_model, input_text)
emotion = np.array(response.get("emotion"))
data = np.array(response.get("data"))
df = pd.DataFrame()
df["Emotion"] = data
df["emotion_propb"] = emotion.T
st.markdown(
f'The Emotion Predectied in the text is: { response.get("prediction") } '
)
fig = px.pie(df["Emotion"], values=df["emotion_propb"], names="Emotion")
st.write(fig)
if __name__ == "__main__":
run()
|
print ("hello")
print ("saya sedang belajar python")
a = 8
b = 6
print ("variable a=",a)
print ("variable b=",b)
print ("hasil penjumblahan a+b=",a+b)
a=input ("masukan nilai a:")
b=input ("masukan nilai b:")
print ("variable a=",a)
print ("variable b=",b)
print ("hasil penggabungan {1}&{0}=%d".format(a,b) %(a+b))
#konversi nilai variable
a=int(a)
b=int(b)
print("hasil penjumblahan {1}+{0}=%d".format(a,b) %(a+b))
print("hasil pembagian {1}/{0}=%d".format(a,b) %(a/b))
|
import math
dp = "%.2f"
def quadratic():
a = float(input("Please enter coefficient a: "))
b = float(input("Please enter coefficient b: "))
c = float(input("Please enter coefficient c: "))
root = math.sqrt((b * b) - 4 * a * c)
x1 = (-b + root) / (2 * a)
x2 = (-b - root) / (2 * a)
print()
print("The solutions are:", dp % x1, dp % x2)
|
# team = 'New England Patriots'
# # letter = team[-2]
# # # print(letter)
# # index = 0
# # while index < len(team):
# # letter = team[index]
# # print(letter)
# # index = index + 1
# # prefixes = 'JKLMNOPQ'
# # suffix = 'ack'
# # for letter in prefixes:
# # if letter == 'O' or letter == 'Q':
# # print(letter + 'u' + suffix)
# # else:
# # print(letter + suffix)
# def find(word, letter):
# index = 0
# while index < len(word):
# if word[index] == letter:
# return index
# index = index + 1
# return -1
# print(find(team, 'E'))
# for i in range(len(team)):
# if team[i] == 'a':
# print(i)
# for i, letter in enumerate(team):
# print(i, letter)
team = 'New England Patriots'
def count(s, letter):
count = 0
for each in s:
if each == letter:
count = count + 1
return count
print(count(team, 'a'))
# team = 'New England'
# print(team.split())
|
# age = 10
# if age >= 18:
# print('Your age is', age)
# print('adult')
# else:
# print('no')
# BMI Categories:
# Underweight = <18.5
# Normal weight = 18.5–24.9
# Overweight = 25–29.9
# Obesity = BMI of 30 or greater
# weight = input('Please enter your weight: ')
# height = input('Please enter your height: ')
# def calc_BMI(weight, height):
# BMI = weight / height
# if BMI < 18.5:
# print('Your BMI is', BMI)
# print('You are underweight')
# elif 18.5 < BMI <= 24.9:
# print('Your BMI is', BMI)
# print('You are normal weight')
# elif 25 < BMI <= 29.9:
# print('Your BMI is', BMI)
# print('You are overweight')
# else:
# print('Your BMI is', BMI)
# print('You are obese')
# print(calc_BMI)
# Assume that two variables, varA and varB, are assigned values, either numbers or strings. Write a piece of Python code that prints out one of the following messages:
# "string involved" if either varA or varB are strings
# "bigger" if varA is larger than varB
# "equal" if varA is equal to varB
# "smaller" if varA is smaller than varB
# def compare(varA, varB):
# if isinstance(varA, str) or isinstance(varB, str):
# print('string involved')
# else:
# if varA > varB:
# print('bigger')
# elif varA == varB:
# print('equal')
# else:
# print('smaller')
# a = 4
# b = 4
# compare(a, b)
# codingbat warmup 1- diff21
# def diff21(n):
# result = n - 21
# abs = result * -1
# if result <= 0:
# return abs
# elif n > 21:
# return result * 2
#logic 1 cigar party
# def cigar_party(cigars, is_weekend):
# if is_weekend and cigars >= 40 or 40 <= cigars <= 60:
# return True
# else:
# return False
# def countdown(n):
# if n <= 0:
# print('Blastoff!')
# else:
# print(n)
# countdown(n-1)
# countdown(8)
|
class P:
def __init__(self, first, last):
self.fn = first
self.ln = last
def name(self):
return self.fn + ' ' + self.ln
class Employee(P):
def __init__(self, first, last, staffnum):
# super().__init__(first, last)
P.__init__(self, first, last)
self.staffnumber = staffnum
def get_employee(self):
return self.name() + ' ' + self.staffnumber
|
"""
to create a class attribute, which we call "counter" in our example
to increment this attribute by 1 every time a new instance will be create
to decrement the attribute by 1 every time an instance will be destroyed
"""
class Count:
"""
Create a class in which it will be used to count the number of instance it would be initialized.
"""
# The class attribute is the key too make this counter to count the num of instance successfully
# It is of course will count the repetition of initialization since class attribute lives in a global scope
# in which it is shared by all the instances.
counter = 0
def __init__(self):
type(self).counter += 1
def __del__(self):
type(self).counter -= 1
if __name__ == '__main__':
x = Count()
print('Number of instances - ' + str(Count.counter))
y = Count()
print('Number of instances - ' + str(Count.counter))
|
"""
Syntax: property(fget, fset, fdel, doc)
Parameters:
fget() – used to get the value of attribute
fset() – used to set the value of atrribute
fdel() – used to delete the attribute value
doc() – string that contains the documentation (docstring) for the attribute
Return: Returns a property attribute from the given getter, setter and deleter.
"""
class Alphabet:
"""
class without @property
"""
def __init__(self, val):
self.__value = val
def get_val(self):
print('Getting value')
return self.__value
def set_val(self, val):
print('Setting value to ' + val)
def del_val(self):
print('Deleting the value')
del self.__value
value = property(get_val, set_val, del_val, )
class Alphabet2:
"""
Class with @property
"""
def __init__(self, val):
self.__val = val
@propert
def value(self):
print('Getting value')
return self.__val
@value.setter
def value(self, val):
print('Setting value' + val)
self.__val = val
@value.deleter
def value(self):
print('Deleting value')
del self.__val
|
# demonstration of the difference of zip() method within p2 and p3
dishes = ["pizza", "sauerkraut", "paella", "hamburger"]
countries = ["Italy", "Germany", "Spain", "USA"]
country_specialities_zip = zip(dishes,countries)
print(list(country_specialities_zip))
#country_specialities_list = list(country_specialities_zip)
#country_specialities_dict = dict(country_specialities_list)
#print(country_specialities_dict)
#
print(list(country_specialities_zip))
|
"""
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behaviour of function or class. Decorators allow us to wrap another function in order to extend the behaviour of the wrapped function, without permanently modifying it.
"""
class MyDecorator:
def __init__(self, function):
self.function = function
def __call__(self):
# some code can be added before the function call
self.function()
# some code can be added again after the function call
# adding decorator to the class
@MyDecorator
def function():
print('GeeksforGeeks.')
function() # Same as function = MyDecorator()
# Class decorator with *args **kwargs
class MyDecorator:
def __init__(self, function):
self.function = function
def __call__(self, *args, **kwargs): # Arbitrary args
self.function(*args, **kwargs)
@MyDecorator
def function(name, msg='hello world'):
print('{} - {}.'.format(name, msg))
function('xuan')
# Class decorator with return statement
class SquareDecorator:
def __init__(self, function):
self.function = function
def __call__(self, *args, **kwargs):
result = self.function(*args, **kwargs)
return result
@SquareDecorator
def get_square(n):
print('Given number is: ', n)
return n*n
print('Square of this number is: ', get_square(10))
# Using class Decorators to print Time required to execute a program
from time import time
class Timer:
def __init__(self, func):
self.function = func
def __call__(self, *args, **kwargs):
start = time()
result = self.function(*args, **kwargs)
end = time()
print('Execution took {} seconds'.format(end-start))
return result
@Timer
def execution_test(delay):
from time import sleep
sleep(delay)
#execution_test(5)
# Checking error parameter using class decorator
"""
This type of class decorators is the most frequently used, the decorator checks parameters before executing the function
preventing the function to become overloaded and enables it to store only logical and necessary statements.
"""
class NumOnly:
def __init__(self, function):
self.function = function
def __call__(self, *params):
if any([isinstance(i, str) for i in params]):
raise TypeError('parameter cannot be a string')
else:
return self.function(*params)
@NumOnly
def add_nums(*nums):
return sum(nums)
print(add_nums(1,2,3))
print(add_nums('1',2,3))
|
# Example of exception in python
# In short, the exception block in python is consist of a try except pair corresponding to language like Java in which it uses try catch block
while True:
try:
n = input("Please enter an integer\n")
n = int(n)
break
except ValueError:
print("No valid integer!")
print("Great, you have just entered an integer")
# Multiple exception clauses
# A try statement may have more than one except clause for different exceptions. But at most one except clause will be executed.
import sys
try:
f = open('integers.txt')
s = f.readline()
i = int(s.strip())
except IOError as e:
errno, strerror = e.args
print('I/O error({0}): {1}'.format(errno, strerror))
print(e)
except ValueError:
print('No valid integer in line')
except:
print('Unexpected error', sys.exc_info()[0])
raise # Raise is called and all the rest of code will stop execution right off the bat
# An except clause may name more than one exception in a tuple of error names, as we see in the following example
try:
f = open('integers.txt')
s = f.readline()
i = int(s.strip())
except (IOError, ValueError):
print('IO error has occured')
except:
print('An unexpected error has occured.')
raise # Trigger the exception explicitly
# Exception occurs inside of a function call
def f():
x = int('two')
try:
f()
except ValueError as e:
print('Exception inside of a function is catched', e)
# Now define exception within the function body and use "raise" key word to propagate the exception to the caller which in this case the try except block outside of
# the function body, see the example below
def f():
try:
x = int('four')
except ValueError as e:
print('Exceptin catched before the try except block outside of the function body')
raise # Propagate the exception to the outside caller
try:
f()
except ValueError as e:
print('Exception outside of the function body')
# Custom-made exception
#raise SyntaxError('Oh it was my fault!') # Use of built in exception name
#
## Inherited from Exception class
#class MyExcept(Exception): # Use of custom exception name definition
# pass
#
#raise MyExcept('An exception has occured and the message is shown in the way of customized.')
#
#
# Clean up actions
# try... except and finally
# Finally block will be trigger if neither try nor except was catched
try:
x = float(input('Your num: '))
inverse = 1.0/x
except ValueError:
print('You should have given either int or float')
except ZeroDivisionError:
print('Infinity')
finally:
print('There may or may not have been an exception')
"""
The try ... except statement has an optional else clause. An else block has to be positioned after all the except clauses. An else clause will be executed if the try clause doesn't raise an exception.
"""
import sys
fn = sys.argv[1]
text = []
try:
fh = open(fn, 'r')
text = fh.readlines()
fh.close()
except IOError:
print('File cannot be opened.')
if text:
print(text[100])
# You need to run the above script as following
# python *.py *.txt
# There is another way to achieve the same result
import sys
fn = sys.argv[1]
text = []
try:
fh = open(fn, 'r')
except IOError:
print('File cannot be opened.')
else:
text = fh.readlines()
fh.close()
if text:
print(text[100])
|
# lambda
sum = lambda x, y: x+y
print(sum(1,1))
# map
# map(func, seq) - Apply each of the elements of seq on func
seq = [1,2,3,4,3,3,3,3,3,3,]
f = list(map(lambda x: (float(9)/5)*x + 32, seq)) # convert celsius to fahrenheit
print(f)
# map can also be applied on more than one list object
a = [1,1,1,]
b = [2,2,2,]
c = [3,3,3,]
print(list(map(lambda a,b,c: (a+b)/c, a, b, c)))
# map will stop at the shortest list that has been consumed in which the len of lists are different
# map functions
from math import sin, cos, tan, pi
def map_func(x, funcs):
"""
map an iterable of functions on the object x
"""
result = []
for each in funcs:
result.append(each(x))
return result
my_funcs = (sin, cos, tan)
print(map_func(pi, my_funcs))
# The above can be simplified with list comprehension
def map_func(x, funcs):
return [ func(x) for func in funcs]
print(map_func(pi, (sin, cos, tan)))
# filtering
fibonacci = [0,1,1,2,3,5,8,13,21,34,55]
# if x % 2 == 1 then the odd number will be output
print(list(filter(lambda x: x % 2, fibonacci)))
# reduce -- reduce has been droped from the core of python3
import functools
print(functools.reduce(lambda x, y: x+y, [11,22,33,44,221,])) # it actually has implemented a "sum"
|
"""
* Class methods are not bound to the instances.
* Class methods are bound to the a class.
"""
class Robot:
__counter = 0
def __init__(self):
type(self).__counter += 1
# Class methods are bound to the class itself
@classmethod
def robot_instances(cls):
return cls, Robot.__counter
if __name__ == '__main__':
print(Robot.robot_instances())
x = Robot()
print(x.robot_instances())
y = Robot()
print(y.robot_instances())
# Call static method from the class directly
print(Robot.robot_instances())
|
from math import sqrt
#for a in range(1,1000):
# for b in range(a+1,1000):
# c = (a**2 + b**2)**0.5
# if a + b + c == 1000:
# print(a, b, c, a*b*c)
for a in range(1,500):
for b in range(a+1, 500):
c = (a**2 + b**2)**0.5
if a + b + c == 1000:
print(a,b,c, a*b*c) |
# -*- coding: utf-8 -*-
import sqlite3
def read_words(database_name):
words = []
conn = sqlite3.connect(database_name)
sql = (
'SELECT word, usage from words '
'LEFT JOIN LOOKUPS ON words.id = LOOKUPS.word_key WHERE words.lang="en" GROUP BY word;'
)
for row in conn.execute(sql):
word = {
'text': row[0].strip().lower().encode('utf-8'),
'context': '',
}
if len(row) > 1 and row[1] and isinstance(row[1], unicode):
word['context'] = row[1].strip().lower().encode('utf-8')
words.append(word)
conn.close()
return words
|
def solution(A , K):
# write your code in Python 3.6
# 利用array相加做出rotation,A[-1]代表array的最後一個,依此類推。
# more detail please check it out at https://openhome.cc/Gossip/CodeData/PythonTutorial/NumericString.html .
if len(A) == 0:
return A
K = K % len(A)
return A[-K:] + A[:-K]
# testcase 1
A = [3, 8, 9, 7, 6]
K = 3
print(solution(A , K))
# testcase 2
A = [0, 0, 0]
K = 1
print(solution(A , K))
# testcase 3
A = [1, 2, 3, 4]
K = 4
print(solution(A , K))
|
import tensorflow as tf
import numpy as np
import utils
def lstm(nlstm=128, layer_norm=False):
"""
Builds LSTM (Long-Short Term Memory) network to be used in a policy.
Note that the resulting function returns not only the output of the LSTM
(i.e. hidden state of lstm for each step in the sequence), but also a dictionary
with auxiliary tensors to be set as policy attributes.
Specifically,
S is a placeholder to feed current state (LSTM state has to be managed outside policy)
M is a placeholder for the mask (used to mask out observations after the end of the episode, but can be used for other purposes too)
initial_state is a numpy array containing initial lstm state (usually zeros)
state is the output LSTM state (to be fed into S at the next call)
An example of usage of lstm-based policy can be found here: common/tests/test_doc_examples.py/test_lstm_example
Parameters:
----------
nlstm: int LSTM hidden state size
layer_norm: bool if True, layer-normalized version of LSTM is used
Returns:
-------
function that builds LSTM with a given input tensor / placeholder
"""
def network_fn(X, nenv=1):
nbatch = X.shape[0]
nsteps = nbatch // nenv
h = tf.layers.flatten(X)
# M = tf.placeholder(tf.float32, [nbatch]) #mask (done t-1)
S = tf.placeholder(tf.float32, [nenv, 2*nlstm]) #states
xs = utils.batch_to_seq(h, nenv, nsteps)
# ms = utils.batch_to_seq(M, nenv, nsteps)
if layer_norm:
h5, snew = lnlstmbase(xs, S, scope='lnlstm', nh=nlstm)
else:
h5, snew = lstmbase(xs, S, scope='lstm', nh=nlstm)
h = utils.seq_to_batch(h5)
initial_state = np.zeros(S.shape.as_list(), dtype=float)
return h, {'S':S, 'state':snew, 'initial_state':initial_state}
return network_fn
def lstmbase(xs, s, scope, nh, init_scale=1.0):
nbatch, nin = [v.value for v in xs[0].get_shape()]
with tf.variable_scope(scope):
wx = tf.get_variable("wx", [nin, nh*4], initializer=utils.ortho_init(init_scale))
wh = tf.get_variable("wh", [nh, nh*4], initializer=utils.ortho_init(init_scale))
b = tf.get_variable("b", [nh*4], initializer=tf.constant_initializer(0.0))
c, h = tf.split(axis=1, num_or_size_splits=2, value=s)
for idx, x in enumerate(xs):
z = tf.matmul(x, wx) + tf.matmul(h, wh) + b
i, f, o, u = tf.split(axis=1, num_or_size_splits=4, value=z)
i = tf.nn.sigmoid(i)
f = tf.nn.sigmoid(f)
o = tf.nn.sigmoid(o)
u = tf.tanh(u)
c = f*c + i*u
h = o*tf.tanh(c)
xs[idx] = h
s = tf.concat(axis=1, values=[c, h])
return xs, s
def _ln(x, g, b, e=1e-5, axes=[1]):
u, s = tf.nn.moments(x, axes=axes, keep_dims=True)
x = (x-u)/tf.sqrt(s+e)
x = x*g+b
return x
def lnlstmbase(xs, s, scope, nh, init_scale=1.0):
nbatch, nin = [v.value for v in xs[0].get_shape()]
with tf.variable_scope(scope):
wx = tf.get_variable("wx", [nin, nh*4], initializer=utils.ortho_init(init_scale))
gx = tf.get_variable("gx", [nh*4], initializer=tf.constant_initializer(1.0))
bx = tf.get_variable("bx", [nh*4], initializer=tf.constant_initializer(0.0))
wh = tf.get_variable("wh", [nh, nh*4], initializer=utils.ortho_init(init_scale))
gh = tf.get_variable("gh", [nh*4], initializer=tf.constant_initializer(1.0))
bh = tf.get_variable("bh", [nh*4], initializer=tf.constant_initializer(0.0))
b = tf.get_variable("b", [nh*4], initializer=tf.constant_initializer(0.0))
gc = tf.get_variable("gc", [nh], initializer=tf.constant_initializer(1.0))
bc = tf.get_variable("bc", [nh], initializer=tf.constant_initializer(0.0))
c, h = tf.split(axis=1, num_or_size_splits=2, value=s)
for idx, x in enumerate(xs):
z = _ln(tf.matmul(x, wx), gx, bx) + _ln(tf.matmul(h, wh), gh, bh) + b
i, f, o, u = tf.split(axis=1, num_or_size_splits=4, value=z)
i = tf.nn.sigmoid(i)
f = tf.nn.sigmoid(f)
o = tf.nn.sigmoid(o)
u = tf.tanh(u)
c = f*c + i*u
h = o*tf.tanh(_ln(c, gc, bc))
xs[idx] = h
s = tf.concat(axis=1, values=[c, h])
return xs, s |
def main():
while True:
print("Welcome to a sloppy script that calculates interest for you based on parameters you give!")
c = getC()
t = getT()
r = getR()
comp = getComp()
mode = getMode()
if mode == False:
output = calculate(c , t , r , comp)
else:
output = dCalculate(c , t , r , comp)
print("Your resulting value is:\n" + str(output) + "\n")
def getC():
c = input("Please input your starting amount:\n")
if not isFloat(c):
print("Don't try to break my fucking program")
getC()
return float(c)
def getT():
t = input("How long (in years) would you like interest to accrue for?\n")
if not isFloat(t):
print("Don't try to break my fucking program")
getT()
return float(t)
def getR():
r = input("Please input the nominal interest rate (Decimal):\n")
if not isFloat(r):
print("Don't try to break my fucking program")
getR()
return float(r)
def getComp():
comp = input("How frequently would you like interest to compound? (Enter q for quarterly, a for annually, m for monthly)\n")
if comp not in "aqm":
print("Don't try to break my fucking program")
getComp()
return comp
def getMode():
mode = input("Would you like to switch into DCA mode? (y/n)\n")
if mode == "y":
return True
if mode == "n":
return False
else:
print("Don't try to break my fucking program")
getMode()
def calculate(c , t , r ,comp):
if comp == "q":
return c*(1+(r/4))**(4*t)
if comp == "a":
return c*(1+r)**t
if comp == "m":
return c*(1+(r/12))**(12*t)
def dCalculate(c , t , r , comp):
tot = 0
if comp == "q":
n = 4
elif comp == "a":
n = 1
elif comp == "m":
n = 12
numTimes = n*t
time = 1
while time <= numTimes:
tot += c/numTimes
tot = tot*(1+r/n)
time += 1
return tot
def isFloat(num):
try:
float(num)
return True
except ValueError:
return False
#Interest = C(1+(r/n))^(nt)
#n = number of times compounded per time t
#t = number of years in this case
#r = interest rate
#C = starting value
if __name__ == "__main__":
main() |
"""
==================
Rasterization Demo
==================
Rasterization is a method where an image described in a vector graphics
format is being converted into a raster image (pixels).
Individual artists can be rasterized for saving to a vector backend
such as PDF, SVG, or PS as embedded images. This can be useful to
reduce the file size of large artists, while maintaining the
advantages of vector graphics for other artists such as the axes
and annotations. For instance a complicated `~.Axes.pcolormesh` or
`~.Axes.contourf` can be made significantly simpler by rasterizing.
Note that the size and resolution of the rasterized artist is
controlled by its physical size and the value of the ``dpi`` kwarg
passed to `~.Figure.savefig`.
"""
import numpy as np
import matplotlib.pyplot as plt
d = np.arange(100).reshape(10, 10) # the values to be color-mapped
x, y = np.meshgrid(np.arange(11), np.arange(11))
theta = 0.25*np.pi
xx = x*np.cos(theta) - y*np.sin(theta) # rotate x by -theta
yy = x*np.sin(theta) + y*np.cos(theta) # rotate y by -theta
# Plot the rasterized and non-rasterized plot
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, constrained_layout=True)
# Create a pseudocolor non-rastertized plot with a non-regular rectangular grid
ax1.set_aspect(1)
ax1.pcolormesh(xx, yy, d)
ax1.set_title("No Rasterization")
# Create a pseudocolor rastertized plot with a non-regular rectangular grid
ax2.set_aspect(1)
ax2.set_title("Rasterization")
m = ax2.pcolormesh(xx, yy, d, rasterized=True)
# Create a pseudocolor non-rastertized plot with a non-regular rectangular
# grid and an overlapped "Text"
ax3.set_aspect(1)
ax3.pcolormesh(xx, yy, d)
ax3.text(0.5, 0.5, "Text", alpha=0.2,
va="center", ha="center", size=50, transform=ax3.transAxes)
ax3.set_title("No Rasterization")
# Create a pseudocolor rastertized plot with a non-regular rectangular
# grid and an overlapped "Text"
ax4.set_aspect(1)
m = ax4.pcolormesh(xx, yy, d, zorder=-20)
ax4.text(0.5, 0.5, "Text", alpha=0.2, zorder=-15,
va="center", ha="center", size=50, transform=ax4.transAxes)
# Set zorder value below which artists will be rasterized
ax4.set_rasterization_zorder(-10)
ax4.set_title("Rasterization z$<-10$")
# ax2.title.set_rasterized(True) # should display a warning
# Save files in pdf and eps format
plt.savefig("test_rasterization.pdf", dpi=150)
plt.savefig("test_rasterization.eps", dpi=150)
if not plt.rcParams["text.usetex"]:
plt.savefig("test_rasterization.svg", dpi=150)
# svg backend currently ignores the dpi
|
nameList = []
print "Enter 5 names (press the Enter key after each name):"
for i in range(5):
name = raw_input()
nameList.append(name)
print "The names are:", nameList
print "Replace one name. Which one? (1-5):",
replace = int(raw_input())
new = raw_input("New name: ")
nameList[replace - 1] = new
print "The names are:", nameList
|
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> friends = []
>>> friends.append('David')
>>> friends.append('Mary')
>>>
>>> letters = ['a', 'b', 'c', 'd', 'e']
>>> print letters[0]
a
>>> print letters[3]
d
>>> print letters[1:4]
['b', 'c', 'd']
>>> print letters[1:2]
['b']
>>> print type(letters[1])
<type 'str'>
>>> print type(letters[1:2])
<type 'list'>
>>> print letter[:2]
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
print letter[:2]
NameError: name 'letter' is not defined
>>> print letters[:2]
['a', 'b']
>>> print letters[2:]
['c', 'd', 'e']
>>> print letters[:]
['a', 'b', 'c', 'd', 'e']
>>>
>>> print letters
['a', 'b', 'c', 'd', 'e']
>>> letters[2] = 'z'
>>> print letters
['a', 'b', 'z', 'd', 'e']
>>> letters[2] = 'c'
>>> print letters
['a', 'b', 'c', 'd', 'e']
>>>
>>> letters.append('n')
>>> print letters
['a', 'b', 'c', 'd', 'e', 'n']
>>> letters.append('g')
>>> print letters
['a', 'b', 'c', 'd', 'e', 'n', 'g']
>>>
>>> letters.extend(['p', 'q', 'r'])
>>> print letters
['a', 'b', 'c', 'd', 'e', 'n', 'g', 'p', 'q', 'r']
>>> letters.insert(2. 'z')
SyntaxError: invalid syntax
>>> letters.insert(2, 'z')
>>> print letters
['a', 'b', 'z', 'c', 'd', 'e', 'n', 'g', 'p', 'q', 'r']
>>>
>>> letters = ['a','b','c','d','e']
>>> letters.extend(['f', 'g', 'h'])
>>> print letters
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> letters = ['a', 'b', 'c', 'd', 'e']
>>> letters.append(['f', 'g', 'h'])
>>> print letters
['a', 'b', 'c', 'd', 'e', ['f', 'g', 'h']]
>>>
>>> letters = ['a', 'b', 'c', 'd', 'e']
>>> letters.remove('c')
>>> print letters
['a', 'b', 'd', 'e']
>>> letters.remove('f')
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
letters.remove('f')
ValueError: list.remove(x): x not in list
>>>
>>> letters = ['a', 'b', 'c', 'd', 'e']
>>> lastLetter = letters.pop()
>>> print letters
['a', 'b', 'c', 'd']
>>> print lastLetter
e
>>>
>>> letters = ['a', 'b', 'c', 'd', 'e']
>>> del letters[3]
>>> print letters
['a', 'b', 'c', 'e']
>>>
>>> letters = ['a', 'b', 'c', 'd', 'e']
>>> second = letters.pop(1)
>>> print second
b
>>> print letters
['a', 'c', 'd', 'e']
>>>
>>> if 'a' in letters:
print "found 'a' in letters"
else:
print "didn't find 'a' in letters"
found 'a' in letters
>>> 'a' in letters
True
>>> 's' in letters
False
>>>
>>> letters = ['a', 'b', 'c', 'd', 'e']
>>> print letters.index('d')
3
>>>
>>> letters = ['a', 'b', 'c', 'd', 'e']
>>> for letter in letters:
print letter
a
b
c
d
e
>>>
>>> letters = ['d', 'a', 'e', 'c', 'b']
>>> print letters
['d', 'a', 'e', 'c', 'b']
>>> letters.sort()
>>> print letters
['a', 'b', 'c', 'd', 'e']
>>>
>>> letters = ['d', 'a', 'e', 'c', 'b']
>>> letters.sort()
>>> print letters
['a', 'b', 'c', 'd', 'e']
>>> letters.reverse()
>>> print letters
['e', 'd', 'c', 'b', 'a']
>>>
>>> letters = ['d', 'a', 'e', 'c', 'b']
>>> letters.sort (reverse = True)
>>> print letters
['e', 'd', 'c', 'b', 'a']
>>>
>>> originial_list = ['Tom', 'James', 'Sarah', 'Fred']
>>> new_list = original_list[:]
Traceback (most recent call last):
File "<pyshell#92>", line 1, in <module>
new_list = original_list[:]
NameError: name 'original_list' is not defined
>>> new_list = original_list[:]
Traceback (most recent call last):
File "<pyshell#93>", line 1, in <module>
new_list = original_list[:]
NameError: name 'original_list' is not defined
>>> original_list[:] = new_list
Traceback (most recent call last):
File "<pyshell#94>", line 1, in <module>
original_list[:] = new_list
NameError: name 'new_list' is not defined
>>> original_list = ['Tom', 'James', 'Sarah', 'Fred']
>>> new_list = original_list[:]
>>> new_list.sort()
>>> print original_list
['Tom', 'James', 'Sarah', 'Fred']
>>> print new_list
['Fred', 'James', 'Sarah', 'Tom']
>>>
>>> original = [5, 2, 3, 1, 4]
>>> newer = sorted(original)
>>> print original
[5, 2, 3, 1, 4]
>>> print newer
[1, 2, 3, 4, 5]
>>>
>>> my_tuple = ("red", "green", "blue")
>>>
>>> joeMarks = [55, 63, 77, 81]
>>> tomMarks = [65, 61, 67, 72]
>>> bethMarks = [97, 95, 92, 88]
>>> classMarks = [joeMarks, tomMarks, bethMarks]
>>> print classMarks
[[55, 63, 77, 81], [65, 61, 67, 72], [97, 95, 92, 88]]
>>>
>>> classMarks = [ [55, 63, 77, 81], [65, 61, 67, 72], [97, 95, 92, 88] ]
>>> print classMarks
[[55, 63, 77, 81], [65, 61, 67, 72], [97, 95, 92, 88]]
>>>
>>> for studentMarks in classMarks:
print sudentMarks
Traceback (most recent call last):
File "<pyshell#119>", line 2, in <module>
print sudentMarks
NameError: name 'sudentMarks' is not defined
>>> print classMarks[0]
[55, 63, 77, 81]
>>> print classMarks[0][2]
77
>>>
>>> phoneNumbers = {}
>>> phoneNumbers["John"] = "555-1234"
>>> print phoneNumbers
{'John': '555-1234'}
>>> phoneNumbers["Mary"] = "555-6789"
>>> phoneNumbers["Bob"] = "444-4321"
>>> phoneNumbers["Jenny"] = "867-5309"
>>> print phoneNumbers
{'Bob': '444-4321', 'John': '555-1234', 'Mary': '555-6789', 'Jenny': '867-5309'}
>>> print phoneNumbers["Mary"]
555-6789
>>>
>>> phoneNumbers.keys()
['Bob', 'John', 'Mary', 'Jenny']
>>> phoneNumbers.values()
['444-4321', '555-1234', '555-6789', '867-5309']
>>> for key in sorted(phoneNumbers.keys()):
print key, phoneNumbers[key]
Bob 444-4321
Jenny 867-5309
John 555-1234
Mary 555-6789
>>> for value in sorted(phoneNumbers.values()):
for key in phoneNumbers.keys():
if phoneNumbers[key] == value:
print key, phoneNumbers[key]
Bob 444-4321
John 555-1234
Mary 555-6789
Jenny 867-5309
>>>
>>> del phoneNumbers["John"]
>>> print phoneNumbers
{'Bob': '444-4321', 'Mary': '555-6789', 'Jenny': '867-5309'}
>>> phoneNumbers.clear()
>>> print phoneNumbers
{}
>>> phoneNumbers = {'Bob': '444-4321', 'John': '555-1234', 'Mary': '555-6789', 'Jenny': '867-5309'}
>>> "Bob" in phoneNumbers
True
>>> "Barb" in phoneNumbers
False
>>>
|
length = float(raw_input ('length of the room in feet: '))
width = float(raw_input ('width of the room in feet: '))
cost_per_yard = float(raw_input ('cost per square yard: '))
area_feet = length * width
area_yards = area_feet / 9.0
total_cost = area_yards * cost_per_yard
print 'The area is', area_feet, 'square feet.'
print 'That is', area_yards, 'square yards.'
print 'Which will cost', total_cost
|
user_dictionary = {}
while 1:
command = raw_input("'a' to add word, 'l' to lookup a word, 'q' to quit ")
if command == "a":
word = raw_input("Type the word: ")
definition = raw_input("Type the definition: ")
user_dictionary[word] = definition
print "Word added!"
elif command == "l":
word = raw_input("Type the word: ")
if word in user_dictionary.keys():
print user_dictionary[word]
else:
print "That word isn't in the dictionary yet."
elif command == 'q':
break
|
__author__ = 'pallavipriya'
def mergeSort( arr, start, end ):
if end-start<=0:
return None
mid = (start+end)/2
mergeSort(arr, start, mid)
mergeSort(arr, mid+1, end)
merge(arr, start, mid, end)
def merge( arr, start, mid, end ):
tarr = []
i, j = start, mid+1
while i<=mid and j<=end:
if arr[i]<=arr[j]:
tarr.append( arr[i] )
i+=1
else:
tarr.append( arr[j] )
j+=1
while i<=mid:
tarr.append( arr[i] )
i+=1
while j<=end:
tarr.append( arr[j] )
j+=1
arr[ start:end+1 ] = tarr
L = [1,4,2,6,3,10,-1,8,5,9,7,-2]
print( 'Input: ', L )
mergeSort(L,0,len(L)-1)
print( 'Output: ', L ) |
__author__ = 'pallavipriya'
class linkedList():
def __init__(self,value=None,next=None):
self.value = value
self.next = next
def getValue(self):
return self.value
def getNext(self):
return self.next
def setNext(self,next):
self.next = next
def setValue(self,value):
self.value = value
class operation():
def __init__(self):
self.root = None
def insert(self,value,after=None):
head = self.root
if not head:
node = linkedList(value)
self.root = node
else:
node = linkedList(value)
if after:
while head:
if head.getValue() == after:
node.setNext(head.getNext())
head.setNext(node)
head = head.getNext()
else:
head.setNext(node)
def traverse(self):
head = self.root
while head:
print(head.getValue())
head = head.getNext()
def deleteItem(self,value):
head = self.root
while head.getNext():
if head.getNext().getValue() == value:
head.setNext(head.getNext().getNext())
head = head.getNext()
o = operation()
o.insert(5)
o.insert(6)
o.insert(3,5)
o.insert(7,5)
o.traverse()
o.deleteItem(7)
print('deleted')
o.traverse()
|
__author__ = 'pallavipriya'
def reverse(arr):
length = len(arr)
for itr in range(int(length/2)):
(arr[itr],arr[length-1-itr]) = (arr[length-1-itr],arr[itr])
arr = [1,4,2,8,5]
reverse(arr)
print (arr) |
__author__ = 'pallavipriya'
"""How to check if two Strings are anagrams of each other? """
def anagrams(istring,bstring):
astr = sorted((istring.lower()))
bstr = sorted(bstring.lower())
if len(astr) != len(bstr):
return ("string are not anagram of each other")
else:
for i,j in zip(astr,bstr):
if i!=j:
return "string are not anagram of each other"
else:
return "string are anagram of each other"
print(anagrams("character","cHraaCter")) |
__author__ = 'pallavipriya'
def binarySearchRecursion(value,L):
if len(L) <1:
print ("Not found")
else:
mid = len(L) / 2
if value < L[mid]:
binarySearchRecursion(value,L[:mid])
elif value > L[mid]:
binarySearchRecursion(value,L[mid+1:])
elif value == L[mid]:
print "value found at index {0}".format(mid)
binarySearchRecursion(10,L=[1,2,3,5,9])
|
#!/bin/python
import sys
def staircase(n):
spaces = n-1
while( spaces >= 0 ):
print ' ' * spaces + '#' * (n-spaces)
spaces -= 1
if __name__ == "__main__":
n = int(raw_input().strip())
staircase(n) |
#!/usr/bin/python
"""
This is the code to accompany the Lesson 1 (Naive Bayes) mini-project.
Use a Naive Bayes Classifier to identify emails by their authors
authors and labels:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import preprocess
import numpy as np
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
### features_train and features_test are the features for the training
### and testing datasets, respectively
### labels_train and labels_test are the corresponding item labels
features_train, features_test, labels_train, labels_test = preprocess()
clf = GaussianNB()
t0 = time()
clf.fit(features_train,labels_train)
print "training time:", round(time()-t0, 3), "s"
t0 = time()
pred = clf.predict(features_test)
print "prediction time:", round(time()-t0, 3), "s"
t0 = time()
acc = accuracy_score(labels_test,pred)
print "accuracy calculating time:", round(time()-t0, 3), "s"
print(acc)
#########################################################
### OUTPUT ###
### no. of Chris training emails: 4406
### no. of Sara training emails: 4383
### training time: 0.681 s
### prediction time: 0.91 s
### accuracy calculating time: 0.005 s
### 0.972693139151
#########################################################
|
from abc import ABC, abstractmethod
class Formula(ABC):
"""
Return the result of computing the formula.
:param Dict[str, float] Network state: key: species name, value: concentration
:returns float of result
"""
@abstractmethod
def compute(self, state):
pass
"""
Change value of given variables in the formula
:param Dict[str, Tuple[float, str]] mutation: dictionary of variables to mutate
"""
@abstractmethod
def mutate(self, mutation):
pass
@abstractmethod
def get_params(self):
pass
@staticmethod
def get_formula_string():
pass
|
'''
This file implements the collaborative filtering mechanism.
The feature upweights the relevant movies of the previous user that is most similar to the current user
and downweights the irrelevant movies of the previous user that is most similar to the current user
'''
import numpy as np
import math
'''
Find the euclidean distance between the current query vector and a previous query vector
'''
def euclidean_distance(current_query, previous_query):
distance = 0.0
for index in range(0, len(current_query)):
distance += (current_query[index] - previous_query[index]) ** 2
distance = math.sqrt(distance)
return distance
'''
Find the previous user that is the most similar to the current user
previous_queries is a list of previous queries where each item follows the following tuple format:
(query_vector_weights (list), list of relevant movie_ids, list of irrelevant movie_ids)
Returns a list of previously relevant movies and a list of previously irrelevant movies
'''
def find_nearest_neighbor(current_query, previous_queries):
relevant_movie_ids = []
irrelevant_movie_ids = []
min_distance = np.inf
for previous_query in previous_queries:
query = previous_query[0]
distance = euclidean_distance(current_query, query)
if distance < min_distance:
min_distance = distance
relevant_movie_ids = previous_query[1]
irrelevant_movie_ids = previous_query[2]
return relevant_movie_ids, irrelevant_movie_ids
|
#
# Given a list of numbers, L, find a number, x, that
# minimizes the sum of the absolute value of the difference
# between each element in L and x: SUM_{i=0}^{n-1} |L[i] - x|
#
# Your code should run in Theta(n) time
#
import random as rand
from math import ceil
# Write partition to return a new array with
# all values less then `v` to the left
# and all values greater then `v` to the right
def partition(L, v):
P = []
higher_list = []
num_v = 0
for item in L:
if v > item:
P.append(item) # adds item to lesser side of new list (unordered)
elif v < item:
higher_list.append(item) # add to higher side list
elif v == item:
num_v += 1
# what if the item is equal to v? I have just added them all to middle of two partitions...
for _ in range(num_v):
P.append(v)
P += higher_list
return P
# given this function - I have commented on it
def top_k(L, k):
# a recursive algorithm to find the top/bottom k values (unsorted) in a list using randomly chosen pivots
v = L[rand.randrange(len(L))]
# TODO: does not handle doubled values, must look to change here and partition
(left, middle, right) = partition(L, v)
# if lower list = k, then we have found all k values, with v being 1 above that
if len(left) == k:
return left
# if lower list + 1 = k then, the lower list + v constitutes all k values
if len(left)+1 == k:
return left+[v]
# if lower list is larger than k, then we have too many values, and recursively call this function
# still using value k to partition the lower list to make it smaller, till it reaches length k
if len(left) > k:
return top_k(left, k)
# if lower list is smaller than k, then we have too few values, and recursively call the function
# using a k value lowered by the length of the left list to start a new partition on the right list
# till the length of the new lower list added to length of original lower list = k
return left+[v]+top_k(right, k-len(left)-1)
def minimize_absolute(L):
# this is same as finding the median in the sorted list, which we can get by partitioning to
# find lowest k values, where k = list size/2, essentially splitting list in half,
# then we search the list for the highest value which will be the median
# this takes n operations for the top_k part and 1/2n operations to find max in the return list
# if list is even, will take the lower of two middle values, if odd, ceil gives middle value
length_list = len(L)
half_vals = ceil(length_list / float(2)) # used float as udacity seems to not cast this to a float automatically
lower_half = top_k(L, half_vals)
median = lower_half[0]
# get highest value in list, which is the median
for val in lower_half:
if val > median:
median = val
return median
|
#
# Given a list of numbers, L, find a number, x, that
# minimizes the sum of the square of the difference
# between each element in L and x: SUM_{i=0}^{n-1} (L[i] - x)^2
#
# Your code should run in Theta(n) time
#
def minimize_square(L):
# f(x) = sum(to n) (L[i] - x)**2
# g(x) = x**2, h(x) = L[i] - x
# g'(x) = 2x, h'(x) = -1
# f'(x) = sum (g'(h(x)) . h'(x))
# = sum 2(L[i] - x).(-1)
# = sum -2(L[i] - x)
# minimum f(x) is when f'(x) = 0, or minimise f(x) as f'(x) approaches 0
# therefore: 0 = -2 sum(L[i] - x)
# 0 = sum(L[i) - nx (sum is same as adding all elements and subtracting x, n times)
# nx = sum L[i]
# x = (sum L[i])/n
# This is the average value of the list, so to minimise f(x), find x that is closest to the average
# can do this in two loops, 2n operations, Theta(n) time
average = 0
for item in L:
average += item
average /= len(L)
print("average", average)
smallest_diff = abs(average - L[0])
x = 0
for item in L:
diff = abs(average - item)
if diff < smallest_diff:
x = item
smallest_diff = diff
return x
|
# Implement Dijkstra's algorithm using a heap instead of linear scan to find smallest distance from source node
# given these functions
def parent(i):
return (i - 1) / 2
def left_child(i):
return 2 * i + 1
def right_child(i):
return 2 * i + 2
def is_leaf(L, i):
return (left_child(i) >= len(L)) and (right_child(i) >= len(L))
def one_child(L, i):
return (left_child(i) < len(L)) and (right_child(i) >= len(L))
# given this function
def make_link_weighted(G, node1, node2, w):
if node1 not in G:
G[node1] = {}
if node2 not in G[node1]:
(G[node1])[node2] = 0
(G[node1])[node2] += w
if node2 not in G:
G[node2] = {}
if node1 not in G[node2]:
(G[node2])[node1] = 0
(G[node2])[node1] += w
return G
def dijk_up_heapify(L, values, indexes, i):
# takes a heap as a list of node keys, a dict of the corresponding values for the keys, a dict containing the
# indexes of those nodes in the heap, and a reference node index and makes appropriate swaps for node i and parents
# recursively till list is a heap, returning the list and dict of indexes which may have been altered.
# The indexes must be updated as the nodes are moved in the heap, since we must know
# their position to up heapify correctly if a new shorter path is found and its value is updated
if i == 0:
return L, indexes
node = L[i]
parent_index = int(parent(i))
parent_node = L[parent_index]
if values[node] < values[parent_node]:
# swap keys in heap
L[parent_index] = node
L[i] = parent_node
# swap heap index in dict
indexes[node] = parent_index
indexes[parent_node] = i
return dijk_up_heapify(L, values, indexes, parent_index)
else:
return L, indexes
def down_heapify(L, values, indexes, i):
# Is used to create a heap given a List which is a heap except for a node i and its direct children.
# Recursively check if node i is larger than its children and swap with the smaller of either till
# the node is in its correct position and the list is now a heap. Returns the updated heap and indexes.
# Takes a list of node keys, a dict of corresponding values, a dict of node indexes in the heap, and index of
# the node to down heapify from. Must update the node indexes as they are changed.
# if i is a leaf, it is a heap
if is_leaf(L, i):
return L, indexes
# if i has one child check heap property, and swap values if necessary
if one_child(L, i):
if values[L[i]] > values[L[left_child(i)]]:
# swap values
(L[i], L[left_child(i)]) = (L[left_child(i)], L[i])
# swap indexes
(indexes[L[i]], indexes[L[left_child(i)]]) = (indexes[L[left_child(i)]], indexes[L[i]])
return L, indexes
# if i has two direct children check if the smaller is higher than i, if it is then return, if not
# then we have to swap the smaller of two values
if min(values[L[left_child(i)]], values[L[right_child(i)]]) >= values[L[i]]:
return L, indexes
# check for smaller child and swap with i
if values[L[left_child(i)]] < values[L[right_child(i)]]:
# swap values and indexes
(L[i], L[left_child(i)]) = (L[left_child(i)], L[i])
(indexes[L[i]], indexes[L[left_child(i)]]) = (indexes[L[left_child(i)]], indexes[L[i]])
down_heapify(L, values, indexes, left_child(i))
return L, indexes
# right child is smaller
(L[i], L[right_child(i)]) = (L[right_child(i)], L[i])
(indexes[L[i]], indexes[L[right_child(i)]]) = (indexes[L[right_child(i)]], indexes[L[i]])
down_heapify(L, values, indexes, right_child(i))
return L, indexes
def shortest_dist_node(dist):
best_node = 'undefined'
best_value = 1000000
for v in dist:
if dist[v] < best_value:
(best_node, best_value) = (v, dist[v])
return best_node
def dijkstra(G, v):
# Implementation of Dijkstra's algorithm to find shortest path to each node in graph, G, from node, v.
# Initialise a min heap with node v, using a dict to store its value and a dict for its index in the heap for quick
# access of either value, necessary during this function. Top value (min) of the heap is taken as the current node
# then replaced by the bottom value, and heap down heapified to reform the heap with the next shortest value now at
# the top of the heap. The neighbours of the current node are checked, and if they arent finished already, we can
# add or update their distance so far then add to the heap if necessary then up heapify from that node to maintain
# the heap. After all neighbours are checked, the heap now contains to shortest path so far as the top value and the
# loop can continue finding the next shortest path till all nodes shortest paths are found
dist_so_far_heap = [v] # use heap with initial node key as root or top of heap as it has min distance
unfinished_nodes = {v: 0}
heap_indexes = {v: 0}
final_dist = {}
# continue till all nodes final shortest path value is determined
while len(final_dist) < len(G):
# find shortest dist neighbour (will be top of heap), and use that as the next current node
curr_node = dist_so_far_heap[0]
# set the final distance for this current node and delete from dist_so_far dict
final_dist[curr_node] = unfinished_nodes[curr_node]
# replace top of heap with the value at bottom of heap (removing the bottom value)
# then down heapify to ensure a new valid heap is formed so we can find next shortest path
dist_so_far_heap[0] = dist_so_far_heap[len(dist_so_far_heap)-1]
heap_indexes[dist_so_far_heap[0]] = 0
del dist_so_far_heap[len(dist_so_far_heap)-1]
del unfinished_nodes[curr_node]
del heap_indexes[curr_node]
dist_so_far_heap, heap_indexes = down_heapify(dist_so_far_heap, unfinished_nodes, heap_indexes, 0)
# check neighbours of current node to see if the distance to them from curr node is shortest path
for x in G[curr_node]:
if x not in final_dist: # neighbour is a child not a parent ie hasnt got a final distance yet
if x not in unfinished_nodes: # havent given distance so far yet, calculate and set it
unfinished_nodes[x] = final_dist[curr_node] + G[curr_node][x]
# add to end of heap for sorting using up heapify
dist_so_far_heap.append(x)
heap_indexes[x] = len(dist_so_far_heap) - 1
dist_so_far_heap, heap_indexes = dijk_up_heapify(dist_so_far_heap, unfinished_nodes, heap_indexes,
len(dist_so_far_heap) - 1)
# has a distance already, check if this path is shorter, if so, update its value
elif final_dist[curr_node] + G[curr_node][x] < unfinished_nodes[x]:
unfinished_nodes[x] = final_dist[curr_node] + G[curr_node][x]
# must try up heapify the changed value as heap may not be valid now
dist_so_far_heap, heap_indexes = dijk_up_heapify(dist_so_far_heap, unfinished_nodes, heap_indexes,
heap_indexes[x])
return final_dist
def test_dijk():
(a,b,c,d,e,f,g) = ('A', 'B', 'C', 'D', 'E', 'F','G')
# triples = ((a,c,4),(c,b,1),(a,b,6),(d,b,5),(c,d,7),(d,f,10),(d,e,7),(e,f,2))
triples = ((a,c,3),(c,b,10),(a,b,15),(d,b,9),(a,d,4),(d,f,7),(d,e,3),
(e,g,1),(e,f,5),(f,g,2),(b,f,1))
G = {}
for (i,j,k) in triples:
make_link_weighted(G, i, j, k)
dist = dijkstra(G, a)
print(dist)
|
import smtplib
import tkinter as tk
from tkinter import BOTH, END, LEFT
root = tk.Tk()
canvas = tk.Canvas(root, height=700, width=700, bg="#263D42")
canvas.pack()
frame = tk.Frame(root, bg="White")
frame.place(relwidth = 0.8, relheight =0.8, relx = 0.1, rely = 0.1)
whom = ""
body = ""
subject = ""
def emailSend():
gmailaddress = "Enter your email here"
gmailpassword = "Enter your password here"
mailServer = smtplib.SMTP('smtp.gmail.com' , 587)
mailServer.starttls()
mailServer.login(gmailaddress , gmailpassword)
mailServer.sendmail(gmailaddress, whom.get(), body.get("1.0",END))
print(" \n Sent!")
mailServer.quit()
def emailCreate():
global whom
global subject
global body
rootM = tk.Tk()
frameM = tk.Frame(rootM, width = 500, height = 400, bg="#263D42")
frameM.pack(fill = None, expand = True)
frameM.place(x=500,y=500)
whom = tk.Entry(rootM)
whom.pack()
whom.insert(tk.END, "Recipients")
subject = tk.Entry(rootM)
subject.pack()
subject.insert(tk.END, "Subject")
body = tk.Text(rootM, height = 20, width = 30)
body.pack()
body.insert(tk.END, "Body \n \n \n \n \n \n \n")
send = tk.Button(rootM, text="Send", padx = 10, pady = 5, fg="White", bg="#263D42", command = emailSend)
send.pack()
rootM.mainloop()
newEmail = tk.Button(root, text="New Email", padx = 10, pady=5, fg="White", bg="#263D42", command = emailCreate)
newEmail.pack()
root.mainloop()
|
#!/usr/bin/env python3.5
#-*- coding: utf-8 -*-
import cryptocompare
def getCoinsList() :
liste = []
listOfCoins = cryptocompare.get_coin_list(format=True)
for coin in listOfCoins:
liste.append(coin)
print(liste)
def getCoinPrice(coin):
if (cryptocompare.get_price(coin)):
price = cryptocompare.get_price(coin)
print('\n',price.get(coin).get('EUR'), '€')
else:
if (coin == 'liste') :
return
else :
print('Il n\'y a aucune monnaie du nom de', coin,'\n')
print('\nBienvenue sur l\'outil qui permet de savoir le prix de toutes les cryptomonnaies. Commençons...\n')
while (True):
question = input('\nPour voir l\'ensemble des monnaies, entrez "liste". \nPour quitter, tapez "quitter". \nPour voir le prix d\'une monnaie particulière, entrez son nom en majuscules.\n\n')
if (question == 'liste'):
getCoinsList()
if (question == 'quitter'):
exit()
else:
getCoinPrice(question) |
import sys
print("Olá " + input("Digite seu nome:\n"))
while True :
resposta = input("Fala comigo bebê \n")
print(input(resposta +'?\n'))
|
main_dict={}
def insert_item(item):
if item in main_dict:
main_dict[item] += 1
else:
main_dict[item] = 1
#Driver code
insert_item('Key1')
insert_item('Key2')
insert_item('Key2')
insert_item('Key3')
insert_item('Key1')
print(main_dict)
print (len(main_dict))
|
class Book:
'''Has the following properties:
-id
-title
-description
-author
'''
def __init__(self, id, title, description, author):
self._id = id
self._title = title
self._description = description
self._author = author
def __repr__(self):
#Prints the book's details
return "Book #%d:\nTitle: %s\nDescription: %s\nAuthor: %s\n" % (self._id, self._title, self._description, self._author)
def __eq__(self, other):
return (isinstance(other, self.__class__)
and self.__dict__ == other.__dict__)
def getId(self):
#Returns the id of the book
return self._id
def setId(self, id):
#sets the book's id
self._id = id
def getTitle(self):
#Returns the book's title
return self._title
def setTitle(self, title):
#Sets the book's title
self._title = title
def getDescription(self):
#Returns the book's description
return self._description
def setDescription(self, description):
#Sets the book's description
self._description = description
def getAuthor(self):
#Returns the book's author
return self._author
def setAuthor(self, author):
#Sets the book's author
self._author = author
|
from math import sqrt
def is_prime(n):
"""this function checks if a number is prime or not.
If it is prime, it will show True and False otherwise"""
if n == 2:
return True
if n < 2 or n % 2 == 0:
return False
for i in range(3, int(sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
def find_Gol_Con(n):
""""This function is going to generate the Goldbach's conjecture.
If there are not valid pairs, the function will show a message."""
k = 0
l = []
for i in range(2, n - 2):
if is_prime(i):
if is_prime(n - i):
l.append((i, n - i))
return l
l = find_Gol_Con(100)
if len(l) == 0:
print("There are no such numbers")
else:
for e in l:
print(e)
|
import sys
import controler
from copy import deepcopy
def read_command():
"""This function splits up the command"""
cmd = input("Command: ")
if cmd.find(" ") == -1:
command = cmd
params=""
else:
command = cmd[0:cmd.find(" ")]
params = cmd[cmd.find(" "):]
params = params.split(" ")
for i in range(0, len(params)):
params[i] = params[i].strip()
return command,params
def add_command(List, par):
"""This function checks the introduced parameter.
If it is not a complex number, the function will show an alert message."""
if controler.check_val(par[1], complex):
controler.add_number(List, complex(par[1]))
else:
print("The number is invalid")
def add_more_numbers(List, par):
for i in range(len(par)):
add_insert.add_number(List, complex(par[i]))
else:
print("Not a valid command!")
def insert_number_at_position(List, par):
"""This function validates the number and the position
and inserts the number in the list"""
if par[2] == 'at':
if controler.check_val(par[1], complex) and controler.check_val(par[3], int):
controler.insert_number(List, complex(par[1]), int(par[3]))
else:
print("Invalid number or position!")
else:
print("Invalid command!")
def remove_item_at_poz(List, par):
"""The function calls the remove function and removes an element."""
if controler.check_val(par[1], int):
controler.remove_position(List, int(par[1]))
else:
print("Invalid position or command!")
def remove_more_numbers(List, par):
"""The function calls the remove function and removes an element."""
for i in range(len(par)):
if controler.check_val(par[i], int):
controler.remove_position(List, int(par[i]))
def remove_items_range(List, par):
"""This function removes items in a given range"""
if controler.check_val(par[1], int) and controler.check_val(par[3], int) and par[2] == 'to':
controler.remove_items(List, int(par[1]), int(par[3]))
def replace_item(List, par):
"""This function replaces an item by ots given position."""
if par[2] == 'with':
if controler.check_val(par[1], complex) and controler.check_val(par[3], complex):
controler.replace_item_range(List, complex(par[1]), complex(par[3]))
else:
print("Invalid numbers!")
else:
print("Invalid command!")
def return_sume(List, par):
if controler.check_val(par[1], int) and controler.check_val(par[3], int) and par[2] == 'to':
controler.sum_nbs(List, int(par[1]), int(par[3]))
else:
print("Invalid numbers!")
def return_prod(List, par):
if controler.check_val(par[1], int) and controler.check_val(par[3], int) and par[2] == 'to':
controler.prod_nbs(List, int(par[1]), int(par[3]))
else:
print("Invalid numbers!")
def print_entire_list(List, par):
controler.print_list(List)
def print_real_numbers(List, par):
if Params[3] == 'to':
if controler.check_val(par[2], int) and controler.check_val(par[4], int):
controler.print_real_nbs(List, int(par[2]), int(par[4]))
else:
print("Invalid numbers")
else:
print("Invalid command enter help for information!")
def print_modulo_numbers(List, par):
if controler.check_val(par[3], int) or controler.check_val(par[3], float):
controler.print_numbers_modulo(List, par[2], float(par[3]))
else:
print("That is not a number")
def filter_real_numbers(List, par):
controler.filter_real(List)
def filter_modulo_numbers(List, par):
if controler.check_val(par[3], int) or controler.check_val(par[3], float):
if par[2] != 0 and par[3] != 0:
controler.filter_modulo(List, par[2], float(par[3]))
else:
print("That is not a number")
def exit_function(my_list, params):
sys.exit()
def print_help(params):
print("\nHelp:")
print("\tadd <number>")
print("\tinsert <number> at <position>")
print("\tadd <numbers>")
print("\tremove <position>")
print("\tremove_more <positions>")
print("\tremove <start position> to <end position>")
print("\treplace <old number> with <new number>")
print("\tlist")
print("\tlist real <start position> to <end position>")
print("\tlist modulo [<|=|>] <number>")
print("\tsum <start position> to <end position>")
print("\tproduct <start position> to <end position>")
print("\tfilter real")
print("\tfilter modulo [<|=|>] <number>")
print("\tundo")
print("\tExit!")
print("\tHelp!")
def undo_list(List, backup_list):
if backup_list[len(backup_list)-1] != List:
backup_list.append(deepcopy(List))
def undo_function(List, backups):
#This frunction replaces the list with the last list before the previous opperation.
if len(backups) > 1:
del backups[len(backups)-1]
del List[:]
for i in range(0,len(backups[len(backups)-1])):
List.append(backups[len(backups)-1][i])
print("Success!")
else:
print("Something went wrong!")
def mainMenu():
#tests.run_tests()
print("\n\tWelcome to the complex number application!")
print("\n\tFor further information, please type Help!\n")
my_list = [[1, 5], [3, 6], [6, 4], [11, 0], [4, 5], [-23, 7], [2, 10], [0, 0], [0, -3], [-8, 0]]
backup_list = []
backup_list.append(deepcopy(my_list))
Commands = {'add': [add_command, 2, "add <number>"],
'insert': [insert_number_at_position, 4, "insert <number> at <position>"],
'add_more': [add_more_numbers, 2, "add_more <numbers>"],
'remove': [remove_item_at_poz, 2, "remove <position>"],
'remove_more': [remove_more_numbers, 2, "remove_more <positions>"],
'remove_in_range': [remove_items_range, 4, "remove <start position> to <end position>"],
'replace': [replace_item, 4, "replace <old number> with <new number>"],
'list': [print_entire_list, 0, "list"],
'list real': [print_real_numbers, 5, "list real <start position> to <end position>"],
'list modulo': [print_modulo_numbers, 4, "list modulo [<|=|>] <number>"],
'sum': [return_sume, 4, "sum <start position> to <end position>"],
'product': [return_prod, 4, "product <start position> to <end position>"],
'filter real': [filter_real_numbers, 2, "filter real"],
'filter modulo': [filter_modulo_numbers, 4, "filter modulo [<|=|>] <number>"],
'undo': ['', '', "undo"],
'Exit!': [exit_function, 0, "Exit!"],
'Help!': [print_help, 0, "Help!"]}
while True:
all_commands = read_command()
Command = all_commands[0]
Params = all_commands[1]
if Command == 'add_more':
for i in range(1, len(Params)):
if controler.check_val(Params[i], complex):
controler.add_number(my_list, complex(Params[i]))
else:
print("Not a valid command!")
if Command == 'remove_more':
i = len(Params) - 1
while i >= 0:
if controler.check_val(Params[i], int):
controler.remove_position(my_list, int(Params[i]))
i -= 1
if Command == 'filter' and len(Params) == 2:
filter_real_numbers(my_list, Params)
if Command == 'filter' and len(Params) == 4:
filter_modulo_numbers(my_list, Params)
if Command in Commands:
if len(Params) > 1:
if Command == 'remove' and len(Params) == 4:
Command = "remove_in_range"
if Command == 'list' and Params[1] == 'real':
Command = 'list real'
if Command == 'list' and Params[1] == 'modulo':
Command='list modulo'
if Command=='filter' and Params[1] == 'modulo':
Command = 'filter modulo'
filter_modulo_numbers(my_list, Params)
if Command == 'Help!':
print_help(Commands)
elif Command == 'undo':
undo_function(my_list,backup_list)
else:
if Commands[Command][1] == len(Params):
Commands[Command][0](my_list, Params)
undo_list(my_list, backup_list)
mainMenu()
|
list1 = [1,2,3,4,5]
list2 = [1,2,3,4,5]
list3 = [1,2,3,4,5]
list4 = [1,2,3,4,5]
def proc(mylist):
global list1
list1 = mylist
#mylist = list1
print list1
#print mylist
list1 = list1 + [6,7]
mylist = mylist + [6,7]
def proc2(mylist):
mylist.append(6)
mylist.append(7)
def proc3(mylist):
mylist+=[6,7]
print "demonstrating proc"
print list1
proc(list1)
print list1
print "demonstrating proc2"
print list2
proc2(list2)
print list2
print "demonstrating proc3"
print list3
proc2(list3)
print list3
print ' test list + [6,7]'
print list1 + [6,7]
|
# player_name = "Manuel"
# player_attack = 10
# player_heal = 16
# health = 100
#player = ["Manuel",10,16,100]
from random import randint
game_running = True
game_results = []
# print(player['name'])
# print(monster['health'])
def cal_monster_attack(attack_min,attack_max):
return randint(attack_min,attack_max)
def game_ends(winner_name):
print(f'{winner_name } won the game')
while game_running == True:
counter = 0
new_round = True
player = {'name':"Manuel", 'attack': 13, 'heal':16, 'health':100}
monster = {'name':'Pogo', 'attack_min':10, 'attack_max':20, 'health':100}
print("-----" * 12)
print("Enter Player name: ")
player['name'] = input()
print("-----" * 12)
print(player['name'] + " has " + str(player['health']) + " health ")
print(monster['name'] + " has " + str(monster['health']) + " health ")
while new_round == True:
counter = counter+1
player_won = False
monster_won = False
print("Please select an action")
print("1> Attack")
print("2> Heal")
print("3> Exit game")
print("4> Show Results")
player_choice = int(input())
if player_choice == 1:
#print("Attack")
monster['health'] = monster['health'] - player['attack']
if monster['health'] <= 0:
player_won = True
else:
player['health'] = player['health'] - cal_monster_attack(monster['attack_min'],monster['attack_max'])
if player['health'] <= 0:
monster_won = True
print(monster['health'])
print(player['health'])
elif player_choice == 2:
#print("Heal Player")
player['health'] = player['health'] + player['heal']
player['health'] = player['health'] - cal_monster_attack(monster['attack_min'],monster['attack_max'])
if player['health'] <= 0:
monster_won = True
elif player_choice == 3:
new_round = False
game_running = False
elif player_choice == 4:
for i in game_results:
print(i)
else:
print("Invalid input")
if player_won == False and monster_won == False:
print(player['name'] + " has " + str(player['health']) + " left ")
print(monster['name'] + " has " + str(monster['health']) + " left ")
elif player_won:
game_ends(player['name'])
round_result = {'name':player['name'],'health':player['health'], 'rounds':counter}
#print(round_result)
game_results.append(round_result)
#print(game_results)
new_round = False
elif monster_won:
game_ends(monster['name'])
round_result = {'name':monster['name'],'health':monster['health'],'rounds':counter}
#print(round_result)
game_results.append(round_result)
#print(game_results)
new_round = False
|
M,N=map(int,input().split())
"""
def mymethod(N):
primes={2:True,3:True}
for i in range(2,int(sqrt(N))+1):
if primes.get(i,True)==False:
continue
#while i*j<N:
for t in range(i*i,N+1,i):
#if i*j not in primes:
primes[t]=False
#j+=1
theprime=[]
for i in range(2,N):
if primes.get(i,True):
theprime.append(i)
return theprime
"""
def ola(N):#欧拉筛法
prime=[]
isprime=[True]*(N+1)
isprime[1]=False
for i in range(2,N):
if isprime[i]:
prime.append(i)
for j in prime:
if i*j>N:
break
isprime[i*j]=False
if i%j==0:
break
return prime
data=ola(105000)
res=data[M-1:N]
while len(res)>10:
print(" ".join([str(i) for i in res[:10]]))
res=res[10:]
print(" ".join([str(i) for i in res])) |
def maxChar(word):
maxChar = ''
for char in word:
if maxChar < char:
maxChar = char
return maxChar
word = input('Gebe ein wort ein: ')
char = maxChar(word)
print(char) |
def reverse(normalString):
reveseString = ''
for c in normalString:
reveseString = c + reveseString
return reveseString
normalString = input('Geben sie ein wort ein: ')
print(reverse(normalString))
|
#python3.8
import json, requests, sys, time, math
APPID = '<--------------------->'
print("API key stored")
print()
"""
#compute location from command line arguments
if len(sys.argv) < 2:
print('Usage: getOpenWeather.py city_name, 2-letter_country_code')
sys.exit()
"""
#location = ' '.join(sys.argv[1:])
city = input("What City? ")
print('City stored!')
print()
country = input("What Country? ")
print('Country stored!')
print()
# Download the JSON data from OpenWeatherMap.org's API.
url = 'https://api.openweathermap.org/data/2.5/weather?q=%s,%s&appid=%s'%(city,country,APPID)
#url = 'https://api.openweathermap.org/data/2.5/weather?q=dallas,tx,usa&appid=<------------------------>'
print('The url is: \n',url)
print()
time.sleep(2)
print('checking status... ')
response = requests.get(url)
print()
response.raise_for_status()
print('status determined')
print()
print("JSON Data:")
print(response.text)
print()
weatherData = json.loads(response.text)
w = weatherData['weather']
m = weatherData['main']
print(w)
print()
print(m)
print()
print(w[0]['main'])
avg_t = m['temp']
feel_temp = m['feels_like']
def kelvin(x):
temperature = 9*float(x)/5 - 459.67
ans = round(temperature,1)
return ans
#temp = 9*float(m['temp'])/5-(460)
#print(temp)
print("The temperature in "+city+" is: "+str(kelvin(avg_t))+" deg F")
print("The temperature in "+city+" feels like: "+str(kelvin(feel_temp))+" deg F")
#print(m['feels_like'])
"""
weatherData = json.loads(response.text)
w = weatherData['list']
print('Current weather in %s:' % (location))
print(w[0]['weather'][0]['main'], '-', w[0]['weather'][0]['description'])
print()
print('Tomorrow:')
print(w[1]['weather'][0]['main'], '-', w[1]['weather'][0]['description'])
print()
print('Day after tomorrow:')
print(w[2]['weather'][0]['main'], '-', w[2]['weather'][0]['description'])
"""
|
import time
class Board(object):
def __init__(self, cells):
self.cells = cells
def next_step(self):
next_state = set([])
interesting_cells = set([])
for cell in self.cells:
interesting_cells.add(cell)
interesting_cells |= self.neighbours(cell)
for cell in interesting_cells:
is_alive = cell in self.cells
fate = self.rules(is_alive, self.neighbours_alive(cell))
if fate:
next_state.add(cell)
self.cells = next_state
return next_state
def rules(self, is_alive, neighbours):
if is_alive and neighbours in (2,3):
return True
elif not is_alive and neighbours == 3:
return True
return False
def neighbours_alive(self, coord):
return len(self.neighbours(coord) & self.cells)
@staticmethod
def neighbours(cell):
deltas = [
(0, 1),
(0, -1),
(1, 1),
(1, -1),
(1, 0),
(-1, 0),
(-1, 1),
(-1, -1)
]
neighbours = set([])
for dx, dy in deltas:
x, y = cell
neighbours.add((x+dx, y+dy))
return neighbours
def __str__(self):
size_x = max([x for x, y in self.cells]) + 2
size_y = max([y for x, y in self.cells]) + 3
size = (size_x, size_y)
rows = []
for y in range(size[0]):
row = ''
for x in range(size[1]):
if (x, y) in self.cells:
row += 'x'
else:
row += '.'
rows.append(row)
return u'\n'.join(rows) + '\n'
if __name__ == "__main__":
seed1 = set([(1, 1), (1, 2), (1, 3)])
seed2 = set([(2, 0), (3, 1), (1, 2), (2, 2), (3, 2), (1, 3), (2, 3), (3, 3)])
seed3 = set([(2, 0), (3, 1), (1, 2), (2, 2), (3, 2)])
b = Board(seed3)
print b
for step in range(1000):
time.sleep(0.25)
b.next_step()
print b
|
import time
import pandas as pd
import pants
# function to read the excel with the distance matrix
def parse_input(path):
distances = pd.read_excel(path, index_col=0)
return distances
dists = parse_input('Lab10DistancesMatrix.xlsx')
# function to get the distance between two points
def getDist(a, b):
return dists[a][b]
# function to check if the initial route has duplicate cities
def is_valid_route(list_of_cities):
return not any(list_of_cities.count(element) > 1 for element in list_of_cities)
# function to run the algorithm
def ACO_algorithm(cities_list):
world = pants.World(cities_list, getDist)
start_time = time.time()
solver = pants.Solver(alpha=10, beta=30, ant_count=10, limit=2500)
solution = solver.solve(world)
end_time = time.time()
duration = end_time - start_time
return solution, duration
# function to print the results starting in P1
def p_print(solution, duration):
best_path = solution.tour
indexP1 = best_path.index('P1')
best_path = best_path[indexP1:] + best_path[:indexP1]
print("******************************** BEST RESULT ********************************")
print("The best route is: ")
print(best_path)
print('Final distance: {0:.3f}'.format(solution.distance))
print("'Found in: {0:.2f} seconds".format(duration))
def main():
# input lists (change on the two functions below)
cities_list15 = ['P' + str(i) for i in range(1, 16)]
cities_list25 = ['P' + str(i) for i in range(1, 26)]
cities_list65 = ['P' + str(i) for i in range(1, 66)]
cities_list100 = [cols for cols in dists.columns]
# checking if the list is valid
if not is_valid_route(cities_list100):
print("Route not valid, has duplicate cities!!")
return
# run the algorithm
solution, duration = ACO_algorithm(cities_list100)
# print the solution
p_print(solution, duration)
if __name__ == '__main__':
main()
|
def bin_search(arr, ele):
start, end = 0, len(arr)
while start <= end:
# print(arr[start:end])
mid = (start + end) // 2
if arr[mid] == ele:
return mid + 1
else:
if arr[mid] < ele:
start = mid + 1
elif arr[mid] > ele:
end = mid - 1
return False
if __name__ == "__main__":
print(
'found : ',
bin_search(list(map(int,
input("Enter data : ").strip().split())),
int(input("Enter num to search : "))))
|
def rotation_generator(arr, x):
print('rotated array : ', arr[x:] + arr[:x])
return arr[x:] + arr[:x]
def rotation_point_finder(arr):
low, high = 0, len(arr) - 1
while low <= high:
print(arr[low:high])
if arr[low] <= arr[high]:
return low
mid = (low + high) // 2
if arr[(mid - 1 + len(arr)) % len(arr)] > mid < arr[(mid + 1) %
len(arr)]:
return mid
if arr[low] >= arr[mid]:
low = mid + 1
elif arr[mid] >= arr[high]:
high = mid - 1
if __name__ == "__main__":
print(
'rotation point at : ',
rotation_point_finder(
rotation_generator(
list(map(int,
input("Enter array : ").strip().split())),
int(input("Enter rotations to be performed : ")))))
|
import math as m
class Heap:
def __init__(self):
self.data=[]
def addNode(self,value):
self.data.append(value)
index=len(self.data)-1
while index!=0:
if self.data[index] < self.data[m.floor((index-1)//2)]:
self.data[index] , self.data[m.floor((index-1)//2)] = self.data[m.floor((index-1)//2)] , self.data[index]
#swap
index=m.floor((index-1)//2)
return True
def display(self):
print(self.data)
def heapify(self,index):
if index < len(self.data):
if (index*2)+1 < len(self.data):
if self.data[index] > self.data[(index*2)+1]:
self.data[index] , self.data[(index*2)+1] = self.data[(index*2)+1],self.data[index]
self.heapify((index*2)+1)
if (index*2)+2 < len(self.data):
if self.data[index] > self.data[(index*2)+2]:
self.data[index] , self.data[(index*2)+2] = self.data[(index*2)+2],self.data[index]
self.heapify((index*2)+2)
def extractMin(self):
self.data[0],self.data[len(self.data)-1]=self.data[len(self.data)-1],self.data[0]
min_value_so_far=self.data.pop(-1)
self.heapify(0)
return min_value_so_far
def heapsort(self):
sorted=[]
while self.data!=[]:
sorted.append(self.extractMin())
return sorted
if __name__ == '__main__':
main_heap=Heap()
for i in [17,3,15,25,12,1,4]:
main_heap.addNode(i)
print("heap is : ")
main_heap.display()
sorted = main_heap.heapsort()
print('sorted data :',sorted)
|
# gesture control python program for controlling certain functions in windows pc
# Code by Harsh Namdev
# add pyautogui library for programmatically controlling the mouse and keyboard.
import pyautogui
import time
def action_func(incoming_data):
# print the incoming data
print('handy', incoming_data)
if '0' in incoming_data: # minimizing window
pyautogui.hotkey('winleft', 'down')
time.sleep(1)
if '1' in incoming_data: # if incoming data is 'next'
# perform "ctrl+pgdn" operation which moves to the next tab
pyautogui.hotkey('ctrl', 'pgdn')
time.sleep(1)
if '2' in incoming_data: # if incoming data is 'previous'
# perform "ctrl+pgup" operation which moves to the previous tab
pyautogui.hotkey('ctrl', 'pgup')
time.sleep(1)
if '3' in incoming_data: # if incoming data is 'down'
# pyautogui.press('down') # performs "down arrow" operation which scrolls down the page
pyautogui.scroll(-100)
if '4' in incoming_data: # if incoming data is 'up'
# pyautogui.press('up') # performs "up arrow" operation which scrolls up the page
pyautogui.scroll(100)
if '5' in incoming_data: # if incoming data is 'change'
# performs "alt+tab" operation which switches the tab
# pyautogui.keyDown('alt')
# pyautogui.press('space')
# pyautogui.keyUp('alt')
pyautogui.hotkey('winleft', 'up') # maximizing window
time.sleep(1)
incoming_data = "" # clears the data
|
# Dijkstra's algorithm in python
def dijkstra(graph,start,end):
D={}# Final distances dict
P={}# Predecessor dict
# Fill the dicts with default values
for node in graph.keys():
D[node] = -1 # Vertices are unreachable
P[node] = "" # Vertices have no predecessors
D[start] = 0 # The start vertex needs no more
unseen_nodes = list(graph) # All nodes are unseen
while len(unseen_nodes) > 0:
# Select the node with the lowest value in D (final distance)
shortest = None
node = ''
for temp_node in unseen_nodes:
if shortest == None:
shortest = D[temp_node]
node = temp_node
elif D[temp_node] < shortest:
shortest = D[temp_node]
node = temp_node
# Remove the selected node from unseen_nodes
unseen_nodes.remove(node)
# For each chile(ie: connected vertex) of the current node
for child_node, child_value in graph[node].items():
if D[child_node] < D[node] + child_value:
D[child_node] = D[node] + child_value
# To go to child_node, you have to go through node
P[child_node] = node
# Set a clean path
path = []
# We begin from the end
node = end
# While we are not arrived at the beginning
while not (node == start):
if path.count(node) == 0:
path.insert(0,node) # insert the predecessor of the current node
node = P[node] # The current node becomes its predessor
else:
break
path.insert(0,start) # Finaly, insert the start vertex
return path
graph = {
'1':{'2':1,'3':2},
'2':{'4':6,'5':12},
'3':{'4':3,'6':4},
'4':{'6':3,'7':15,'8':7},
'5':{'7':7},
'6':{'8':7,'9':15},
'7':{'9':3},
'8':{'9':10},
'9':{}
}
print(dijkstra(graph,'1','9'))
|
# !/usr/bin/env python
# -*- coding=utf-8 -*-
# Summary: HASH表(处理冲突的方法:开放寻址法h(k,i)=(h'(k)+i))mod m );查找的时间为O(1)
# Author: HuiHui
# Date: 2019-04-01
# Reference: 网易公开课-算法导论
# https://www.cnblogs.com/dairuiquan/p/10509416.html
#################################
#创建与内建类型list相似的数组,其初始元素均为None
class Array(object): #新式类,解决了就是类多类继承的顺序问题。
def __init__(self, size=32, init=None): #__**__是python魔法方法,具有特殊的调用方式;__**表私有属性和方法;_**有什么含义?
self._size = size
self._items = [init]*size
def __getitem__(self, index):
return self._items[index]
def __setitem__(self, index, value):
self._items[index]=value
def __len__(self):
return self._size
def clear(self,value=None):
for i in range(self._size):
self._items[i]=value
def __iter__(self): #使得Array是可迭代的,如可通过for实现循环
for item in self._items:
yield item #生成器,函数中每次使用yield产生一个值,函数就返回该值,然后停止执行,等待被激活,被激活后继续在原来的位置执行
#定义哈希表数组的槽
#注意:一个槽有三种状态
#1. 从未被使用过,HashMap.UNUSED。 此槽没有被使用和冲突过,查找时只要找到UNUSED 就不用再继续探查了
#2. 使用过但是remove了,此时是HashMap.EMPTY,该谈差点后面的元素仍可能是有key
#3. 槽正在使用Slot节点
class Slot(object):
def __init__(self, key, value):
self.key = key
self.value = value
#定义哈希表;采用开放寻址法解决冲突;线性探查
class HashTable(object):
UNUSED=None #表示slot从未被使用过
EMPTY=Slot(None,None) #表示slot被使用过但删除了
def __init__(self,size):
self._table=Array(size,init=self.UNUSED)
self.length=0 #已装载的元素数量
@property #内置装饰器,把方法变成属性
def _load_factor(self): #装载因子属性
return self.length/float(len(self._table))
def __len__(self):
return self.length
def _hash(self,key,i): #i从0到len(self._table)-1
return abs(hash(key)+i)%len(self._table) #hash是内置函数,len(self._table)是槽数;线性探查
def _rehash(self): # 哈希表已满,重新哈希化
old_table = self._table
new_size = len(self._table) * 2
self._table = Array(new_size, self.UNUSED)
self.length = 0
for slot in old_table:
if slot is not self.UNUSED and slot is not self.EMPTY: #判断这个slot是有值的
for i in range(new_size):
index = self._hash(slot.key, i)
if self._table[index] is self.UNUSED: #将旧表中的槽插入新
self._table[index] = slot
self.length += 1
break
def hash_search(self, key): #返回key对应的index,value;若没找到,返回-1,None
_len=len(self._table)
for i in range(_len): #线性探查,直至找到key,或者找到从未被使用的槽
index = self._hash(key, i)
if self._table[index] is self.UNUSED:
print("Not Find %s" % key)
return -1, None
if self._table[index].key==key:
print("Find %s index is %d,value is %d" % (key,index,self._table[index].value))
return index,self._table[index].value
print("Not Find %s"%key) #探查完所有的槽都没找到key
return -1,None
def hash_insert(self, key, value):
_len = len(self._table)
for i in range(_len): #线性探查,若找到表中已有key,则更新key的value;若找到从未被使用的槽或使用过但删除了的槽,则将key,value插入
index = self._hash(key, i)
if self._table[index] is self.EMPTY or self._table[index] is self.UNUSED:
self._table[index]=Slot(key, value) #注意这里若self._table[index]未被使用,即为None时,不能直接用.key,.value赋值
print("Change %s value to %d" % (key, value))
self.length+=1
if self._load_factor>=0.8:
self._rehash()
return 1
if self._table[index].key==key:
self._table[index].value = value
print("Change %s value to %d" % (key,value))
return 0 #返回0表示没有执行插入操作,执行的是更新操作
print("Can Not Insert") #探查完所有的槽都没找到能插入的地方
return -1
def hash_remove(self, key):
index, value = self.hash_search(key)
if index!=-1: #找到了key
self._table[index]=self.EMPTY #这里不能直接用.key=None,..
self.length-=1
print("Remove successful")
return 1
else: #没找到key
print("Not Find %s" % key)
return -1
def __iter__(self): #迭代器,遍历槽;
for slot in self._table:
if slot is not self.EMPTY and slot is not self.UNUSED:#slot有值
yield slot #这里改为slot.key,则遍历的时key
###############################
def test_hash_table():
h = HashTable(3)
h.hash_insert('a', 0)
h.hash_insert('b', 1)
h.hash_insert('c', 2)
print(len(h))
h.hash_search('a')
h.hash_search("d")
h.hash_remove("a")
for slot in h:
print(slot.key,slot.value)
print(h._load_factor)
###############################
def main():
test_hash_table()
if __name__ == '__main__': # 当.py文件被直接运行时,if __name__ == '__main__'之下的代码块将被运行;当.py文件以模块形式被导入时,if __name__ == '__main__'之下的代码块不被运行。
main()
|
# !/usr/bin/env python
# -*- coding=utf-8 -*-
# Summary: Dijkstra算法(解决带权重的有向图单源最短路径问题;要求权重非负无环;思路:贪心策略,不断将能最短到达的节点u加入集合S,并松弛从u出发的边)(时间O(n2))
# Author: HuiHui
# Date: 2019-09-20
# Reference:
#################################
# graph:邻接矩阵存储带权有向图(利用字典构造二维散列表,values为权重);s:源点(节点名)
# cost:存储源点到各点的最短路径估计(散列表);path:存储前驱节点(散列表)
# S集合:已找到最短路径的节点集合(列表)
def find_lowest_cost_node(costs,S): # 在未处理的节点中找开销最小的节点
lowest_cost_node=None
lowest_cost=float("inf")
for node in costs.keys():
cost=costs[node]
if cost<lowest_cost and node not in S:
lowest_cost = cost
lowest_cost_node = node
return lowest_cost_node
def dijkstra(graph, s):
if graph == None:
return None
# 获取所有节点
V=graph.keys()
costs = {}
path = {}
infinity=float("inf")
#初始化cost和path
for key in V:
if key==s:
costs[key]=0
else:
costs[key]=infinity
path[key]=None
S=[]#存储处理过的节点 ,即已找到最短路径的节点
node=find_lowest_cost_node(costs,S)#在未处理的节点中找开销最小的节点
while node is not None:#只要还有未处理的节点,则执行
cost=costs[node]
neighbors=graph[node]
# 松弛所有从node出发的边
for key in neighbors.keys():
if costs[key]>cost+neighbors[key]: #key从node通过最短路径更小,更新cost和path
costs[key]=cost+neighbors[key]
path[key]=node
S.append(node)#标记node为处理过的
node = find_lowest_cost_node(costs,S)#找出接下来要处理的节点
return costs,path
####################################
if __name__ == '__main__':
graph={"O":{"A":6,"B":2},"A":{"F":1},"B":{"A":3,"F":5},"F":{}}
s="O"
costs,path=dijkstra(graph, s)
print(costs)
print(path)
|
#!/usr/bin/python3
"""Save all info to a JSON file"""
import json
import requests
def save_all_to_json():
"""
Save info to a JSON file. That info? Still employee record.
"""
users_and_tasks = {}
users_json = requests.get('https://jsonplaceholder.typicode.com/users')\
.json()
todos_json = requests.get('https://jsonplaceholder.typicode.com/todos')\
.json()
user_info = {}
for user in users_json:
user_info[user['id']] = user['username']
for task in todos_json:
if users_and_tasks.get(task['userId'], False) is False:
users_and_tasks[task['userId']] = []
task_dict = {}
task_dict['username'] = user_info[task['userId']]
task_dict['task'] = task['title']
task_dict['completed'] = task['completed']
users_and_tasks[task['userId']].append(task_dict)
with open('todo_all_employees.json', 'w') as jsonFile:
json.dump(users_and_tasks, jsonFile)
return 0
if __name__ == "__main__":
save_all_to_json()
|
# Função para ler uma String passada pelo usuário
def digite_mensagem(mensagem):
return input(mensagem)
# Função para ler um número de ponto flutuante
def digite_numero(numero):
return float(input(numero)) |
import csv
with open("data.csv", newline='') as f :
reader = csv.reader(f)
file_data = list(reader)
print(file_data)
data = file_data[0]
print(data)
def mean(data):
n = len(data)
total = 0
for i in data:
total += int(i)
mean = total/n
return mean
squared_list = []
for num in data:
a = int(num)-mean(data)
a = a**2
squared_list.append(a)
sum =0
for x in squared_list:
sum += x
result = sum/(len(data)-1)
import math
standard_deviation = math.sqrt(result)
print("SD is :"+str(standard_deviation))
|
def string_length(i):
if type(i) == int:
return "A number has no length"
elif type(i) == float:
return "This is a float, it has no length either"
else:
return len(i)
#i = input("Enter a string to see its length: ")
print(string_length(10.0))
|
class Position(object):
row_dict = {
1: 'A',
2: 'B',
3: 'C',
4: 'D',
5: 'E',
6: 'F',
7: 'G',
8: 'H'
}
def __init__(self, x, y):
if x < 0:
raise ValueError("Figure's row value must be greater than 0")
if x > 7:
raise ValueError("Figure's row value must be less than 7")
if y < 0:
raise ValueError("Figures's column value must be greater than 0")
if y > 7:
raise ValueError("Figure's column value must be less than 7")
assert y >= 0 and y <= 7
self.x = x
self.y = y
def __str__(self):
return self.row_dict[self.x + 1] + str(self.y + 1)
def __eq__(self, position: Position):
return self.x == position.x and self.y == position.y
pos = Position(-1, 0)
print(pos)
|
import numpy as np
import pandas as pd
dfPaises = pd.read_csv('paises.csv', delimiter=';')
# print(dfPaises['Region'])
oceania = dfPaises[dfPaises['Region'].str.contains("OCEANIA")]
# Exercicio 1
print("--- Paises da OCEANIA ---")
print(oceania['Country'])
print("--- Nº de Paises da OCEANIA ---")
print(oceania['Country'].count())
# Exercicio 2
print("\n")
print("--- Maior População ---")
population = dfPaises[dfPaises['Population']==dfPaises['Population'].max()]
print(population.filter(['Country', 'Region', 'Population']))
# Exercicio 3
print("\n")
print("--- Alfabetização por Região ---")
alfabetizacaoPorRegiao = dfPaises.groupby(['Region'], as_index=False)['Literacy (%)'].mean()
print(alfabetizacaoPorRegiao)
# Exercicio 4
print("\n")
print("--- Não possuem Costa Marítima ---")
noCoastFilter = dfPaises[dfPaises['Coastline (coast/area ratio)']==0]
noCoastFilter.to_csv('noCoast.csv', sep=';', header=True)
print("Gerado CSV")
# Exercicio 5
print("\n")
print("--- Taxa de Mortalidade ---")
dfPaises['Humanitarian Help'] = np.where(dfPaises['Deathrate'] < 9, "Balanced", "Urgent")
print(dfPaises)
dfPaises.to_csv('taxaMortalidade.csv', sep=';', header=True) |
"""
NP2 - C210
Código referente a Questão 1
"""
# Usado para plotar o gráfico no PyCharm
import matplotlib.pyplot as plt
import numpy as np
from skfuzzy import control as ctrl
# Antecedentes
nivelTanque = ctrl.Antecedent(np.arange(0,101,1), "nivel do tanque")
erroLeitura = ctrl.Antecedent(np.arange(0,101,1), "erro de leitura")
# consequente
bomba = ctrl.Consequent(np.arange(0,101,1), "potência da bomba")
nivelTanque.automf(3, names=["baixo", "medio", "alto"])
erroLeitura.automf(3, names=["baixo", "medio", "alto"])
bomba.automf(3, names=["baixo", "medio", "alto"])
# plotando grafico
nivelTanque.view()
erroLeitura.view()
bomba.view()
plt.show()
# criando regras
# Coluna0 (Baixa) X ( Linha0, Linha1 e Linha2)
rule1 = ctrl.Rule(nivelTanque["baixo"] & erroLeitura["baixo"], bomba["alto"])
rule2 = ctrl.Rule(nivelTanque["alto"] | erroLeitura["baixo"], bomba["baixo"])
rule3 = ctrl.Rule(nivelTanque["medio"] | erroLeitura["medio"], bomba["medio"])
# Criando o Sistema
bomba_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])
potenciaBomba = ctrl.ControlSystemSimulation(bomba_ctrl)
# A) Nível do tanque: 50; Erro de leitura: 10
potenciaBomba.input["nivel do tanque"] = 50
potenciaBomba.input["erro de leitura"] = 10
potenciaBomba.compute()
print("A potencia da bomba é: ", potenciaBomba.output["potência da bomba"], "%")
bomba.view(sim=potenciaBomba)
plt.show()
# B) Nível do tanque: 80; Erro de leitura: 20
potenciaBomba.input["nivel do tanque"] = 80
potenciaBomba.input["erro de leitura"] = 20
potenciaBomba.compute()
print("A potencia da bomba é: ", potenciaBomba.output["potência da bomba"], "%")
bomba.view(sim=potenciaBomba)
plt.show()
# C) Nível do tanque: 10; Erro de leitura: 50
potenciaBomba.input["nivel do tanque"] = 10
potenciaBomba.input["erro de leitura"] = 50
potenciaBomba.compute()
print("A potencia da bomba é: ", potenciaBomba.output["potência da bomba"], "%")
bomba.view(sim=potenciaBomba)
plt.show() |
'''
author: Camilo Hernández
This script takes an image file and converts it into pixelart based on the given initial parameters
file_name # this should point to the name of the image file (without the file extension)
file_format # this should be the type of file
new_file_appendix # this should be what is added to the file name on the new image
pixel_size # this should be the size of a square in the pixelart, i.e. how many pixels wide and high it is
color_palette_src # this should point to a file containing data on the colors used in the pixelart image
'''
import os
import sys
from PIL import Image
#returns color closest to the given color using Euclidean distance
def pixel_color(pixel, palette):
closest_color = palette[0]
minimum_distance = (closest_color[0]-pixel[0])**2+(closest_color[1]-pixel[1])**2+(closest_color[2]-pixel[2])**2
for color in palette: #color[0]=R, color[1]=G, color[2]=B
distance = (color[0]-pixel[0])**2+(color[1]-pixel[1])**2+(color[2]-pixel[2])**2
if distance < minimum_distance:
minimum_distance = distance
closest_color = color
return closest_color
#converts the given image into pixelart
def pixelart(img, size, color_palette_src, fast=True):
#get the color palette
try:
print("Opening palette...")
color_file = open(color_palette_src, "r")
color_data = color_file.readlines()
palette = []
for color in color_data:
c = color.split(",")
palette.append((int(c[0]), int(c[1]), int(c[2])))
print("Successful!\n")
except Exception as e:
print("Failed!")
print("Error: " + str(e))
print("Image returned without modification.\n")
return img #return the image non-modified
img = img.convert('RGB') #convert the image to rgb
width, height = img.size #get dimensions
img = img.crop((0, 0, width - width % size, height - height % size)) #crop the image to fit the pixel size
width, height = img.size #get new dimensions
pixels = img.load() #get pixels
print("Processing pixels...")
if not fast:
for x in range(width):
for y in range(height):
pixels[x, y] = pixel_color(pixels[x, y], palette)
print("Progress: " + str(x + 1) + " / " + str(width), end="\r")
for x in range(0, width, size):
for y in range(0, height, size):
r, g, b = 0, 0, 0
for i in range(x, x+size):
for j in range(y, y+size):
r, g, b = r + pixels[i, j][0], g + pixels[i, j][1], b + pixels[i, j][2]
r, g, b = r/(size**2), g/(size**2), b/(size**2)
color = pixel_color((r, g, b), palette)
for i in range(x, x+size):
for j in range(y, y+size):
pixels[i, j] = color
print("Progress: " + str(x + 1) + " / " + str(width), end="\r")
print("Pixels processed!\n")
return img
def main():
#initial data
file_name = "test" #name of the image to be converted
file_format = "jpg" #format of the image to be converted
new_file_appendix = "_pixelart" #added to the name of the new file, leave as empty string if source file should be replaced
src = file_name + "." + file_format
pixel_size = 8 #how many pixels wide and high should a "pixel" be in the new image
color_palette_src = "palette_16" #name of the file containing color palette, each color should be on a new line, rgb values should be comma separated, no whitespace
#open the image
try:
print("Opening image...")
img = Image.open(src)
print("Successful!\n")
except Exception as e:
print("Failed!")
print("Error: " + str(e) + "\n")
print("Program will terminate.")
return #end the program
#process the image
try:
print("Converting...\n")
img = pixelart(img, pixel_size, color_palette_src)
print("Conversion successful!\n")
except Exception as e:
print("Conversion failed!")
print("Error: " + str(e) + "\n")
#save the image
try:
print("Saving image...")
new_src = file_name + new_file_appendix + "." + file_format
img.save(new_src)
print("Successful!\n")
except Exception as e:
print("Failed!")
print("Error: " + str(e) + "\n")
print("Program will terminate.")
return #end the program
main()
#end of program
|
x = int(input())
if x % 2 == 0:
print ('even')
else:
print ('odd') |
#Sum of Digits of a Number
# 112 -> 1+1+2=4
number = int(input("Input a Number : "))
sum=0
temp = number
for i in range(len(str(number))):
rem = number %10
sum += rem**3
number = number//10
if (temp == sum):
print("Number is Armstrong")
else:
print("Number is Not Armstrong")
#check wether number is Armstrong or Not
# 153 => 1^3+5^3+3^3 = 1 + 125+ 27 = 153 |
#Exception Handling
#Error
#-syntactical error
#-run time error
#-exception -> exception Handling
a = int(input("Enter number 1 :"))
b = int(input("Enter number 2 :"))
try:
#list1 = [1,2,3,4]
#print(list1[100])
p = a+b
print("sum=",p)
q = a-b
print("sub=",q)
r = a*b
print("mul=",r)
s = a/b
print("div=",s)
#except BaseException as be:
# print(be)
except ZeroDivisionError as a1:
print(a1)
except IndexError as a2:
print(a2)
finally :
print("Hello")
|
list1 = [5,6,0,3,9,1]
for i in range(len(list1)):
for j in range(0,len(list1)-i-1):
if list1[j] > list1[j+1]:
list1[j],list1[j+1] = list1[j+1],list1[j]
print(list1)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Size(object):
"""Class Size
"""
# Attributes:
def __init__(self, width=0, height=0):
r"""
@Arguments:
- `args`:
- `kwargs`:
@Construct
Size()
Size(width=100, height=100)
"""
self.width = width
self.height = height
# Operations
def get(self):
"""function get
@return: tuple(Width, Height)
"""
return (self.width, self.height)
def set(self, size):
"""function set
@return: None
set(Size())
"""
if isinstance(size, (tuple, list, Size)):
self.set_width(size[0])
self.set_height(size[1])
else:
# TODO: (Atami) [2015/02/17]
raise TypeError()
def get_width(self):
"""function get_width
returns Width
"""
return self.width
def set_width(self, width):
"""function set_width
width:
returns
"""
self.width = width
def del_width(self, ):
r"""SUMMARY
del_width()
@Return:
@Error:
"""
self.width = 0
def get_height(self):
"""function get_height
returns Height
"""
return self.height
def set_height(self, height):
"""function set_height
height:
returns
"""
self.height = height
def del_height(self, ):
r"""SUMMARY
del_height()
@Return:
@Error:
"""
self.height = 0
def __str__(self):
return str((int(self.width), int(self.height)))
def __repr__(self):
return ('{0.__class__.__name__}(width={0.width}, height={0.height})'
.format(self))
def __len__(self):
return len(self.get())
def __nonzero__(self):
return not (self.width == 0 and self.height == 0)
def __eq__(self, other):
return (self.width, self.height) == other
def __ne__(self, other):
return not self == other
# def __add__(self, other):
# if isinstance(other, (Width, )):
# return self.__class__(self.width + other, self.height)
# if isinstance(other, (Height, )):
# return self.__class__(self.width, self.height + other)
# if isinstance(other, (int, )):
# return self.__class__(self.width + other, self.height + other)
# return self.__class__(self.width + other[0], self.height + other[1])
# def __iadd__(self, other):
# size = self + other
# self.width = size.get_width()
# self.height = size.get_height()
# return self
# def __sub__(self, other):
# if isinstance(other, (Width, )):
# return self.__class__(self.width - other, self.height)
# if isinstance(other, (Height, )):
# return self.__class__(self.width, self.height - other)
# if isinstance(other, (int, )):
# return self.__class__(self.width - other, self.height - other)
# return self.__class__(self.width - other[0], self.height - other[1])
# def __isub__(self, other):
# size = self - other
# self.width = size.get_width()
# self.height = size.get_height()
# return self
# def __mul__(self, other):
# if isinstance(other, (Width, )):
# return self.__class__(self.width * other, self.height)
# if isinstance(other, (Height, )):
# return self.__class__(self.width, self.height * other)
# if isinstance(other, (int, )):
# return self.__class__(self.width * other, self.height * other)
# return self.__class__(self.width * other[0], self.height * other[1])
# def __imul__(self, other):
# size = self * other
# self.width = size.get_width()
# self.height = size.get_height()
# return self
# def __div__(self, other):
# if isinstance(other, (Width, )):
# return self.__class__(self.width / other, self.height)
# if isinstance(other, (Height, )):
# return self.__class__(self.width, self.height / other)
# if isinstance(other, (int, )):
# return self.__class__(self.width / other, self.height / other)
# return self.__class__(self.width / other[0], self.height / other[1])
# def __idiv__(self, other):
# size = self / other
# self.width = size.get_width()
# self.height = size.get_height()
# return self
def __iter__(self):
return iter(self.get())
def __getitem__(self, index):
return self.get()[index]
def __setitem__(self, index, val):
self[index].set(val)
def __delitem__(self, index):
if 0 == index:
self.width = 0
elif 1 == index:
self.height = 0
else:
raise TypeError()
# def __del__(self):
# self.width, self.height = 0, 0
# For Emacs
# Local Variables:
# coding: utf-8
# End:
# size.py ends here
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.