text stringlengths 37 1.41M |
|---|
#My calculator calculates how far one can run using three inputs
print("Filler")
SPEED = int(input("What is your average speed (MPH) during (excluding break time) the run? "))
RUNTIME = int(input("How long (in MINTUES) will your ENTIRE run (including break time) be? "))
BREAKTIME = int(input("How long will your break be? "))
Final_Distance = ((RUNTIME - BREAKTIME)/60)*SPEED
print (F"Your computed running distance is {Final_Distance} miles!")
|
# გვაქვს n სართულიანი კიბე, ერთ მოქმედებაში შეგვიძლია ავიდეთ 1 ან 2 საფეხურით.
# დაწერეთ ფუნქცია რომელიც დაითვლის n სართულზე ასვლის ვარიანტების რაოდენობას.
#4
def stair_options(n):
if n == 1 or n == 0:
return 1
elif n == 2:
return 2
else:
return stair_options(n - 2) + stair_options(n - 1)
|
#!/bin/python3
import datetime
class FridayFinder:
def __init__(self, date):
self.__date = date
def get_days_to_friday(self):
weekday = self.__date.weekday()
return (4 - weekday) % 7
def get_next_friday(self):
days_to_friday = self.get_days_to_friday()
return self.__date + datetime.timedelta(days=days_to_friday)
def find_next_friday_13th(self):
friday = self.get_next_friday()
while friday.day != 13:
friday += datetime.timedelta(weeks=1)
return friday
if __name__ == "__main__":
today = datetime.date.today()
finder = FridayFinder(today)
friday = finder.get_next_friday()
friday_13th = finder.find_next_friday_13th()
print("Next friday will be at: " + str(friday))
print("Next friday the 13th will be at: " + str(friday_13th))
|
#=========================================================================
# SikkemaTHW3.py
# Tyler Sikkema
# Created June 4, 2016
# Last updated 6/8/2016
# Abstract: Used for calculating total pay
#=========================================================================
global HOURLY_PAY_RATE
global COMMISSION_RATE
global WITHHOLDING_RATE
HOURLY_PAY_RATE = 7.5
COMMISSION_RATE = 0.05
WITHHOLDING_RATE = 0.25
def Main():
DisplayMessage()
name = input('Enter employee name: ')
sales = input('Enter sales amount: ')
hours = input('Enter hours: ')
hourlyPay = float(hours)*HOURLY_PAY_RATE
commission=float(sales)*COMMISSION_RATE
grossPay=hourlyPay+commission
withholding=grossPay * WITHHOLDING_RATE
netPay = grossPay - withholding
DisplayResults(hourlyPay,commission,grossPay,withholding,netPay)
def DisplayMessage():
print('This program calculates the salesperson\'s pay\n'\
'Five values are dislpayed:\n'\
'hourly pay, comission, gross pay, withholding, and net pay\n\n')
def DisplayResults(hourlyAmount,commissionAmount,grossAmount,withholdingAmount,netAmount):
print('RESULTS:\n'\
'Hourly Pay:\t\t{}\n'\
'Commission:\t\t{}\n'\
'Gross Pay:\t\t{}\n'\
'Withholding Amount:\t{}\n'\
'Net Pay:\t\t{}\n'.format(hourlyAmount,commissionAmount,grossAmount,withholdingAmount,netAmount))
Main()
input('Press ENTER to continue...')
|
pt1 = [(50, 0), (170, 180), (210, 250)]
pt2 = [(50, 0), (170, 170), (210, 250)]
union = set(pt1) | set(pt2)
intersection = set(pt1) & set(pt2)
difference = set(pt1) - set(pt2)
print(union)
print(intersection)
print(difference) |
lista = [1,2,3,4,5,6,7,8,9,10]
print("Lista: ",lista)
lista.reverse()
print("Lista Invertida: ",lista) |
import pyglet
def center_image(image):
"""Sets an image's anchor point to its center"""
image.anchor_x = image.width / 2
image.anchor_y = image.height / 2
# Tell pyglet where to find the resources
pyglet.resource.path = ['./resources']
pyglet.resource.reindex()
# Load the three main resources and get them to draw centered
player_image = pyglet.resource.image("cat.png")
center_image(player_image)
monster_image = pyglet.resource.image("monster.png")
center_image(monster_image)
goblin_image = pyglet.resource.image("goblin.png")
center_image(goblin_image)
background = pyglet.resource.image('background.png')
life_image = pyglet.resource.image("fishy.png")
center_image(life_image)
# asteroid_image = pyglet.resource.image("asteroid.png")
# center_image(asteroid_image)
# The engine flame should not be centered on the ship. Rather, it should be shown
# behind it. To achieve this effect, we just set the anchor point outside the
# # image bounds.
# engine_image = pyglet.resource.image("engine_flame.png")
# engine_image.anchor_x = engine_image.width * 1.5
# engine_image.anchor_y = engine_image.height / 2
|
import sys
for line in open(sys.argv[1], 'r').readlines():
s = line
def reverse(st):
rev = ""
for p in st:
rev = p + rev
return rev
n = len(s)
r = reverse(s)
def findPal(s, r, n):
m = [0] * (n+1)
for a in range(n+1):
m[a] = [0] * (n+1)
root = [0] * (n+1)
for a in range(n+1):
root[a] = [0] * (n+1)
for i in range(1, n+1):
for j in range(1, n+1):
if s[i-1] == r[j-1]:
m[i][j] = (m[i-1][j-1] + 1)
root[i][j] = '`'
else:
if m[i-1][j] >= m[i][j-1]:
m[i][j] = m[i-1][j]
root[i][j] = '^'
else:
m[i][j] = m[i][j-1]
root[i][j] = '-'
e = ""
a = b = n
while a != 0 and b != 0:
if root[a][b] == '`':
e += s[a-1]
a -= 1
b -= 1
elif root[a][b] == '^':
a -= 1
else:
b -= 1
return e
e = findPal(s, r, n)
print("Length: " + str(len(e)))
print("Sequence: " + e)
|
import matplotlib
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def lecture():
df = pd.read_csv('russian_housing.csv')
df.head()
# Size of dataset
print("Number of rows/columns: ", df.shape)
print("Data types: ", df.dtypes)
# Select the numeric columns
df_numeric = df.select_dtypes(include=[np.number])
numeric_cols = df_numeric.columns.values
print("Numeric columns: ", numeric_cols)
# Select the non numeric columns
df_non_numeric = df.select_dtypes(exclude=[np.number])
non_numeric_cols = df_non_numeric.columns.values
print("Non-numeric columns: ", non_numeric_cols)
matplotlib.rcParams['figure.figsize'] = (12, 8)
# Technique 1: Missing Data Heatmap
cols = df.columns[:30] # First 30 columns
colors = ['#000099', '#ffff00'] # Specify the colors - yellow is missing
sns.heatmap(df[cols].isnull(), cmap=sns.color_palette(colors))
# plt.show()
# Technique 2: Missing Data percentage list
missing_data = [(col, round(np.mean(df[col].isnull())*100)) for col in df.columns]
missing_data = sorted(missing_data, key=lambda x: x[1], reverse=True)
for data in missing_data:
if (data[1] == 0):
break
print('{} - {}%'.format(data[0], data[1]))
# Technique 3:
# first create missing indicator for features with missing data
for col in df.columns:
missing = df[col].isnull()
num_missing = np.sum(missing)
if num_missing > 0:
df['{}_ismissing'.format(col)] = missing
# then bassed on the indicator, plot the histogram of missing values
ismissing_cols = [col for col in df.columns if 'ismissing' in col]
df['num_missing'] = df[ismissing_cols].sum(axis=1)
df['num_missing'].value_counts().reset_index().sort_values(by='index').plot.bar(x='index', y='num_missing')
plt.show()
# drop rows with a lot of missing values
ind_missing = df[df['num_missing'] > 35].index
df_less_missing_rows = df.drop(ind_missing, axis=0)
|
class Account:
#Input: account number, amount initally in account, account name, dictionary of all accounts
#Output: account object
#Description: creates an account object which has an account number, amount in it, account name,
#and adds it to the account dict
def __init__(self, account, amount, name, accountDict):
self.isCreated = True
if accountDict.has_key(account):
self.isCreated = False
elif amount < 0:
self.isCreated = False
else:
self.account = account
self.amount = amount
self.name = name
accountDict[account] = self
#Input: amount to withdraw
#Output: nothing
#Description: reduces the ammount of money in this account
def withdrawMoney(self, amount) :
if amount < 0:
return False
if self.amount - int(amount) < 0:
return False
self.amount -= int(amount)
return True
#Input: amount to deposit
#Output: nothing
#Description: increases the amount of money in this account
def depositMoney(self, amount):
if self.amount + int(amount) > 99999999:
return False
self.amount += int(amount)
return True
#Input: amount to transfer, the other account to put the money in
#Output: nothing
#Description: withdraws specified amount from this account,
#deposits money of specified ammount in other account
def transfer(self, amount, toAccount):
if self.withdrawMoney(amount):
if toAccount.depositMoney(amount):
return True
else:
self.depositMoney(amount)
return False
#Input: Name of account
#Output: Boolean representing whether this account can be deleted
#Description: only returns true if this account has no money and its name matches
def canDeleteAccount(self, name) :
if self.amount != 0:
return False
if self.name != name:
return False
return True
|
from Account import Account
import os.path
import pdb
#Nicholas Petrielli 10107308
#Andrew Storus 10103737
#Jordan McGregor 10052770
#The intention of this program is to implement a backend of a banking system.
#The backend reads in the input files given which are a merged transaction summary file and a master account list.
#After setting up all of the accounts in the master account list file all of the transactions from the merged transaction summary file are applied
#Upon completion the program outputs a new updated master account list file, as well as a valid account list file.
#The program is intended to be ran with the master account list file as well as the merged transaction summary file to be in the same
#directory as the python file. The accounts should be named MasterAccountList.txt and MergedTransactionSummaryFile.txt to
#represent the master account list and the merged transaction summary file respectively.
class BackEnd:
#Input: None
#Output: The Backend Object
#Description: Reads in the Master Account List and Merged Transaction Summary File
#Into a dictionary containing account objects
def __init__(self):
self.accountIdx = 0
self.amountIdx = 1
self.nameIdx = 2
self.transactionIdx = 0
self.accountToIdx = 1
self.accountFromIdx = 2
self.amountDataIdx = 3
self.nameDataIdx = 4
self.masterAccountListName = "MasterAccountList.txt"
self.mergedTransactionSummaryFileName = "MergedTransactionSummaryFile.txt"
self.validAccountsFile = "ValidAccounts.txt"
self.accountDict = self.readAccountDictFromFile()
#Input: Old Master Account List File
#Output: Dictionary of account objects indexed by account number
#Description: Parses the master account list file into a dictionary
def readAccountDictFromFile(self):
accountDict = dict()
if os.path.exists(self.masterAccountListName):
masterAccountListFile = open(self.masterAccountListName, 'r')
for line in masterAccountListFile.readlines():
lineData = line.split()
if len(lineData) == 0:
break;
account = lineData[self.accountIdx]
amount = int(lineData[self.amountIdx])
name = lineData[self.nameIdx]
wasCreated = Account(account, amount, name, accountDict).isCreated
masterAccountListFile.close()
return accountDict
#Input: Dictionary of all accounts
#Output: New Master Account List File
#Description: Formats all the accounts at the end of a backend session into a text file
def writeAccountsFiles(self):
masterAccountList = []
for key in self.accountDict:
masterAccountList.append(self.accountDict[key])
masterAccountList = sorted(masterAccountList, key=lambda x: x.account)
masterAccountListFile = open(self.masterAccountListName, 'w+')
validAccountsListFile = open(self.validAccountsFile, 'w+')
for account in masterAccountList:
masterLineToWrite = str(account.account) + " " + str(account.amount) + " " + str(account.name) + "\n"
masterAccountListFile.writelines(masterLineToWrite)
validLineToWrite = str(account.account) + "\n"
validAccountsListFile.writelines(validLineToWrite)
masterAccountListFile.close()
validAccountsListFile.writelines("00000000")
validAccountsListFile.close()
#Input: Merged Transaction Summary File
#Output: None
#Description: Reads Merged Transaction Summary File, updates the accounts dictionary
#based on the contents of the transaction summary file
def readMergedFile(self):
transactionSummaryFile = open(self.mergedTransactionSummaryFileName)
transactionSummaryFileData = transactionSummaryFile.readlines()
idx = 0
while idx < len(transactionSummaryFileData):
lineData = transactionSummaryFileData[idx].split()
if len(lineData) == 5:
self.transactionCodeChooser(lineData)
idx += 1
if len(transactionSummaryFileData) == 0:
return
if transactionSummaryFileData[-1].split()[0] == "ES":
self.writeAccountsFiles()
else:
print "The merged transaction summary file is invalid"
#Input: Parsed line from merged transaction summary file
#Output: Updated accounts Dictionary
#Description: Based on the contents of the merged transaction summary file line,
#update the accounts dict to reflect the command
def transactionCodeChooser(self, lineData):
transactionCode = lineData[self.transactionIdx]
accountTo = lineData[self.accountToIdx]
accountFrom = lineData[self.accountFromIdx]
amount = lineData[self.amountDataIdx]
name = lineData[self.nameDataIdx]
if self.accountDict.has_key(accountTo):
if transactionCode == "DL":
if self.accountDict[accountTo].canDeleteAccount(name):
del self.accountDict[accountTo]
else:
print "Incorrect name or account does not exist"
elif transactionCode == "TR":
if self.accountDict.has_key(accountFrom):
if not self.accountDict[accountTo].transfer(amount, self.accountDict[accountFrom]):
print "Error Transferring"
else:
print "Error Transferring"
elif transactionCode == "WD":
if not self.accountDict[accountTo].withdrawMoney(amount):
print "Withdraw error"
elif transactionCode == "DE":
if not self.accountDict[accountTo].depositMoney(amount):
print "Deposit error"
else:
if transactionCode == "CR":
wasCreated = Account(accountTo, amount, name, self.accountDict).isCreated
backEnd = BackEnd()
backEnd.readMergedFile()
|
# Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
# (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
# Find the minimum element.
# You may assume no duplicate exists in the array.
import sys
def find_minimum(sorted_arr):
min = sorted_arr[0]
for ele in sorted_arr:
if ele < min:
min = ele
break
return min
def find_minimum_recursive(sorted_arr):
pivot = int(len(sorted_arr) / 2)
print(sorted_arr, pivot)
if sorted_arr[pivot] > sorted_arr[pivot + 1]:
return sorted_arr[pivot + 1]
elif sorted_arr[0] > sorted_arr[pivot]:
return find_minimum_recursive(sorted_arr[0:pivot + 1])
else:
return find_minimum_recursive(sorted_arr[pivot + 1:])
def main():
if len(sys.argv) != 2:
raise Exception("Input rotated sorted array as '3,4,5,1,2'")
print(find_minimum_recursive(sys.argv[1].split(",")))
if __name__ == "__main__":
try:
sys.exit(main())
except Exception as e:
print(e)
sys.exit(1)
|
# #Entrada de datos
# numero1 = 10
# numero2 = 15
# # Calculos y/o Operaciones
# suma = numero1 + numero2
# # Salida de datos
# print("Suma = " + str(suma))
# print(f"Suma = {suma}")
# se debe configurahdr
# numero3 =float(input("Escribe un numero: "))
numero3 =int(input("Escribe un numero: "))
numero4 = input("Escribe otro numero: ")
numero4 = int(numero4)
suma = numero3 + numero4
print("Suma = " + str(suma)) |
#!/usr/bin/python
#-*- coding: utf-8 -*-
#author=moc
#Use Babyloninan (aka simplified Newton's) to solve square root
from math import log10
from math import ceil
from math import floor
from math import sqrt
number=70000
num_digit=int(ceil(log10(number)))
print num_digit
#determine the start point, reduce calculation time
start=int(10**floor(num_digit/2))
#Babylonian algorithm
for i in range(0,num_digit):
print start
start=(start+number/start)/2
#compare to the original
print sqrt(number) |
import time
up = True
n = 0
i = 50
while True:
if up:
n += 1
if n == i:
up = False
if not up:
n -= 1
if n == 0:
up = True
print("#" * n)
time.sleep(0.01)
|
print("Hello")
print("World")
print("maar")
print("dan")
print("nu")
print("verdeeld")
print("over")
print("meerdere")
print("regels")
tekst = "hello world maar dan nu over meerdere regels"
tekst_los = tekst.split(" ")
for regel in tekst_los:
print(tekst_los)
'''
maak dit makkelijker zodat je slechts 1 keer print() gebruikt
maak gebruik van split() en een for-loop ...
''' |
"""
You have 6 sticks of lengths 10, 20, 30, 40, 50, and 60 centimeters. Find the number of non-congruent
triangles that can be formed by using three of these sticks as sides
"""
# The length of any side of a triangle must be larger
# than the positive difference of the
# other two sides, but smaller than the sum of
# the other two sides.
"""
idizi1=[10,20,30,40,50,60]
dizi2=[10,20,30,40,50,60]
dizi3=[10,20,30,40,50,60]
a=0
b=1
c=2
for i in range(6):
x=dizi1[a]
y=dizi2[b]
z=dizi3[c]
if b==6:
a+=1
b=0
if c==6:
b+=1
c=0
print (x,y,z)
""" |
''' This is proposed as a semplificate example of Object oriented programming in python'''
#Definition of super class who define the properties of an account
class Account:
#Class Initialization
def __init__(self, name, accountNumber):
self.name = name
self.accountNumber = accountNumber
#Definition of class who implement the super class
class BankAccount(Account):
#Class Initialization
def __init__(self, name,accountNumber,amount):
super().__init__(name, accountNumber)
self.__balance = amount
#method that allow to withdraw the money
def withdraw(self, amount):
self.__balance -= amount
#Method that allow to deposit money
def deposit(self, amount):
self.__balance += amount
#Method that stamp a description
def description(self):
print('Name: ' + self.name,
'Account: ' + self.accountNumber,
'Balance: ' + str(self.__balance))
#Getter and setter
@property
def balance(self):
return self.__balance
@balance.setter
def balance(self, amount):
self.withdraw(self.__balance)
self.deposit(amount)
#Class that allow to do some bank operation
class BankAccountManager:
@staticmethod
def bankTransfer(source, recipient, amount):
source.withdraw(amount)
recipient.deposit(amount)
#Test
b1 = BankAccount('Pippo', '08990', 1000)
b2 = BankAccount('Pino', '07790', 2000)
b1.description()
b2.description()
BankAccountManager.bankTransfer(b1,b2, 500)
b1.description()
b2.description()
|
class Hero:
def __init__(self, name, health, attack, armor):
self.name = name
self.health = health
self.attack = attack
self.armor = armor
def serang(self, lawan):
print(self.name + ' menyerang ' + lawan.name)
lawan.diserang(self, self.attack)
def diserang(self, lawan, attack_lawan):
print(self.name + ' diserang ' + lawan.name)
attack_diterima = attack_lawan/self.armor
print('serangan terasa ' + str(attack_diterima))
self.health -= attack_diterima
print("Darah " + self.name + " tersisa " + str(self.health))
sniper = Hero('sniper', 100, 10, 5)
rikimaru = Hero('rikimaru', 100, 20, 10)
sniper.serang(rikimaru)
print('\n')
rikimaru.serang(sniper)
|
#ARRAY & List
#Memory allocation is static/fixed
#List()
#Datatype is heterogeneous
#Memory Allocation is dynamic
n=5
groclist=[]
print(type(groclist))
#<class 'list'>
i=1
while i<=5:
elem = input("Enter grocery elements : ")
groclist.append(elem)
i+=1
#list can have heterogeneous data
#But since it PY3.7 we have to explicitly define the datatype
groclist.append(123)
#groclist[10]="Kuldeep"
#above be "IndexError: list assignment index out of range"
print("\nGrocery list as per input ")
print(groclist)
groclist[3] = "Wheat"
print("\n Changing 3rd value to Wheat: ")
print(groclist)
#Remove any item from the list
toremove = input("\nInput which item to remove : ")
if(toremove in groclist):
groclist.remove(toremove)
else:
print("\n",toremove," doest exist in the list ")
print("\nGrocery list after removing a value ")
print(groclist)
#If any value given out of list will throw an error.
#groclist.remove(toremove)
#ValueError: list.remove(x): x not in list
i=0
for item in groclist:
#print (item)
if(item == 'Wheat'):
groclist[i] = 'Rice'
i+=1
print("\nGrocery list after all operations ")
print(groclist)
#to find the index of a value
# groclist.indexof("Rice")
|
#Program 2
#Matrimony eligibility
#Enter Name
#Enter Gender
#Enter Year of Birth (Date of Birth ( Year of Birth ) find out Age)
import datetime
name=input("Enter Name : ")
gender=input("Enter Gender (M/F) : ")
c=input("Enter Year of Birth: ")
yr=int(c)
#curr=now.year
curr=2019
if(gender == "M"):
if((curr-yr) >= 21):
print(name + " is eligible for marriage")
else:
print(name + " is NOT eligible for marriage")
elif(gender == "F"):
if((curr-yr) >= 18):
print(name + " is eligible for marriage")
else:
print(name + " is eligible NOT for marriage")
else:
print("Invalid Input");
|
class CarBase:
def __init__(self, brand, speed, tires):
self.brand = brand
self.speed = speed
self.tires = tires
def __str__(self):
return f"'{self.brand}' mooves using {self.tires} with {self.speed} km/h."
class Car(CarBase):
def __init__(self, brand, speed, tires, seats_count):
super().__init__(brand, speed, tires)
self.seats_count = seats_count
def __str__(self):
main_str = super().__str__()
nem_str = f"The car {main_str}\nThe passenger seat count = {self.seats_count}"
return nem_str
class Truck(CarBase):
def __init__(self, brand, speed, tires, сargo_volume):
super().__init__(brand, speed, tires)
self.сargo_volume = float(сargo_volume)
def __str__(self):
main_str = super().__str__()
nem_str = f"The truck {main_str}\nThe сargo volume = {self.сargo_volume} ton / tons"
return nem_str
print("-" * 45)
seat = Car("Seat", 100, "winter tires", 5)
print(seat)
print("-" * 45)
man = Truck("Man", 70, "winter tires", 1.5)
print(man)
print("-" * 45)
|
for i in range(1, 101):
num = ""
if i % 3 == 0:
num += "Fizz"
if i % 5 == 0:
num += "Buzz"
print(num or i)
|
import time
def timer(num):
def decor_func(func):
def wrapper():
full_run_time = 0
result = 0
for _ in range(num):
start_time = time.perf_counter()
value = func()
end_time = time.perf_counter()
run_time = end_time - start_time
full_run_time += run_time
result = value
print(f"Function took {run_time: .6f} seconds to complete.")
print(f"Total time = {full_run_time: .6f}\nFunction {func.__name__!r}")
print(f"Last result = {result}")
return result
return wrapper
return decor_func
@timer(10)
def waste_time():
total = 0
for i in range(10000):
total += 1
return total
time_result = waste_time()
|
"""
This file contains the logic of the program
This file has the main functions
1.) load_cencus_data
2.) filter_data_by_colom and floor
This file also imports few modules namely
1.) os
2.) sys
3.) helper - self designed to help with the program
4.) csv - to read csv file
"""
""""""""""" Imports """""""""
import os
import sys
import helper
import csv
# this variable would store headings (the coloms of the csv file)
headings = ()
# declared this as a global variable
# in capital becuase value remains constant to differentiate
DEBUG = False
"""
This function loads the data from the csv file into the memory
It validates the rows and then loads them on the memory
:param: path -> The path to the csv file
:return: a tuple of valid data
"""
def load_cencus_data(path="./file.csv"):
try:
if(os.path.isfile(path) == False):
# this checks if the path provided to the file exists
print("Please provide with a correct file path. You can provide the file path as an argument when running the program EG python driver.py <path to file> ")
sys.exit(1)
global headings
global DEBUG # this checks if DEBUG mode is turned on
validated_rows = [] # list of validated rows
# open the file to read
with open(path, "r") as file:
reader = csv.DictReader(file)
# populate the global headings
# save it in the form of tupleas and not list
headings = tuple(reader.fieldnames)
for row in reader:
# check if the row is valid and append the validated row to list
result = helper.validate_row_data(row, headings)
if result:
# only add if the result is not false
validated_rows.append(result)
elif DEBUG:
# this is for debugging and would not run in the final version
not_validated_rows.append(row)
# make sure that the file is getting closed
# only in Debug mode
if DEBUG:
assert file.closed, "The file was not closed automatically "
return tuple(validated_rows)
except AttributeError as e:
print(str(e))
print("An attribute Error orrucered trying again")
except Exception as e:
print("An unknown error has occured ")
print("Please rerun the program")
"""
This function gets an input from the user and validates it
If the user enters input incorrectly thrice it quits
:param: input_for -> This is used to differentiate what the function is being called for
1 -> user input for colum based on ennumeration
2 -> user input for floor value
:return: The integer value of the user input
"""
def get_user_input(input_for):
try:
global DEBUG
if input_for == 1:
global headings
temp = enumerate(headings)
for enum in temp:
print("{}) {}".format((enum[0] + 1), enum[1]))
#helper function takes care of the checking
value = helper.get_user_data(question="Please enter an integer based on one of the ennumeration EG 1 for Zip Code: ",
validate_func = helper.validate_user_input,
alert = "Please enter a valid number betweeen 1 and 7",
counter = 0)
# Just a design desion we dont ask the user to enter value from 0
# but start from 1 and we adjust it here
value = value - 1
elif input_for == 2:
value = helper.get_user_data(question="Please enter a floor value: ",
validate_func = helper.validate_floor_value,
alert="Please enter a valid floor value",
counter = 0)
return value
except Exception as e:
print(str(e))
print("An error occured please re-enter a valid value")
sys.exit(1)
"""
This function creates a new list from the data based on the colum and the floor_value
NOTE - This function removes the reduandant step of first returning the rows
and then then filtering through the rows for the colum.
This function straight away returns the colum and value tuple
filtered based on the users input
:param: data -> Validated tuple of data from csv file
:param: colum_name -> The colum to filter data by
:param: floor_value -> The value to check if value greater than or equal to
:return: tuple of the new list created
"""
def filter_data_by_colum_and_floor(data, colum_name, floor_value):
try:
# get the name of the heading based on the int value
global headings
if len(headings) == 0:
load_cencus_data()
colum_name = helper.get_colum_name(headings, colum_name)
#loop through the validated data
filtered_data = []
for row in data:
for k,v in row.items():
if k == colum_name and row[colum_name] >= floor_value:
filtered_data.append(row)
if len(filtered_data):
return tuple(filtered_data)
else:
return False
except Exception as e:
print("A proble occured while running the program")
print(str(e))
"""
This function gets the only colum required based on the colum entered by the user
:param: data -> The filtered data which has all the values in the dict
:param: colum_name -> The int value of the column to get
:return: dictionary with the colum required
"""
def get_data_by_colum(data, colum_name):
try:
# get the name of the heading based on the int value
global headings
if len(headings) == 0:
load_cencus_data()
colum_name = helper.get_colum_name(headings, colum_name)
filtered_list = []
for row in data:
for k, v in row.items():
if k == colum_name:
filtered_list.append({k: v})
if len(filtered_list):
return tuple(filtered_list)
else:
return False
except Exception as e:
print("Problem in the get_data_by_colum function")
print(str(e))
"""
This function sorts the filtered data
:param: data -> The data to sort
:param: colum_name -> the colum to solve by (int value)
:return: sorted data
"""
def sord_filtered_data(data, colum_name):
try:
global headings
if len(data):
# just make sure that the data recieved is not empty
colum_name = helper.get_colum_name(headings, colum_name)
return sorted(data, key=lambda x: x[colum_name])
except Exception as e:
print(str(e))
"""
This is the function that deals with writing filtered, sorted data to a file
Saves the file in a folder called exports
Uses helper method get_file_name_and_make_path
:param: data -> The filtered and the sorted tuple of the dictionaries with a particular column.
"""
def write_to_csv(data):
try:
# we create a constant DIR capital letters just to differentiate that its value would not change
DIR = 'exports'
if os.path.isdir(DIR) is False:
os.mkdir(DIR)
path = os.path.join(os.getcwd(), DIR)
# get the file name and check if it doesnot already exists
fname = helper.get_file_name_and_make_path(path)
path = os.path.join(path, fname)
# get fieldname so that we donot have to hardcode it
for key in data[0].keys():
fields = [key]
# open a file and WRITE to it
with open(path, 'w') as file:
writer = csv.DictWriter(file, fieldnames=fields)
writer.writeheader()
for row in data:
writer.writerow(row)
#returns true after the program has finished
return True
except Exception as e:
print(str(e))
|
def convertWords(words):
result = ""
for i in range(0, len(words), 2):
result += (words[i] + "\t" + words[i+1] + "\n")
return result
## Raw text conversion
def convertFromConsole():
print("Enter/Paste your words (press Ctrl-D or Ctrl-Z on Windows when finished):")
words = []
while True:
try:
words.append(input())
except EOFError:
break
print(convertWords(words))
# File based conversion
def convertFromFile():
print("Enter file name:")
filename = input()
f = open(filename, "r+", encoding="utf8")
words = f.read().split("\n")
f.write("\n" + convertWords(words))
f.close()
print("Press 1 if you want to convert words from a file:")
convertFromFile() if input() == "1" else convertFromConsole()
print("Conversion finished") |
# coding = utf -8
import threading
def sum(a):
print(a+2)
threads = []
for i in range(3):
#print(i)
t = threading.Thread(target=sum,args=(i,))
threads.append(t)
for j in threads:
j.start()
|
from tkinter import *
root = Tk()
root.title("Simple Calculator")
e = Entry(root, width=50, borderwidth=10)
e.grid(row=0, column=0, columnspan=3) #padx=10, pady=10)
def button_click(number):
current = e.get()
e.delete(0, END)
e.insert(0, str(current) + str(number))
def button_add():
first_num = e.get()
global f_num
global math
math = "addition"
f_num = float(first_num)
e.delete(0, END)
def button_clear():
e.delete(0, END)
def button_equal():
second_num = e.get()
e.delete(0, END)
if math == "addition":
e.insert(0, f_num + float(second_num))
if math == "subtraction":
e.insert(0, f_num - float(second_num))
if math == "multiplication":
e.insert(0, f_num * float(second_num))
if math == "division":
e.insert(0, f_num / float(second_num))
if math == "remainder":
e.insert(0, f_num % float(second_num))
def button_multiply():
first_num = e.get()
global f_num
global math
math = "multiplication"
f_num = float(first_num)
e.delete(0, END)
def button_subtract():
first_num = e.get()
global f_num
global math
math = "subtraction"
f_num = float(first_num)
e.delete(0, END)
def button_divide():
first_num = e.get()
global f_num
global math
math = "division"
f_num = float(first_num)
e.delete(0, END)
def button_remainder():
first_num = e.get()
global f_num
global math
math = "remainder"
f_num = float(first_num)
e.delete(0, END)
button_1 = Button(root, text="1", font=("Century Gothic",10,"bold"), padx=30, pady=20, command=lambda: button_click(1))
button_2 = Button(root, text="2", font=("Century Gothic",10,"bold"), padx=30, pady=20, command=lambda: button_click(2))
button_3 = Button(root, text="3", font=("Century Gothic",10,"bold"), padx=30, pady=20, command=lambda: button_click(3))
button_4 = Button(root, text="4", font=("Century Gothic",10,"bold"), padx=30, pady=20, command=lambda: button_click(4))
button_5 = Button(root, text="5", font=("Century Gothic",10,"bold"), padx=30, pady=20, command=lambda: button_click(5))
button_6 = Button(root, text="6", font=("Century Gothic",10,"bold"), padx=30, pady=20, command=lambda: button_click(6))
button_7 = Button(root, text="7", font=("Century Gothic",10,"bold"), padx=30, pady=20, command=lambda: button_click(7))
button_8 = Button(root, text="8", font=("Century Gothic",10,"bold"), padx=30, pady=20, command=lambda: button_click(8))
button_9 = Button(root, text="9", font=("Century Gothic",10,"bold"), padx=30, pady=20, command=lambda: button_click(9))
button_0 = Button(root, text="0", font=("Century Gothic",10,"bold"), padx=30, pady=20, command=lambda: button_click(0))
button_dot = Button(root, text=".", font=("Century Gothic",10,"bold"), padx=30, pady=20, command=lambda: button_click("."))
button_add = Button(root, text="+", font=("Century Gothic",10,"bold"), padx=30, pady=20, command=button_add)
button_clear = Button(root, text="Clear", font=("Century Gothic",10,"bold"), padx=60, pady=20, command=button_clear)
button_equal = Button(root, text="=", font=("Century Gothic",10,"bold"), padx=30, pady=20, command=button_equal)
button_subtract = Button(root, text="-", font=("Century Gothic",10,"bold"), padx=30, pady=20, command=button_subtract)
button_multiply = Button(root, text="*", font=("Century Gothic",10,"bold"), padx=30, pady=20, command=button_multiply)
button_divide = Button(root, text="/", font=("Century Gothic",10,"bold"), padx=30, pady=20, command=button_divide)
button_perc = Button(root, text="%", font=("Century Gothic",10,"bold"), padx=30, pady=20, command=button_remainder)
button_9.grid(row=1, column=2)
button_8.grid(row=1, column=1)
button_7.grid(row=1, column=0)
button_6.grid(row=2, column=2)
button_5.grid(row=2, column=1)
button_4.grid(row=2, column=0)
button_3.grid(row=3, column=2)
button_2.grid(row=3, column=1)
button_1.grid(row=3, column=0)
button_0.grid(row=4, column=0)
button_add.grid(row=5, column=0)
button_clear.grid(row=6, column=1)
button_equal.grid(row=4, column=2)
button_subtract.grid(row=5, column=1)
button_multiply.grid(row=5, column=2)
button_divide.grid(row=6, column=0)
button_dot.grid(row=4, column=1)
button_perc.grid(row=6, column=2)
myLabel = Label(root, text="copyright@ UDAY. LOL").grid(row=7, column=1)
root.mainloop()
|
import re
usr_inpt=str(input("Enter String: "))
srch_exp=re.findall("Inform.",usr_inpt)
print(srch_exp)
#############################################################
import re
usr_inpt=str(input("Enter String: "))
srch_exp=re.findall("Inform",usr_inpt)
for i in srch_exp:
print(i)
#############################################################
Regular Expression
import re
strn=input("Enter String: ")
if regex is re.findall("\w{0,6}.\w{0,6}@\w{0,6}.\w{0,3}",strn):
print("Valid Email")
print(regex)
else:
print("Invalid")
|
# nomber1 = int(input("Введите первое число"))
# nomber2 = int(input("Введите второе число"))
# nomber3 = int(input("Введите третье число"))
# print(nomber1 + nomber2 * nomber3)
# texst1 = input("Введите первое число")
# texst2 = input("Введите второе число")
# print(texst1 + "+" + texst2 + "= дружба на века")
|
a = ""
a = "Переправа, переправа, берег левый, берег, правыыый"
# print(a)
# print(a[1])
# print(a[-2])
# print(a[:9])
# print(a[28:34])
# print(a[35:])
# print(a[-12:-1])
print(a[::5])
print(a[:9:3])
print(len(a))
print(a.upper())
print(a.lower())
print(a.title())
print(a.count("берег"))
print(a.find("берег"))
print(a.rfind("берег"))
print(a.lower().count("переправа"))
print(a.replace("берег","крекер"))
print(a[::-1]) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
class operacion:
def __init__(self):
print "-----Bienvenido al juego 2048-----"
def iniciarJuego(self):
import random
global n
n = 4
global matriz
matriz = [[0] * n for f in range(n)]
for f in range(n):
for c in range(n):
num=random.randint(0, 2)
matriz[f][c] = num * 2
def imprimir(self):
for fila in matriz:
print(' '.join([str(elem) for elem in fila]))
def izquierda(self):
for f in range(n):
for c in range(n):
if(c < 3):
if (matriz[f][c] == 2048):
pass
else:
if (matriz[f][c] == matriz[f][c+1]):
matriz[f][c] = matriz[f][c] + matriz[f][c+1]
globals()["matriz"][f][c+1] = 0
def derecha(self):
for f in range(n):
for c in range(3,0,-1):
if(c > 0):
if (matriz[f][c] == 2048):
pass
else:
if (matriz[f][c] == matriz[f][c-1]):
matriz[f][c] = matriz [f][c] + matriz[f][c-1]
globals()["matriz"][f][c-1] = 0
def arriba(self):
for f in range(n):
for c in range(n):
if (f < 3):
if (matriz[f][c] == 2048):
pass
else:
if (matriz[f][c] == matriz[f+1][c]):
matriz[f][c] = matriz[f][c] + matriz[f+1][c]
globals()["matriz"][f+1][c] = 0
def abajo(self):
for f in range(3,0,-1):
for c in range(n):
if (f > 0):
if (matriz[f][c] == 2048):
pass
else:
if (matriz[f][c] == matriz[f-1][c]):
matriz[f][c] = matriz[f][c] + matriz[f-1][c]
globals()["matriz"][f-1][c] = 0
def acomodArriba(self):
f = 4
while f> 0:
f -= 1
for c in range(n):
if(f > 0):
if (matriz[f][c] > 0 and matriz[f-1][c]==0):
globals()["matriz"][f-1][c] = matriz[f][c]
globals()["matriz"][f][c] = 0
c=4
f=4
break
def acomodAbajo(self):
f=-1
while f < 4:
f+=1
for c in range(n):
if(f < 3):
if (matriz[f][c] > 0 and matriz[f+1][c]==0):
globals()["matriz"][f+1][c] = matriz[f][c]
globals()["matriz"][f][c] = 0
c=4
f=-1
break
def acomodDerecha(self):
for f in range(n):
c=-1
while c < 4:
c+= 1
if(c < 3):
if (matriz[f][c] > 0 and matriz[f][c+1]==0):
globals()["matriz"][f][c+1] = matriz[f][c]
globals()["matriz"][f][c] = 0
c=-1
def acomodIzquierda(self):
for f in range(n):
c=4
while c > 0:
c-=1
if(c > 0):
if (matriz[f][c] > 0 and matriz[f][c-1]==0):
globals()["matriz"][f][c-1] = matriz[f][c]
globals()["matriz"][f][c] = 0
c=4
def nuevaCasilla(self):
encontrado=0
for f in range(n):
c=-1
while c < 3:
c+=1
if(matriz[f][c]==0):
globals()["matriz"][f][c] = 2
encontrado=1
c=4
f=4
break
if (encontrado==1):
break
def calcularMovimientos(self, num):
res=0
res=(10 ** 2)
if(1 <= num and num <= res):
return num
else:
return 0
def terminarJuego(self):
print "\nTus movimientos terminaron\nFin del Juego"
def validarNumeros(self,mensaje):
while True:
num= raw_input(mensaje)
try:
num=int(num)
return num
break
except ValueError:
print "Error: Ingresa solo numeros"
def jugar(self):
self.iniciarJuego()
self.imprimir()
numM =self.validarNumeros("Introduce el numero de movimientos: ")
num=self.calcularMovimientos(numM)
while num > 0:
num=num-1
mover =self.validarNumeros("Elige un movimiento \n1.- Izquierda \n2.- Derecha \n3.- Arriba \n4.- Abajo\n ")
if 1 == mover:
print "---Izquierda---"
self.acomodIzquierda()
self.izquierda()
self.acomodIzquierda()
self.nuevaCasilla()
self.imprimir()
num=num-1
elif mover == 2:
print "---Derecha---"
self.acomodDerecha()
self.derecha()
self.acomodDerecha()
self.nuevaCasilla()
self.imprimir()
num=num-1
elif mover == 3:
print "---Arriba---"
self.acomodArriba()
self.arriba()
self.acomodArriba()
self.nuevaCasilla()
self.imprimir()
num=num-1
elif mover == 4:
print "---Abajo---"
self.acomodAbajo()
self.abajo()
self.acomodAbajo()
self.nuevaCasilla()
self.imprimir()
num=num-1
else:
print "**Elige un movimiento valido**"
num+=1
objOperacion=operacion()
objOperacion.jugar()
objOperacion.terminarJuego()
|
print("\t1")
def hello():
for i in range(3):
print("Hello World")
hello()
print("=========================")
print("\t2")
def tong(a,b):
print(a+b)
tong(3,6)
|
#!/usr/bin/python3
"""
@Time : 2019/3/31
@Author : Mei Zhaohui
@Email : mzh.whut@gmail.com
@Filename: person.py
@Software: PyCharm
@Desc : basic class
"""
class Person:
"""say hello & count the num""" # 定义类的docstring
num = 0 # 定义类变量
# 定义类的方法
# 初始化类
def __init__(self, name):
"""initializes the person's data""" # 定义方法的docstring
self.name = name # 定义实例变量
print('(Initizlizing %s)' % self.name)
Person.num += 1 # 对类的变量进行操作
def say_hi(self):
"""Say Hello to someone"""
print('Hello,%s,how are you?' % self.name)
def print_all(self):
"""Count the sum"""
print('Sum is:%s' % Person.num)
def main():
"""main function"""
print(Person.__doc__)
print(Person.say_hi.__doc__)
person1 = Person('Hanmeimei')
person1.say_hi()
person1.print_all()
person2 = Person('Lilei')
person2.say_hi()
person2.print_all()
if __name__ == '__main__':
main()
|
import unittest
from typing import List
class Solution:
def distributeCandies(self, candyType: List[int]) -> int:
n = len(candyType) // 2
unique_candy_type = set(candyType)
return n if n < len(unique_candy_type) else len(unique_candy_type)
class TestSolution(unittest.TestCase):
def setUp(self) -> None:
self.solution = Solution()
def test_first_case(self):
self.assertEqual(
self.solution.distributeCandies([1,1,2,2,3,3]),
3
)
def test_second_case(self):
self.assertEqual(
self.solution.distributeCandies([1,1,2,3]),
2
)
def test_third_case(self):
self.assertEqual(
self.solution.distributeCandies([6,6,6,6]),
1
)
if __name__ == "__main__":
unittest.main() |
# 1. Реализовать подсчёт елементов в классе Matrix с помощью collections.Counter.
# Можно реализовать протоколом итератора и тогда будет такой вызов - Counter(maxtrix). Либо сделать какой-то
# метод get_counter(), который будет возвращать объект Counter и подсчитывать все элементы внутри матрицы.
# Какой метод - ваш выбор.
# 2. Используя модуль unittests написать тесты: сложения двух матриц, умножения матрицы и метод transpose
import copy
from collections import Counter
class Matrix:
def __init__(self, list_of_lists):
self.matrix = copy.deepcopy(list_of_lists)
def size(self):
number_of_rows = len(self.matrix)
number_of_columns = len(self.matrix[0])
size_of_matrix = (number_of_rows, number_of_columns)
return size_of_matrix
def transpose(self):
trans_matrix = list(zip(*self.matrix))
self.matrix = trans_matrix
return trans_matrix
@classmethod
def create_transposed(cls, list_of_lists):
instance = cls(list_of_lists)
return instance.transpose()
def __add__(self, other):
if self.size() == other.size():
resulted_matrix = []
for new_list in zip(self.matrix, other.matrix):
rows = []
for elements in zip(new_list[0], new_list[1]):
rows.append(sum(elements))
resulted_matrix.append(rows)
return resulted_matrix
else:
raise ValueError(f"Matrices have different sizes - Matrix #1 {self.size()} and Matrix #2 {other.size()}")
def __mul__(self, scalar):
resulted_matrix = []
for row in self.matrix:
rows = []
for column in row:
rows.append(column * scalar)
resulted_matrix.append(rows)
return resulted_matrix
def __str__(self):
return '\n'.join([''.join(['%d\t' % column for column in row]) for row in self.matrix])
def get_counter(self):
counter_object = Counter()
for rows in self.matrix:
counter_object += Counter(rows)
return counter_object
a = Matrix([[1, 2, 3], [4, 5, 6]])
b = Matrix([[1, 2, 3], [4, 5, 6]])
print(a + b, a * 2)
print(a.__add__(b))
print(a.__mul__(2))
print(a.__str__())
print(a.get_counter())
|
# coding=utf-8
"""
Abstract Service
"""
__author__ = 'Seray Beser'
from abc import abstractmethod
class AbstractService(object):
"""
Abstract Service for importing and exporting data
"""
def __init__(self, url='localhost'):
"""
:param url: Default url is `localhost`
"""
self.url = url
@abstractmethod
def save_to_db(self, data):
"""
Saves the data in the database
:param data:
"""
pass
@abstractmethod
def read_from_db(self, query):
"""
Reads entries in the database by the query
:param query:
"""
pass
@abstractmethod
def print_all_entry(self):
"""
Prints all entries in the database
"""
pass
|
#!/usr/bin/env python3
"""
@author: David Bonilla Castillo (dmgf2008@hotmail.com)
@version: 1
"""
import socket
import sys
import logging
class PortScanner():
"""Simple PortScanner
Scans a single port or a range, returns dictionary with True/False
"""
verbose = False
def __init__(self):
return
@staticmethod
def scan(targetIp, port):
"""Single Port Scan"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((targetIp, port)) == 0
if PortScanner.verbose:
logging.info("port: " + str(port) + " - " + ("Open" if result else "Closed"))
return result
@staticmethod
def scanRange(targetIp, range):
"""Port Range Scan"""
ports = {}
for port in range:
ports[port] = PortScanner.scan(targetIp, port)
return ports
if "-v" in sys.argv:
PortScanner.verbose = True
sys.argv.remove("-v")
logging.basicConfig(format="%(message)s", level=logging.DEBUG)
else:
logging.basicConfig(format="%(message)s")
if len(sys.argv) < 3:
raise Exception("Not enough arguments")
elif len(sys.argv) == 3:
result = PortScanner.scan(sys.argv[1], int(sys.argv[2]))
if PortScanner.verbose:
logging.info("Scanning " + sys.argv[1])
elif len(sys.argv) == 4:
if PortScanner.verbose:
logging.info("Scanning " + sys.argv[1])
result = PortScanner.scanRange(sys.argv[1], range(int(sys.argv[2]), int(sys.argv[3]) + 1))
print(result)
|
# recursive
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
return fibonacci(n-1) + fibonacci(n-2)
def fibonacci1(n):
f = [0, 1]
for i in range(2, n+1):
f.append(f[i-1] + f[i-2])
return f[n]
if __name__ == '__main__':
print(fibonacci(11))
print(fibonacci1(11))
|
"""
Explanation of The Solution
The driver function takes into account the order and the warehouses.
A) Assumptions:
1. Best way to ship order is by using minimum number of warehouses.
2. The quantities can be postitive or zero but never negative.
3. The cost of items/inventory in each warehouse is same.
B) Priority Distribution:
1. Order can be fulfilled by single warehouse.
2. Order can be fullfilled by more than one warehouse but higher priority to path with lesser number of
warehouses.
3. If there are more than one path with least number of warehouses, higher priority will be given to the path
starting with nearest warehouse.
C) Workflow
1. To check if the order can be completed using one warehouse with the help of "completeOrder" function
2. If not, check if a part of the order can be completed using a warehouse with the help of the "halfOrder" function
3. 'items_found' checks if the current warehouse can help with some items to fulfill the existing order. If yes it is
added to path_Exists.
4. path_Exists keeps track if a path is possible with the current warehouse, if yes it is added to All_paths.
5. All_paths keeps a track of differnet ways to deliver the order.
6. smallest_Path returns the best way to fullfill the order based upon Assumptions and Priority Distribution mentioned
above.
"""
import math
# Function "completeOrder" to check if the current warehouse can full fill
# the entire order
def complete_order(order, warehouse):
"""
Function "completeOrder" to check if the current warehouse can fullfill
the entire order
:param order: order needs to be fulfilled
:param warehouse: warehouse in consideration
:return: Boolean
"""
for item in order.keys():
if item not in warehouse["inventory"].keys() or warehouse["inventory"][item] < order[item]:
return False
return True
# Function "halfOrder" to check if the current Warehouse can provide some items of the Order
def half_order(remaining_order, warehouse, start, end):
"""
Function "halfOrder" to check if the current Warehouse can provide some items of the Order
:param remaining_order: order needs to be fulfilled
:param warehouse: warehouse in consideration
:param start: index of current warehouse
:param end: index of the last Warehouse
:return: the number of items taken from one warehouse to fulfill the order, Handles the case if Order cannot be
shipped because there is not enough inventory
"""
order_filled = {}
for item in remaining_order.keys():
if remaining_order[item] == 0:
continue
else:
if item in warehouse["inventory"].keys():
if warehouse["inventory"][item] >= remaining_order[item]:
order_filled[item] = remaining_order[item]
remaining_order[item] = 0
elif (warehouse["inventory"][item] < remaining_order[item]) and warehouse["inventory"][item] > 0:
order_filled[item] = warehouse["inventory"][item]
remaining_order[item] -= warehouse["inventory"][item]
if start == end and remaining_order[item] > 0:
return [], remaining_order
if not order_filled:
return {}, remaining_order
else:
return {warehouse["name"]: order_filled}, remaining_order
# Function "smallest_Path" to return the best way to ship order
def smallest_path(all_paths):
"""
Function "smallest_Path" to return the best way to ship order
:param all_paths: Ways to fulfill the order
:return: the path with least number of warehouses
"""
minimum_length = math.inf
index = 0
for i, path in enumerate(all_paths):
if len(path) < minimum_length:
minimum_length = len(path)
index = i
return all_paths[index]
# Driver Function - inventory_Allocator
def inventory_allocator(order={}, warehouses=[]):
"""
Driver Function - inventory_Allocator
:param order: Order to be completed
:param warehouses: Set of all all warehouse available to satisfy the order
:return: Returns a path if order can be fulfilled
"""
if not order or type(order) != dict:
return "Invalid Order"
if not warehouses or type(warehouses) != list:
return []
all_paths = []
original_order = order.copy()
break_condition = False
for index in range(len(warehouses)): # Checks all warehouses starting from the nearest
if complete_order(original_order, warehouses[index]):
return [{warehouses[index]["name"]: original_order}]
path_exists = []
order_ = order.copy() # Preserving the state to compute different Paths
for sub_index in range(index, len(warehouses)): # checks if we can complete orders using multiple warehouses
for i in range(sub_index + 1, len(warehouses)): # checks if at any instant remaining order can be completely
# filled by a single warehouse amongst the remaining warehouses
if complete_order(order_, warehouses[i]):
path_exists.append({warehouses[i]["name"]: order_})
break_condition = True # Since this is already the best path using current Warehouse[sub_index]
break # We need not to check any further
else:
continue
if break_condition:
break_condition = False
break
items_found, order_ = half_order(order_, warehouses[sub_index], sub_index, len(warehouses) - 1)
if items_found == []:
if not all_paths and sub_index == len(warehouses) - 1:
return [] # if we have checked all warehouses and we cannot fulfill order
else:
path_exists = [] # if we cannot fulfill order just using the current warehouse, flush curr_path
break
elif items_found:
path_exists.append(items_found)
if path_exists and path_exists not in all_paths:
all_paths.append(path_exists)
return smallest_path(all_paths)
|
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits import mplot3d
from numpy.lib.function_base import meshgrid
from mpl_toolkits.mplot3d.axes3d import Axes3D
def plot(y):
"""
plot helps to plot the graph of a function defined as y(x).
It accepts:
> arg (String): It's the function y(x), written in variable x.
Example: plot(x**2)
> While writing equations one can use all numpy libraries, with numpy as np.
Expample: plot(np.sin(x))
"""
x=np.array(range(-100,100))
z=eval(y)
plt.xlabel('x')
plt.ylabel('y')
plt.plot(x,z)
plt.savefig("An\\plot.png")
plt.close()
def plot3D(a):
b = np.array(range(-100,100))
c = np.array(range(-100,100))
B,C = meshgrid(b,c)
d=eval(a)
d=np.expand_dims(d,axis=0)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(B,C,d, rstride=1, cstride=1,
cmap='viridis', edgecolor='none')
plt.xlabel('b')
plt.ylabel('c')
plt.savefig("An\\plot3D.png")
plt.close()
|
with open('scrabble_list2.txt') as f:
words = f.read().splitlines()
if len(words[1:6]):
print (len(words))
with open('scrabble_list2.txt') as f:
words = f.read()
count = 0
for w in words:
if w[:3] == 'r':
count += 1
print(count)
file = open('scrabble_list2.txt', 'r')
contents = file.read()
print (len(contents))
|
"""
Tovar, Brianna
CS2302 Aguirre Diego, TA Eduardo
11/30
Lab 6: Kruskal's Algorithm and Topological Sort
"""
from collections import defaultdict
class Graph:
def __init__(self,vertices):
self.graph = defaultdict(list)
"""
dictionary used to contain the list of edges, vertices as an AL
"""
self.vertices = vertices
def addEdge(self,u,v):
"""
Appending, adding, vertices in graph
Ex: u=5, position 5 will have v=0, vertex 0
Creates the edge
"""
self.graph[u].append(v)
def topologicalSort(self):
"""
vertices set to not visited since we are starting
"""
visited = [False]*self.vertices
stack =[]
"""
using stack, problems with using code given by
professor (using queues) so I'm using a new approach
"""
for i in range(self.vertices):
"""
traversing thru number of vertices, checking
if false, and if is, goes to helper method
"""
if visited[i] == False:
self.topologicalSortUtil(i,visited,stack)
print(stack)
def topologicalSortUtil(self,v,visited,stack):
"""
this is our visited list: visited=[False]*self.vertices
with [v]=i from self.topo..(i,visited,stack)
this'll set our not visited list at index v from previous for-loop to be True
"""
visited[v] = True
"""
traversing using v=i from previous for loop
"""
for i in self.graph[v]:
if visited[i] == False:
self.topologicalSortUtil(i,visited,stack) #recursion to change to True
#inserting vertex into stack
stack.insert(0,v)
g= Graph(6)
g.addEdge(5, 2)
g.addEdge(5, 0)
g.addEdge(4, 0)
g.addEdge(4, 1)
g.addEdge(2, 3)
g.addEdge(3, 1)
print("Resulted Graph")
g.topologicalSort()
class Graph:
"""
another graph needed for Kruskal's Algorithm
"""
def __init__(self,vertices):
self.V= vertices
self.graph = [] #default dict
def addEdge(self,u,v,w):
"""
appends the two vertices and the weight given
"""
self.graph.append([u,v,w])
def Kruskal(self):
result =[] #resulted list
"""
Sort all the edges in order
order of their weight, and create a copy of graph
so not to alter it
"""
self.graph = sorted(self.graph)
#unifinished
g = Graph(4)
g.addEdge(0, 1, 10)
g.addEdge(0, 2, 6)
g.addEdge(0, 3, 5)
g.addEdge(1, 3, 15)
g.addEdge(2, 3, 4)
print("New graph, weighted")
print(g.graph)
g.Kruskal() |
from room import Room
from player import Player
from world import World
import random
from random import choice
from ast import literal_eval
# from graph import Graph
from util import Queue, Stack, Graph
# Load world
world = World()
# You may uncomment the smaller graphs for development and testing purposes.
# map_file = "maps/test_line.txt" # this one passes currently
# map_file = "maps/test_cross.txt"
# map_file = "maps/test_loop.txt"
# map_file = "maps/test_loop_fork.txt"
map_file = "maps/main_maze.txt"
#
# Loads the map into a dictionary
room_graph = literal_eval(open(map_file, "r").read())
world.load_graph(room_graph)
# Print an ASCII map
world.print_rooms()
player = Player(world.starting_room)
# Fill this out with directions to walk
# traversal_path = ['n', 'n']
traversal_path = []
# THIS IS MY CODE BELOW.... WATCH IT DO WHAT IT DO BABY!
# start by adding the vertexes from the list of rooms in world.rooms.value
# that way all ther vertices are already existing and we don't have to worry about making that as we go
# make dft that creates the edges as it goes.. dont use a visited in the main dft....
# when looking for what room to do next at a junction point look for what has a value == '?'
# start out with grabing the starting location
g = Graph()
current_R = player.current_room
print(f"starting_room: {current_R.id}")
starting_room = current_R.id
# this creates the graph with neighbors (key being direction) with the neighboring rooms (as the value )
for each in world.rooms:
g.add_vertex(each)
for exit in world.rooms[each].get_exits():
g.vertices[each][exit] = '?'
# print(g.vertices)
# this looks at entire graph and looks for values with "?"
def get_opposite(dir):
direction = {'n': 's', 's': 'n', 'w': 'e', 'e': 'w'}
return direction[dir]
def pick_room(list):
if len(list) >= 1:
dir = random.choice(list)
return dir
else:
return None
def find_all_Qs():
qs = {}
for each in g.vertices:
# print(f"room: ", each)
if g.get_room_Q(each) != None:
qs[each] = g.get_room_Q(each)
if len(qs) == 0:
return None
return qs
the_q_list = find_all_Qs()
# print(f"the_q_list: {the_q_list}, len(the_q_list): {len(the_q_list)}")
# g.get_room_Q(g.vertices[player.current_room.id])
# will get you either None if empty or a list of
# the directions for that room with value == '?'
def bfs_to_another_hallway(visited, currentV, Qpath, old_path, plan_to_visit, pathDirs):
q = Queue()
q.enqueue([currentV])
# visited is being used from
# adding to path needs to be the 'next_room'
# adding current on the way back adds
# the ending of the hallway 2x's
q_list = find_all_Qs()
together_now = ''
while q.size() > 0 and len(q_list) > 0:
q_list = find_all_Qs()
# print(f"list of the dirs with '?' {q_list}")
current_path = q.dequeue()
current_room = current_path[-1]
any = g.get_room_Q(current_room)
# print(
# f"any from bfs at current_room: {current_room}, exits: {any}")
if any == None:
# print('means no room is unused at this loc')
# add directions and save a path then return it
visited.add(current_room)
next_rooms = g.get_neighbors(current_room)
for dir in next_rooms:
# print(f"direction avail: {dir}")
# print(
# f"next room would be: {g.vertices[current_room][dir]}")
if g.vertices[current_room][dir] != '?' and g.vertices[current_room][dir] not in visited:
Qpath.append(g.vertices[current_room][dir])
new_path = Qpath.copy()
pathDirs.append(dir)
# hopefully this puts the dir in the right spot... we'll see
traversal_path.append(dir)
q.enqueue(new_path)
player.travel(dir)
else:
# print(f"found a room {current_room} with exits{any}")
# print(f"current_path outside bfs: {old_path}")
# print(f"path: {Qpath}")
# print(f"player current location: {player.current_room.id}")
# now need to push current room to stack to continue the
together_now = old_path + Qpath
# print(
# f"together_now-putting traversal path together: {together_now}")
return together_now
def get_to_all_room():
starting_room = current_R.id
plan_to_visit = Stack()
plan_to_visit.push([starting_room])
# mainly for the breadth first back to find next crosspoint with unused exits
Qpath = []
# try to use this to collect the dirs along the way of traversal, at the point of traversal
pathDirs = []
visited = set()
# now start the loop for the dft whileloop
been_to = False
# maybe need to add condition to look for all room to have no '?'
while plan_to_visit.size() > 0 and been_to == False:
current_path = plan_to_visit.pop()
current = current_path[-1]
# print(
# f"at top of while loop, current room: {current}, current path: {current_path}")
# current_dir_list = g.get_room_Q(current)
current_dir_list = g.get_neighbors(current)
if current_dir_list == None:
# this means that the current room has no other directions to choose from not already seen
# print(
# f"current room has no unused directions\nAlso may be the end of a hallway\n current room: {current}")
# print(f"{current_path}")
path = bfs_to_another_hallway(
visited, current, Qpath, current_path, plan_to_visit, pathDirs)
plan_to_visit.push(path)
# at end of hallway this is where we bfs back to
# head back to find room with unexplored exits
# current_N = g.get_neighbors(current)
# print(f"current_dir_list: {current_dir_list}\ncurrent_N: {current_N}")
next_dir = pick_room(current_dir_list)
if next_dir == None:
return f"its at the end of this line {current_path}, current loc: {current}"
# print(f"next_dir: ", next_dir)
next_room = player.current_room.get_room_in_direction(next_dir)
next_room = next_room.id
# print(f"next_room: {next_room}")
g.add_edge(current, next_dir, next_room)
g.add_edge(next_room, get_opposite(next_dir), current)
# print(g.vertices)
# now we travel down the hallway
current_path.append(next_room)
copy_path = current_path.copy()
pathDirs.append(next_dir)
# adding to the traversal_path
traversal_path.append(next_dir)
# print(f"copy_path: {copy_path}, pathDirs: {pathDirs}")
the_q_list = find_all_Qs()
if the_q_list == None:
been_to = True
# print(f"the_q_list: {the_q_list}")
player.travel(next_dir)
plan_to_visit.push(copy_path)
get_to_all_room()
####
# NOW BACK TO PREVIOUSLY WRITTEN CODE (NOT MINE BELOW)... ITS THE TEST TRAVERSAL
# TRAVERSAL TEST - DO NOT MODIFY
visited_rooms = set()
player.current_room = world.starting_room
visited_rooms.add(player.current_room)
for move in traversal_path:
player.travel(move)
visited_rooms.add(player.current_room)
if len(visited_rooms) == len(room_graph):
print(
f"TESTS PASSED: {len(traversal_path)} moves, {len(visited_rooms)} rooms visited")
else:
print("TESTS FAILED: INCOMPLETE TRAVERSAL")
print(f"{len(room_graph) - len(visited_rooms)} unvisited rooms")
#######
# UNCOMMENT TO WALK AROUND
#######
# player.current_room.print_room_description(player)
# while True:
# cmds = input("-> ").lower().split(" ")
# if cmds[0] in ["n", "s", "e", "w"]:
# player.travel(cmds[0], True)
# elif cmds[0] == "q":
# break
# else:
# print("I did not understand that command.")
|
import numpy as np
import matplotlib.pyplot as plt
from sklearn import neighbors
X=[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
Y=[2,5,7,9,11,16,19,23,22,29,29,35,37,40,46,42,39,31,30,28,20,15,10,6]
X=np.array(X).reshape(-1,1)
y=np.array(Y)
plt.plot(X,Y,'ro')
x0=np.linspace(3,25,10000).reshape(-1,1)
y0=[]
knn=neighbors.KNeighborsRegressor(n_neighbors=3)
knn=knn.fit(X,y)
y0=knn.predict(x0)
plt.plot(x0,y0)
plt.show() |
classList = [12345, 23456]
def removeStudent(pawPrint):
if (pawPrint in classList):
classList.remove(pawPrint)
return True
def checkStudent(pawPrint):
#Check if student ID is valid
count = 0
paw = pawPrint
while(pawPrint>0):
count = count+1
pawPrint = pawPrint//10
if(count<3):
return False
else:
result = removeStudent(paw)
return result
def main():
print(checkStudent(12345))
if __name__ == "__main__":
main() |
#!/usr/bin/python2
# -*- coding:utf-8 -*-
## TODO:TODOリストを作成する
## TODOリストとして、「内容/完了フラグ」を基本
import sqlite3,sys
def showAllTodo():
db_connecter = sqlite3.connect("data.db")
cursor = db_connecter.cursor()
cursor.execute("select todo,flg from todo_list")
result = cursor.fetchall()
print "==TODO Lists=="
for row in result:
if row[1] == "true":
print u"✓ " + row[0]
else:
print u"・" + row[0]
print ""
cursor.close()
db_connecter.close()
def showTodo():
db_connecter = sqlite3.connect("data.db")
cursor = db_connecter.cursor()
cursor.execute("select todo,flg from todo_list where flg='false'")
result = cursor.fetchall()
print "==TODO Lists=="
for row in result:
print row[0]
print ""
cursor.close()
db_connecter.close()
def addTodo():
db_connecter = sqlite3.connect("data.db")
print "TODO追加します"
mes = sys.stdin.readline().split("\n")
sql = "insert into todo_list values ('" + mes[0] + "', 'false')"
db_connecter.execute(sql)
db_connecter.commit()
db_connecter.close()
print "追加しました!\n"
def selectMenu():
# ループ終了フラグ
exit_flg = True
while exit_flg:
print "--MENU--\nadd:TODO追加\nlist:TODO表示\nall:TODO全て表示\nexit:終了"
# メニュー選択
menu = sys.stdin.readline().split("\n")
input_menu = menu[0]
if input_menu == "add":
addTodo()
elif input_menu == "all":
showAllTodo()
elif input_menu == "list":
showTodo()
elif input_menu == "exit":
exit_flg = False
if __name__ == "__main__":
selectMenu()
print "終了します"
|
from random import randrange
'''global variables'''
board = ["0", "1", "2", "3", "4", "5", "6", "7", "8"]
'''methods'''
def resetBoard():
global board
x = 0
while x < len(board):
board[x] = str(x)
x += 1
printBoard()
def printBoard():
print()
print(board[0] + " " + board[1] + " " + board[2])
print(board[3] + " " + board[4] + " " + board[5])
print(board[6] + " " + board[7] + " " + board[8])
print()
#determines if someone has won or there is a tie
def gameOver():
x = 0
winner = ''
#checks across rows
while x < len(board):
if board[x] == board[x+1] and board[x+1] == board[x+2]: #checks across rows
winner = board[x]
break
else:
x += 3
x = 0
#checks down columns
while x < 3:
if board[x] == board[x+3] and board[x+3] == board[x+6]:
winner = board[x]
break
else:
x += 1
x = 0
#checks diagonals
if board[0] == board[4] and board[4] == board[8]:
winner = board[x]
elif board[2] == board[4] and board[4] == board[6]:
winner = board[x]
#if there was no winner, check if all of the spaces are full; end function if so
if winner == '':
x = 0
while x <= len(board):
if board[x] != 'X' and board[x] != 'O':
break
elif x == 8:
print("Tie Game!")
playAgain = raw_input("Enter a y to play another game.")
if playAgain == "y":
resetBoard()
return False
else:
return True
else:
x += 1
#print("x = " + str(x))
if winner == 'X':
print("Player1 Wins the Game!")
playAgain = raw_input("Enter a y to play another game.")
if playAgain == "y":
resetBoard()
return False
else:
return True
elif winner == 'O':
print("Player2 Wins the Game!")
playAgain = raw_input("Enter a y to play another game.")
if playAgain == "y":
resetBoard()
return False
else:
return True
else:
return False
def play(player):
if player == "player1":
symbol = 'X'
else:
symbol = 'O'
while True:
try:
space = int(input("Enter the number of the space you would like to occupy: "))
if space > 8 or space < 0:
print("Please choose an integer between 0 and 8.")
elif board[space] == "X" or board[space] == "O":
print("Sorry, that space is already taken. Please try again")
else:
break
except ValueError:
print("Please enter an integer.")
board[space] = symbol
def main():
x = randrange(0, 2) #chooses 0 or 1
player = "player1" if x == 0 else "player2"
printBoard()
while gameOver() == False:
print("It's " + player + "'s turn.")
play(player)
printBoard()
if player == "player1":
player = "player2"
else:
player = "player1"
'''executing section'''
main()
|
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
class Employee(dict):
Employees = []
def __init__(self, position=None, name=None, surname=None, plz=None, city=None, phonenumber=None, organisation = None, qualification = None, image=None, street=None, personalwebsite = None, email=None, xing=None):
dict.__init__(self)
self["Funktion"] = position
self["Nachname"] = surname
self["Vorname"] = name
self["PLZ (Geschäft)"] = plz
self["Ort (Geschäft)"] = city
self["Telefon (Geschäft)"] = phonenumber
self["Organisation"] = organisation
self["Qualifikation"] = qualification
self["Bild"] = image
self["Strasse"] = street
self["Eigene Website"] = personalwebsite
self["EMail"] = email
self["Xing"] = xing
def get_info(self):
employee_str = ""
separator_counter = 1
for key, value in self.items():
if key == "surname":
separator = " "
elif separator_counter < len(self.items()):
separator = ", "
else:
separator = ""
employee_str += key + ": " + value + separator
separator_counter += 1
return employee_str
def add_employee(self):
Employee.Employees.append(self)
# to call a Class Method without self
@staticmethod
def get_employees():
return Employee.Employees
# In[ ]:
#for copy&paste purposes
#Employee(position=position, name=name, surname=surname, plz=plz, city=city, phonenumber=phonenumber, organisation = organisation, qualification = qualification, image=image, street=street, personalwebsite = personalwebsite, email=email, xing=xing).add_employee()
#atList = ["image", "surname", "name", "phonenumber", "position", "street", "city", "plz"]
#employeeAdd = get_employee_add_string(atList)
#print(employeeAdd)
# In[ ]:
position=None
name=None
surname=None
plz=None
city=None
phonenumber=None
organisation = None
qualification = None
image=None
street=None
personalwebsite = None
email=None
xing=None
|
#/usr/bin/python3
#
#dict loop tips
print("=" * 100)
print("5.6 dict")
print("=" * 100)
#use items to get key and value
d1 = {'key1':'value1', 'key2':'value2','key3':'value3'}
for k,v in d1.items():
print("{} : {} , {}".format(k,v,d1[k]))
#enumerate to get list index
for i,v in enumerate([5,6,7,8,9]):
print(i, v)
print("=" * 100)
#use zip function if iterate two lists at same time
l1 = list(range(10))
l2 = [x**2 for x in list(range(10))]
l3 = [x**3 for x in list(range(10))]
for x,y,z in zip(l1,l2,l3):
print(x,y,z)
print("=" * 100)
#reversed
for i in reversed(l3):
print(i)
print("=" * 100)
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for i in sorted(basket):
print(i)
print(basket)
#set can clear deduplication
for i in sorted(set(basket)):
print(i)
#if wanna change list item value, create new one list is better
import math
raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
filterList = []
for i in raw_data:
if not math.isnan(i):
filterList.append(i)
print(filterList) |
#5-2 del
#del: delete list element or clear list
a=[1,2,3,4,5,6]
del a[0]
print(a)
#5-3 tuples and sequences
t=123,45,"a"
print(t)
u=t,(0,1,2,3)
print(u)
#5-4 Set
newSet={"a","b","c"} #or use set()
otherSet=set(["b","c","d"])
print(type(newSet))
print(newSet)
print(otherSet)
print(newSet | otherSet) # or
a={x for x in 'abcddgafhxf' if x not in 'abcd'}
print(a) |
#/usr/bin/python3
#
#Class
print("=" * 100)
print("10.11 Quality Control")
print("=" * 100)
#doctest
import doctest
def average(values):
"""
This is average
>>> print(average([1,2,3,4]))
2.5
"""
return sum(values) / len(values)
doctest.testmod()
#comlated: unittest
import unittest
class TestFunctions(unittest.TestCase):
def testAverage(self):
self.assertEqual(average([10,20,30]),20)
self.assertEqual(round(average([1,2,3]),1),2.0)
with self.assertRaises(ZeroDivisionError):
average([])
with self.assertRaises(TypeError):
average(20, 30, 70)
unittest.main() |
#/usr/bin/python3
#
#data structure
print("=" * 100)
print("5.1 List")
print("=" * 100)
l = list(range(10))
print(l)
l.append(11)
print(l)
l2 = list(range(15,21))
l.append(l2)
print(l)
#extand iterable item
l.extend(l2)
print(l)
l.insert(0,'a')
print(l)
#remove the first value equal given, return valueErr if not found
l.remove(15)
print(l)
#pop can specific index
print(l.pop(12))
print(l)
#clear equals del l[:]
del l[0:3]
#print(l)
#l.clear()
print(l)
#get index of the value which first match, or return valueErr
print(l.index(17))
#or search given range
print(l.index(17,4,15))
#print the value match times
print(l.count(1111))
#sort(*,key=none, reverse=False)
l.sort(reverse=True)
#some method return default None
print(l.sort())
print(l)
l.reverse()
print(l)
#list copy : shadow copy
l.append(l2)
l3=l.copy()
l4=l
del l[-1][5]
print("l: ",l, id(l), "l[0] id: ", id(l[0]))
#l4 have same address
print("l4: ",l4, id(l4), "l4[0] id: ", id(l4[0]))
#index 0 ipaddress still same
print("l3: ",l3, id(l3), "l3[0] id: ", id(l3[0]))
print("=" * 100)
print("5.1.1 List implement stack")
print("=" * 100)
#first in last out, using append() and pop
stack = list(range(11))
print(stack)
stack.append(199)
print(stack)
stack.pop()
print(stack)
print("=" * 100)
print("5.1.2 List implement queue")
print("=" * 100)
#you can use insert() and pop, but low efficiency
#or use collections.deque, can input and output faster
from collections import deque
queue = deque(list(range(10)))
print(queue)
print(queue.append(100), "queue:", queue)
print(queue.popleft(), "queue:", queue)
print("=" * 100)
print("5.1.3. List Comprehensions")
print("=" * 100)
#more simple generate complex list
test = []
for i in range(10):
test.append(i**2)
print(test)
# need a range iterable object
#use lambda
test = list(map(lambda x: x**2, range(10)))
print(test)
#or
test = [x**2 for x in range(10)]
print(test)
test = [(x,y) for x in [1,2,3] for y in [3,1,4] if x != y]
print(test)
vec = [[1,2,3], [4,5,6], [7,8,9]]
print([x for inside in vec for x in inside])
print("=" * 100)
print("5.1.4 List Comprehensions")
print("=" * 100)
matrix = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
]
print(matrix)
#change
print([[row[i] for row in matrix] for i in range(4)])
#use built-in functions 'zip' have good efficiency
print(list(zip(*matrix))) |
#encoding: utf-8
print ("hello world")
print("a\tb") #a b
# use r before quote can be raw string
print(r"a\tb") # a\tb
print("""three double quote or singo quote
can show new line in the string ,but use \\ can break warp text \ ...
""")
word='hello world'
print(word[1]) #h
print(word[-1]) #d
print(word[2:5]) #llo
#list
list=[]
list1=[1,2,3,4,5]
list.append(1) # or you can use + ==>list1+[2,3,4]==>1,2,3,4,5,2,3,4
list.append(2)
list[:]=[] #clear
list.append([1,2,3])
list.append([4,5,6]) #list==> [[1,2,3],[4,5,6]]
print(len(list1)) #show list length
print(sum(list1)) #sum all elements (all elements should be digital)
print(list1.count(2)) #count digital 2 occurrences
|
#/usr/bin/python3
#
#Class
print("=" * 100)
print("9.9 Generator")
print("=" * 100)
#generator is a tool for creating iterators. use yield to return the object.
#when generator invoke next() function, it will goto last leave point .
#generator will create __iter__() and __next__() function automatically
def reverse(data):
for i in range(len(data)-1,-1,-1):
yield data[i]
for char in reverse("This is apple"):
print(char)
|
if __name__ == '__main__':
record = '....................100 .......513.25 ..........'
SHARES = slice(20, 32)
PRICE = slice(40, 48)
cost = int(record[SHARES]) * float(record[PRICE])
print(f'cost: {cost}')
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
]
from collections import Counter
counter = Counter(words)
top_three = counter.most_common(3)
print(f'top three words: {top_three}')
|
from collections import deque
if __name__ == '__main__':
q = deque(maxlen=3)
q.append(1)
q.append(2)
q.append(3)
print(f'append 1 2 3, {q}')
q.append(4)
print(f'append 4, {q}')
q.append(5)
print(f'append 5, {q}') |
######################################################
# Function 1
def first_past_the_post(votes):
''' Count the votes for each candidate and return the winner.
Takes a list of strings, with one instance of candidate's name as
a vote. NOT case-sensitive. Returns tie if winning votes are equal.'''
# First, build a tally of the candidates and their votes:
tally = {}
for candidate in votes:
if candidate in tally:
tally[candidate] += 1
else:
tally[candidate] = 1
# Then, filter through the dictionary for the candidate(s) with max votes:
winner = []
max_votes = max(tally.values())
for i in tally.keys():
if tally[i] == max_votes:
winner.append(i)
# Finally, check if there is more than one winner:
if len(winner) > 1:
return 'tie'
else:
return winner[0]
#############################################################
# Function 2
def second_preference(votes):
''' Count second preference voting and return the winner.
Takes a list of lists. One instance of candidate's name (as str) is
a preference, and a total list is a vote. NOT case-sensitive.
Returns tie if winning votes are equal.'''
# Collect first pref votes:
tally = {}
for i in votes:
if i[0] in tally:
tally[i[0]] += 1
else:
tally[i[0]] = 1
# Calculate the FPTP winner by first preference:
FPTP_winner = []
max_votes = max(tally.values())
for i in tally.keys():
if tally[i] == max_votes:
FPTP_winner.append(i)
turnout = len(votes)
if (len(FPTP_winner) == 1) and ((max_votes / turnout) >= 0.5):
return FPTP_winner[0]
# If there's no absolute majority, we calculate second preference.
# Find the losing candidates by first preference:
loser = []
for i in tally:
if tally[i] == min(tally.values()):
loser.append(i)
# Get string value for the loser, tiebreaking multiple losers by name:
if len(loser) > 1:
loser = sorted(loser)[0]
else:
loser = loser[0]
# Remove loser from tally, and allocate loser's second preference votes:
tally.pop(loser)
for i in votes:
if i[0] == loser:
if i[1] in tally:
tally[i[1]] += 1
else:
tally[i[1]] = 1
# Evaluate the new vote totals
max_votes = max(tally.values())
winner = []
for i in tally.keys():
if tally[i] == max_votes:
winner.append(i)
# Return winner
if len(winner) > 1:
return 'tie'
else:
return winner[0]
#############################################################
# Function 3
def multiple_preference(votes):
''' Count multiple preference votes and return the winner.
Takes a list of ordered lists. One instance of candidate's name (as str) is
a preference, and an ordered list is a vote. NOT case-sensitive.
Returns tie if winning votes are equal.'''
# Build dictionary of full-preference votes. Updates with re-allocations;
# includes empty entries for candidates with no firstpref votes.
tally = {}
for vote in votes:
if vote[0] in tally:
tally[vote[0]].append(vote)
else:
tally[vote[0]] = [vote, ]
for pref in vote:
if pref not in tally:
tally[pref] = []
winner = []
eliminated = []
turnout = len(votes)
while not winner:
# Count votes for each remaining candidate
vote_count = {}
for candidate in tally:
vote_count[candidate] = len(tally[candidate])
max_votes = max(vote_count.values())
# If there's more than 2 candidates left and no majority, reallocate
if (len(tally) > 2) and max_votes / turnout <= 0.5:
# Find the loser in this round, and add them to those eliminated
roundloser = []
for candidate in vote_count:
if vote_count[candidate] == min(vote_count.values()):
roundloser.append(candidate)
roundloser = sorted(roundloser)[0]
eliminated.append(roundloser)
# For each of the loser's votes: extract prefs only for those
# not yet eliminated & add them to the next-preferred's tally entry
for vote in tally[roundloser]:
extracted_vote = []
for pref in vote:
if pref not in eliminated:
extracted_vote.append(pref)
if len(extracted_vote) > 0:
tally[extracted_vote[0]].append(extracted_vote)
# Remove roundloser's now-redundant tally entry and go back up
# to `vote_count` to evaluate our new tally for a potential winner
tally.pop(roundloser)
# We now have winning candidate(s), so can break out of our loop
else:
for candidate in vote_count:
if vote_count[candidate] == max_votes:
winner.append(candidate)
if len(winner) == 1:
return winner[0]
else:
return 'tie' |
loop = int(raw_input())
numer=0
while loop!=0:
loop-=1
string_inp = raw_input().split(".")
teststr = string_inp[1]
for i in range(len(teststr)):
if teststr[i]=="a" or teststr[i]!='i' or teststr[i]!='o' or teststr[i]!='u' or teststr[i]!='e':
numer+=1
print numer+"/"+len(teststr) |
DIRECTIONS = {'U': (0, 1),
'R': (1, 0),
'D': (0, -1),
'L': (-1, 0),
}
def main():
input_file = '../inputs/03.txt'
wires = []
with open(input_file, 'r') as fh:
for line in fh:
wire = wire_from_steps(line.split(','))
wires.append(wire)
intersections = set.intersection(*map(set, wires))
sol_1 = min([sum(map(abs, intersection)) for intersection in intersections])
sol_2 = min([sum([wire.index(intersection) + 1 for wire in wires]) for intersection in intersections])
print(f"The solution to part 1 is {sol_1}.")
print(f"The solution to part 2 is {sol_2}.")
def wire_from_steps(steps):
position = (0, 0)
wire = []
for step in steps:
distance = int(step[1:])
direction = DIRECTIONS.get(step[0])
for _ in range(distance):
position = tuple(map(sum, zip(position, direction)))
wire.append(position)
return wire
if __name__ == '__main__':
main()
|
class Environment:
"""This class emulates an infinite BrainCurry environment,
including a memory tape and a pointer to the current cell."""
def __init__(self, max):
self.max = max
self.tape = Tape()
self.pointer = 0
self.stash = [] # A stack to stash state data on for reversion
# Stashes the cell pointer to prevent lambdas from changing it globally
def Stash(self): self.stash.append(self.pointer)
def Restore(self): self.pointer = self.stash.pop()
def ChangeCell(self, delta):
self.cell += delta
def SetCell(self, value):
self.cell = value
def ChangePointer(self, delta):
self.pointer += delta
if self.pointer < self.tape.leftMost:
self.tape.extendleft([0]*(self.tape.leftMost - self.pointer))
elif self.pointer > self.tape.rightMost:
self.tape.extend([0]*(self.pointer - self.tape.rightMost))
@property
def cell(self):
return self.tape[self.pointer]
@cell.setter
def cell(self, value):
self.tape[self.pointer] = value % self.max
class Tape:
"""This iterable class mimics infinite memory tape
for the environment class to use internally."""
def __init__(self):
self.left = []
self.right = [0]
def __getitem__(self, index):
return self.right[index] if index >= 0 else self.left[abs(index)-1]
def __setitem__(self, index, value):
(self.right if index >= 0 else self.left)[index if index >= 0 else abs(index)-1] = value
def __len__(self):
return len(self.right) + len(self.left)
def __str__(self):
return str(
list(reversed(self.left)) + self.right
)
@property
def leftMost(self):
"""Return the leftmost (lowest) index still on the generated tape."""
return -len(self.left)
@property
def rightMost(self):
"""Return the rightmost (highest) index still on the generated tape."""
return len(self.right) - 1
def extend(self, iterable):
self.right += iterable
def extendleft(self, iterable):
self.left += iterable |
#Anastasia Douka
#260768503
import doctest
def which_delimiter(string):
'''
(str)-> str
This function returns the most commonly used delimiter.
>>> which_delimiter('0 1 2, 3')
' '
'''
delimiterDict = {} #empty dict where we will put delimiters
for char in string:
if char == ' ' or char == ',' or char == '\t':
if char not in delimiterDict:
delimiterDict[char] = 1
else:
delimiterDict[char] += 1
if len(delimiterDict) == 0:
raise AssertionError("There exists no delimiter!")
return max(delimiterDict) #take the delimeter used the most
def stage_one(input_filename, output_filename):
'''
(file, file) -> int
This function takes two files as inputs and will return an integer
of how many lines were written to the second file input.
>>> stage_one('1111111.txt', 'stage1.tsv')
3000
'''
inFile = open(input_filename, 'r')
outFile = open(output_filename, 'w', encoding = 'utf-8')
records = inFile.readlines()
for line in records:
delimiter = which_delimiter(line)
if delimiter != '\t':
line = line.replace(delimiter, '\t')
line = line.replace('/', '-')
line = line.replace('.', '-')
line = line.upper()
outFile.write(line)
outFile.close()
inFile.close()
return len(records)
def stage_two(input_filename, output_filename):
'''
(file, file) -> int
This function takes as input two files, it makes changes in the first file
and then returns how many lines were written to the second file (output_filename).
>>> stage_two(’stage1.tsv’, ’stage2.tsv’)
3000
'''
inFile = open(input_filename, 'r', encoding = 'utf-8')
outFile = open(output_filename, 'w', encoding = 'utf-8')
records = inFile.readlines()
for line in records: #each line in the records
columns = line.split('\t') #each column in line
if len(columns) > 9:
if len(columns[-2])== 1:
columns[-3] = ''.join(columns[-3:-1])
del columns[-2]
else:
columns[-3]= '.'.join(columns[-3:-1])
del columns[-2]
line='\t'.join(columns)
outFile.write(line)
outFile.close()
inFile.close()
return len(records)
if __name__ == '__main__':
doctest.testmod
stage_one('260768503.txt', 'stage1.tsv')
stage_two('stage1.tsv', 'stage2.tsv')
|
# Pedir dos numeros por teclado, si el primer numero es mayor que el segundo, intercambiarlos
aux = 0
a = int(input("Digita el primer numero: "))
b = int(input("Digita el segundo numero: "))
print("")
print("El primer numero es: ",a, "y el segundo numero es: ",b)
if a > b:
aux = a
a = b
b = aux
print("El primer numero es: ",a, "y el segundo numero es: ",b)
|
# if
x = 30
if x < 20:
print('X es menor que 20')
else:
print('X es mayor que 20')
print('------------------------------------')
color = 'verde'
if color == "rojo":
print('El color es rojo')
elif color == "azul":
print('El color es azul')
else:
print('cualquier color')
print('------------------------------------')
nombre = "Jhon"
apellido = "Karter"
if nombre == "Jhon":
if apellido == "Perez":
print("Tu eres Jhon Karter")
else:
print("Tu nombre y apellido no corresponden")
print('------------------------------------')
|
# preguntar al usuario por la contraseña e imprima por pantalla si la contraseña introducida por el usuario coincide con la guardada en la variable sin tener en cuenta mayúsculas y minúsculas.
clave = 'entrada'
password = input("Escriba la contraseña de ingreso: ")
if clave == password.lower():
print("Contraseña correcta")
else:
print("Contraseña INCORRECTA")
|
# Escribir un programa que pida al usuario su peso (en kg) y estatura (en metros), calcule el índice de masa corporal y lo almacene en una variable, e imprima por pantalla la frase Tu índice de masa corporal es <imc> donde <imc> es el índice de masa corporal calculado redondeado con dos decimales.
print("")
peso = input("Digita tu peso corporal: ")
estatura = input("Digita tu estatura: ")
# round: redondea el resultado, 2,2: dos decimales despues de la coma ,
imc = round(float(peso)/float(estatura)**2,2)
print("Tu indice de masa corporal es de: " +str(imc))
|
# type: que tipo de variable es
print(type(98)) # int
print(type(43.4)) # float
print(type("Hola"))
print("--------------------------------------------")
# ** : al cubo
print('2 al cubo es: ' ,2 ** 3) # 8, 2*2=4*2=8
# % : muestra el residuo de una division
print('El residuo de la division 3 % 2 es: ' ,3 % 2)
# / : division con resultado tipo float
print('La division entre 3 / 2 es:' ,3 / 2, 'resultado tipo float') # 1.5
# // : division con resultado tipo entero
print('La division entre 3 // 2 es:' ,3 // 2, 'resultado tipo entero') # 1
print(' ')
# input: permite pedir datos por teclado
edad = input('Digita tu edad: ')
print(edad +' años') # edad años
# Se coloca int para pasar la variable edad a tipo entero porque es de tipo string, se guarda en otra variable
nueva_edad = int(edad) + 5
print('Mas 5 años es:',nueva_edad,'años')
print("-------------------------------------------")
# Elige el mayor numero
print(max(43,56,76,98,126)) # 126
# Elige el menor numero
print(min(43,65,87,3)) # 3
|
a = int(input('Digite o primeiro número: '))
b = int(input('Digite o segundo número: '))
c = int(input('Digite o terceiro número: '))
if a < b and b < c:
print('crescente')
else:
print('não está em ordem crescente')
|
# randomgraphics.py
import random
import matplotlib.pyplot as plt
class Diegraphic:
""""Clase para graficar lanzamientos con uno o m�s dados"""
def __init__(self, nlanz=0, ndies=1, nfaces=6):
self.ndies = ndies
self.nfaces = nfaces
self.nlanz = nlanz
posibles_resultados = []
frecuencias = []
resultado = 0
for i in range(ndies*nfaces):
posibles_resultados.append(i+1)
frecuencias.append(0)
#print(posibles_resultados)
#print(frecuencias)
for k in range(nlanz):
resultado = 0
for m in range(ndies):
resultado += random.randrange(1, nfaces + 1)
#print(resultado, end=' ')
frecuencias[resultado - 1] += 1
x = posibles_resultados
y = frecuencias
plt.plot(x, y, color='r')
plt.scatter(x, y, color='b')
plt.grid()
plt.show()
|
import unittest
from models import articles
articles = articles.Articles
class articlesTest(unittest.TestCase):
'''
Test Class to test the behaviour of the articles class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_articles = articles('techcrunch','techcrunch','Romain Dillet','following BCH fork','The Bitcoin Cash chain split into two different chains back in November','http://techcrunch.com/2019/02/15/coinbase-users-can-now-withdraw-bitcoin-sv-following-bch-fork','https://techcrunch.com/wp-content/uploads/2017/08/bitcoin-split-2017a.jpg?w=711','2019-02-15T14:53:40Z')
def test_instance(self):
self.assertTrue(isinstance(self.new_articles,articles))
def test_init(self):
'''
set up a method that tests if the source object is correctly initiated
'''
self.assertEqual(self.new_articles.id,"techcrunch")
self.assertEqual(self.new_articles.name,"techcrunch")
self.assertEqual(self.new_articles.author,"Romain Dillet")
self.assertEqual(self.new_articles.title,"following BCH fork")
self.assertEqual(self.new_articles.urlToImage,"https://techcrunch.com/wp-content/uploads/2017/08/bitcoin-split-2017a.jpg?w=711")
self.assertEqual(self.new_articles.url,"http://techcrunch.com/2019/02/15/coinbase-users-can-now-withdraw-bitcoin-sv-following-bch-fork")
self.assertEqual(self.new_articles.publishedAt,"2019-02-15T14:53:40Z")
if __name__ == '__main__':
unittest.main() |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
1. 检查先决条件
2. 定义子程序要解决的问题
3. 为子程序命名
4. 决定如何测试子程序
5. 在标准库中搜寻可用的功能
6. 考虑错误处理
7. 考虑效率问题
8. 研究算法和数据类型
9. 编写伪代码
1. 首先简要地用一句话来写下该子程序的目的,
2. 编写很高层次的伪代码
3. 考虑数据
4. 检查伪代码
10. 在伪代码中试验一些想法,留下最好的想法
'''
class Solution:
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 1
from queue import deque
a2 = deque()
a3 = deque()
a5 = deque()
a2.append(2)
a3.append(3)
a5.append(5)
x = 1
while n > 1:
x2 = a2.popleft()
x3 = a3.popleft()
x5 = a5.popleft()
x = min(x2, x3, x5)
if x == x2:
a3.appendleft(x3)
a5.appendleft(x5)
a2.append(x * 2)
a3.append(x * 3)
a5.append(x * 5)
elif x == x3:
a2.appendleft(x2)
a5.appendleft(x5)
a3.append(x * 3)
a5.append(x * 5)
elif x == x5:
a2.appendleft(x2)
a3.appendleft(x3)
a5.append(x * 5)
n -= 1
return x
sol = Solution()
print(sol.nthUglyNumber(1))
print(sol.nthUglyNumber(2))
print(sol.nthUglyNumber(3))
print(sol.nthUglyNumber(4))
print(sol.nthUglyNumber(5))
print(sol.nthUglyNumber(6))
print(sol.nthUglyNumber(7))
print(sol.nthUglyNumber(8))
print(sol.nthUglyNumber(9))
print(sol.nthUglyNumber(10))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
1. 检查先决条件
2. 定义子程序要解决的问题
3. 为子程序命名
4. 决定如何测试子程序
5. 在标准库中搜寻可用的功能
6. 考虑错误处理
7. 考虑效率问题
8. 研究算法和数据类型
9. 编写伪代码
1. 首先简要地用一句话来写下该子程序的目的,
2. 编写很高层次的伪代码
3. 考虑数据
4. 检查伪代码
10. 在伪代码中试验一些想法,留下最好的想法
'''
class Solution:
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
return moves.count('R') == moves.count('L') and moves.count('U') == moves.count('D')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
1. 检查先决条件
2. 定义子程序要解决的问题
3. 为子程序命名
4. 决定如何测试子程序
5. 在标准库中搜寻可用的功能
6. 考虑错误处理
7. 考虑效率问题
8. 研究算法和数据类型
9. 编写伪代码
1. 首先简要地用一句话来写下该子程序的目的,
2. 编写很高层次的伪代码
3. 考虑数据
4. 检查伪代码
10. 在伪代码中试验一些想法,留下最好的想法
'''
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
import re
s = re.search(needle, haystack)
return s.start() if s else -1
sol = Solution()
assert sol.strStr("hello", "ll") == 2
assert sol.strStr("aaaaa", "bba") == -1
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Stack.ArrayStack import ArrayStack
class Solution:
def calPoints(self, ops):
"""
:type ops: List[str]
:rtype: int
"""
self.mystack = ArrayStack()
self.mystack.push(0)
self.mystack.push(0)
for op in ops:
if op not in {'+', 'C', 'D'}:
self.mystack.push(op)
elif op == '+':
a = self.mystack.pop()
b = self.mystack.pop()
c = int(a) + int(b)
self.mystack.push(b)
self.mystack.push(a)
self.mystack.push(c)
elif op == 'D':
d = self.mystack.top()
self.mystack.push(d)
self.mystack.push(int(d) * 2)
elif op == 'C':
self.mystack.pop()
total = 0
while not self.mystack.isEmpty():
total += int(self.mystack.pop())
return total
if __name__ == '__main__':
s = Solution()
print(s.calPoints(["+"]))
print(s.calPoints(["5", "2", "C", "D", "+"]))
print(s.calPoints(["5", "-2", "4", "C", "D", "9", "+", "+"]))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
1. 检查先决条件
2. 定义子程序要解决的问题
3. 为子程序命名
4. 决定如何测试子程序
5. 在标准库中搜寻可用的功能
6. 考虑错误处理
7. 考虑效率问题
8. 研究算法和数据类型
9. 编写伪代码
1. 首先简要地用一句话来写下该子程序的目的,
2. 编写很高层次的伪代码
3. 考虑数据
4. 检查伪代码
10. 在伪代码中试验一些想法,留下最好的想法
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if not head:
return None
t = []
while head:
t.append(head.val)
head = head.next
t[m - 1:n] = t[m - 1:n][::-1]
res = tmp = ListNode(1)
for i in t:
tmp.next = ListNode(i)
tmp = tmp.next
return res.next
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
1. 检查先决条件
2. 定义子程序要解决的问题
3. 为子程序命名
4. 决定如何测试子程序
5. 在标准库中搜寻可用的功能
6. 考虑错误处理
7. 考虑效率问题
8. 研究算法和数据类型
9. 编写伪代码
1. 首先简要地用一句话来写下该子程序的目的,
2. 编写很高层次的伪代码
3. 考虑数据
4. 检查伪代码
10. 在伪代码中试验一些想法,留下最好的想法
'''
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_ = 0
count = 0
for i in nums:
if i == 1:
max_ += 1
if count < max_:
count = max_
else:
max_ = 0
return count
if __name__ == '__main__':
solution = Solution()
print(solution.findMaxConsecutiveOnes([1, 0, 1, 1, 1, 0, 1]))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
1. 检查先决条件
2. 定义子程序要解决的问题
3. 为子程序命名
4. 决定如何测试子程序
5. 在标准库中搜寻可用的功能
6. 考虑错误处理
7. 考虑效率问题
8. 研究算法和数据类型
9. 编写伪代码
1. 首先简要地用一句话来写下该子程序的目的,
2. 编写很高层次的伪代码
3. 考虑数据
4. 检查伪代码
10. 在伪代码中试验一些想法,留下最好的想法
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
p = None
while head:
q = head
head = head.next
q.next = p
p = q
return p
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
while val in nums:
nums.remove(val)
return len(nums)
sol = Solution()
assert sol.removeElement([3, 2, 2, 3], 3) == 2
|
import os
import sys
def start():
while True:
choice = int(input("Enter number: 1-encode, 2-decode, 3-quit\n"))
if choice == 1:
encrypt()
elif choice == 2:
decrypt()
elif choice == 3:
break
else:
print("Unknown command")
def encrypt():
#Выбираем степень кодирования
degree = int(input("Enter degree of encoding: 1/2/4/8:\n"))
#Проверка на возможную длину текста для данной картинки
text_len = os.stat('text2.txt').st_size
img_len = os.stat('start.bmp').st_size
if text_len >=img_len * degree / 8 -54:
print("Too long text")
return
#Считываем текст
text = open('text2.txt', 'r')
#Открываем данное изображение
start_bmp = open('start.bmp', 'rb')
#Создаем сообщение с информацией
encode_bmp = open('finish.bmp', 'wb')
first54 = start_bmp.read(54)
#print(first54)
#В новой картинке певые54бит такие же как в оригинале
encode_bmp.write(first54)
#просмотр маски
text_mask, img_mask = create_masks(degree)
print(bin(text_mask))
while True:
symbol = text.read(1)
if not symbol:
break
#print("\nSymbol {0}, bin {1:b}".format(symbol, ord(symbol)))
symbol = ord(symbol)
for byte_amount in range(0, 8, degree):
#Преобразуем из байт в инт и накладываем маску
img_byte = int.from_bytes(start_bmp.read(1), sys.byteorder) & img_mask
bits = symbol & text_mask
bits >>=(8 - degree)
#print("img {0}, bits {1:b}, num {1:d}".format(img_byte, bits))
img_byte |= bits
#print('Encoded ' + str(img_byte))
#print('Writing: ' + str(img_byte.to_bytes(1, sys.byteorder)))
encode_bmp.write(img_byte.to_bytes(1, sys.byteorder))
symbol <<= degree
# print(start_bmp.tell())
encode_bmp.write(start_bmp.read())
#Закрываем то ,что понаоткрывали
text.close()
start_bmp.close()
encode_bmp.close()
def decrypt():
degree = int(input("Enter degree of encoding: 1/2/4/8:\n"))
to_read = int(input("How many symbols to read:\n"))
img_len = os.stat('finish.bmp').st_size
if to_read >=img_len * degree / 8 -54:
print("Too long text")
return
text = open('decoded.txt', 'w')
encoded_bmp = open('finish.bmp', 'rb')
encoded_bmp.seek(54)
text_mask, img_mask = create_masks(degree)
img_mask = ~img_mask
read = 0
while read < to_read:
symbol = 0
for bits_read in range(0, 8, degree):
img_byte = int.from_bytes(encoded_bmp.read(1), sys.byteorder) & img_mask
symbol <<=degree
symbol |=img_byte
#print("Symbol #{0} is {1:c}".format(read, symbol))
read +=1
text.write(chr(symbol))
text.close()
encoded_bmp.close()
#Создание масок к логическим операциям
def create_masks(degree):
text_mask = 0b11111111
img_mask = 0b11111111
text_mask <<= (8 - degree)
text_mask%= 256
img_mask >>= degree
img_mask <<= degree
return text_mask, img_mask
start()
|
from node import Node
class Queue:
def __init__(self):
self.size = 0
self.first = None
self.last = None
def isEmpty(self):
return self.size == 0
def enqueue(self, val):
node = Node(val)
if self.isEmpty():
self.first = node
else:
self.last.setNextNode(node)
self.last = node
self.size += 1
def getFirst(self):
return self.first
def dequeue(self):
old_first = self.first
self.first = self.first.getNextNode()
self.size -= 1
return old_first.getVal()
|
##############################
# define class
##############################
# class Classname(object): Chang's example
# <define attributes here>
"""
import math
class Coordinate(object):
# this class define a coordinate with x any y attribue
def __init__(self,x,y):
self.x = x
self.y = y
# def distance(self,other):
# # calculate self distance with another coordinate
# return math.sqrt((self.x - other.x) ** 2 + (self.y - other.y)**2)
class Plot(object):
def __init__(self, name):
self.name=name
def distance(self, one, another):
return math.sqrt((one.x - another.x) ** 2 + (one.y - another.y)**2)
point1 = Coordinate(3,4)
point2 = Coordinate(1,3)
# print("calculating distance...")
# print(point1.distance(point2))
# print(point2.distance(point1))
plot1 = Plot('Chang的坐标系')
print(plot1.distance(point1,point2))
# MIT example:
class Coordinate(object):
def __init__(self,x,y):
self.x = x
self.y = y
def distance(self,other):
x_diff_sq = (self.x - other.x) ** 2
y_diff_sq = (self.y - other.y) ** 2
return (x_diff_sq + y_diff_sq) ** 0.5
def __str__(self):
return '<' + str(self.x) + ',' + str(self.y) + '>'
def __sub__(self,other):
return Coordinate(self.x - other.x,self.y - other.y)
c = Coordinate(3,4)
origin = Coordinate(0,0)
print(c.distance(origin)) # = print(Coordinate.distance(c,origin))
print(type(c))
# use isinstance() to check if an object is a Coordinate
print(isinstance(c,Coordinate))
print(c.__str__())
print(c.__sub__(origin))
########################################
# Classes Examples
########################################
class fraction(object):
def __init__(self,numer,denom):
self.numer = numer
self.denom = denom
def __str__(self):
return str(self.numer) + '/' + str(self.denom)
def getNumer(self):
return self.numer
def getDenom(self):
return self.denom
def __add__(self,other):
numerNew = other.getDenom() * self.getNumer() + self.getDenom() * other.getNumer()
denomNew = other.getDenom() * self.getDenom()
return fraction(numerNew,denomNew) ########## ??????????????? fraction
def __sub__(self, other):
numerNew = other.getDenom() * self.getNumer() - self.getDenom() * other.getNumer()
denomNew = other.getDenom() * self.getDenom()
return numerNew / denomNew
def convert(self):
return self.getNumer() / self.getDenom()
oneHalf = fraction(1,2)
twoThird = fraction(2,3)
new = oneHalf + twoThird
sub = oneHalf - twoThird
print(oneHalf)
print(oneHalf.getNumer()) # = print(fraction.getNumer(oneHalf)
print(new.convert())
print(sub)
# Example 2: a set of integers
class intset(object):
def __init__(self):
self.vals = []
def insert(self,e):
if e not in self.vals:
self.vals.append(e)
return self.vals
def member(self,e):
return e in self.vals
def remove(self,e):
try:
self.vals.remove(e)
except:
raise ValueError(str(e) + ' not found')
def __str__(self):
self.vals.sort()
result = ''
for e in self.vals:
result = result + str(e) + ','
return '{' + result[:-1] + '}'
s = intset()
s.insert(5)
print(s.member(3))
print(s)
########################################
# Why OOP
########################################
# 1.
class Animal(object):
def __init__(self,age):
self.age = age
self.name = None
def get_age(self):
return self.age
def get_name(self):
return self.name
def set_age(self,newage):
self.age = newage
def set_name(self,newname):
self.name = newname
def __str__(self):
return "animal:" + str(self.name) + ":" + str(self.age)
# getter and setter could be used outside of class to access data attributes
myAnimal = Animal(3)
# print(myAnimal)
myAnimal.set_name('chang')
# print(myAnimal)
########################################
# Hierarchies:
########################################
class Cat(Animal):
def speak(self):
print("meow")
def __str__(self):
return "cat:" + str(self.name) + ":" + str(self.age) # override behaviour
jelly = Cat(1)
print(jelly.get_name())
jelly.set_name('JellyBelly')
print(jelly.get_name())
print(jelly)
class Rabbit(Animal):
def speak(self):
return "meep"
def __str__(self):
return "rabbit:" + str(self.name) + ":" + str(self.age)
Peter = Rabbit(5)
print(jelly.speak())
print(Peter.speak())
class Person(Animal):
def __init__(self,name,age):
Animal.__init__(self,age)
Animal.set_name(self,name)
self.friends = []
def get_friends(self):
return self.friends
def add_friend(self,fname):
if name not in self.friends:
self.friends.append(fname)
def speak(self):
print('hello')
def age_diff(self,other):
diff = self.get_age() - other.get_age()
return diff
def __str__(self):
return "person:" + str(self.name) + ":" + str(self.age)
Eric = Person('eric',45)
print(Eric)
other = Person('Cindy',18)
print(Eric.age_diff(other))
import random
class Student(Person):
def __init__(self,name,age,major = None):
Person.__init__(self,name,age)
self.major = major
def change_major(self,major):
self.major = major
def speak(self):
r = random.random()
if r < 0.25:
print('i have homework')
elif 0.25 < r <= 0.5:
print('i need sleep')
elif 0.5 < r <= 0.75:
print('i should eat')
else:
print('i am watching TV')
def __str__(self):
return "student" + str(self.name) + ":" + str(self.age) + ":" + str(self.major)
cindy = Student('Cindy',25,'cs')
print(cindy)
print(cindy.speak())
cindy.change_major('ba')
print(cindy)
########################################
# Class Variables:
########################################
class Animal(object):
def __init__(self,age):
self.age = age
self.name = None
def get_age(self):
return self.age
def get_name(self):
return self.name
def set_age(self,newage):
self.age = newage
def set_name(self,newname):
self.name = newname
def __str__(self):
return "animal:" + str(self.name) + ":" + str(self.age)
class Rabbit(Animal):
tag = 1
def __init__(self,age,parent1 = None, parent2 = None):
Animal.__init__(self,age)
self.parent1 = parent1
self.parent2 = parent2
self.rid = Rabbit.tag
Rabbit.tag += 1 # tag used to give unique id to each new Rabbit instance
def get_rid(self):
return str(self.rid).zfill(3)
def get_parent1(self):
return self.parent1
def get_parent2(self):
return self.parent2
def __add__(self, other):
return Rabbit(0, self, other)
def __eq__(self,other):
parents_same = self.parent1.rid == other.parent1.rid and self.parent2.rid == other.parent2.rid
parents_opposite = self.parent2.rid == other.parent1.rid and self.parent1.rid == other.parent2.rid
return parents_opposite or parents_same
peter = Rabbit(2)
peter.set_name('Peter')
hopsy = Rabbit(3)
hopsy.set_name('Hopsy')
cotton = Rabbit(1,peter,hopsy)
# print(cotton)
# print(cotton.get_parent1)
mopsy = peter + hopsy # define + operator
mopsy.set_name('Mopsy')
# print(mopsy.get_parent1())
# print(mopsy.get_parent2())
print(cotton.rid)
print(mopsy.rid)
print(mopsy.__eq__(cotton))
"""
########################################
# Building a class
########################################
import datetime
class Person(object):
def __init__(self,name):
self.name = name
self.birthday = None
self.lastName = name.split(' ')[-1]
def getLastName(self):
return self.lastName
def __str__(self):
return self.name
def setBirthday(self,month,day,year):
self.birthday = datetime.date(year,month,day)
def getAge(self):
if self.birthday == None:
raise ValueError
return (datetime.date.today() - self.birthday).days
def __lt__(self,other): # sort function
if self.lastName == other.lastName:
return self.name < other.name
return self.lastName < other.lastName
def __str__(self):
return self.name
def speak(self,utterance):
return (self.getLastName() + " says: " + utterance)
# cindy = Person('Cindy Yuan')
# cindy.setBirthday(6,15,1992)
# print(cindy.lastName)
# print(cindy.birthday)
# print(cindy.getAge())
# m1 = Person('Chang Liu')
# m1.setBirthday(5,7,1993)
# m2 = Person('Cindy Yuan')
# m2.setBirthday(6,15,1992)
# m3 = Person('Qian Lin')
# m3.setBirthday(8,14,1995)
#
# personList = [p1,p2,p3]
# personList.sort()
#
# for e in personList:
# print(e)
#
class MITPerson(Person):
nextIdNum = 0
def __init__(self,name):
Person.__init__(self,name)
self.idNum = MITPerson.nextIdNum
MITPerson.nextIdNum += 1
def getIdNum(self):
return self.idNum
def __lt__(self,other):
return self.idNum < other.idNum
def speak(self,utterance):
return (self.getLastName() + " says: " + utterance)
#
p1 = MITPerson('Eric')
p2 = MITPerson('John')
p3 = MITPerson('John')
p4 = Person('John')
#
# print(p1.idNum)
# print(p2.idNum)
#
# print(p1 < p2) # --> p1.__lt__(p2) MITPerson.__lt__
# # print(p1 < p4) # --> p1.__lt__(p4)
# print(p4 < p1) # --> p4.__lt__(p1) Person.__lt__
#############################
# Add another class
#############################
class Student(MITPerson):
pass
class UG(Student):
def __init__(self,name,classYear):
MITPerson.__init__(self,name)
self.year = classYear
def getClass(self):
return self.year
def speak(self,utterance):
return MITPerson.speak(self, " Dude, " + utterance)
class Grad(Student):
pass
class TransferStudent(Student):
pass
def isStudent(obj):
# return isinstance(obj,UG) or isinstance(obj,Grad) or isinstance(obj,TransferStudent)
return isinstance(obj,Student)
# s1 = UG('Matt Damon',2017)
# s2 = UG('Ben Affleck',2017)
# s3 = UG('Lin Manuel Mirande',2018)
# s4 = Grad('Leonardo di Caprio')
# #
# print(s1)
# print(s1.getClass())
# print(s1.speak('where is the quiz?'))
# print(s2.speak('I have no idea'))
#
# print(isStudent(s3))
#############################
# Using Inherited Methods
#############################
class Professor(MITPerson):
def __init__(self,name,department):
MITPerson.__init__(self,name)
self.department = department
def speak(self,utterance):
new = 'In course ' + self.department + ' we say '
return MITPerson.speak(self,new + utterance)
def lecture(self,topic):
return self.speak('it is obvious that ' + topic)
# print(m1.speak('hi there'))
# print(s1.speak('Hi, there'))
#
# faculty = Professor('Doctor Arrogant','six')
# print(faculty.speak('hi, there'))
#
# print(faculty.lecture('hi, there'))
#############################
# Gradebook Example
#############################
# create class that includes instances of other classes within it
class Grades(object):
def __init__(self):
self.students = []
self.grades = {}
self.isSorted = True
def addStudent(self,student):
# assume student is a type of Student
if student in self.students:
raise ValueError('Duplicate student')
self.students.append(student)
self.grades[student.getIdNum()] = []
self.isSorted = False
def addGrade(self,student,grade):
try:
self.grades[student.getIdNum()].append(grade)
except:
raise ValueError ('Student not in grade book')
def getGrade(self,student):
try:
a = student.getIdNum()
b = self.grades[a]
return b[:] # return a copy
except:
raise ValueError('Student not in grade book')
def allStudents(self):
if not self.isSorted:
self.students.sort()
self.isSorted = True
return self.students[:] # return a copy
def gradeReport(course):
# assume course is of type grades
report = []
for s in course.allStudents():
tot = 0.0
numGrades = 0
for g in course.getGrade(s):
tot += g
numGrades += 1
try:
average = tot/numGrades
report.append(str(s) + '\'s mean grade is ' + str(average))
except ZeroDivisionError:
report.append(str(s) + ' has no grades')
return '\n'.join(report)
ug1 = UG('Matt Damon',2018)
ug2 = UG('Ben Affleck',2019)
ug3 = UG('Drew Houston',2017)
ug4 = UG('Mark Zuckerberg',2017)
g1 = Grad('Bill Gates')
g2 = Grad('Steve Wozniak')
six00 = Grades()
six00.addStudent(g1)
six00.addStudent(ug1)
six00.addStudent(g2)
six00.addStudent(ug2)
six00.addStudent(ug3)
six00.addStudent(ug4)
six00.addGrade(g1,100)
six00.addGrade(g1,90)
six00.addGrade(g2,25)
six00.addGrade(g2,45)
six00.addGrade(ug1,95)
six00.addGrade(ug1,80)
six00.addGrade(ug2,85)
six00.addGrade(ug2,75)
six00.addGrade(ug3,75)
six00.addGrade(ug4,45)
print(gradeReport(six00))
#print(six00.getGrade(ug4))
|
import time, os, sys, transpo_encrypt, transpo_decrypt
def main():
input_filename = 'frankenstein.txt'
output_filename = 'frankenstein.encrypted.txt'
my_key = 10
my_mode = 'encrypt'
# if the input file does not exist, the program terminates early
if not os.path.exists(input_filename):
print('The file %s does not exist. Quitting...' % (input_filename))
sys.exit()
# if the output file already exists, give the user a chance to quit
if os.path.exists(input_filename):
print('This will overwrite the file %s. (C)ontinue or (Q)uit' % (output_filename))
response = input('> ')
if not response.lower().startswith('c'):
sys.exit()
# read in the message from the input file
file_obj = open(input_filename)
content = file_obj.read()
file_obj.close()
print('%sing...' % (my_mode.title()))
# measure how long the encryption/decrytion takes
start_time = time.time()
if my_mode == 'encrypt':
translated = transpo_encrypt.encrypt_message(my_key, content)
elif my_mode == 'decrypt':
translated = transpo_encrypt.encrypt_message(my_key, content)
total_time = round(time.time() - start_time, 2)
print('%sion time: %s seconds' % (my_mode.title(), total_time))
# write out the translated message to the output file
output_file_obj = open(output_filename, 'w')
output_file_obj.write(translated)
output_file_obj.close()
print('Done %sing %s.' % (my_mode.title(), output_filename))
# if transposition cipher file is run instead of imported as a module
if __name__ == '__main__':
main()
|
import unittest
import data
import output
class DataTest(unittest.TestCase):
def setUp(self):
self.student1 = data.Student("1", "A")
self.test1 = data.Test("1", "1", "10")
self.test1.marks['1'] = "78"
self.test2 = data.Test("2", "1", "40")
self.test2.marks['1'] = "87"
self.test3 = data.Test("3", "1", "50")
self.test3.marks['1'] = "95"
data.DataStore.tests['1'] = self.test1
data.DataStore.tests['2'] = self.test2
data.DataStore.tests['3'] = self.test3
self.student2 = data.Student("2", "B")
self.test1.marks["2"] = "78"
self.test2.marks["2"] = "87"
self.test3.marks["2"] = "15"
def test_computeGrades(self):
self.student1.computeGrades()
self.assertEqual(round(self.student1.grades['1'], 2), 90.1)
self.student2.computeGrades()
self.assertEqual(round(self.student2.grades['1'], 2), 50.1)
def test_computeAverage(self):
self.student1.grades = {"1": 90.1, "2": 51.8, "3": 74.2}
self.student1.computeAverage()
self.assertEqual(round(self.student1.average, 2), 72.03)
if __name__ == '__main__':
unittest.main() |
## A Word Game: Words With Friends / Scrabble
# Part 1: Word Scores
def getWordScore(word, n):
"""
Returns the score for a word. Assumes the word is a valid word.
"""
score = 0
SUM = 0
for char in word:
SUM += SCRABBLE_LETTER_VALUES[char]
if len(word) == n:
score = (SUM)*len(word) + 50
else:
score = (SUM)*len(word)
return score
# Part 2: Dealing With Hands
def updateHand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that letter in it.
returns: dictionary (string -> int)
"""
updated = hand.copy()
for letter in word:
updated[letter] = updated[letter] - 1
return updated
# Part 3: Valid Words
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
"""
if word not in wordList:
return False
for i in word:
if word.count(i) > hand.get(i, 0):
return False
return True
# Part 4: Hand Length
def calculateHandlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string int)
returns: integer
"""
h = 0
for i in range(len(hand)):
h += hand[hand.keys()[i]]
return h
# Part 5: Playing a Hand
def playHand(hand, wordList, n):
"""
Allows the user to play the given hand.
"""
score = 0
total = hand.copy()
while calculateHandlen(total) > 0:
print 'Current Hand: ',
print (displayHand(total))
word = raw_input('Enter word, or a "." to indicate that you are finished: ')
if word == '.':
break
else:
if isValidWord(word, total, wordList) == False:
print ('Invalid word, please try again.\n')
else:
score += getWordScore(word, n)
print '"'+str(word) + '" earned '+str(getWordScore(word, n))+' points. Total: '+str(score)+' points.'
total = updateHand(total, word)
if calculateHandlen(total) > 0:
print 'Goodbye! Total score: '+str(score)+ ' points.'
else:
print 'Run out of letters. Total score: '+ str(score) + ' points.'
# Part 6: Playing a Game
def playGame(wordList):
"""
Allow the user to play an arbitrary number of hands.
"""
userInput = None
newHand = None
while userInput != 'e':
userInput = raw_input('Enter n to deal a new hand, '
'r to replay the last hand, or e to end game: ')
if userInput == 'n':
newHand = dealHand(HAND_SIZE)
playHand(newHand.copy(), wordList, HAND_SIZE)
print
elif userInput == 'r':
if newHand == None:
print ('You have not played a hand yet.'
' Please play a new hand first!')
print
else:
playHand(newHand.copy(), wordList, HAND_SIZE)
elif userInput != 'e':
print 'Invalid command'
# Part 7: Computer Chooses a Word
def compChooseWord(hand, wordList, n):
"""
Given a hand and a wordList, find the word that gives
the maximum value score, and return it.
"""
maxScore = 0
bestWord = None
for i in wordList:
if isValidWord(i,hand,wordList):
score = getWordScore(i,n)
if score > maxScore:
maxScore = score
bestWord = i
return bestWord
# Part 8: Computer Plays a Hand
def compChooseWord(hand, wordList, n):
"""
Given a hand and a wordList, find the word that gives
the maximum value score, and return it.
"""
maxScore = 0
bestWord = None
for i in wordList:
if isValidWord(i,hand,wordList):
score = getWordScore(i,n)
if score > maxScore:
maxScore = score
bestWord = i
# return the best word you found.
return bestWord
def compPlayHand(hand, wordList, n):
"""
Allows the computer to play the given hand, following the same procedure
as playHand, except instead of the user choosing a word, the computer
chooses it.
"""
def displayNewHand(hand):
disp = ''
for letter in hand.keys():
for j in range(hand[letter]):
disp += letter + ' '
return disp
newHand = hand.copy()
newScore = 0
while compChooseWord(newHand, wordList, n):
print "Current Hand: " + displayNewHand(newHand)
newWord = compChooseWord(newHand, wordList, n)
scores = getWordScore(newWord,n)
newScore += scores
print '"'+ newWord + '" ' + "earned " + str(scores) + " points. Total: " + str(newScore) + " points"
print
newHand = updateHand(newHand, newWord)
if sum(newHand.values()) != 0:
print "Current Hand: " + displayNewHand(newHand)
print "Total score: " + str(newScore) + " points"
# Part 9: You and Your Computer.
def playGame(wordList):
"""
Allow the user to play an arbitrary number of hands.
wordList: list (string)
"""
newHands = None
userIn = raw_input('Enter n to deal a new hand, '
'r to replay the last hand, or e to end game: ')
while userIn != 'e':
if userIn == 'n':
newHands = dealHand(HAND_SIZE)
elif userIn == "r":
if newHands == None:
print ('You have not played a hand yet.'
' Please play a new hand first!')
userIn = raw_input("Enter n to deal a new hand, r to replay the " +
"last hand, or e to end game: ")
print
continue
else:
print 'Invalid command.'
print
userIn = raw_input("Enter n to deal a new hand, r to replay the " +
"last hand, or e to end game: ")
print
continue
playerTurn = raw_input("Enter u to have yourself play, c to have the " +
"computer play: ")
while playerTurn != "c" and playerTurn != "u":
print 'Invalid command'
print
playerTurn = raw_input("Enter u to have yourself play, c to have " +
"the computer play: ")
if playerTurn == "u":
playHand(newHands, wordList, HAND_SIZE)
else:
compPlayHand(newHands, wordList, HAND_SIZE)
userIn = raw_input("Enter n to deal a new hand, r to replay the last " +
"hand, or e to end game: ")
print |
def cubeRoot(n):
t = 0
for i in range(abs(n)):
t += 1
if i**3 == abs(n):
break
print(t)
if i**3 != abs(n):
print('Not')
else:
if n < 0:
i = -i
print(str(i)+ ' is cube root of ' + str(n))
|
import math
import random
class Node:
def __init__(self, value):
self.value = value
self.children = {}
def print_tree(self):
a = [self.value]
for key, test in self.children.items():
a.append(self.children[key].print_tree())
return a
def print_tree_test(self):
if len(self.children) == 0:
return str(self.value)
else:
temp = str(self.value)
for key, test in self.children.items():
temp += self.children[key].print_tree()
return temp
def read_data_text_file(file_name):
"""
Reads the file and returns the data
"""
file = open(file_name, 'r')
data = []
for line in file:
data.append(line.rstrip('\n').split('\t'))
return data
def get_outputs(data):
"""
Get list of outputs from data
"""
outputs = []
for example in data:
outputs.append(example[-1])
return outputs
def is_same_output(examples):
"""
Checks if all data have the same classification/output
"""
outputs = get_outputs(examples)
last_output = outputs[0]
for output in outputs:
if last_output is not output:
return False
last_output = output
return True
def plurality_value(examples):
"""
Get the most common output value among a set of examples, breaking ties randomly
"""
outputs = get_outputs(examples)
max_count = 0
most_common_output = None
for x in set(outputs):
count = examples.count(x)
if count > max_count:
max_count = count
most_common_output = x
return most_common_output
def B(q):
if q == 0 or q == 1:
return q
else:
return -(q * math.log(q, 2) + (1 - q) * math.log((1 - q), 2))
def entropy(examples, attribute):
"""
Calculate entropy of attribute
"""
position = 0
if len(examples) == 0:
return 0
for i in examples:
if i[attribute] == examples[0][attribute]:
position += 1
return B(position / len(examples))
def importance(examples, attributes):
"""
Get attribute with lowest entropy
"""
attribute_entropy = {}
for attribute in attributes:
attribute_entropy[attribute] = entropy(examples, attribute)
min_value = 10
chosen_attribute = None
for e in attribute_entropy:
if attribute_entropy[e] < min_value:
min_value = attribute_entropy[e]
chosen_attribute = e
return chosen_attribute
def random_attribute(attributes):
"""
Get a random attribute
"""
return attributes[random.randint(0, len(attributes) - 1)]
def get_attribute_value_set(examples, chosen_attribute):
"""
Returns a set of possible values for an attribute
"""
possible_attribute_values = []
for example in examples:
if example[chosen_attribute] not in possible_attribute_values:
possible_attribute_values.append(example[chosen_attribute])
possible_attribute_values.sort()
return possible_attribute_values
def decision_tree_learning(examples, attributes, parent_examples, importance_enabled):
"""
Recursive function that creates trains a decision tree based on data examples.
"""
if not examples:
return Node(plurality_value(parent_examples))
elif is_same_output(examples):
return Node(examples[0][-1]) # Return classification
elif not attributes:
return Node(plurality_value(examples))
else:
if importance_enabled:
chosen_attribute = importance(examples, attributes)
else:
chosen_attribute = random_attribute(attributes)
tree = Node(chosen_attribute)
attribute_value_set = get_attribute_value_set(examples, chosen_attribute)
for possible_attribute_value in attribute_value_set:
chosen_examples = []
for example in examples:
if example[chosen_attribute] == possible_attribute_value:
chosen_examples.append(example)
updated_attributes = list(attributes)
updated_attributes.remove(chosen_attribute)
subtree = decision_tree_learning(chosen_examples, updated_attributes, examples, importance_enabled)
tree.children[possible_attribute_value] = subtree
return tree
def classify(tree, example):
"""
Classify example with tree
"""
while tree.children:
print("Example: ", example)
print("Tree.value:", tree.value)
print("Tree.children", tree.children)
tree = tree.children[example[tree.value]]
return tree.value
def test(tree, examples):
"""
Returns results of testing for a tree
"""
correct_count = 0
for example in examples:
if example[-1] == classify(tree, example):
correct_count += 1
print("Tests matching: " + str(correct_count) + " of " + str(len(examples)) + ". Accuracy: " + str(
(correct_count / len(examples)) * 100) + "%")
if __name__ == '__main__':
# Get training data and attributes
training_data = read_data_text_file('training.txt')
attributes = [x for x in range(len(training_data[0]) - 1)]
# Get test data
test_data = read_data_text_file('test.txt')
# Random tree
print("Random Tree")
random_tree = decision_tree_learning(training_data, attributes, [], False)
print(random_tree.print_tree())
test(random_tree, test_data)
# Importance tree
print("\nImportance tree")
importance_tree = decision_tree_learning(training_data, attributes, [], True)
print(importance_tree.print_tree())
test(importance_tree, test_data)
|
# Euler - problem 56
"""A googol (10^100) is a massive number: one followed by one-hundred zeros; 100^100
is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum
of the digits in each number is only 1. Considering natural numbers of the form, a^b,
where a, b < 100, what is the maximum digital sum?"""
maxsum = 1
for a in range(1, 100):
for b in range(1, 100):
strnum = str(a**b)
maxsum = max(maxsum, sum([int(digit) for digit in strnum]))
print maxsum
|
# Euler - problem 22
"""Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over
five-thousand first names, begin by sorting it into alphabetical order. Then working out the
alphabetical value for each name, multiply this value by its alphabetical position in the list to
obtain a name score. For example, when the list is sorted into alphabetical order, COLIN,
which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would
obtain a score of 938 x 53 = 49714. What is the total of all the name scores in the file?"""
import sys
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
f = open(sys.argv[1], 'rU')
text = f.read()
names = sorted(text.split(','))
namescore = 0
for index, name in enumerate(names):
namescore += sum([(alphabet.find(char) + 1)*(index + 1) for char in name])
print namescore
|
#Euler - problem 5
""" 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without
any remainder. What is the smallest positive number that is evenly divisible by all of the numbers
from 1 to 20?"""
# This code solves the more general problem of finding the smallest positive integer evenly
# divisible by all numbers from 1 to maxfactor
from operator import mul
from math import sqrt
def isfactor(num1, num2):
return num1%num2 == 0
factors = [1]
maxfactor = 20
duplicates = []
for num in range(2, maxfactor + 1):
#IDEA: add number to factor set only if it is not a factor of the product of existing factors
if not isfactor(reduce(mul, factors), num):
factors.append(num)
#IDEA: remove factors of factors
for factor in factors[:-1]:
if isfactor(factors[-1], factor):
del factors[factors.index(factor)]
break
print reduce(mul, factors)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 15 09:02:12 2020
@author: trismonok
"""
import socket
import sys
# create a socket (coonnect two computer)
def create_socket():
try:
global host
global port
global s
host = ""
port = 9999
s = socket.socket()
except socket.error as msg:
print("Socket creation error: " + str(msg))
# Binding the socket and listening for connections
def bind_socket():
try:
global host
global port
global s
print("Binding the port " + str(port))
s.bind((host,port))
s.listen(5)
except socket.error as msg:
print("Socket binding error" + str(msg) + "\n" + "Retrying ...")
# recursive function
bind_socket()
# Establish connection with a client (socket must be listening)
def socket_accept():
conn, address = s.accept()
print("Connection has been established! | IP " + address[0] + " | Port " + str(address[1]))
send_command(conn)
conn.close()
# Send commands to client
def send_command(conn):
while True:
cmd = input()
if cmd == "quit" or cmd=="exit":
conn.close()
s.close()
sys.exit()
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
client_response = str(conn.recv(1024), "utf-8")
print(client_response, end="")
# main finction
def main():
create_socket()
bind_socket()
socket_accept()
# run main function:
main()
|
class Human:
def __init__(self, name, age=0):
self._name = name
self._age = age
def _say(self, text):
print(text)
def say_name(self):
self._say(f'Hello, I am {self._name}')
def say_how_old(self):
self._say(f'I am {self._age} years old')
class Planet:
def __init__(self, name, population=None):
self.name = name
self.population = population or []
def add_human(self, human):
print(f'Welcome to {self.name}, {human._name}!')
self.population.append(human)
mars = Planet('Mars')
bob = Human('Bob', age=29)
mars.add_human(bob)
bob.say_name()
bob.say_how_old()
|
class EvenLengthMixin:
def even_length(self):
return len(self) % 2 == 0
class MyList(list, EvenLengthMixin):
def pop(self):
x = super(MyList, self).pop()
print('Last value is', x)
return x
class MyDict(dict, EvenLengthMixin):
pass
x = MyDict()
x['key'] = 'value'
x['another_key'] = 'another_value'
print(x.even_length()) # True
ml = MyList([1, 2, 4, 17])
z = ml.pop()
print(z)
print(ml) |
import pandas as pd
s = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
print(s)
d = {'Moscow': 1000, 'London': 300, 'New York': 150, 'Barcelona': None}
cities = pd.Series(d)
print(cities)
print(cities['Moscow'])
print(cities[['Moscow', 'London']])
print(cities < 1000)
print(cities[cities < 1000])
cities['Moscow'] = 100
print(cities)
cities[cities < 1000] = 3
print(cities)
print(cities * 3)
print(cities[cities.isnull()])
print(cities[cities.notnull()])
|
def bubble_sort(A):
"""
Sort on place with Bubblesort algorithm
:type A: list
"""
for bypass in range(1, len(A)):
for k in range(0, len(A) - bypass):
if A[k] > A[k+1]:
A[k], A[k+1] = A[k+1], A[k]
def test_sort():
A = [4, 2, 5, 1, 3]
B = [1, 2, 3, 4, 5]
bubble_sort(A)
print("#1:", "Ok" if A == B else 'Fail')
A = list(range(40, 80)) + list(range(40))
B = list(range(80))
bubble_sort(A)
print('#2:', 'Ok' if A == B else 'Fail')
A = [4, 2, 4, 2, 1]
B = [1, 2, 2, 4, 4]
bubble_sort(A)
print('#3:', 'Ok' if A == B else 'Fail')
print(test_sort())
|
class User:
def __init__(self, name, email):
self.name = name
self.email = email
def get_email_data(self):
return {
'name': self.name,
'email': self.email
}
jane = User('Jane Doe', 'janedoe@example.com')
print(jane.get_email_data())
class Singleton:
instance = None
def __new__(cls):
if cls.instance is None:
cls.instance = super().__new__(cls)
return cls.instance
a = Singleton()
b = Singleton()
print(a is b)
class User:
def __init__(self, name, email):
self.name = name
self.email = email
def __str__(self):
return f'{self.name} <{self.email}>'
jane = User('Jane Doe', 'janedoe@example.com')
print(jane)
class User:
def __init__(self, name, email):
self.name = name
self.email = email
def __hash__(self):
return hash(self.email)
def __eq__(self, obj):
return self.email == obj.email
jane = User('Jane Doe', 'jdoe@example.com')
joe = User('Joe Doe', 'jdoe@example.com')
print(jane == joe)
print(hash(jane))
print(hash(joe))
user_email_map = {user: user.name for user in [jane, joe]}
print(user_email_map)
class Researcher:
def __getattr__(self, name):
return 'Nothing found :()\n'
def __getattribute__(self, name):
print(f'Looking for {name}')
return object.__getattribute__(self, name)
obj = Researcher()
print(obj.attr)
print(obj.method)
print(obj.DFJ2H3J00KLL)
class Ignorant:
def __setattr__(self, name, value):
print(f'Not gonna set {name}!')
obj = Ignorant()
obj.math = True
# print(obj.math)
class Polite:
def __delattr__(self, name):
value = getattr(self, name)
print(f'Good {name}, you were {value}!')
object.__delattr__(self, name)
obj = Polite()
obj.attr = 10
del obj.attr
class Logger:
def __init__(self, filename):
self.filename = filename
def __call__(self, func):
def wrapped(*args, **kwargs):
with open(self.filename, 'a') as f:
f.write('Oh Danny boy...')
return func(*args, *kwargs)
return wrapped
logger = Logger('log.txt')
@logger
def completely_useless_function():
pass
import random
class NoisyInt:
def __init__(self, value):
self.value = value
def __add__(self, obj):
noise = random.uniform(-1, 1)
return self.value + obj.value + noise
a = NoisyInt(10)
b = NoisyInt(20)
for _ in range(3):
print(a + b)
class PascalList:
def __init__(self, original_list=None):
self.container = original_list or []
def __getitem__(self, index):
return self.container[index - 1]
def __setitem__(self, index, value):
self.container[index - 1] = value
def __str__(self):
return self.container.__str__()
numbers = PascalList([1, 2, 3, 4, 5])
print(numbers[1])
numbers[5] = 25
print(numbers)
|
import re
from abc import ABC, abstractmethod
# create system
class System:
def __init__(self, text):
tmp = re.sub(r'\W', ' ', text.lower())
tmp = re.sub(r' +', ' ', tmp).strip()
self.text = tmp
def get_processed_text(self, processor):
result = processor.process_text(self.text)
print(*result, sep='\n')
# abstract class with abstract method
class TextProcessor(ABC):
@abstractmethod
def process_text(self, text):
pass
# counter words
class WordCounter:
def count_words(self, text):
self.__words = dict()
for word in text.split():
self.__words[word] = self.__words.get(word, 0) + 1
def get_count(self, word):
return self.__words.get(word, 0)
def get_all_words(self):
return self.__words.copy()
class WordCounterAdapter(TextProcessor):
def __init__(self, adaptee):
self.adaptee = adaptee
def process_text(self, text):
self.adaptee.count_words(text)
words = self.adaptee.get_all_words().keys()
return sorted(words,
key=lambda x: self.adaptee.get_count(x),
reverse=True)
text = 'В прошлом видео мы разобрались с паттерном проектирования Adapter. Поняли, зачем он применятся и в каких задачах используется. Давайте сейчас на практике разберемся, как реализовать паттерн Adapter с использованием языка программирования Python. Пусть у нас есть некоторая система, которая берет какой-то текст, делает его предварительную обработку, а дальше хочет вывести слова в порядке убывания их частоты. Но собственного обработчика у системы нету. Она принимает в качестве обработчика некоторый объект, который имеет интерфейс доступа, который вы видите сейчас на экране.'
# create instance of System
system = System(text)
# print(system)
# create instance of WordCounter
counter = WordCounter()
# raise AttributeError: 'WordCounter' object has no attribute 'process_text'
# system.get_processed_text(counter)
# create adapter for system
adapter = WordCounterAdapter(counter)
system.get_processed_text(adapter)
|
from pprint import pprint
import requests
city = input('City? ')
api_key = 'e7bb679b81c3710fc4192bcc1018a907'
api_url = 'http://api.openweathermap.org/data/2.5/weather'
params = {
'q': city,
'appid': api_key,
'units': 'metric'
}
'https://api.openweathermap.org/data/2.5/weather?q=Moscow&appid=e7bb679b81c3710fc4192bcc1018a907'
res = requests.get(api_url, params=params)
# print(res.status_code)
# print(res.headers['Content-Type'])
# pprint(res.json()) # return json.loads(res.text)
data = res.json()
temp = data['main']['temp']
print(f'Current temperature in {city} is {temp}') |
if x%3 == 0:
print("Число делится на три.")
elif x%3 == 1:
print("При делении на три остаток - один.")
else:
assert x%3 == 2 # assert здесь является комментарием, гарантирующим истинность утверждения
print("Остаток при делении на три - два.")
|
'''
class Counter:
def __init__(self):
self.count = 0
def inc(self):
self.count += 1
def reset(self):
self.count = 0
print(Counter)
x = Counter()
x.inc()
print(x.count)
Counter.inc(x)
print(x.count)
x.reset()
print(x.count)
'''
class b:
a = 0
def __init__(self):
self.a = 100
def foo(self):
self.a += 10
s = b()
#------атрибуты------
print(s.a) #100 - атрибут экземпляра равен 100
print(b.a) #0 - атрибут класса равен 0
b.a = 2 # меняем атрибут класса
print(s.a) #атрибут экземпляра по прежнему 100
#------методы экземпляров------
s.foo() #атрибут экземпляра + 10
print(s.a) #110 действительно, 110 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.