text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
# We know that the lowest crime rate is 130.
# This is the second column of the data.
# We need to find the corresponding value in the first column -- the city with the lowest crime rate.
# Let's load the csv file
f = open('crime_rates.csv', 'r')
data = f.read()
rows = data.split('\n')
full_data = []
for row in rows:
split_row = row.split(",")
split_row[1] = int(split_row[1])
full_data.append(split_row)
city = ""
# Assign the city with the lowest crime rate to city.
for row in full_data:
if row[1] == 130:
city = row[0] |
#!/usr/bin/env python
# We can count how many times items appear in a list using dictionaries.
pantry = ["apple", "orange", "grape", "apple", "orange", "apple", "tomato", "potato", "grape"]
# Create an empty dictionary
pantry_counts = {}
# Loop through the whole list
for item in pantry:
# If the list item is already a key in the dictionary, then add 1 to the value of that key.
# This is because we've seen the item again, so our count goes up.
if item in pantry_counts:
pantry_counts[item] = pantry_counts[item] + 1
else:
# If the item isn't already a key in the count dictionary, then add the key, and set the value to 1.
# We set the value to 1 because we are seeing the item, so it's occured once already in the list.
pantry_counts[item] = 1
print(pantry_counts)
# Count how many times each presidential last name appears in us_presidents. Assign the #counts to us_president_counts.
us_presidents = ["Adams", "Bush", "Clinton", "Obama", "Harrison", "Taft", "Bush", "Adams", "Wilson", "Roosevelt", "Roosevelt"]
us_president_counts = {}
for president in us_presidents:
if president in us_president_counts:
us_president_counts[president] = us_president_counts[president] + 1
else:
us_president_counts[president] = 1 |
#!/usr/bin/env python
column_list = ['Fiber_TD_(g)', 'Sugar_Tot_(g)']
# Let's sum the amount of fiber and sugar in each of the foods.
row_total = food_info[column_list].sum(axis=1)
# This gives us a sum for each row in the data
print(row_total)
# Let's sum up the total amount of fiber and sugar across all the foods.
column_total = food_info[column_list].sum(axis=0)
print(column_total)
vitamin_columns = ['Calcium_(mg)', 'Iron_(mg)', 'Magnesium_(mg)', 'Phosphorus_(mg)', 'Potassium_(mg)', 'Sodium_(mg)', 'Zinc_(mg)', 'Copper_(mg)', 'Manganese_(mg)', 'Selenium_(mcg)', 'Vit_C_(mg)', 'Thiamin_(mg)', 'Riboflavin_(mg)', 'Niacin_(mg)', 'Vit_B6_(mg)', 'Vit_B12_(mcg)', 'Vit_A_IU', 'Vit_A_RAE', 'Vit_E_(mg)', 'Vit_D_mcg', 'Vit_D_IU', 'Vit_K_(mcg)']
# Sum up the amount of vitamins in each food (using the vitamin_columns list to get columns
# from the dataframe), and assign the result to vitamin_totals.
# You'll need to sum the total in each row.
vitamins = food_info[vitamin_columns]
vitamin_totals = vitamins.sum(axis=1)
# When axis is 0, it gives you a new series with the sums of all of the columns in the dataframe.
# When axis is 1, it gives you a new series with sums of all of the rows in the dataframe. |
#!/usr/bin/env python
# start by making a list of Pmfs to represent the dice:
def make_die(num_sides):
die = Pmf(range(1, num_sides+1))
die.name = 'd%d' % num_sides
die.normalize()
return die
dice = [make_die(x) for x in [4, 6, 8, 12, 20]]
print(dice)
|
#!/usr/bin/env python
most_nutritious_foods = []
# Find the three most nutritious foods by sorting food_info using the "nutritional_rating" column.
# Get the name of those foods (the "Shrt_Desc" column), and assign the names to most_nutritious_foods.
# If most_nutritious_foods isn't a list at the end, use the list() function to turn it into one.
sorted_food_info = food_info.sort(["nutritional_rating"], ascending=[False])
most_nutritious_foods = sorted_food_info["Shrt_Desc"].iloc[0:3]
most_nutritious_foods = list(most_nutritious_foods) |
#!/usr/bin/env python
import matplotlib.pyplot as plt
# We can use the plt.plot() function to make a line plot.
plt.plot(forest_fires["temp"], forest_fires["area"])
plt.show()
# Hmm, the above plot looks really strange (check in the plots area to look for yourself)
# The reason it does is because we didn't sort based on the x-axis variable first.
# If we don't sort, points are placed wherever they occur in the data, which means lines can be drawn all across the figure.
# Sorting puts all of the values in the order of the x axis, which means a line is drawn from left to right.
forest_fires = forest_fires.sort(["temp"])
plt.plot(forest_fires["temp"], forest_fires["area"])
plt.show()
# The above plot looks much better!
# Plot "rain" on the x axis and "area" on the y axis.
# Plot "wind" on the x axis and "area" on the y axis.
# Remember to sort on the x-axis values first!
forest_fires = forest_fires.sort(["rain"])
plt.plot(forest_fires["rain"], forest_fires["area"])
plt.show()
forest_fires = forest_fires.sort(["wind"])
plt.plot(forest_fires["wind"], forest_fires["area"])
plt.show() |
#!/usr/bin/env python
# Cannot be parsed into an int with the int() function.
invalid_int = ""
# Can be parsed into an int.
valid_int = "10"
# Parse the valid int
try:
valid_int = int(valid_int)
except Exception:
# This code is never run, because there is no error parsing valid_int into an integer.
valid_int = 0
# Try to parse the invalid int
try:
invalid_int = int(invalid_int)
except Exception:
# The parsing fails, so we end up here.
# The code here will be run, and will assign 0 to invalid_int.
invalid_int = 0
print(valid_int)
print(invalid_int)
another_invalid_int = "Oregon"
another_valid_int = "1000"
# Use try/except statements to parse another_invalid_int and another_valid_int.
# Assign 0 to another_invalid_int in the except block.
# At the end, another_valid_int will be parsed properly, and another_invalid_int will be 0.
try:
another_invalid_int = int(another_invalid_int)
except Exception:
another_invalid_int = 0
try:
another_valid_int = int(another_valid_int)
except Exception:
another_valid_int = 0
|
import datetime
start_time=datetime.datetime.now().replace(microsecond=0)
fishes=0
Eggs = 0
async def log_start():
print("Start date & time " + str(start_time))
async def log_fish(Fish_Catches):
global fishes
fishes += Fish_Catches
async def log_eggs(EggsNum):
global Eggs
Eggs += EggsNum
async def log(Encounters, Catches, EggsNum):
global fishes
current_time=datetime.datetime.now().replace(microsecond=0)
time_elapsed=current_time - start_time
print(("Time Elapsed : " + str(time_elapsed)) + " | Encounters : " + (str(Encounters)) + " | Catches : " + (str(Catches)) + " | Fish Catches : " + (str(fishes) + "| Eggs : " + (str(Eggs)))) |
class Node:
def __init__(self, info):
self.info = info
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
self.queue = []
def create(self, value):
if self.root == None:
self.root = Node(value)
queue = []
queue.append(self.root)
while len(queue) != 0:
top = queue.pop(0)
if top.left != None:
queue.append(top.left)
else:
top.left = Node(value)
break
if top.right != None:
queue.append(top.right)
else:
top.right = Node(value)
break
def inOrder(root):
if root != None:
inOrder(root.left)
print (root.info,end =" ")
inOrder(root.right)
def level_order(root):
queue = []
queue.append(root)
while len(queue) != 0:
top = queue.pop(0)
print (top.info,end =" ")
if top.left != None:
queue.append(top.left)
if top.right != None:
queue.append(top.right)
tree = BinaryTree()
t = int(input())
arr = list(map(int, input().split()))
for i in range(t):
tree.create(arr[i])
inOrder(tree.root)
level_order(tree.root)
# Todo
# check why level order is printing an extra item |
import math
class Prime:
def __init__(self):
pass
def generates_primes(self,num):
not_prime = False
for i in range(2,math.ceil(math.sqrt(num))):
print(num , i)
print(num % i)
if num % i == 0:
not_prime = True
if not not_prime:
print("prime no ",num)
p = Prime().generates_primes(7919)
|
x= [1,2,3,4,5]
y= ["a","b","c"]
x_and_y = list(zip(x,y))
print(x_and_y)
# it will print zipped but the length of the
# longest will be lost
import itertools
another_x_y = list(itertools.zip_longest(x,y))
print(another_x_y) |
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import math
import sys
def init():
glClearColor(0.0,0.0,0.0,1.0)
gluOrtho2D(0,100,0,100)
def drawPixel(x,y):
glColor3f(0.0,1.0,0.5)
glPointSize(5.0)
glBegin(GL_POINTS)
glVertex2i(x,y)
glEnd()
glFlush()
def drawCircle (xc, yc, x, y):
drawPixel(xc+x, yc+y)
drawPixel(xc-x, yc+y)
drawPixel(xc+x, yc-y)
drawPixel(xc-x, yc-y)
drawPixel(xc+y, yc+x)
drawPixel(xc-y, yc+x)
drawPixel(xc+y, yc-x)
drawPixel(xc-y, yc-x)
def circleBres (xc, yc, r):
x = 0
y = r
d = 3 - 2 * r
drawCircle(xc, yc, x, y)
while y >= x:
x += 1
if d > 0:
y -= 1
d = d + 4 * (x - y) + 10
else:
d = d + 4 * x + 6
drawCircle(xc, yc, x, y)
os.system('cls')
def main():
choice = 0
while (choice != 2):
choice = input("Please Choose \n\t1. Plot a new Circle\n\t2. Exit\n\t\n")
if int(choice) == 1:
x = int(input("\nEnter center:\n\tx: "))
y = int(input("\n\ty: "))
r = int(input("\nRadius: "))
print("starting window....")
glutInit(sys.argv)
glutInitDisplayMode(GLUT_RGB)
glutInitWindowSize(500,500)
glutInitWindowPosition(0,0)
glutCreateWindow("Plot Circle using Bressenham Circle Drawing Algorithm")
glutDisplayFunc(lambda: circleBres(x,y,r))
glutIdleFunc(lambda: circleBres(x,y,r))
init()
glutMainLoop()
elif int(choice) == 2:
sys.exit()
else:
print("Invalid choice")
choice = 0
main()
|
import time
import ast
from types import new_class
def password_isvaid(password):
if (len(password) < 6) or (len(password)>16):
print("Password length should not be less than 6")
isValid = False
elif not any(char.isdigit() for char in password):
print("Password should contain at least a number")
isValid = False
elif not any(char.islower() for char in password):
print("Password should contain at least a lowercase letter [a-z]")
isValid = False
elif not any(char.isupper() for char in password):
print("Password should contain at least a uppercase letter [A-Z]")
isValid = False
else:
isValid=True
return isValid
def write_to_file(data, username=None):
if username is not None:
note = f'milestone/notes/{username}.txt'
with open(note, 'w') as note_file:
note_file.write(data)
return
file = 'milestone/users.txt'
with open(file, 'w') as doc_file:
doc_file.write(f'{data}')
return
def read_file_data(name=None):
if name is not None:
user_note = f'milestone/notes/{name}.txt'
try:
with open(user_note, 'r') as file:
notes = file.read()
return notes
except Exception as e:
return False
user_file = 'milestone/users.txt'
with open(user_file, 'r') as users:
user_data = ast.literal_eval(users.read())
return user_data
user_data = read_file_data()
keep_running = True
while keep_running:
user_activity = input("Enter s to signup, l to login and anyother key to quit\n>>").lower()
if user_activity=='s':
name = input("Full Name:\n>>")
username = input("Enter a username:\n>>")
email = input("Enter a email:\n>>")
pin = input("Enter password:\n>>")
print("Validating username...")
time.sleep(2)
if username in user_data.keys():
print("Username already exists. Try again")
continue
print("validating password...")
time.sleep(2)
if password_isvaid(pin):
data = [('name', name), ('pin', pin), ('email', email)]
user_data[username] = {}
user_data[username].update(data)
else:
continue
print(f"Your account has been successfully activated.\n\n")
elif user_activity=='l':
print("Enter login details below".title())
username = input("Username:\n>>")
pin = input("Password:\n>>")
user_details = user_data.get(username, False)
if user_details and user_details.get('pin')==pin:
logged_in=True
while logged_in:
action = input(f"""Welcome, {user_details.get('name')}!
What would you like to do?
1 for View Profile
2 for Create Note
3 for View Note
Press any other key to logout\n>>""").lower()
if action == '1':
print("Here is your profile!")
print(f"Name: {user_details['name']}\nEmail: {user_details['email']}")
edit = input("Do you wish to edit your profile?y/N\n>>").lower()
if edit == 'y':
where = input('Enter a to edit your name, b to edit your email and c to change your password\n>>')
if where == 'a':
new_name = input("Enter Full name:\n>>")
user_details['name'] = new_name
elif where == 'b':
new_email = input("Enter new email:\n>>")
user_details['email'] = new_email
elif where == 'c':
new_password = input("Enter new passowrd:\n>>")
user_details['pin'] = new_password
elif action == '2':
print("Please wait while your note is being created")
time.sleep(4)
content = input("Enter note contents:\n>>")
write_to_file(content, username)
print("Note successfully saved.")
elif action == '3':
user_note = read_file_data(username)
if user_note == False:
print("You currently have no notes. Plese add one")
else:
print(user_note)
edit = input('Enter e to edit your note or c to clear. Press any other key to continue\n>>')
if edit == 'e':
print("Note that editing this note overwrites the original content. Copy your contents to a safe place before proceeding.")
content = input("Enter edited contents:\n>>")
write_to_file(content, username)
elif edit == 'c':
write_to_file("", username)
else:
break
else:
print("Please enter a valid username and password")
tryagain = input("Did you forget your password?y/N\n>>")
if tryagain=='y':
username = input("Enter your username\n>>")
if username in user_data.keys():
full_name = input("Please enter your full name to verify identity\n>>")
fullname = user_data.get(username)['name']
if full_name==fullname:
new_password = input("Enter new password\n>>")
if password_isvaid(new_password):
user_data[username]['pin'] = new_password
print("Password reset succesful")
else:
continue
else:
continue
else:
print("Sorry to see you go.")
break
# write_to_file('transaction',transaction_record)
write_to_file(user_data)
|
import random
import time
import ast
def write_to_file(type, data):
if type == 'customer':
file = 'bankapp_v3/customers.txt'
elif type == 'transaction':
file = 'bankapp_v3/transactions.txt'
with open(file, 'w') as doc_file:
doc_file.write(f'{data}')
def read_file_data():
trans_file = 'bankapp_v3/transactions.txt'
customer_file = 'bankapp_v3/customers.txt'
with open(customer_file, 'r') as customer:
cus_data = customer.read()
customer_data = ast.literal_eval(cus_data)
with open(trans_file, 'r') as transaction:
trans_data = transaction.read()
transaction_data = ast.literal_eval(trans_data)
return customer_data, transaction_data
user_data, transaction_record = read_file_data()
keep_running = True
def update_transaction_record(amount, trans_type, transaction, account_num):
"""This function takes in the amount and other transaction details. Then it updates the transaction dictionary. It doesn't return anything."""
trans_data = {
'amount':amount,
'trans_type':trans_type,
'transaction':transaction
}
transaction_record[account_num].append(trans_data)
def generate_acc_num():
num = [str(i) for i in range(10)]
acc = ['9']
acc.extend([random.choice(num) for i in range(9)])
account_num = "".join(acc)
if account_num in user_data.keys():
return generate_acc_num()
return account_num
while keep_running:
user_activity = input("Enter s to signup, l to login and anyother key to quit\n>>").lower()
if user_activity=='s':
name = input("Name:\n>>")
pin = input("Enter 4 digit pin:\n>>")
account_num =generate_acc_num()
data = [('name', name), ('pin', pin), ('balance', 0)]
user_data[account_num] = {}
user_data[account_num].update(data)
#create empty transaction record
transaction_record[account_num] = []
print(f"Your account has been successfully activated. Your account number is {account_num}. And your current balance is NGN0.\nPlease login to deposit and perform other transactions.\n\n")
elif user_activity=='l':
print("Enter login details below".title())
account_num = input("Account num:\n>>")
pin = input("Enter 4 digit pin:\n>>")
account_details = user_data.get(account_num, False)
if account_details and account_details.get('pin')==pin:
logged_in=True
while logged_in:
action = input(f"""Welcome, {account_details.get('name')}!
What would you like to do?
a for account statement
b for balance
d for deposit
t for transfer
w for withdrawal
Press any other key to logout\n>>""").lower()
if action == 'w':
amount = float(input("Enter amount to withdraw\n>>"))
if amount >= account_details.get('balance', 0):
time.sleep(2)
print("Insufficiant funds")
else:
account_details['balance']-=amount
print('Please take your cash')
#save transaction detail
update_transaction_record(amount,"Debit", "Withdrawal", account_num)
elif action == 'd':
amount = float(input("Enter amount to deposit\n>>"))
account_details['balance']+=amount
print('Deposit complete')
#save transaction detail
update_transaction_record(amount,"Credit", "Deposit", account_num)
elif action == 't':
amount = float(input("Enter amount to transfer\n>>"))
recepient_account = input("Enter destination account number\n>>")
recepient = user_data.get(recepient_account, False)
if recepient:
if amount >= account_details.get('balance', 0):
print("Insufficient funds. GERROUT!")
else:
account_details['balance']-=amount
#save transaction detail
update_transaction_record(amount,"Debit", "Transfer", account_num)
recepient['balance']+=amount
#save transaction detail
update_transaction_record(amount,"Credit", "Transfer", recepient_account)
print("Transfer successful. Gerrout!")
else:
print('No active customer for this account number. Gerrout!')
elif action == 'b':
print(f"Your current balance is NGN{account_details['balance']}\n")
elif action == 'a':
if len(transaction_record[account_num]) > 0:
last_5_transactions = transaction_record[account_num][-5:]
print("Here is your last 5 transactions")
for transaction in last_5_transactions:
print("Amount: ", transaction['amount'])
print("Transaction Type: ", transaction['trans_type'])
print("Transaction Ref.: ", transaction['transaction'])
print()
else:
print("You have not made any transactions. Please make a transaction.")
else:
break
else:
print("Please enter a valid account number and pin")
else:
print("Sorry to see you go.")
break
write_to_file('transaction',transaction_record)
write_to_file('customer',user_data)
|
# # variabe = "Hello world"
# # print(variabe)
# # # set_a = {3,3,1,2, 4,5}
# # # print(set_a)
# # a = 2
# # b = 3
# # c = 7
# # x = (-b + (4*a*c)**0.5) / (2*a)
# # print(x)
# dollar = 30
# naira = 200
# convert_naira_to_dollar = naira * dollar
# print(convert_naira_to_dollar)
# x = 7
# solution = 2*(x**3) - 4*x
# print(solution)
# string1 = "Hello"
# string2 = input("Enter your name:\n")
# print(f"Hey {string2}.\nYou are a good person.\n\tRegards\n\tDesmond") |
from argparse import ArgumentParser
import requests;
import os;
import signal;
def printNewLine():
print("--------------------------------------------");
def terminating(sig, frame):
# a signal handler for ctrl+C (SIGINT)
exit()
signal.signal(signal.SIGINT, terminating);
def printHelp():
# the help message
print("You can select one of the following commands");
printNewLine();
print("t <node id> <amount>: To create a new transaction of amount @amount from you to user with id @id");
print("view: To view all transactions registered in the last valid block")
print("balance: To view the amount of noobcash coins left in your account")
print("help: To view this message again")
print("clear: To clear the window")
print("exit: To close the Noobcash CLIent")
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('-p', '--port', default=5000, type=int, help='port to listen on')
parser.add_argument('-a', '--address', default = '127.0.0.1', help='public accessible ip address');
args = parser.parse_args();
port = args.port;
address = args.address;
baseURL = "http://" + address + ":" + str(port) + "/"
print("Welcome to the Noobcash CLIent");
printHelp()
while(1):
printNewLine();
print("Give a command");
printNewLine();
wholeLine = input();
printNewLine();
splitLine = wholeLine.split(' ');
command = splitLine[0];
args = splitLine[1::];
if command.lower() == 't':
if len(args) != 2:
print("Sorry, this command takes 2 arguments.")
print("If you are not sure about usage of this command type help and read the CLI manual");
continue;
requestData = '{"id": "' + args[0] + '", "amount":' + args[1] + '}';
url = baseURL + "newTransaction";
response = requests.post(url, data = requestData);
print(response.json())
elif command.lower() == 'view':
url = baseURL + "viewTransactions"
response = requests.get(url);
print(response.json())
elif command.lower() == 'balance':
url = baseURL + "getBalance";
response = requests.get(url);
print(response.json())
elif command.lower() == 'help':
printHelp();
elif command.lower() == 'clear':
if os.name == 'nt':
os.system('cls');
else:
os.system('clear');
elif command.lower() == 'exit':
exit();
else:
print("Invalid command. Please give a valid command or type help to read the manual");
|
'''
๋ ์ ์ a, b๊ฐ ์ฃผ์ด์ก์ ๋ a์ b ์ฌ์ด์ ์ํ ๋ชจ๋ ์ ์์ ํฉ์ ๋ฆฌํดํ๋ ํจ์, solution์ ์์ฑํ์ธ์.
์๋ฅผ ๋ค์ด a = 3, b = 5์ธ ๊ฒฝ์ฐ, 3 + 4 + 5 = 12์ด๋ฏ๋ก 12๋ฅผ ๋ฆฌํดํฉ๋๋ค.
'''
def solution(a, b):
# ํ์ด์ฌ์์๋ ๋ค์๊ณผ ๊ฐ์ด ํ ์ค๋ก ๋ ๊ฐ์ ๋ฐ๊ฟ์น๊ธฐํ ์ ์์ต๋๋ค.
if (b > a):
a, b = b, a
return (a + b) * (a - b + 1) / 2
def adder(a, b):
# ํจ์๋ฅผ ์์ฑํ์ธ์
return sum(range(min(a, b), max(a, b) + 1)) |
'''
1. sort
์๋ณธ์ ๋ณํ์์ผ ์ ๋ ฌํ๋ค. '๋ณ์. sort( )' ํํ๋ก ์ฌ์ฉ.
2. sorted
์ ๋ ฌ๋ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํ. ์ํ์ ๋ณํ์ํค์ง ์๋๋ค. ๊ดํธ( ) ์์ ๋ฐ๋ณต ๊ฐ๋ฅํ iterable ์๋ฃํ์ ์
๋ ฅํ์ฌ ์ฌ์ฉํ๋ค. ์ ๋ ฌ ๊ธฐ์ค์ ๋ฌธ์์ด์ ์ํ๋ฒณ, ๊ฐ๋๋ค์์ด๊ณ ์ซ์๋ ์ค๋ฆ์ฐจ์์ด ๊ธฐ๋ณธ๊ฐ์ด๋ค.
3. Parameter
sort, sorted ๋ชจ๋ key, reverse ๋งค๊ฐ๋ณ์๋ฅผ ๊ฐ๊ณ ์๋ค.
3-1. reverse
bool๊ฐ์ ๋ฃ๋๋ค. ๊ธฐ๋ณธ๊ฐ์ reverse=False(์ค๋ฆ์ฐจ์)์ด๋ค.
reverse=True๋ฅผ ๋งค๊ฐ๋ณ์๋ก ์
๋ ฅํ๋ฉด ๋ด๋ฆผ์ฐจ์์ผ๋ก ์ ๋ ฌํ ์ ์๋ค.
>>> num_list = [15, 22, 8, 79, 10]
>>> num_list.sort(reverse=True)
>>> print(sorted(list, reverse=True))
3-2. key
์ ๋ ฌ์ ๋ชฉ์ ์ผ๋ก ํ๋ ํจ์๋ฅผ ๊ฐ์ผ๋ก ๋ฃ๋๋ค. lambda๋ฅผ ์ด์ฉํ ์ ์๋ค.
key ๊ฐ์ ๊ธฐ์ค์ผ๋ก ์ ๋ ฌ๋๊ณ ๊ธฐ๋ณธ๊ฐ์ ์ค๋ฆ์ฐจ์์ด๋ค.
>>> str_list = ['์ข์ํ๋ฃจ','good_morning','๊ตฟ๋ชจ๋','niceday']
>>> print(sorted(str_list, key=len)) # ํจ์
['๊ตฟ๋ชจ๋', '์ข์ํ๋ฃจ', 'niceday', 'good_morning']
>>> print(sorted(str_list, key=lambda x : x[1])) # ๋๋ค
['niceday', 'good_morning', '๊ตฟ๋ชจ๋', '์ข์ํ๋ฃจ']
'''
'''๋ฌธ์์ด๋ก ๊ตฌ์ฑ๋ ๋ฆฌ์คํธ strings์, ์ ์ n์ด ์ฃผ์ด์ก์ ๋, ๊ฐ ๋ฌธ์์ด์ ์ธ๋ฑ์ค n๋ฒ์งธ ๊ธ์๋ฅผ ๊ธฐ์ค์ผ๋ก ์ค๋ฆ์ฐจ์ ์ ๋ ฌํ๋ ค ํฉ๋๋ค.
์๋ฅผ ๋ค์ด strings๊ฐ [sun, bed, car]์ด๊ณ n์ด 1์ด๋ฉด ๊ฐ ๋จ์ด์ ์ธ๋ฑ์ค 1์ ๋ฌธ์ u, e, a๋ก strings๋ฅผ ์ ๋ ฌํฉ๋๋ค.'''
def solution(strings, n):
return sorted(sorted(strings), key=lambda x: x[n])
answer = []
_answer = []
for j in strings:
answer.append(j[n] + j)
answer.sort()
for i in answer:
_answer.append(i[1:])
return _answer
'''๋ฌธ์ ์ค๋ช
๋ฌธ์์ด s์ ๋ํ๋๋ ๋ฌธ์๋ฅผ ํฐ๊ฒ๋ถํฐ ์์ ์์ผ๋ก ์ ๋ ฌํด ์๋ก์ด ๋ฌธ์์ด์ ๋ฆฌํดํ๋ ํจ์, solution์ ์์ฑํด์ฃผ์ธ์.
s๋ ์๋ฌธ ๋์๋ฌธ์๋ก๋ง ๊ตฌ์ฑ๋์ด ์์ผ๋ฉฐ, ๋๋ฌธ์๋ ์๋ฌธ์๋ณด๋ค ์์ ๊ฒ์ผ๋ก ๊ฐ์ฃผํฉ๋๋ค.'''
def solution(s):
# ''.join() ๋ฉ์๋๋ก list to string
answer = ''.join(sorted(s, reverse=True))
return answer
|
#!/usr/bin/python3
"""Module with the 'Base' class"""
import json
class Base:
"""Base class"""
__nb_objects = 0
def __init__(self, id=None):
"""Initializes base class"""
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = self.__nb_objects
@staticmethod
def to_json_string(list_dictionaries):
"""Returns the JSON string representation of list_dictionaries"""
if list_dictionaries is None or list_dictionaries == []:
return "[]"
return json.dumps(list_dictionaries)
@staticmethod
def from_json_string(json_string):
"""Returns a JSON string that represent a list of dictionaries"""
if json_string is None or len(json_string) == 0:
return []
return json.loads(json_string)
@classmethod
def save_to_file(cls, list_objs):
"""Save a JSON representation of list_objs to <class-name>.json"""
with open("{}.json".format(cls.__name__), 'w') as l_o_file:
if list_objs:
l_o_file.write(cls.to_json_string(
[obj.to_dictionary() for obj in list_objs]))
else:
l_o_file.write("[]")
@classmethod
def create(cls, **dictionary):
"""Returns a new instance of 'class' with its attributes set"""
if dictionary and dictionary != {}:
if cls.__name__ is "Rectangle":
dummy = cls(1, 1)
elif cls.__name__ is "Square":
dummy = cls(1)
cls.update(dummy, **dictionary)
return dummy
@classmethod
def load_from_file(cls):
"""Load the objects defined in the JSON file <class-name>.json"""
try:
with open("{}.json".format(cls.__name__), 'r') as ifile:
return [cls.create(**obj)
for obj in cls.from_json_string(ifile.read())]
except FileNotFoundError:
return []
|
#!/usr/bin/python3
def safe_print_list(my_list=[], x=0):
try:
for index in range(x):
print(my_list[index], end='')
return x
except IndexError:
return index
finally:
print()
|
#!/usr/bin/python3
"""Module tahat provides a function 'matrix_divided'
that divides a matrix by a number"""
def matrix_divided(matrix, div):
"""Divide each element of a matrix by a number"""
if not (matrix and
isinstance(matrix, list) and
all(isinstance(row, list) and
all(isinstance(item, (float, int))
for item in row) for row in matrix)):
raise TypeError(
"matrix must be a matrix (list of lists) of integers/floats"
)
if not all(len(a) == len(b) for a, b in zip(matrix, matrix[1:])):
raise TypeError("Each row of the matrix must have the same size")
if not isinstance(div, (float, int)):
raise TypeError("div must be a number")
try:
return [[round(n / div, 2) for n in row] for row in matrix]
except ZeroDivisionError:
raise ZeroDivisionError("division by zero")
|
print("Give me five kinds of fruits:")
fruits = []
index = 0
while index < 5:
new_fruit = input()
fruits.append(new_fruit)
index += 1
print("Fruits that you entered:")
print(fruits)
|
from utility.draw import draw_line
print("Enter the number of rows:")
num_rows = int(input())
print("Enter the number of columns:")
num_columns = int(input())
print("Enter the symbol of the rectange:")
symbol = input()
for _ in range(num_rows):
draw_line(num_columns)
|
fruits = ["apple", "orange", "banana", "strawberry"]
fruits[1] = "mango" # Change the second item to mango
print(fruits)
fruits.append("cherry") # Add cherry to the end of the list
print(fruits)
|
# TODO: Use for-loop to print 0 to 9.
# Tip: range(n) starts from 0 and ends at n - 1
n = range(10)
for x in n:
print(x) |
fruit_list = ["apple", "orange", "banana"]
for fruit in fruit_list:
print(fruit)
|
# TODO: Use while-loop to print the integers from 0 to 10
number = 0
while number <= 10:
print(number)
number += 1
|
# TODO: Complete the following program by completing the function lcm so that the lowest common multiple (LCM) of two
# positive integers can be computed.
# TODO: return the LCM of num1 and num2
def lcm(num1, num2):
pass
print("Input the first integer: ", end="")
num1 = int(input())
print("Input the second integer: ", end="")
num2 = int(input())
print(f"Their LCM is {lcm(num1, num2)}.")
|
"""
An implementation of Minimum Spanning Tree functionality by Kruskal's algorithm
"""
from collections import OrderedDict
"""
Calculates the distance between 2 two-dimensional points in space
"""
def calculate_dist(a,b):
return ((a[0] - b[0])**2 + (a[1] - b[1])**2)**0.5
"""
The mst_kruskal dunction takes an nX2 numpy array as a parameter
and returns a tuple whose first element is the distance traversed
along the MST and the second element of the tuple is a list of edges
represented in the MST
"""
def mst_kruskal(array):
nodesList=[]
mstList=[]
edgeList=[]
seen_edges=[]
distances = {}
color={}
colornodes={}
sumdist=0
n=len(array)
for i in range(1,n+1):
colornodes[i]=[i-1]
for i in range(n):
nodesList.append(i)
color[i]=i+1
for i in range(n):
for j in range(i+1,n):
edgeList.append((i,j))
for edge in edgeList:
distances[edge]=calculate_dist(array[edge[0]],array[edge[1]])
sorted_distances = OrderedDict(sorted(distances.items(),key=lambda x: x[1]))
for edge in sorted_distances.keys():
if edge not in seen_edges and color[edge[0]]!=color[edge[1]]:
seen_edges.append(edge)
temp=colornodes[color[edge[0]]]
temp_copy=temp[:]
for node in temp_copy:
temp_col = color[node]
color[node]=color[edge[1]]
colornodes[temp_col].remove(node)
colornodes[color[edge[1]]].append(node)
mstList.append(edge)
sumdist+=sorted_distances[edge]
return (sumdist, mstList)
|
"""Task 1 - Enoch Leow 30600022 """
from math import pow
from math import log
from math import ceil
def get_digit(integer, base, digit):
"""
Get_digit computes the value of the specified 'digit' in 'base' of the 'integer'
:time complexity: O(1)
:param integer: Any positive integer in range [1, 2^64 โ 1]
:param base: Any integer in the range [2, inf)
:param digit: Integer representing what digit to compute eg. 1, 2, 3...
:return: value of the specified 'digit' in 'base' of the 'integer'
"""
modulo = integer%pow(base, digit) # integer modulo(base^digit)
modulo = modulo/pow(base, digit-1) # divide by base, digit-1 to isolate specified digit
return int(modulo//1) # return value in the 1s place
def radix_pass(array, base, digit):
"""
Sorts elements in array from smallest to largest according to specified digit and using provided base
:time complexity: O(N+b) where
N is the total number of integers in the input list
b is the base
:param array: List containing positive integers in the range[1, 2^64 โ 1]
:param base: Any integer in the range [2, inf
:param digit: Integer representing what digit to compute eg. 1, 2, 3...
:return: Sorted array from smallest to largest according to specified digit
"""
count = (base+1) * [0] # Initialise count for each base value
for i in range(len(array)): # Counts number of each base value
count[get_digit(array[i], base, digit)] += 1
pos = (base+1) * [0] # Initialise position to store element index's
for value in range (1, base+1): # Places initial index for each base value in pos
pos[value] = pos[value-1] + count[value-1]
temp = len(array) * [0] # initialise temp list for sorted list
for i in range(len(array)): # place each element from array into list according to-
num = get_digit(array[i], base, digit) # -index in pos
temp[pos[num]] = array[i]
pos[num]+= 1
return temp # return sorted list according to digit
def radix_sort(array, base):
"""
Takes as input a list of numbers to be sorted and a base, returns the sorted list (small>lar)
:time complexity: O((N+b)M) where
N is the total number of integers in the input list
b is the base
M is the number of digits in the largest number in the input list, when represented in
base b
:param array: List containing positive integers in the range[1, 2^64 โ 1]
:param base: Any integer in the range [2, inf)
:return: Sorted list (small>lar)
"""
maximum = max(array) # Maximum = max element in list
digits = ceil(log(maximum, base)) + 1 # calculates maximum digit of largest element +1(edge case)
temp = array.copy() # copy given array (to not modify given list)
for i in range(1, digits+1):
temp = radix_pass(temp, base, i)
return temp # return sorted list
|
"""Quick analysis
pairs solution is O(N) space and time complexity
triplets solutions is O(N^2) time and O(N) space complexity
"""
def get_nums(path="./input.txt"):
"""Read file for number input
return: sorted array on numbers
"""
nums = []
with open(path, "r") as _f:
for line in _f.readlines():
nums.append(int(line.strip()))
nums.sort()
return nums
def get_pairs(arr, target_sum=2020):
"""Find a pair of numbers in the array whose sum equals target"""
left = 0
right = len(arr) - 1
while left < right:
current_sum = arr[left] + arr[right]
if current_sum == target_sum:
return arr[left], arr[right]
elif current_sum < target_sum:
# move left pointer rightward since sum is below target
left += 1
elif current_sum > target_sum:
# move right pointer leftward since sum is above target
right -= 1
return None
def get_triplets(arr, target_sum=2020):
"""Find three numbers in the array such that they add up to target_sum"""
for idx, num in enumerate(arr):
new_target = target_sum - num
pair = get_pairs(arr[idx+1:], new_target)
if pair:
a, b = pair
return num, a, b
return None
if __name__ == "__main__":
nums = get_nums()
pairs = get_pairs(nums)
if pairs:
print(pairs)
print(pairs[0]*pairs[1])
triplets = get_triplets(nums)
if triplets:
print(triplets)
print(triplets[0]*triplets[1]*triplets[2])
|
import time
class User(object):
username = 'liam'
password = '123456'
def printWelcome(self):
print('********************')
print('********************')
print(' ๆฌข่ฟๅ
ไธด ')
print('********************')
print('********************')
def printFunction(self):
print('*******************')
print('* ๆฅ่ฏข๏ผ1๏ผ ๅญๆฌพ๏ผ2๏ผ*')
print('* ๅๆฌพ๏ผ3๏ผ ๆนๅฏ๏ผ4๏ผ*')
print('*******************')
def userLogin(self):
userInput = input('่ฏท่พๅ
ฅๆจ็็จๆทๅ๏ผ')
if self.username != userInput:
print('่ดฆๆท่พๅ
ฅ้่ฏฏ๏ผ')
return 0
passInput = input('่ฏท่พๅ
ฅๆจ็ๅฏ็ ๏ผ')
if self.password != passInput:
print('ๅฏ็ ้่ฏฏ๏ผ')
return 0
else:
print('่ดฆๆทๅฏ็ ๆญฃ็กฎ๏ผ่ฏท็จๅ>>')
time.sleep(3)
def main():
user = User()
user.printWelcome()
if user.userLogin() == 0:
print('่พๅ
ฅๆ่ฏฏ๏ผ่ฏท้ๆฐ่พๅ
ฅ')
else:
user.printFunction()
res = input('่ฏท้ๆฉๆจ็ไธๅก:')
if res == '1':
print('ๆจ้ๆฉไบๆฅ่ฏขไธๅก')
if res == '2':
print('ๆจ้ๆฉไบๅญๆฌพไธๅก')
if res == '3':
print('ๆจ้ๆฉไบๅๆฌพไธๅก')
if res == '4':
print('ๆจ้ๆฉไบๆนๅฏไธๅก')
if __name__ == '__main__':
main()
|
# This sets the variable `formatter` to the format string "%r %r %r %r"
formatter = "%r %r %r %r"
# This command tells python to print the output "1 2 3 4"
print formatter % (1, 2, 3, 4)
# This command tells python to print the output "'one', 'two', 'three', 'four'"
print formatter % ("one", "two", "three", "four")
# This command tells python to print the output "True False False True"
print formatter % (True, False, False, True)
# This command tells python to print the output "'%r %r %r %r' '%r %r %r %r' '%r %r %r %r' '%r %r %r %r'". Note that this inserts the original variable into the output a total of four times, on purpose, which outputs a total of 16 formatters in the output string
print formatter % (formatter, formatter, formatter, formatter)
# This command tells python to print the output "'I had this thing.' 'That you could type up right.' 'But it didn't sing.' 'So I said goodnight.'". Note that using a comma after the first three strings is necessary to satisfy the number of arguments python expects, which in this instance is four, as specified in the variable `formatter`
print formatter % (
"I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight."
)
# From "Exercise 8: Printing, Printing" from Learn Python the Hard Way
# I learned that when printing a string with a variable that includes more than one argument, you need to use commas between the arguments in order for that command to execute correctly.
# I observed that I still don't quite understand when to use the formatter ``%s` and when to use ``%r`. However, when I temporarily changed the formatters in the variable `formatter` from "%r" (as per the original instructions in the exercise) to "%s", the output in my Terminal was visually cleaner, i.e., the 2nd, 4th, and 5th commands printed without any quotes :). Alas, it's a mystery to me why python chose to print line 20 with double-quotes yet lines 18, 19, and 21 with single-quotes.
|
#miles = input("enter milage: ")
#for miles in range(10, 70, 10):
# km = miles * 1.609
# print("%d miles --> %3.2f kilometers"%(miles, km))
#print ("%3.2f "%(km))
#print (miles)
#x = 25
#print("the number is " + str(x))
mylist = ["nice", "cool", "nice", "road", "trip", "cool"]
print(set(mylist))
#to change all ouput to upper case
miles = input("enter new ")
print(miles.upper())
#to change input to upper case #miles = input("enter new ").upper()
|
import platform
from enum import Enum
from typing import Self
class Site(Enum):
"""Supported Recordpool websites."""
BANDCAMP = "Bandcamp"
BEATJUNKIES = "Beatjunkies"
BPMSUPREME = "BPMSupreme"
DJCITY = "DJCity"
# Not using StrEnum here since that will use the variable name in lowercase,
# and I want to maintain the correct formatting for each name.
def __str__(self) -> str:
return self.value
class Platform(Enum):
"""OS platform enum."""
LINUX = "Linux"
MAC = "macOS"
WINDOWS = "Windows"
def is_linux(self) -> bool:
"""Returns true if on Linux."""
return self == Platform.LINUX
def is_mac(self) -> bool:
"""Return true if on macOS."""
return self == Platform.MAC
def is_windows(self) -> bool:
"""Returns true if on Windows."""
return self == Platform.WINDOWS
@classmethod
def get(cls) -> Self:
"""Initialize Platform enum for current OS."""
platform_name = platform.system().lower()
if platform_name == "darwin":
return Platform.MAC
elif platform_name == "windows":
return Platform.WINDOWS
elif platform_name == "linux":
return Platform.LINUX
raise RuntimeError(f"Unsupported OS: '{platform.system()}'")
def __str__(self) -> str:
return self.value
def __repr__(self) -> str:
"""Format platform name with version info."""
if self.is_windows():
(release, version, *others) = platform.win32_ver()
try:
build_version = int(version.split(".")[-1])
# Windows 11 is still numbered as version 10, but we can check build number
if build_version > 2200:
release = 11
except ValueError:
build_version = version
# For example: 'Windows 11 Professional 22621'
return f"{self.value} {release} {platform.win32_edition()} {build_version}"
# For example: 'macOS 12.6 x86_64'
return f"{self.value} {platform.mac_ver()[0]} {platform.machine()}"
|
# pylint: disable-all
# NOTE : Python 2.7 does not require parenthesis to print
# Python 3 does however
# Excercise 1
print (5/3)
print 5%3
print 5.0 / 3
print 5/3.0
print 5.2%3
#Exercise 2
print 2000.3**200
print 1.0 + 1.0 - 1.0
print 1.0 + 1.0e20 - 1.0e20
#Exercise 3
print float(123)
print float('123')
print float('123.23')
print int(123.23)
print int('123.23')
print int(float('123.23'))
print str(12)
print str(12.2)
print bool('a')
print bool(0)
print bool(0.1)
#Exercise 4
print range(5)
print type(range(5))
#Exercise 5
numFound = 0
x = 11
while numFound < 20:
if x % 2 == 0 and x % 7 == 0 and x % 11 == 0:
print x
numFound = numFound + 1
x = x + 1
# Exercise 6A
def printme(n):
if(n < 2):
return False
x = 2
isPrime = True
while(x < n):
if((n % x) == 0):
isPrime = False
x = x + 1
return isPrime
# 2,3,5,7,11,13,17,19,23
print printme(2)
print printme(1)
print printme(0)
print printme(-1)
print printme(191)
print printme(192)
print printme(193)
print printme(197)
# Exercise 6B
def betterprime(n):
if n < 2:
return False
if n == 2 or n == 3:
return True
k = 1
value = 0
isprime = False
while value <= n and isprime == False:
value = 6 * k
if((value + 1) == n) or ((value - 1) == n):
isprime = True
k = k + 1
return isprime
print betterprime(2)
print betterprime(3)
print betterprime(5)
print betterprime(7)
print betterprime(11)
print betterprime(-1)
print betterprime(191)
print betterprime(192)
print betterprime(193)
print betterprime(197)
#Exercise 7
rlist = ['a','b','c','d','e']
def printelements(rlist):
count = 0
print rlist
for i in rlist:
count = count + 1
print i
printelements(rlist)
def reverseList(r):
newList = []
for i in r:
newList.insert(0, i)
for x in newList:
print x
reverseList(rlist)
def customLength(lList):
itemCount = 0
for i in lList:
itemCount = itemCount + 1
return itemCount
print customLength(rlist)
#Exercise 8
a = ['a','b','c','d','e']
b = a
print a
b[1] = 'Change One'
# A[1] also changed since they are both pointing to the same object
print a
c = a[:]
print c
c[2] = 'Change Two'
print a
#No change because it creates a shallow copy
def set_first_elem_to_zero(l):
l[0] = 0
return l
print a
set_first_elem_to_zero(a)
print a
# Exercise 9
sets = [[3, 4], [5, 6], [9, 10], [45, 65]]
print sets
def innerList(l):
newList=[]
for p in l:
for x in range(2):
newList.append(p[x])
return newList
otherList = innerList(sets)
print otherList
# Exercise 10
import matplotlib.pyplot as plt
import math
import numpy as np
x = np.linspace(0, 2, 1024)
y = ( (np.sin(x-2)**2) * (np.e**(-x**2)))
plt.plot(x,y)
plt.ylabel('Time')
plt.xlabel('Speed')
plt.title('Exercise 10: Time vs. Speed')
plt.show()
# Exercise 11
def almostFactorial(list):
if (list is not None):
if len(list) > 0:
product = 1
for i in list:
product = product * i
return product
inputlistOne = [1, 2, 3, 4]
inputlistNone = []
print almostFactorial(inputlistOne)
print almostFactorial(inputlistNone)
inputlistTwo = [7, 8, 9, 10, 11, 12]
inputlistThree = None
def almostFactorialRec(inputlist):
if (inputlist is not None):
if(len(inputlist) == 0):
return 1
else:
return inputlist[len(inputlist)-1] * almostFactorialRec(inputlist[:-1])
print almostFactorialRec(inputlistTwo)
print almostFactorialRec(inputlistThree)
# Exercise 12
def fibo(n):
if n >= 0 and n < 38:
if n==0:
return 0
elif n == 1:
return 1
else:
return fibo(n-1) + fibo(n-2)
else:
return "Number out of range"
print fibo(-1)
print fibo(14)
print fibo(38)
# Exercise 13
import re
with open('emails.txt') as file:
lines = file.read()
match = re.findall(r'[\w\"\.-@]*[\w\"\.-]+@[\w\.-]+\.[\w]+', lines)
print (match) |
print("problema 05")
nr= int(input("Dati numarul lui Ion: "))
print(nr-2, nr-1 , nr, nr+1, nr+2 , sep = "_")
|
# # if conditional
# hasGoodCredit = True
# price = 1000000
# if hasGoodCredit:
# print(price * 0.1)
# else:
# print(price * 0.2)
#
# hasHighIncome = False
# hasGoodCredit = True
#
# if hasGoodCredit and hasHighIncome:
# print("Elegible for loan")
# else:
# print("Not Elegible for loan")
#
#
# isMayorEdad = False
#
# #While conditional
# while not isMayorEdad:
# edad = input("Ingrese su edad")
# isMayorEdad = int(edad) >= 18
# print("Puede entrar a la discoteca")
for item in 'Christian':
print(item)
print("=========")
for var in ['a','b','c','d']:
print(var)
numbers = [5,2,5,2,2]
for x in numbers:
print('X'*x)
# Define speak below:
def speak(animal='woof'):
if animal == 'pig':
return 'oink'
elif animal == 'duck':
return 'quack'
elif animal == 'cat':
return 'miau'
elif animal == 'dog':
return 'woof'
elif animal == 'woof':
return 'woof'
else:
return '?' |
def divide(num1, num2):
try:
return num1/num2
except TypeError:
print ("Please provide two integers or floats")
except ZeroDivisionError:
print ("Please do not divide by zero")
divide(1, 0)
try:
age = int(input("Ingrese un numero ()"))
print(age)
except ValueError:
print("Numero invalido")
def colorize(text, color):
if type(text) is not str:
raise ValueError("texto debe ser un valor literal")
print(f"Printed: {text} in color: {color}")
colorize("Domain Drive Desing", "blue")
try:
number=int(input("Ingrese un numero: "))
print("You've ingress :" + str(number))
except Exception:
print("It's not a number")
else:
print("this run when no exception occurs")
finally:
print("Finally run this code") |
# input an integer number
number = int(input('input an integer number:'))
if number == 0:
factorial = 1
else:
factorial = number
while number > 1:
factorial = factorial * (number - 1)
number = number -1
print ('Factorial ', factorial)
|
from abc import ABC, abstractmethod
import random
class AI(ABC):
'''Abstract AI class'''
@abstractmethod
def play(self, game):
pass
class RandomAI(AI):
def play(self, game):
'''An AI player that chooses a legal move at random out of all
available legal moves in Tic-Tac-Toe state member'''
return random.choice(game.state.moves)
class AlphaBetaAI(AI):
def play(self, game):
'''An AI player that chooses the optimal legal move by using
the MiniMax algorithm with alpha beta pruning in a Tic-Tac-Toe game'''
move = self.alphabeta_search(game)
return move
def alphabeta_search(self, game):
'''search game approach to find best action, using alpha-beta pruning:
alpha = best (highest) move found so far for Max
beta = best (lowest) move found so far for Min'''
# Functions used by alphabeta
def max_value(game,state,alpha,beta):
#if termninal node return value and no move
if game.game_over(state):
return game.utility(state, game.state.to_move),None
value = -float('inf') #initiallize worst case val
bestMove = None #initialize best move
#itterate over available moves
for move in state.moves:
#get result from the next node
resp,_ = min_value(game,game.result(move,state),alpha,beta)
#if the response was better than value
#update value and best move
if resp>value:
value = resp
bestMove = move
#prune if value is greater than beta
if value>=beta: return value,bestMove
#update alpha
alpha = max(alpha,value)
return value,bestMove
def min_value(game, state, alpha, beta):
#if terminal node return value and no move
if game.game_over(state):
return game.utility(state, game.state.to_move),None
#initialize value to worst case
value = float('inf')
#initialize best move var
bestMove = None
#itterate over available moves
for move in state.moves:
#get the response from max value
resp,_ = max_value(game,game.result(move,state),alpha,beta)
#if the response is less than val
#update value and best move
if resp<value:
value = resp
bestMove = move
#if the value is less than or equal to alpha return
if value<=alpha: return value,bestMove
#update beta
beta = min(beta,value)
return value,bestMove
# Body of alphabeta_cutoff_search:
# player = game.state.to_move
alpha = -float('inf')
beta = float('inf')
_,action = max_value(game,game.state,alpha,beta)
return action
if __name__ == '__main__':
ai1 = RandomAI()
ai2 = AlphaBetaAI() |
import string
import unidecode
from sentences import CONJUNCTION, NEGATION
# format user entry (unaccented, no punctuation, lowercase)
def formatText(text: str):
unaccentedStr = ' '.join(unidecode.unidecode(text).split("'"))
formattedStr = unaccentedStr.translate(
str.maketrans('', '', string.punctuation)).lower()
return formattedStr
# detect conjunction in user entry and divide it in multiple sub-sentences
def detectMultipleConjunction(text: str):
for conj in CONJUNCTION:
splitted = text.split(conj)
if (len(splitted) > 1):
for i in range(len(splitted)):
splitted[i] = detectMultipleConjunction(splitted[i])
return splitted
return splitted
# prend une liste a N dimension et la retourne en liste a une seule dimension
# take a N dimension list and return it in one dimension
def flattenList(ndlist: list, outputList: list):
for elem in ndlist:
if isinstance(elem, list):
outputList = flattenList(elem, outputList)
else:
outputList.append(elem)
return outputList
# check if negation is in sentence
def checkNegation(text: [str]):
for neg in NEGATION:
if neg in text:
return False
return True
|
print("{:=^20}".format(" ์ ์ด๋ฌธ "))
print("{:-^20}".format(" if๋ฌธ "))
# if ๋ฌธ
print("-" * 20)
if 1 > 10:
print("test")
print("test")
if 1 < 20:
print("test")
if True:
print("aaa")
# if - else ๋ฌธ
print("-" * 20)
a = 10
if a % 2 == 0:
print("์ง์")
else:
print("ํ์")
# if - elif - else ๋ฌธ
print("-" * 20)
a = -10
if a > 0:
print("์์")
elif a < 0:
print("์์")
else:
print("zero")
print("-" * 10)
if 10 > 1:
print("test")
elif 20 > 1:
print("test")
elif 30 > 1:
print("test")
# ์ฐ์ฐ์
print("-" * 20)
print((1 > 10) and (1 < 10))
x = 6
if 1 < x < 10:
print("test")
# in ์ฐ์ฐ์
print("-" * 20)
print("a" not in ["a", 'b', 'c'])
print("a" in "abc")
# ์๋ฃํ์ True/False
print("-" * 20)
if "python":
print("test")
if 10:
print("test")
if None:
print("aaaa")
print("{:-^20}".format(" while๋ฌธ "))
# while ๋ฌธ
print("-" * 20)
i = 0
while i < 10:
print("hello")
i += 1 # i = i + 1
# break ๋ฌธ
x = 0
print("-" * 20)
while True:
if 3 * x > 56:
break
x += 1
print(x)
x = 0
while x < 100:
if x > 20:
break
print(x)
x += 1
# continue ๋ฌธ
a = 0
while a <= 20:
a = a + 1
if a % 2 == 1:
continue
print(a)
print("{:-^20}".format(" for๋ฌธ "))
print("-" * 20)
a = [1, 2, 3, 4, "python"]
for x in a:
print(x)
for x in "ABCDEF":
print(x)
# range ๊ฐ์ฒด
for n in range(3, 10):
print(n)
# for - continue
for x in range(20):
if x % 2 == 1:
continue
print(x)
# ๊ตฌ๊ตฌ๋จ
print("-" * 20)
for x in range(2, 10):
for y in range(1, 10):
print("{} * {} = {}".format(x, y, x * y))
print("-" * 10)
# ๋ฆฌ์คํธ ์ปดํ๋ฆฌํจ์
print("-" * 20)
square_lst = []
for num in range(1, 11):
square_lst.append(num ** 2)
print(square_lst)
square_lst_2 = [num ** 2 for num in range(1, 11)]
print(square_lst_2)
# ๋ฆฌ์คํธ zip
print("-" * 20)
lst1 = [10, 'b', 'c']
lst2 = ['A', 'B', 'C', 'D', 'E']
lst3 = [3, 4, 5, 6, 7]
for x, y, z in zip(lst1, lst2, lst3):
print(x, y, z)
print("-" * 10)
# enumerate
print("-" * 20)
lst = ["A", "B", "C", "D", "A", "B"]
i = 0
for x in lst:
print(i, x)
i += 1
print("-" * 10)
for i, x in enumerate(lst):
print(i, x)
|
# problem 1
a = 20180123
year = int(a / 10000)
month = int((a % 10000) / 100)
day = a % 100
print("{:04d}.{:02d}.{:02d}".format(year, month, day))
# problem 2
input_str = input("insert your string : ")
print(input_str[0] + "_" * (len(input_str) - 1))
# problem 3
input_str = input("insert your string : ")
word_lst = input_str.split()
print(word_lst[0], word_lst[-1])
# problem 4
score_dict = {"Korean": 80, "Math": 88, "English": 100}
# problem 5
score_str = input("insert your score : ")
score_lst = score_str.split()
score_dict = {"Korean": score_lst[0],
"Math": score_lst[1],
"English": score_lst[2]}
|
tasklist = [23,"Jane",["lesson 23",560,{"currency":"KES",}],987,(76,"John")]
#1.determine the type of variable in task list using an inbuilt function
a = print(type(tasklist))
#2. print KES-said
print(tasklist[2][2]["currency"])
#3. print 560- patricia
print(tasklist[2][1])
#4. length of task list
print(len(tasklist))
#5. rotate 987 to 789 using indexing only
z = tasklist [3]="789"
print (tasklist)
z = str(z)
#to rotate using indexing,we use as below
z = z[::-1]
print (z)
#6. change the name "John" to "jane"
#n/a. not applicable because its a tuple
|
m,n=map(int,input().split())
a,b=map(int,input().split())
s,d=map(int,input().split())
if(m==a==s):
print("yes")
elif(n==b==d):
print("yes")
elif(m==n and a==b and s==d):
print("yes")
else:
print("no")
|
keycode = {
'a': 65,
'b': 66,
'c': 67,
'd': 68,
'e': 69,
'f': 70,
'g': 71,
'h': 72,
'i': 73,
'j': 74,
'k': 75,
'l': 76,
'm': 77,
'n': 78,
'o': 79,
'p': 80,
'q': 81,
'r': 82,
's': 83,
't': 84,
'u': 85,
'v': 86,
'w': 87,
'x': 88,
'y': 89,
'z': 90,
'0': 48,
'1': 49,
'2': 50,
'3': 51,
'4': 52,
'5': 53,
'6': 54,
'7': 55,
'8': 56,
'9': 57
}
def convert_keycode(input):
result = ''
for item in input:
result += str(keycode[item]) + ','
result = result[:-1]
result += ' 0'
print(result)
def main():
positive_input = ['fjdkls', 'fjdkls', 'fjdksl', 'jfkdls', 'ghfjdk', 'hfjdks', 'fhdjks', 'fhdjskl', 'fhdjks',
'fhdjksl', 'fgdhjsk', 'ghfjdksl', 'fgdhsjka', 'fgdhjsk', 'vbcnxmz', 'vbcnxmz', 'vbcnxzm',
'cbnxmz', 'vbcnxmz', 'vbcnxmz', 'vbcxnzm', 'vcbxnzm', 'vbcnxmz', 'tryeuiw', 'tryeuwi',
'tryeuwiqo', 'yreuiwo', 'tyrueiow', 'ryeuwio', 'ryueiwo', 'yreuiwoq', 'tyreuiwo', 'ryeuiwo',
'yrueiwoq', 'tyruei', 'vcbxnm', 'fgdhsjka', 'tryeuwi', 'fjdks', 'fgdhjlska', 'gfhdjks',
'gdhsjakl', 'vcbnxmz', 'fgdhjskal', 'vcbxnmz', 'tryeuwioq', 'rteywuiqo', 'yrueiwop', 'treywuiq',
'ytruieowpq', 'vcbxnzm', 'dgshjak', 'rteywuio', 'dghsjakl', 'tryeuwioqp', 'gdhsjka', 'fgdhjs',
'vcbxn', 'fdgshj', 'fgdhsjk', 'gfdhjsk', 'gshajkl', 'fdgshajk', 'gfhdjskl', 'rtyeuwio',
'gfdhsjkl', 'vcbxnm', 'tyrueiow', 'tyrueiwo', 'fghj', 'tewyui', 'tyreuiow', 'ryeuwio', 'etwyquio',
'yreuiwop', 'fgdhsjkl', 'bcxz', 'fgdhsjakl', 'ryeuio', 'yreuiwo', 'yrueiow', 'yrueiwo',
'tryeuwio', 'fgdhsjk', 'vcbnxmz', 'fgdhsjk', 'tryeuiwo', 'fgdhsjk', 'cvbxnm', 'fgdhsjk',
'rteywuio', 'tyurioep', 'dfsghaj', 'cvxbnzm', 'rtyeuiw', 'vcxbnzm', 'gdhsjak', 'ryueiow',
'tryeuiw', 'tyreuiw', 'ytuiroep', 'etwyuqio', 'yuitropew', 'rwtyuqio', 'yutiroep', 'treyuwiqo',
'yrueiwopw', 'ytuirope', 'rueiowp', 'uwiopq', 'ryueiwo', 'ureiowp', 'ywuqio', 'gfhdjksl',
'fsghaj', 'ghfjdksl', 'dgshjak', 'hfdjksl', 'hfdjksl', 'jdskla', 'fhdjksla', 'gfhdjk', 'gfdhjska',
'fhdjksl', 'vbcnmx', 'cbxnzm', 'cbnxmx', 'vcbxnm', 'bznm', 'bcnxm', 'cbxnzm', 'bcnxm', 'bcnxzm',
'cbxnm', 'vbcnxmz', 'vcbxnz', 'vbcnxmz', 'bxnzm', 'vcxbnzm', 'cbxnzm', 'vbcnxm', 'yreuiw',
'trueiow', 'utiroep', 'hfdjksl', 'yeuwiqop', 'uewioq', 'dhsjk', 'hfdjksls', 'ureiowp', 'dhsjk',
'ryueiwo', 'dhsjak', 'yrueiow', 'fdhjsk', 'cbxnm', 'cvbxnm', 'ryeui', 'gdhsj', 'tyruieo', 'cbnxm',
'utrieo', 'fgdhsj', 'rteyuwi', 'utrieo', 'cxhjz', 'fdhjsk', 'tyurieow', 'gdhsjak', 'ryeuwio',
'hfjdk', 'uyitorp', 'gfhdjsk', 'tryeuiw', 'vcbnxmz', 'fgdhjsk', 'tryeuiw', 'gfdhsjk', 'vcbxnmz',
'yutiroe', 'uyitorp', 'erwtqyui', 'fdgshja', 'cvbxnzm', 'ghfjdkl', 'yturieo', 'gfdhsj',
'retwyuqi', 'uyiotpr', 'hgjfkd', 'bvcnxm', 'dfsghaj', 'vbcnxmz', 'fgdhjsk', 'gfhdjks', 'fjdksl',
'gdhsj', 'gshajk', 'hgjfkdl', 'gfhdjks', 'tryeuiw', 'cvxbnz', 'dfgshaj', 'rteywui', 'yutiorp',
'gfhdjsk', 'cvbxnm', 'gfhdjsk', 'dfsgahj', 'cvxbnzm', 'tyrueio'
]
negtive_input = ['uhv', 'rghn', 'xfyu', 'erthn', 'cvghui', 'rth', 'ergh', 'dfyui', 'sdfj', 'njio', 'sxc', 'vghui',
'ertghn', 'drtyui', 'rtyj', 'wertyj', 'cgui', 'xfyuio', 'rthjm', 'xdfyuio', 'rthjm', 'cghuio',
'wedfb', 'xfghu', 'ijm', 'oih', 'efefgh', 'serfghj', 'cfyuk', 'ertyhbn', 'xdthj', 'tyuhgcx',
'wsdfghj', 'iuytrdc', 'fgui', 'sfdgfh', 'hfsd', 'sbhjiu', 'weuh', 'bchui', 'xcfgyu', 'rth',
'werty', 'oiug', 'drtyh', 'xcvbhu', 'poiuyg', 'qwscv', 'cyui', 'oiuytf', 'ertyhn', 'qscvb', 'cfyu',
'oiuyt', 'kjhv', 'srtyu', 'zxcgyu', 'iuytrd', 'zsrtyj', 'cgh', 'iuyg', 'erth', 'sertyui',
'cfgyuio', 'oiuytd', 'wdfghj', 'xcghui', 'dtyui', 'rdftgh', 'gvhu', 'txrfuygk', 'ijiuh', 'vghj',
'xcfg', 'iuyf', 'edfghjk', 'xfyui', 'nhre', 'asdfgui', 'cgui', 'dfghn', 'dfghj', 'yuio', 'oihg',
'rghn', 'xfyui', 'uygfc', 'efgh', 'hgfrfghn', 'cfghu', 'uigyuf', 'ezrtxgfk', 'hgdv', 'ashck',
'qvebick', 'qxgk', 'sdabhvioz', 'weiurdacsb', 'zuvcdgks', 'sdjivhs', 'wqfbucow', 'bdhuca', 'bsaf',
'efbiwuo', 'sdauhicg', 'wudviy', 'vbieuo', 'bfhjwa', 'sbjkadv', 'qbufw', 'abiu', 'bxiueo', 'abvio',
'absvidghs', 'bjscgiu', 'hfiea', 'sdiaco', 'biufa', 'baivsoa', 'bcuaui', 'bwisvbid', 'vdsbaico',
'bahcoei', 'cftyh', 'rtyh', 'xftyujb', 'cfyhb', 'erfvhj', 'jhhu', 'iuhsc', 'hacl', 'dsbkvj',
'asuhdke', 'sjbzckh', 'wauef', 'vbhes', 'zhuiexh', 'aiuehc', 'sbhdiak', 'bahscek', 'bhusave',
'irghd', 'saiode', 'weriuy', 'sbhdocb', 'aiufh', 'weirg', 'xvbis', 'woefuh', 'abiuewf', 'xibcvb',
'rigoj', 'qwydbh', 'zise', 'ergh', 'xvisa', 'siuhfh', 'zbisd', 'rgoijz', 'vniesrn', 'eahfng',
'naoen', 'oefanjk', 'aowrjk', 'isuevnjk''asdkh', 'asduasd', 'bcish', 'sdiagv', 'aiyfcv',
'awuiegfbc', 'zxhc', 'saeioj', 'bsnidu', 'qdsvg', 'sbthov', 'csuv', 'ersughbv', 'bcuys', 'rgohavb',
'qwdvuc', 'dsvui', 'zcvuye']
swipe_right = ['tyui', 'tyuio', 'tyuiop', 'rtyuio', 'wertyui', 'qwertyu', 'wertyu', 'ertyui', 'rtyuio', 'sdfghj',
'xcvbnm', 'sdfghjk', 'ertyui', 'ertyuio', 'sdfghj', 'ertyui', 'dfghj', 'dfghjk', 'ertyuio', 'dfghj',
'xcvbnm', 'ertyui', 'dfghj', 'xcvbnm', 'ertyui', 'wertyu', 'sdfgh', 'zxcvbn', 'ertyuio', 'dfghj',
'dcvbnm', 'rtyui', 'dfghj', 'zxcvbn', 'rtyuio', 'sdfghjk', 'dfghjk', 'asdfghj', 'ertyuio', 'wertyj',
'rtyui', 'dfgh', 'xcvbn', 'yuio', 'dfghj', 'tyuio', 'werty', 'cvbn', 'fghjk', 'tyuio', 'werty',
'sdfgh', 'cvbn', 'yuio', 'dfghj', 'asdfgh', 'xcvbn', 'tyui', 'ertyu', 'dfghjk', 'xcvbn', 'sdfgh',
'rtyuio', 'wertyu', 'dfghj', 'xcvbn', 'dfghjk', 'tyuio', 'dfghj', 'cvbn', 'fghjk', 'tyuio', 'rtyui',
'yuiop', 'tyuiop', 'ghjk', 'cvhj', 'dfghjk', 'ertyu', 'wertyu', 'fghjk', 'rtyu', 'cvb', 'asdfg',
'rtyui', 'xcvbnm', 'cvbnm', 'vbnmwert', 'qwer', 'uiop', 'tyuio', 'dfgh', 'ghjkl', 'sdfgh', 'xcvbn',
'rtyu', 'sdfgh', 'xcvbn', 'zxcvbn', 'asdfgh', 'qwerty', 'rtyui', 'ertyui', 'tyrion', 'yup', 'sdfghj',
'ghjkl', 'dfghjk', 'asdfghj', 'asdfgh', 'zxcvbn', 'cvbnm', 'zxcvbn', 'xcvbn', 'cvbn', 'ertyu',
'wert', 'dfghj', 'asdfgh', 'tyuio', 'rtyu', 'tyui', 'yuio', 'ertyui', 'asdf', 'fight', 'ghjkl',
'asdfg', 'dfghj', 'sdfgh', 'ghjk', 'rtyu', 'wertyu', 'qwer', 'ertyu', 'rtyu', 'wert', 'tyui', 'yuio',
'yuiop', 'uiop', 'tyuio', 'ertyu', 'asdf', 'sdfgh', 'dfgh', 'fghj', 'ghjk', 'ghjk', 'hjkl', 'dfghj',
'zxcvb', 'zxcvbn', 'xcvbn', 'cvbnm', 'cvbn', 'vbnm', 'zxcvbn', 'dfghj', 'werty', 'rtyui', 'yuiop',
'fghjk', 'ghjkl', 'sdfgh', 'asdfgh', 'sdfghj', 'fghjkl', 'ghjk', 'xcvbn', 'vbnm', 'zxcv', 'cvbnm',
'qwe', 'qwer', 'qwert', 'qwerty', 'qwertyu', 'qwertyui', 'qwertyuio', 'wert', 'werty', 'wertyu',
'wertyui', 'wertyuio', 'wertyuiop', 'ertyui', 'ertyuio', 'ertyuiop', 'rty', 'rtyu', 'rtyui',
'rtyuio', 'rtyuiop', 'tyu', 'tyui', 'tyuio', 'tyuiop', 'yui', 'yuio', 'yuiop', 'uiop', 'asdf',
'sdfg', 'dfghj', 'fghjk', 'ghjkl', 'asdfgh', 'asdfghjk', 'sdfghjkl', 'dfghjkl', 'fghjkl', 'ghjkl',
'zxcv', 'xcvbn', 'cvbnm', 'cvbnm', 'zxcvbnm'
]
swipe_left = ['uytre', 'hgfd', 'nbvcx', 'jhgfds', 'ytrew', 'uytre', 'oiuytr', 'poiuyt', 'kjhg', 'nbvc', 'hgfd',
'iuytr', 'hgfds', 'bvcx', 'rewq', 'gfds', 'bvcxz', 'hgfdsa', 'ytrewq', 'hgfdsa', 'bvcxz', 'nbvcxz',
'mnbvcxz', 'kjhgfds', 'kjhgfd', 'oiuyt', 'oiuytr', 'jhg', 'bvc', 'ytre', 'hgfds', 'iuytre', 'bvcx',
'gfds', 'jhgfds', 'ytrew', 'iuytr', 'nbvcx', 'jhgfds', 'poiuytr', 'jhgfd', 'nbvcx', 'hgfds', 'ytrew',
'jhgfd', 'nbvcx', 'hgfdsa', 'uytrew', 'bvcxz', 'hgfds', 'vcxz', 'kjhgfd', 'poiuyt', 'gfdsa', 'ytrew',
'gfds', 'bvcxz', 'rewq', 'gfdsa', 'nbvcxz', 'poiuytr', 'lkjhgff', 'mnbvc', 'hgfds', 'ytre', 'bvcx',
'gfds', 'hgfds', 'uytre', 'gfds', 'ytrewq', 'uytrew', 'iuytre', 'jhgfds', 'nbvcx', 'kjhgfd',
'oiuytre', 'hgfdsa', 'nbvcxz', 'jhgfds', 'iuytr', 'jhgfds', 'bvcx', 'hgfdsa', 'uytrew', 'gfdsa',
'nbvcx', 'mnbvc', 'iuytr', 'kjhgfd', 'oiuytr', 'hgfdsa', 'nbvcx', 'bvcx', 'fdsa', 'trewq', 'hgfdsa',
'nbvcxz', 'hgfds', 'uytrew', 'oiuyt', 'jhgfd', 'mnbvcx', 'uytre', 'oiuytre', 'nbvc', 'jhfd', 'kjhgfd',
'nbvcx', 'uytre', 'cxz', 'hgfdsa', 'mnbvcx', 'trewq', 'jhgfds', 'bvcxz', 'jhgfd', 'mnbvc', 'poi',
'iuyt', 'oiuyt', 'iuytr', 'iuyt', 'uytr', 'ytre', 'trewq', 'trew', 'ytrew', 'trewq', 'rewq', 'lkjh',
'jhg', 'jhgfd', 'hgfds', 'hgfdsa', 'fdsa', 'gfds', 'kjhgfd', 'lkjhg', 'mnbvc', 'nbvcx', 'bvcx', 'vcx',
'cxz', 'mnbvcx', 'bvcxz', 'lkjhgf', 'jhgfds', 'gfdsa', 'uytrew', 'trewq', 'oiuyt', 'poiu', 'oiuy',
'iuyt', 'uytre', 'ytre', 'trew', 'rewq', 'poiuyt', 'oiuytre', 'iuytrew', 'uytrew', 'trewq', 'lkjhgf',
'kjhgf', 'jhgfd', 'hgfds', 'gfds', 'fdsa', 'mnbvc', 'nbvc', 'bvcxz', 'vcxz', 'mnbvcxz', 'kjhgfd',
'gfdsa', 'iuytre', 'nbvcxv', 'poiu', 'poiuy', 'poiuyt', 'poiuytr', 'poiuytre', 'poiuytrew', 'oiuyt',
'oiuytr', 'oiuytre', 'oiuytrew', 'oiuytrewq', 'iuytr', 'uytre', 'iuytrew', 'iuytrewq', 'uytrew',
'ytrew', 'ytrewq', 'ytre', 'trew', 'trewq', 'lkjh', 'kjhg', 'jhgf', 'hgfd', 'gfds', 'fdsa', 'lkjhg',
'kjhgfd', 'jhgfds', 'hgfds', 'hgfdsa', 'gfdsa', 'mnbv', 'nbvc', 'bvcx', 'vcxz', 'mnbvc', 'nbvcx',
'bvcxz', 'mnbvcx', 'nbvcxz', 'mnbvcxz'
]
for item in negtive_input:
convert_keycode(item)
main()
|
from functools import reduce
from operator import mul
def main():
max_x, max_y, trees = read()
counts = []
for dx, dy in (1, 1), (3, 1), (5, 1), (7, 1), (1, 2):
counts.append(count_trees(max_x, max_y, trees, dx, dy))
mul_count = reduce(mul, counts)
print(mul_count)
def count_trees(max_x, max_y, trees, dx, dy):
x, y = 0, 0
count = 0
while y <= max_y:
if (x % max_x, y) in trees:
count += 1
x += dx
y += dy
return count
def read():
trees = set()
for y, line in enumerate(open("../inputs/d03-input.txt")):
for x, c in enumerate(line):
if c == "#":
trees.add((x, y))
return x, y, trees
if __name__ == "__main__":
main()
|
numCalls=0
def fib(n):
global numCalls
numCalls+=1
if n<=1:
print('fib of',n)
return 1
else:
print('fib of',n)
return fib(n-1)+fib(n-2)
print(numCalls)
memo={0:0,1:1}
def fib1(n):
global memo
global numCalls
numCalls+=1
if not n in memo:
memo[n]=fib1(n-1)+fib1(n-2)
return memo[n]
|
#ๅๅนถๆๅบๆณ
def merge(left,right):
"""Assume left and right are sorted lists.Return a new sorted list containing the same elements as (left+right) would contain."""
result=[]
i,j=0,0
while i<len(left) and j<len(right):
if left[i]<=right[j]:
result.append(left[i])
i=i+1
else:
result.append(right[j])
j=j+1
while i<len(left):
result.append(left[i])
i=i+1
while j<len(right):
result.append(right[j])
j=j+1
return result
def mergesort(L):
"""Return a new sorted list with the same elements as L"""
print(L)
if len(L)<2:
return L[:]
else:
middle=int(len(L)/2)
left=mergesort(L[:middle])
right=mergesort(L[middle:])
together=merge(left,right)
print('merged',together)
return together
def create(smallest,largest):
intSet=[]
for i in range(smallest,largest+1): intSet.append(None)
return intSet
def insert(intSet,e):
intSet[e]=1
def member(intSet,e):
return intSet[e]==1
def hashChar(c):
#c is a char
#function returns a different integer in the range 0-255
#for each possible value of c
return ord(c) #ord()ๅฝๆฐๆฏchr()ๅฝๆฐ๏ผๅฏนไบ8ไฝ็ASCIIๅญ็ฌฆไธฒ๏ผๆunichr()ๅฝๆฐ๏ผๅฏนไบUnicodeๅฏน่ฑก๏ผ็้
ๅฏนๅฝๆฐ๏ผๅฎไปฅไธไธชๅญ็ฌฆ๏ผ้ฟๅบฆไธบ1็ๅญ็ฌฆไธฒ๏ผไฝไธบๅๆฐ๏ผ่ฟๅๅฏนๅบ็ASCIIๆฐๅผ๏ผๆ่
Unicodeๆฐๅผ
def cSetCreate():
cSet=[]
for i in range(0,255): cSet.append(None)
return cSet
def cSetInsert(cSet,e):
cSet[hashChar(e)]=1
def cSetMember(cSet,e):
return cSet[hashChar(e)]==1
def readFloat(requestMsg,errorMsg):
while True:
val=input(requestMsg)
try:
val=float(val)
return val
except:
print(errorMsg)
#print(readFloat('Enter float:','Not a float.')
def readVal(valType,requestMsg,errorMsg):
while True:
val=input(requestMsg)
try:
val=valType(val)
return val
except:
print(errorMsg)
#print(readVal(int,'Enter int:','Not an int.')
|
#Demonstrating popen and popen2
import os
#determine operating system, then set directory-listing and reverse-sort commands
if os.name =="nt" or os.name == "dos":
fileList = "dir /B"
sortReverse = "sort /R"
elif os.name =="posix":
fileList = "ls -l"
sortReverse = "sort -r"
else:
sys.exit("OS not supported by this program")
#obtain stdout of directory-listing commands
dirOut = os.popen(fileList,"r")
#obtain stdin, stdout of reverse-sort commands
sortIn,sortOut = os.popen2(sortReverse)
filenames = dirOut.read()
#display output from directory-listing commands
print "Before sending to sort"
print "(Output from '%s'):" % fileList
print filenames
sortIn.write(filenames) #send to stdin of sort commands
dirOut.close()
sortIn.close()
#display output from sort commands
print "After sending to sort"
print "(Output from '%s'):" % sortReverse
print sortOut.read()
sortOut.close()
|
class Items(object):
def __init__(self, name, type, price):
self.itemName = name
self.itemType = type
self.unitPrice = price
class Store(object):
def __init__(self):
self.itemInventory = dict()
def buyItem(self, name, quantity):
for i, j in self.itemInventory.items():
if name.lower() == i.itemName.lower() and j == 0:
return None
if name.lower() == i.itemName.lower() and quantity > j:
bill = i.unitPrice * j
self.itemInventory[i] = 0
return bill
elif name.lower() == i.itemName.lower() and quantity <= j:
bill = i.unitPrice * quantity
self.itemInventory[i] = j - quantity
return bill
return None
if __name__ == '__main__':
n = int(input())
store = Store()
temp_dict = {}
for _ in range(n):
name, type, uprice, stock = input(), input(), int(input()), int(input())
store.itemInventory[Items(name, type, uprice)] = stock
m = int(input())
order = {}
for _ in range(m):
name, quantity = input(), int(input())
order[name] = quantity
for itemName, itemQuant in order.items():
bill = store.buyItem(itemName, itemQuant)
if not bill:
print(f'{itemName} is not available')
else:
print(f'Bill of the item {itemName} = {bill}')
print("Stock in Hand:")
for item, stock in store.itemInventory.items():
print(f'{item.itemName} {stock}')
|
# A traveler wants to start his/her journey from Pune
# to Ahmedabad. Before starting the journey, he/she uses
# the GPS system to find all the paths to reach from
# the source to the destination. He/she will use the
# smallest or the second smallest path to start the journey.
# Write a logic to find the smallest and the second
# smallest distance from the list of all distances.
# Input:
# 1. The first input contains N, the total number of paths
# from source to the destination.
# 2. The second input contains N sorted integers separated
# by newline A1,A2...An, representing the distance of all
# paths.
# Output contains two numbers separated by a single space character.
# If all paths are equal. then the system should generate a message
# as "Equal".
# If N is less than 2, then the system should generate a message as
# "Invalid Input".
# Constraints:
# 2 < N <= 10
# 1 <= A[i] <= 1000
# Example 1:
# Input:
# 4
# 100
# 400
# 300
# 250
# Output:
# 100 250
# Explaination:
# Out of the 4 possible paths, only 100 and 250 are the
# smallest distances to reach the destination.
# Example 2:
# Input:
# 1
# 200
# Output:
# Invalid Input
# Explaination:
# In the given constraints, the first value must be greater
# than 2.
# Example 3:
# Input:
# 3
# 100
# 100
# 100
# Output:
# Equal
import heapq
def findingLastTwoSmallest(arr):
if len(arr) == 1:
return "Invalid Input"
elif (len(set(arr)) == 1):
return "Equal"
elif len(arr) == 2:
return arr
else:
arr = list(set(arr))
heapq.heapify(arr)
result = [heapq.heappop(arr) for _ in range(2)]
return result
array = list(map(int, input().split()))
result = findingLastTwoSmallest(array)
print(result) |
class Passenger(object):
def __init__(self, name, age, dist):
self.passengerName = name
self.passengerAge = age
self.distanceTravelled = dist
def calculateTicketFare(passengers, fare):
total = 0
for i in passengers:
if i.passengerAge >= 60 or i.passengerAge < 12:
total += (i.distanceTravelled * fare)
elif i.passengerAge > 20 and i.passengerAge < 60:
total += (i.distanceTravelled * fare) + ((i.distanceTravelled * fare) * 0.12)
elif i.passengerAge >= 12 and i.passengerAge < 21:
total += (i.distanceTravelled * fare) + ((i.distanceTravelled * fare) * 0.10)
return total
def countSeniorJuniorPassengers(passengers):
count = 0
for i in passengers:
if i.passengerAge >= 60 or i.passengerAge < 12:
count += 1
return count
n = int(input())
pass_obj = []
for _ in range(n):
name, age, dist = input(), int(input()), int(input())
pass_obj.append(Passenger(name, age, dist))
fare = int(input())
temp = calculateTicketFare(pass_obj, fare)
print(temp)
count = countSeniorJuniorPassengers(pass_obj)
print(count) |
N=int(input("Enter the limit:"))
if N<0:
print("Invalid input")
else:
print("Armstrong number between 0 and",N,"are:")
for N in range(1,N+1):
sum=0
i=N
l=len(str(N))
while i>0:
sum=sum+((i%10)**l)
i//=10
if N==sum:
print(N,end=" ")
|
# # Make a SQL database using `psycopg2`
#
# When you make a database in SQL, you have to execute the command from within a database that already exists.
# By default every PgSQL cluster has a database named `postgres`, so in the code below we connect to that database
# before issuing the command to create the new database named in the `MY_DB` variable.
#
# ### Notes:
# - If the database already exists, this will fail with a `DuplicateDatabase` error
# - This only creates a basic database, it does not enable PostGIS
import psycopg2
MY_DB = "teaching_bucket"
UN = "postgres"
PW = "Bunnywithspt54"
HOST = "localhost"
# Connect to the postgres database
db_uri = f"postgresql://{UN}:{PW}@{HOST}:5432/postgres"
connection = psycopg2.connect(db_uri)
connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
cursor = connection.cursor()
# Execute the CREATE command
query_to_make_db = f"CREATE DATABASE {MY_DB};"
cursor.execute(query_to_make_db)
# Commit and close the database connection
cursor.close()
connection.commit()
connection.close()
|
import numpy as np
#Array with Array
#Array with Scalar
#Universal Array Function
arr = np.arange(0,11)
print(arr)
#Addition of 2 array elements
add_arr = arr + arr
print(add_arr)
#Add 100 to each element of array
arr_100 = arr + 100
print(arr_100)
#Universal Array Functions
#If you wantto take square root of each element then
arr_sqrt = np.sqrt(arr_100)
print(arr_sqrt)
#Find min max out of array
arr_min = np.min(arr_100)
print(arr_min)
|
'''
Author: Christian Duncan
Modification: David Lepore, Alex Hutman, Stephen Kern
Date: Spring 2019
Course: CSC350 (Intelligent Systems)
This sample code shows how one can read in our JSON image files in Python3. It reads in the file and then outputs the two-dimensional array.
It applies a simple threshold test - if value is > threshold then it outputs a '.' otherwise it outputs an 'X'. More refinement is probably better.
But this is for displaying images not processing or recognizing images.
'''
from os import listdir
from os.path import isfile, join
import re
from keras.models import Sequential
from keras.layers import Dense, Activation
import numpy as np
import sys
import random
from DigitClassifier import DigitClassifier
"""
Prints out the given "image" (a 2-dimensional array).
This just replaces any values greater than a threshold with . and otherwise with an X.
"""
def print_image(img, threshold):
for row in img:
for pixel in row:
print('.' if pixel > threshold else 'X', end='')
print() # Newline at end of the row
"""
K cross validation method: Splits data into k groups where each group holds a random set of files from the data set.
The k value used is k = 10.
First it divides the length of data by k which represents the number of files per group
then assign data to a temp data.
then initialize an empty array of groups.
Then for k-1 times to obtain all training groups:
train = a random sample number of files from temp data equal to numofFilesPerGroup
temp_data = the remainder of what files were taken from temp data
append train into groups array
lastly finish and append the last part of temp data remaining as the last group.
"""
def kCross(k, data):
numofFilesPerGroup = round(len(data)/k)
temp_data = data
groups = []
for i in range(k-1):
train = random.sample(temp_data,numofFilesPerGroup)
temp_data = list(set(temp_data)-set(train))
groups.append(train)
groups.append(temp_data)
return groups
"""
Main entry point. Assumes all the arguments passed to it are file names.
For each argument, reads in the file and the prints it out.
First we take all files from the path holding all data.
then we find all matches to our regular expression into our matches list.
then we get all jsonfiles from that matches list.
Once this happens we create our random partitions using kCross
it returns 10 partitions from all json files
Finally, we call digitclassifier using the data above, structuring into a neural network model
"""
def main():
my01path = "C:/DigitProject/DigitDetector/binaryFolder/digit_data/"
files = [f for f in listdir(my01path) if isfile(join(my01path, f))]
matches = [re.search("^input_[0-9]+_[0-9]+_[0-9]+\.json$", i) for i in files]
jsonFiles = [i.group(0) for i in matches if i]
partitions = kCross(10, jsonFiles)
DigitClassifier(partitions, my01path, 'neural')
# This is just used to trigger the Python to run the main() method. The if statement is used so that if this code
# were imported as a module then everything would load but main() would not be executed.
if __name__ == "__main__":
main()
|
๏ปฟdef move(f,t):
print("move disk from {} to {}!".format(f,t))
#move("A","C")
def moveVia(f,v,t):
move(f,v)
move(v,t)
def hanoi(n,f,h,t):
if(n==0):
pass
else:
hanoi(n-1,f,t,h)
move(f,t)
hanoi(n-1,h,f,t)
hanoi(8,"A","B","C")
|
"""
Author: Alejandro Sanchez Uribe
Date: 12 Dec 19
"""
import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix(str): suffix of the file name to be found
path(str): path of the file system
Returns:
a list of paths
"""
output = []
# check input validity:
if suffix == '' or path == '':
return 'Invalid suffix or path: Input was empty string'
if not isinstance(suffix, str) or not isinstance(path, str):
return 'Invalid suffix or path: Input was not of type str'
# base case:
if os.path.isfile(path):
if path.endswith(suffix):
output.append(path)
return output
# check if recursion required:
if os.path.isdir(path):
for sub_path in os.listdir(path):
output.extend(find_files(suffix, os.path.join(path, sub_path)))
return output
# test cases below:
found_files = find_files('.c', './testdir')
# finds: ./testdir/subdir1/a.c, ./testdir/subdir3/subsubdir1/b.c, ./testdir/subdir5/a.c, ./testdir/t1.c
print(found_files)
found_files = find_files('.c', './testdir/subdir1')
# finds: ./testdir/subdir1/a.c
print(found_files)
found_files = find_files('.c', './testdr')
# finds: nothing, since the file directory doesn't exist
print(found_files)
found_files = find_files('.c', '')
# returns warning of empty string
print(found_files)
found_files = find_files('.c', 0)
# returns warning of non string input
print(found_files)
|
"""
Author: Alejandro Sanchez Uribe
Date: 19 Dec 2019
"""
import random
def rotated_array_search(input_list, number):
"""
Find the index by searching in a rotated sorted array
Args:
input_list(list): Input array to search
number(int): The target
Returns:
int: Index or -1
"""
start = 0
stop = len(input_list) - 1
while start <= stop:
# implement binary search
midpoint = (start + stop) // 2
if input_list[midpoint] == number:
return midpoint
# check if left side is sorted
if input_list[start] <= input_list[midpoint]:
# check if number is in range of the sorted left side
if input_list[start] <= number < input_list[midpoint]:
# continue search on left side
stop = midpoint - 1
else:
# continue search on right side
start = midpoint + 1
# check if number is in range of sorted right side
if input_list[midpoint] < number <= input_list[stop]:
# continue search on right side
start = midpoint + 1
else:
# continue search on left side
stop = midpoint - 1
return -1
def linear_search(input_list, number):
for index, element in enumerate(input_list):
if element == number:
return index
return -1
def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
print(str(number) + ' @ ' + str(rotated_array_search(input_list, number)), end=': ')
if linear_search(input_list, number) == rotated_array_search(input_list, number):
print("Pass")
else:
print("Fail")
# Test Cases below:
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 6])
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 8])
test_function([[6, 7, 8, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 10])
test_function([[], 1])
test_function([[1], 1])
test_function([[1, 2], 2])
test_function([
[72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71]
, random.randint(0, 99)])
|
import math
import matplotlib.pyplot as plt
import numpy.random as rand
plt.rcParams['figure.dpi'] = 280
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f'Vector({self.x}, {self.y})'
def magnitude(self):
mag = math.hypot(self.x, self.y)
return mag
def add(self, vector):
""" Add the x and y components, and return a new Vector. """
xf = self.x + vector.x
yf = self.y + vector.y
return Vector(xf, yf)
def __add__(self, other):
""" Add the x and y components, and return a new Vector. """
# Check if the other parameter is a Vector or a scalar
if isinstance(other, Vector):
# the parameter is a Vector, add the components
xf = self.x + other.x
yf = self.y + other.y
elif not hasattr(other, '__len__'):
# the other parameter is a scalar, add it to each component
xf = self.x + other
yf = self.y + other
else:
return NotImplemented
return Vector(xf, yf)
def __sub__(self, other):
""" Subtract the x and y components, and return a new Vector. """
# Check if the other parameter is a Vector or a scalar
if isinstance(other, Vector):
# the parameter is a Vector, subtract the components
xf = self.x - other.x
yf = self.y - other.y
elif not hasattr(other, '__len__'):
# the other parameter is a scalar, subtract it from each component
xf = self.x - other
yf = self.y - other
else:
return NotImplemented
return Vector(xf, yf)
def subtract(self, vector):
""" Subtract other Vector from this vector, return a new Vector. """
xf = self.x - vector.x
yf = self.y - vector.y
return Vector(xf, yf)
def __mul__(self, other):
""" Multiply by components, and return a new Vector. """
# Check if the other parameter is a Vector or a scalar
if isinstance(other, Vector):
# the parameter is a Vector, multiply each component pai
xf = self.x * other.x
yf = self.y * other.y
elif not hasattr(other, '__len__'):
# the other parameter is a scalar, multiply each component by it
xf = self.x * other
yf = self.y * other
else:
return NotImplemented
return Vector(xf, yf)
def v_multiply(self, vector):
""" Multiply two Vectors by components. """
xf = self.x * vector.x
yf = self.y * vector.y
return Vector(xf, yf)
def s_multiply(self, c):
""" Multiply this Vector by a scalar. """
xf = self.x * c
yf = self.y * c
return Vector(xf, yf)
class Planet:
def __init__(self, mass, radius, pos, vel, name):
self.name = name
self.r = radius
self.m = mass
# pos parameter is a Vector
self.pos = pos
self.x = pos.x
self.y = pos.y
self.vel = vel
# Momentum equals mass*velocity
# Note that momentum should not be a vector.
self.momentum = vel.s_multiply(self.m)
self.accel = None
def force(self, planet):
# Initialize the force vector at 0
force_vector = Vector(0, 0)
G = 0.004
e = 0.0001
# neg_vector unused
# neg_vector = self.pos.s_multiply(-1)
# parameter planet is a list of all planets to check
for i in range(len(planet)):
# check if the planet i is the current planet
if planet[i].name != self.name:
# distance vector between planets = current pos - pos[i]
# dot notation: use Vector.subtract method from pos
# distance Vector points from current planet to planet[i]
dist_vec = self.pos - planet[i].pos
# distance magnitude
dist = dist_vec.magnitude()
# F vector = G*m1*m2/(r+e)**3 * distance vector
# e = small additive value, unknown
# distvec/dist**3 gives the unit vector divided by dist**2
force_vector1 = dist_vec * (G * planet[i].m * self.m / (dist + e) ** 3)
# if the distance is less than the current planet's radius,
# make the force negative (magnitude still the same?)
if dist < self.r:
force_vector1 = force_vector1 * -1
# Add the result to the total force vector
force_vector = force_vector + force_vector1
# return the force vector negated?
return force_vector * -1
def simulate(planets, nsteps):
# Time resolution delta t
dt = 0.001
# Number of calculation steps
X = [[] for i in range(len(planets))]
Y = [[] for i in range(len(planets))]
# loop through the number of steps, counting down from initial steps value
for step in range(nsteps):
# for each planet, by index
for i in range(len(planets)):
# Acceleration = F/m
planets[i].accel = planets[i].force(planets) * (1/planets[i].m)
# Velocity changes by accel*dt
# with the __add__ method, the + operator can be used
planets[i].vel = planets[i].vel + planets[i].accel * dt
# planet's position changes by momentum*dt/mass = v*dt
# with the __add__ method, the + operator can be used
planets[i].pos = planets[i].pos + planets[i].vel * dt
# Add each position component to the position lists for this planet
X[i].append(planets[i].pos.x)
Y[i].append(planets[i].pos.y)
return X, Y
def main(nbodies, nsteps):
# List of all the planets
planets = []
# Create n randomly generated planets
for i in range(nbodies):
# Create a list of 4 random numbers 0-1 for pos and vel components
a = rand.random(4)
p = Planet(10,
0.001,
Vector(a[0], a[1]),
Vector(a[2], a[3]),
str(i))
planets.append(p)
X, Y = simulate(planets, nsteps)
fig1, ax = plt.subplots()
ax.set_aspect('equal')
# for each planet, plot the position components over time
for i in range(len(planets)):
ax.plot(X[i], Y[i])
ax.scatter(X[i][-1], Y[i][-1], s=30)
ax.set_title(f'N Body Problem (n = {nbodies})')
plt.show()
if __name__ == '__main__':
main(nbodies=5, nsteps=5000)
|
import os
import sqlite3
import sys
import masterScript
def screen_Scripts() :
'''
Show all the available operations that can be done on the bam files
'''
pass
def screen_Cancer() :
'''
Show the cancers available to analyze. To do that, check on the database.
After get the bams, ask if the bams should be deleted or not.
'''
# Constants
#Path to database
pathDb = "/g/strcombio/fsupek_cancer2/TCGA_bam/info/info.db"
#Connect to database
try :
con = sqlite3.connect(pathDb)
cursor = con.cursor()
cursor.execute("select cancer, count(*) from patient p, sample s where s.submitter=p.submitter group by cancer")
rows = cursor.fetchall()
it = 0
print "\nWhich cancer analyse?\n======================================"
# 0 - Name of the cancer
# 1 - Number of bams in each cancer
for r in rows :
print "\t[{}] {} ({} bams)".format(it, r[0], r[1])
it += 1
print "======================================\n"
opt = int(raw_input("Your option: "))
if opt < 0 or (opt+1) > len(rows):
raise KeyError("Invalid option for the cancer")
#TODO get the number of bams to analyse: only for a test, or all the bams
cancer = rows[opt][0]
delete = raw_input("Delete bams after successful analysis? [y/n] ")
if delete != 'y' and delete != 'n' :
raise KeyError("Invalid option for deleting the bams")
return (cancer, delete)
except sqlite3.Error, e :
print "SQLITE3 ERROR -> {}".format(e)
sys.exit(1)
except (KeyError, ValueError), e :
print "ERROR: found error during execution\n\t{}".format(e)
finally :
if con :
con.close()
def run() :
'''
Run the script passed by parameter
Store the standar output and the error output in corresponding logs
Check output
'''
pass
def main() :
(cancerType, deleteBam) = screen_Cancer()
print cancerType
print deleteBam
if __name__ == "__main__":
main()
|
import pickle
import os
class account():
def __init__(s):
s.acno = 0
s.name = ""
s.deposit = 0
s.type = ""
def create_account(s): # function to get data from user
name =input("\n\nEnter the name of the account holder: ")
s.name = name.capitalize()
type =input("\nEnter type of the account (C/S): ")
s.type = type.upper()
s.deposit =int(input("\nEnter initial amount\n(>=500 for Saving and >=1000 for Current): "))
def show_account(s): # function to show data on screen
print("\nAccount No. :", s.acno)
print("\nAccount holder name: ", s.name)
print("\nType of account", s.type)
print("\nBalance amount: ", s.deposit)
def modify(s): # function to get new data from user
print("\nAccount No. : ", s.acno)
s.name = input("\n\nEnter the name of account holder: ")
type = input("\n\nEnter type of account (C/S): ")
s.type = type.upper()
s.deposit = int(input("\nEnter the amount: "))
def dep(s, x): # function to accept amount and add to balance
s.deposit += x
def draw(s, x): # function to accept amount and subtract from balance amount
s.deposit -= x
def report(s): # function to show data in tabular format
print("%-10s" % s.acno, "%-20s" % s.name, "%-10s" % s.type, "%-6s" % s.deposit)
def retacno(s): # function to return account number
return s.acno
def retdeposit(s): # function to return balance amount
return s.deposit
def rettype(s): # function to return type of account
return s.type
"""*****************************************************************************
FUNCTION TO GENERATE ACCOUNT NUMBER
*****************************************************************************"""
def gen_acno():
try:
inFile = open("account2.dat", "rb")
outFile = open("text2.dat", "wb")
n = inFile.read()
n = int(n)
while True:
n += 1
outFile.write(str(n).encode('utf-8'))
inFile.close()
outFile.close()
os.remove("account2.dat")
os.rename("text2.dat", "account2.dat")
yield n
except IOError:
print("I/O error occured")
"""*****************************************************************************
FUNCTION TO WRITE RECORD IN BINARY FILE
*****************************************************************************"""
def write_account():
try:
ac = account()
outFile = open("account.dat", "ab")
print('aptron')
ch = gen_acno()
ac.acno = next(ch)
ac.create_account()
pickle.dump(ac, outFile)
outFile.close()
print("\n\n Account Created Successfully")
print("\n\n YOUR ACCOUNT NUMBER IS: ", ac.retacno())
except:
pass
"""*****************************************************************************
FUNCTION TO DISPLAY ACCOUNT DETAILS GIVEN BY USER
*****************************************************************************"""
def display_sp(n):
flag = 0
try:
inFile = open("account.dat", "rb")
print ("\nBALANCE DETAILS\n")
while True:
ac = pickle.load(inFile)
if ac.retacno() == n:
ac.show_account()
flag = 1
except EOFError:
inFile.close
if flag == 0:
print("\n\nAccount number not exist")
except IOError:
print("File could not be open !! Press any Key...")
"""*****************************************************************************
FUNCTION TO MODIFY RECORD OF FILE
*****************************************************************************"""
def modify_account(n):
found = 0
try:
inFile = open("account.dat", "rb")
outFile = open("temp.dat", "wb")
while True:
ac = pickle.load(inFile)
if ac.retacno() == n:
print(30 * "-")
ac.show_account()
print(30 * "-")
print("\n\nEnter The New Details of Account")
ac.modify()
pickle.dump(ac, outFile)
print("\n\n\tRecord Updated")
found = 1
else:
pickle.dump(ac, outFile)
except EOFError:
inFile.close()
outFile.close()
if found == 0:
print("\n\nRecord Not Found ")
except IOError:
print("File could not be open !! Press any Key...")
os.remove("account.dat")
os.rename("temp.dat", "account.dat")
"""*****************************************************************************
FUNCTION TO DELETE RECORD OF FILE
*****************************************************************************"""
def delete_account(n):
found = 0
try:
inFile = open("account.dat", "rb")
outFile = open("temp.dat", "wb")
while True:
ac = pickle.load(inFile)
if ac.retacno() == n:
found = 1
print("\n\n\tRecord Deleted ..")
else:
pickle.dump(ac, outFile)
except EOFError:
inFile.close()
outFile.close()
if found == 0:
print("\n\nRecord Not Found")
except IOError:
print("File could not be open !! Press any Key...")
os.remove("account.dat")
os.rename("temp.dat", "account.dat")
"""*****************************************************************************
FUNCTION TO DISPLAY ALL ACCOUNT DETAILS
*****************************************************************************"""
def display_all():
print("\n\n\tACCOUNT HOLDER LIST\n\n")
print(60 * "=")
print("%-10s" % "A/C No.", "%-20s" % "Name", "%-10s" % "Type", "%-6s" % "Balance")
print(60 * "=", "\n")
try:
inFile = open("account.dat", "rb")
while True:
ac = pickle.load(inFile)
ac.report()
except EOFError:
inFile.close()
except IOError:
print("File could not be open !! Press any Key...")
"""*****************************************************************************
FUNCTION TO DEPOSIT/WITHDRAW AMOUNT FOR GIVEN ACCOUNT
*****************************************************************************"""
def deposit_withdraw(n, option):
found = 0
try:
inFile = open("account.dat", "rb")
outFile = open("temp.dat", "wb")
while True:
ac = pickle.load(inFile)
if ac.retacno() == n:
ac.show_account()
if option == 1:
print("\n\n\tTO DEPOSIT AMOUNT")
amt =int(input("Enter the amount to be deposited: "))
ac.dep(amt)
elif option == 2:
print("\n\n\tTO WITHDRAW AMOUNT")
amt = int(input("Enter amount to be withdraw: "))
bal = ac.retdeposit() - amt
if ((bal < 500 and ac.rettype() == "S") or (bal < 1000 and ac.rettype() == "C")):
print("Insufficient balance")
else:
ac.draw(amt)
pickle.dump(ac, outFile)
found = 1
print("\n\n\tRecord Updated")
else:
pickle.dump(ac, outFile)
except EOFError:
inFile.close()
outFile.close()
if found == 0:
print("\n\nRecord Not Found")
except IOError:
print("File could not be open !! Press any Key...")
os.remove("account.dat")
os.rename("temp.dat", "account.dat")
"""*****************************************************************************
INTRODUCTORY FUNCTION
*****************************************************************************"""
def intro():
print("\n\n\tBANK")
print("\n\tMANAGEMENT")
print("\n\n\nMADE BY : Enter your name")
print("\nSCHOOL : Enter your school name")
"""*****************************************************************************
THE MAIN FUNCTION OF PROGRAM
*****************************************************************************"""
intro()
while True:
print(3 * "\n", 60 * "=")
print("""MAIN MENU
1. New Account
2. Deposit Amount
3. Withdraw Amount
4. Balance Enquiry
5. All Account Holder List
6. Close An Account
7. Modify An Account
8. Exit
""")
try:
ch =int(input("Enter Your Choice(1~8): "))
if ch == 1:
write_account()
elif ch == 2:
num =int(input("\n\nEnter Account Number: "))
deposit_withdraw(num, 1)
elif ch == 3:
num =int(input("\n\nEnter Account Number: "))
deposit_withdraw(num, 2)
elif ch == 4:
num =int(input("\n\nEnter Account Number: "))
display_sp(num)
elif ch == 5:
display_all()
elif ch == 6:
num = int(input("\n\nEnter Account Number: "))
delete_account(num)
elif ch == 7:
num = int(input("\n\nEnter Account Number: "))
modify_account(num)
else:
print("Input correcr choice...(1-8)")
except NameError:
print("Input correct choice...(1-8)")
input("\n\n\n\n\nTHANK YOU\n\nPress any key to exit...")
"""*****************************************************************************
END OF PROJECT
*****************************************************************************"""
|
def sum_n(n):
if n == 1:
return 1
else:
return n + sum_n(n-1)
print(sum_n(5))
|
#define function chorus, which repeats many time in the song
#We have to define function before it is called
def chorus(duck_num):
print("{} little ducks".format(duck_num))
print("Went out one day")
print("Over the hill and far away")
print("Mother duck said")
print("\"Quack, quack, quack, quack.\"")
print("But only {} little ducks came back.".format(duck_num-1))
print("")
######### Main Program Start ########
for ducks in range(5, 1, -1):
chorus(ducks) #Call function to complete song writing |
my_name = 'Eric Yang'
my_age = 42 # not a lie
my_height = 1.71 # metre
my_weight = 80 # kg
my_eyes = 'black'
my_teeth = 'white'
my_hair_color = 'black'
my_hair_style = 'short'
print ('My name is',my_name,'and my age is:', my_age)
print("Let's talk about %s." % my_name)
print("He's %4.2f metres tall." % my_height)
print("He's %d kilogram heavy." % my_weight)
print("Actually that's not too heavy.")
print("He has %s eyes." % my_eyes)
print("He's got %s and %s hair." % (my_hair_style, my_hair_color))
print("His teeth are usually %s depending on the coffee." % my_teeth)
# this line is tricky, try to get it exactly right
print ("If I squred %.2f and divided by %.2f, I get BMI %.2f." % (
my_height, my_weight, my_weight/(my_height ** 2)))
'''
HOMEWORK:
Rewrite the above codes using .format() function
'''
|
number=int(input())
tem=number
re=0
while(number>0):
dig=number%10
re=re*10+dig
number=number//10
if(tem==re):
print("yes")
else:
print("no")
|
import random
SHIP_SIZE = 4
DIMENSION = 10
#Create a board
board = [[0 for i in range(DIMENSION)] for x in range(DIMENSION)]
#randomly generate a ship
check = False
while check != True:
ship = [random.randint(0,DIMENSION-1),random.randint(0,DIMENSION-1),random.randint(0,1)]
#The number represents row_num,col_num,Direction respectively
#0 stands for down, 1 stands for right
#Make sure the randomly generated ship will be on board. If yes, add it on the board. If no, regenerate it
if ship[2]==0:
if ship[1]>=DIMENSION-(SHIP_SIZE-1):
continue
for x in range(SHIP_SIZE):
board[ship[0]][ship[1]+x]=1
check = True
else:
if ship[0]>=DIMENSION-(SHIP_SIZE-1):
continue
for x in range(SHIP_SIZE):
board[ship[0]+x][ship[1]]=1
check = True
#Game start:
print("Hello!Welcome to the Battleship game. Let's start!",end="\n"*2)
right_guess = 0
score = 0
while right_guess < SHIP_SIZE:
#Display the board:
#Row label:
for row_label in range(65,65+DIMENSION):
print(" "+chr(row_label),end="")
print("\n")
#col label and grid:
for row in range(DIMENSION+1):
#Print row line
print(" "+"+---"*DIMENSION+"+",end="\n")
#Make sure we won't have extra col_line(since col_line is one less than row_line
if row==DIMENSION:
break
#Print col_label
print(str(row),end="")
#Print col_line
for col in range(DIMENSION):
if board[row][col] == 2:
print("| # ",end="")
elif board[row][col] == 3:
print("| X ",end="")
else:
print("| ",end="")
#print the last "|"
print("|",end="\n")
#Ask for input
player_input = input("Enter coordinate to target(e.g. A1,B2): ")
#Score count
score = score + 1
#Check whether the input is a capitalized letter followed by number
if player_input[0].isalpha() == False:
print("Wrong input!Your row guess should be a letter like:A. Input again!",end="\n"*2)
continue
elif player_input[0].isupper() == False:
print("Wrong input!Your row guess should be a capitalized letter like:A. Input again!",end="\n"*2)
continue
elif player_input[1:].isdigit() == False:
print("Wrong input!Your column guess should be a integer like:1. Input again!",end="\n"*2)
continue
#After making sure the input is the right format,convert it into row and col value
col_guess = ord(player_input[0])-65
row_guess = int(player_input[1:])
#Check whether input is within the board and is not a repetitive guess
if row_guess>=DIMENSION or row_guess<0 or col_guess<0 or col_guess>=DIMENSION:
print("Wrong input!Your guess exceeds the board limit. Input again!",end="\n"*2)
continue
elif board[row_guess][col_guess] == 2: #2 stands for a marked wrong guess
print("Wrong input!You already checked this location. Input again!",end="\n"*2)
#Mark the guess and check whether player guess right:
if board[row_guess][col_guess] == 1:
right_guess = right_guess + 1
print("You guess one right!",end="\n"*2)
board[row_guess][col_guess] = 3 # 3 stands for a marked right guess
else:
board[row_guess][col_guess] = 2
print("You guess wrong! Try again",end="\n"*2)
#End of the game:
print("Congratulations!You win the game:)",end="\n"*2)
print("You used",str(score),"times to win this game")
|
"""
Day-1 (29/05/2021)
Binary sort
Author: Prajwal Prakash
Time complexity: Process finished --- 2.8371810913085938e-05 seconds ---
Data structures used:
Result: Successful
"""
import time
def linear_search(list, element):
for i in range(len(list)):
if element == list[i]:
return i
###############################################################################
# Driver Code
arr = [
2,
3,
5,
8,
9,
11,
22,
56,
45,
56,
59,
60,
62,
65,
68,
69,
74,
75,
78,
79,
80,
81,
83,
84,
87,
89,
90,
92,
95,
97,
99,
100,
]
x = 79
start_time = time.time()
print("The element in list is found at :", linear_search_2(arr, x))
print("Process finished --- %s seconds ---" % (time.time() - start_time))
|
import math
########################
# PYTAGORAS
########################
def pytagoras(delta_x, delta_y) -> float:
return math.sqrt(delta_x**2 + delta_y**2)
def distance_to(pos1, pos2) -> float:
""" Returns the distance between two object on a 2d plane (using the formula of Pytagoras) """
return pytagoras(pos1[0] - pos2[0], pos1[1] - pos2[1])
def distance_to_3d(pos1, pos2) -> float:
""" Returns the distance between two object on a 3d plane (using the formula of Pytagoras) """
delta_x, delta_y, delta_z = abs(pos1[0] - pos2[0]), abs(pos1[1] - pos2[1]), abs(pos1[2] - pos2[2])
delta_xz = pytagoras(delta_x, delta_z)
return pytagoras(delta_xz, delta_y)
########################
# Triangle
########################
def translate_triangle(x, y, diagonal, new_len) -> (float, float):
""" To translate a 90deg triangle with a x sized diagonal to a smaller/bigger diagonal triangle
per example: the famous 3 4 5 triangle could become: .6 .8 1 """
mul = new_len / diagonal
return x * mul, y * mul
########################
# UNIT CIRCLE
########################
def radian_to(pos1, pos2) -> float:
""" Get a radian between two objects on a 2d plane """
distance = distance_to(pos1, pos2)
delta_x = pos1[0] - pos2[0]
delta_y = pos1[1] - pos2[1]
dx, dy = translate_triangle(delta_x, delta_y, distance, 1)
return math.acos(dx) * (-1 if dy > 0 else 1)
########################
# INTERSECTION
########################
# def intersection(line1, line2):
# """ Get the coordinates of the intersection of two lines """
# line1_delta = (line1[1][0] - line1[0][0], line1[1][1] - line1[0][1])
# a = line1_delta[1] / line1_delta[0]
# print("a", a)
# line2_delta = (line2[1][0] - line2[0][0], line2[1][1] - line2[0][1])
# a = line2_delta[1] / line2_delta[0]
# print("a", a)
# if __name__ == "__main__":
# print(intersection(
# ((0, 0), (5, 1)),
# ((1, 0), (1, 4))
# ))
|
#CLASS: Dinosaur
#Author: Richard Fleming
#Create Date: August 10, 2021
from attacks import Attacks
class Dinosaur:
#Constructor
def __init__(self, name): #, attack_power):
self.name = name
#self.attack_power = attack_power
self.health = 100
self.attack_types = []
self.energy = 100
#Methods
def attack(self, robot, index):
robot.health -= self.attack_types[index].attack_power
self.energy -= 10
def add_attack(self):
chomp = Attacks("Chomp", 30)
stomp = Attacks("Stomp", 25)
romp = Attacks("Romp", 15)
self.attack_types.append(chomp)
self.attack_types.append(stomp)
self.attack_types.append(romp)
def get_attack(self, index):
print("You selected " + self.attack_types[index].name)
return self.attack_types[index]
|
#!/usr/bin/env python3
# coding: utf-8
# Teste si le caractรจre c est une lettre minuscule.
def is_alpha_min(c):
return (ord(c) >= ord('a') and ord(c) <= ord('z'))
# Teste si le caracรจre c est une lettre majuscule.
def is_alpha_maj(c):
return (ord(c) >= ord('A') and ord(c) <= ord('Z'))
# Teste si le caractรจre c est une lettre.
def is_alpha(c):
return is_alpha_maj(c) or is_alpha_min(c)
# Renvoie la string s sans ses espaces
def clean_espace(s):
tmp = ""
for c in s:
if c != ' ':
tmp += c
return tmp
# Retourne le contenue de filename dans une chaรฎne de caractรจre
def extract_in_file(filename):
f = open(filename, "r")
s = ""
for line in f.readlines():
s += line
f.close()
return s
# Ecrit la chaรฎne s dans filename.
def write_in_file(filename, s):
f = open(filename, "w")
bufsize = 50
i = 0
while (i < len(s)):
f.write(s[i:(i + bufsize)])
i += bufsize
f.close
# Retire la ponctuation du texte
def without_punc(text):
punc_dict = {}
tmp = text
i = 0
while i < len(text):
c = text[i]
if is_alpha_min(c) == False:
punc_dict[i] = c
tmp = tmp.replace(c, "")
i += 1
return (tmp, punc_dict)
# Remet la ponctuation du texte
def put_punc(tmp, dico):
l_ind = list(dico)
i = 0
text = tmp
while i < len(tmp) + len(l_ind):
if i in l_ind:
text = text[:i] + dico[i] + text[i:]
i += 1
return text
|
from sqlalchemy import*
db = create_engine('sqlite:///tutorial2.db')
# The create_engine() function takes a single parameter that's a URI, of the form:
# "engine://user:password@host:port/database"
# Most of these options can be omitted,
db.echo = False
metadata = MetaData(bind=db)
#Before creating our table definitions we have to create the object that will manage them.
users2 = Table('users2', metadata,
Column('user_id', Integer, primary_key = True),
Column('name', String(40)),
Column('age', Integer),
Column('password', String),
)
#users2.create() database is already created.
ins = users2.insert()
ins.execute(name = "Tony", age = 21, password = "monkmonk12")
ins.execute({'name': "Tom", 'age': 33, 'password': "hungryhippo"},
{'name': "Tina", 'age': 13, 'password': "turtleteeth"},
{'name': "Ralf", 'age': 23, 'password': "riffraff"},
{'name': "Zack", 'age': 14, 'password': "executables"},
)
name = raw_input("Name:")
age = raw_input("Age:")
password = raw_input("Password:")
ins.execute(name = name, age = age, password = password)
sel = users2.select()
rs = sel.execute()
row = rs.fetchone()
print 'ID:', row[0] # can also be row.uder_id
print 'Name:', row.name # can also be row[1]
print 'Age:', row.age # can also be row[2]
print 'password:', row.password
for row in rs:
print "%r is %r years old!" % (row.name, row.age)
def run(stmt):
rs = stmt.execute()
for row in rs:
print row
# s = users2.select(users2.c.name == 'Tina')
# run(s)
# s = users2.select(users2.c.age < 40)
# run(s)
# Python keywords like and or and not can't be overloaded, so SQLAlchemy uses functions instead
s = user.select(and_(users2.c.age < 40, users.c.name != 'Ralf'))
run(s)
# or you can use and -and- or but watch out for priority
s = user.select((users2.c.name == 'Tony') & (users2.c.age == 21))
run(s)
|
import string
word='and'
n=1
s=list(string.ascii_lowercase)
s1=[i for i in s if i!=word[0]]
def sub(s1,w):
substitute=[]
s2=[i for i in s if i!=word[w]]
for i in s2:
for j in s1:
substitute.append(j+i)
return substitute
s3=[]
for i in range(n-1):
s1=sub(s1,w=i+1)
for i in s1:
s3.append(i+word[n:])
print(s3)
|
""" Day 23: BST Level-Order Traversal test """
from hackT import bst_traversal
def test_1():
a = [3, 5, 4, 7, 2, 1]
myTree = bst_traversal.Solution()
root=None
for i in a:
data = i
root=myTree.insert(root,data)
res = myTree.levelOrder(root)
assert res == [3, 2, 5, 1, 4, 7]
#test_1()
|
""" Day 22: Binary Search Trees test """
from hackT import bin_trees
def test_1():
a = [3, 5, 2, 1, 4, 6, 7]
myTree = bin_trees.Solution()
root=None
for i in a:
data = i
root=myTree.insert(root,data)
height=myTree.getHeight(root)
assert height == 3
|
"""Day 11: 2D Arrays"""
def getHourglassSum(arr, startRow, startCol):
""" Returns sum of hourglass in arr matrix stating at [startRow, startCol] position (zero based indices)
Return value is None where hourglass is not possible to construct
"""
retVal = 0
if startRow > 3 or startCol > 3:
return None
for i in range(3):
retVal += arr[startRow][startCol + i]
retVal += arr[startRow + 1][startCol + 1]
for i in range(3):
retVal += arr[startRow + 2][startCol + i]
return retVal
def getHourglassMaxSum(arr):
maxSum = -9 * 8 # No more then 7 of -9 can be in matrix as hourglass
for row in range(6):
for col in range(6):
rv = getHourglassSum(arr, row, col)
if rv != None:
if rv > maxSum:
maxSum = rv
return maxSum
#print(getHourglassMaxSum(arr))
|
#This script gets job posting from github
# IMPORTS
#Make Python understand how to read things on the Internet
import urllib2
#Make Python understand the stuff in a page on the Internet is JSON
import json
# Make Python understand csv
import csv
# Make Python know how to take a break so we don't hammer API and exceed rate limit
from time import sleep
def get_jobposting():
# tell computer where to put CSV
outfile_path='/home/hamyna/Documents/Git/BullFrogIT/Jobs-WebScrapping/Results/Github/jobPosting_gitHub-.csv'
# open it up, the w means we will write to it
writer = csv.writer(open(outfile_path, 'w'))
#create a list with headings for our columns
headers = ['id', 'title', 'created_at', 'location', 'type', 'description', 'company', 'how_to_apply', 'url']
location = ['Atlanta', 'boston', 'bristol', 'brooklyn', 'CA', 'chicago', 'DC', 'LA', 'london', 'MA', 'Maryland', 'NC', 'NY', 'TORONTO', 'WATERLOO', 'Washington']
#write the row of headings to our CSV file
writer.writerow(headers)
i=1 #iteration count
#loop through pages of JSON returned, 5 (ce), note that iteration can be increased or decreased
while i<6:
#print out what number loop we are on, which will make it easier to track down problems when they appear
print "Currently downloading job postings from github"
print i
#create the URL for the json data, location is north america and page number is iteration i
#and set the number of tweets per JSON file to the max of 5, so we have to do as little looping as possible
url = urllib2.Request('https://jobs.github.com/positions.json?description&location=TORONTO&page=' + str(i))
#use the JSON library to turn this file into a Pythonic data structure
parsed_json = json.load(urllib2.urlopen(url))
print parsed_json
#run through each item in results, and jump to an item in that dictionary, ex: the text of the tweet
for posting in parsed_json:
#initialize the row
row = []
#add every 'cell' to the row list, identifying the item just like an index in a list
row.append(str(posting['id'].encode('utf-8')))
row.append(str(posting['title'].encode('utf-8')))
row.append(str(posting['created_at'].encode('utf-8')))
row.append(str(posting['location'].encode('utf-8')))
row.append(str(posting['type'].encode('utf-8')))
row.append(str(posting['description'].encode('utf-8')))
row.append(str(posting['company'].encode('utf-8')))
row.append(str(posting['how_to_apply'].encode('utf-8')))
row.append(str(posting['url'].encode('utf-8')))
#once you have all the cells in there, write the row to your csv
writer.writerow(row)
#increment our loop counter, now we're on the next time through the loop
i = i +1
#tell Python to rest for 5 secs, so we don't exceed our rate limit
sleep(5)
if __name__ == "__main__":
get_jobposting() |
import math
class turtle():
def __init__(self, obj):
self.Interface = obj
self.Y = 100
self.X = 100
self.Pen = True
self.Angle = 0
def parseCode(self):
code = str(self.Interface.getCode())
code = code.split('\n')
for f in code:
#print callable(eval("self."+f))
eval("self."+f)
def mov1e(self, steps, angle):
rad = angle * (math.pi/180)
x = math.sin(rad)
y = math.cos(rad)
ratio = x/y
print ratio
for x in range(self.X, (steps+self.X)):
self.X = x
self.Y = x*ratio
self.interface.setPixel(x , int(x*ratio))
def move(self, steps, angle):
self.Angle += angle
for i in range(steps):
self.Angle += angle
self.X += self.getX(self.Angle)
self.Y += self.gety(self.Angle)
if self.Pen:
self.Interface.setPixel(int(self.X), int(self.Y))
def getX(self, angle):
angle -= 90
if(angle < 0):
angle = 360 + angle
angle = angle * math.pi / 180.0
return math.cos(angle)
def gety(self, angle):
angle -= 90
if(angle < 0):
angle = 360 + angle
angle = angle * math.pi / 180.0
return math.sin(angle)
def put(self, x, y):
self.Y = y
self.X = x
|
s=0
for x in range(0,1000):
if x%3==0 or x%5==0:
s=s+x
print (s) |
# -*- coding: utf-8 -*-
"""
Clever iterative solution
Like a two box kernel moving forward one number at a time
"""
def fib5(n: int) -> int:
"""
Time complexity = O(N-1)
Space complexity = O(2)
we just accumulate the two previous numbers
nifty
"""
if n == 0:
return n
last: int = 0
next: int = 1
for _ in range(1, n):
last, next = next, last + next
return next
if __name__ == '__main__':
# Only the memo or iterative make this fast enough to complete
print(fib5(50))
|
is_foodie = False
do_cook = False
if is_foodie and do_cook:
print("Are you a foodie!")
elif is_foodie and not(do_cook):
print("You are not a foodie.")
else:
print("You are not a foodie and don't cook?!")
# >, <, >=, <=, !=, ==
if 1 > 3:
print("number omparison was true")
if "dog" == "cat":
print("string omparison was true")
|
#Syntax
#lambda arguments : expression
#A lambda function is a small anonymous function.
#A lambda function can take any number of arguments, but can only have one expression.
x = lambda a: a + 15
print(x(5))
|
import sqlite3
import Main as Main
from abc import ABC, abstractmethod
ConDb = sqlite3.connect('manajementoko.db')
Cursor = ConDb.cursor()
class Masuk:
def LoginManager(self):
pass
def login_karyawan(self):
pass
class Login(Masuk):
def LoginManager(self):
print("Selamat Datang Koh Manager")
username = input("Masukkan ID Anda")
password = input("Masukkan Password Anda")
query = 'SELECT * from data_manager WHERE username="{}" AND password="{}"'.format(username, password)
Cursor.execute(query)
if Cursor.fetchone() is not None:
print("Berhasil login!! ")
MenuUtama().MenuManager()
else:
print("Maaf anda gagal login")
Login().LoginManager()
def LoginKaryawan(self):
print("Selamat datang gan")
username=input("Masukkan ID anda ")
password=input("Masukkan password anda ")
query='SELECT * from data_karyawan WHERE username="{}" AND password="{}"' .format(username, password)
Cursor.execute(query)
if Cursor.fetchone() is not None:
print("Berhasil login!! ")
MenuUtama().MenuKaryawan()
else:
print("Maaf anda gagal login")
Login().LoginKaryawan()
class MenuUtama():
def MenuLogin(self):
pilihan = int(input('''
Selamat datang!! Silahkan pilih..
1. Manager
2. Karyawan
'''))
if pilihan == 1:
Login().LoginManager()
elif pilihan == 2:
Login().LoginKaryawan()
else :
print("Maaf Pilihan Tidak Tersedia")
MenuUtama().MenuLogin()
def MenuManager(self):
MenuManager=int(input('''
Silahkan pilih :
1. Tambah Data Karyawan
2. Hapus Data Karyawan
3. Lihat Data Karyawan
4. Ubah Data Karyawan
5. Menu barang
6. Selesai
Masukkan Pilihan Menu:
'''))
if MenuManager == 1:
Main.TambahDataKaryawan()
MenuUtama().MenuManager()
elif MenuManager == 2:
Main.HapusDataKaryawan()
MenuUtama().MenuManager()
elif MenuManager == 3:
Main.LihatDataKaryawan()
MenuUtama().MenuManager()
elif MenuManager == 4:
Main.UbahDataKaryawan()
MenuUtama().MenuManager()
elif MenuManager == 5:
MenuUtama().MenuBarangMgr()
elif MenuManager == 6:
print("Terima kasih koh")
MenuUtama().MenuLogin()
else:
print("Maaf anda salah input ")
MenuUtama().MenuManager()
def MenuKaryawan(self):
MenuKaryawan = int(input('''
Silahkan pilih dari Menu ini :
1. Lihat profil
2. Ubah password
3. Menu barang
4. Selesai
'''))
if MenuKaryawan == 1:
Main.LihatProfil()
MenuUtama().MenuKaryawan()
elif MenuKaryawan == 2:
Main.UbahPassword()
MenuUtama().MenuKaryawan()
elif MenuKaryawan == 3:
MenuUtama().MenuBarangKry()
elif MenuKaryawan == 4:
print("Terima kasih gan")
MenuUtama().MenuLogin()
else:
print("Maaf anda salah input ")
MenuUtama().MenuKaryawan()
def MenuBarangMgr(self):
MenuBarangMgr=int(input('''
Silahkan pilih :
1. Tambah data barang
2. Hapus data barang
3. Lihat data barang
4. Ubah data barang
5. Lihat laporan barang
6. Selesai
Masukkan Pilihan Menu:
'''))
if MenuBarangMgr == 1:
Main.TambahDataBarang()
MenuUtama().MenuBarangMgr()
elif MenuBarangMgr == 2:
Main.HapusDataBarang()
MenuUtama().MenuBarangMgr()
elif MenuBarangMgr == 3:
Main.LihatDataBarang()
MenuUtama().MenuBarangMgr()
elif MenuBarangMgr == 4:
Main.UbahDataBarang()
MenuUtama().MenuBarangMgr()
elif MenuBarangMgr == 5:
Main.LihatLaporan()
MenuUtama().MenuBarangMgr()
elif MenuBarangMgr == 6:
print("Terima kasih koh")
MenuUtama().MenuLogin()
else:
print("Maaf anda salah input ")
MenuUtama().MenuBarangMgr()
def MenuBarangKry(self):
MenuBarangKry = int(input('''
Silahkan pilih dari Menu ini :
1. Lihat data barang
2. Cek stok barang
3. Laporan barang
4. Selesai
'''))
if MenuBarangKry == 1:
Main.LihatDataBarang()
MenuUtama().MenuBarangKry()
elif MenuBarangKry == 2:
Main.CekBarang()
MenuUtama().MenuBarangKry()
elif MenuBarangKry == 3:
Main.Laporkan()
MenuUtama().MenuBarangKry()
elif MenuBarangKry == 4:
print("Terima kasih gan")
MenuUtama().MenuLogin()
else:
print("Maaf anda salah input ")
MenuUtama().MenuBarangKry()
user1 = MenuUtama()
user1.MenuLogin() |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: ARAVINTHAN
#
# Created: 07/02/2018
# Copyright: (c) ARAVINTHAN 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
num = float(input("Input a number: "))
if num > 0:
print("Number is positive number")
elif num == 0:
print("Number is Zero")
else:
print("Number is a negative number")
if __name__ == '__main__':
main()
|
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Aravinthan
#
# Created: 30/01/2018
# Copyright: (c) Aravinthan 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
num =int(input("enter a number"))
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
if __name__ == '__main__':
main()
|
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Aravinthan
#
# Created: 11/02/2018
# Copyright: (c) Aravinthan 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
def separate_string(sentence):
l = list(sentence)
l2 = list()
for letter in range(l):
index = l.index(letter)
if index % 2 != 0:
l2.append(l[letter])
l.remove(letter)
if __name__ == '__main__':
separate_string('abcedfg')
|
import tkinter as tk
from student import Student
from student import StudentListUtilities
class StudentGui:
DEFAULT_NAME = ""
DEFAULT_GRADE = 9
DEFAULT_ADDRESS = "123 Main St, 456"
DEFAULT_PHONE = "123 456 7890"
def __init__(self):
"""Constructor for a GUI for Student."""
self._root = tk.Tk()
# -------------- one message widget ---------------------
header = "Enter student info"
self._header = tk.Message(self._root, text=header)
self._header.config(font=("times", 18, "italic"),
bg="lightblue", width=300)
# ----------------- some label widgets ------------------
self._label_name = tk.Label(self._root, text="Name",
padx=20, pady=10)
self._label_grade = tk.Label(self._root, text="Grade",
padx=20, pady=10)
self._label_address = tk.Label(self._root, text="Address",
padx=20, pady=10)
self._label_phone = tk.Label(self._root, text="Phone",
padx=20, pady=10)
# Assume this will be used to show list of students at the start
self._label_answer_text = tk.Label(self._root, padx=20, pady=10)
self._label_answer_value = tk.Label(self._root, padx=20, pady=10)
# ----------------- some entry widgets ------------------
self._entry_name = tk.Entry(self._root)
self._entry_name.insert(0, self.DEFAULT_NAME)
self._entry_grade = tk.Entry(self._root)
self._entry_grade.insert(0, str(self.DEFAULT_GRADE))
self._entry_address = tk.Entry(self._root)
self._entry_address.insert(0, self.DEFAULT_ADDRESS)
self._entry_phone = tk.Entry(self._root)
self._entry_phone.insert(0, self.DEFAULT_PHONE)
# ----------------- some button widgets ------------------
self._button_add = tk.Button(self._root, text="Add",
command=self._add_student)
self._button_remove = tk.Button(self._root, text="Remove",
command=self._remove_student)
self._button_student_info = tk.Button(self._root, text="Student Info",
command=self._student_info)
self._button_all_students = tk.Button(self._root, text="All Students",
command=self._all_students)
# ------------ place all widgets using grid layout -------------
self._header.grid(row=0, column=0, columnspan=2, sticky=tk.EW)
self._label_name.grid(row=1, column=0, sticky=tk.E)
self._entry_name.grid(row=1, column=1, padx=25, sticky=tk.W)
self._label_grade.grid(row=2, column=0, sticky=tk.E)
self._entry_grade.grid(row=2, column=1, padx=25, sticky=tk.W)
self._label_address.grid(row=3, column=0, sticky=tk.E)
self._entry_address.grid(row=3, column=1, padx=25, sticky=tk.W)
self._label_phone.grid(row=4, column=0, sticky=tk.E)
self._entry_phone.grid(row=4, column=1, padx=25, sticky=tk.W)
self._label_answer_text.grid(row=5, column=0, pady=4, sticky=tk.E)
self._label_answer_value.grid(row=5, column=1, sticky=tk.W)
self._button_add.grid(row=6, column=0, padx=20, sticky=tk.EW)
self._button_remove.grid(row=6, column=1, padx=20, sticky=tk.EW)
self._button_student_info.grid(row=7, column=0, padx=25, pady=15,
sticky=tk.EW)
self._button_all_students.grid(row=7, column=1, padx=25, pady=15,
sticky=tk.EW)
# ------ Initialize a list to hold students as they are added -----
self._students = []
# to make testing easier
# self._students = [
# Student("JP", 10),
# Student("Jasmine", 10),
# Student("Bresy", 11),
# Student("Francisco", 11),
# Student("Jonathan", 11),
# Student("Jacob", 12),
# ]
self._display_students()
@property
def root(self):
return self._root
def _add_student(self):
"""event handler to add a student."""
# First, create a Student object with name and grade
name = self._entry_name.get()
grade = int(self._entry_grade.get())
student = Student(name, grade)
# Now, try to set address and phone
address = self._entry_address.get()
try:
student.address = address
except ValueError:
self._label_answer_text.config(text="Error")
message = f"*** Failed to set {address} as new address ***"
self._label_answer_value.config(text=message)
return
phone = self._entry_phone.get()
try:
student.phone = phone
except ValueError:
self._label_answer_text.config(text="Error")
message = f"*** Failed to set {phone} as new phone ***"
self._label_answer_value.config(text=message)
return
# Finally, add to our list of students and display updated list
self._students.append(student)
self._display_students()
def _display_students(self):
self._label_answer_text.config(text="Students")
students = StudentListUtilities.to_gui_string(self._students)
self._label_answer_value.config(text=students)
def _remove_student(self):
"""event handler to remove a student."""
name = self._entry_name.get()
index = StudentListUtilities.linear_search(name, self._students)
if index == StudentListUtilities.NOT_FOUND:
self._label_answer_text.config(text="Error")
result = f"Name '{name}' not found."
else:
self._students.pop(index)
self._label_answer_text.config(text="Students")
result = StudentListUtilities.to_gui_string(self._students)
self._label_answer_value.config(text=result)
def _student_info(self):
"""event handler to display full info of a student."""
name = self._entry_name.get()
index = StudentListUtilities.linear_search(name, self._students)
if index == StudentListUtilities.NOT_FOUND:
self._label_answer_text.config(text="Error")
result = f"Name '{name}' not found."
else:
self._label_answer_text.config(text="Student Info")
result = f"Record for {name} - {self._students[index]}"
self._label_answer_value.config(text=result)
def _all_students(self):
"""event handler to display all students."""
self._label_answer_text.config(text="Students")
students = StudentListUtilities.to_gui_string(self._students)
self._label_answer_value.config(text=students)
demo = StudentGui()
demo.root.title("Student GUI")
demo.root.mainloop()
|
hastag = int(input("Please enter the number"))
if hastag == 1:
print("#")
else:
print("#" * hastag)
for i in range(hastag-2):
print("#" + " " *(hastag-2) + "#")
print("#" * hastag)
|
text = list(input("Please enter the text :").lower())
vowels = ["a","e","i","u","o"]
result=False
if len(text) <= 1:
result = False
else:
for i in range(len(text)-1):
if text[i] in vowels and text[i+1] in vowels:
result = True
break
if result:
print("positive")
else:
print("negative")
|
# linear search algorithm
class LinearSearch:
def linear_search(self,lis,find):
found=0;count=0
for a in lis:
if a==find:
found=a
else:
found=None
count=count+1
index=count-1
return found,index
if __name__=='__main__':
li=[];count=0 # [6,5,4,3,2,1]
print "Enter any 6 numbers (Insertion Sort)"
while count<=5:
a=int(raw_input())
li.append(a)
count=count+1
to_search=int(raw_input("Enter an element to be searched: "))
Linsearch=LinearSearch()
na,index=Linsearch.linear_search(li,to_search)
print "The element found is list is: ",na,"at index",index
|
to_find=[12,23,54,56,67,78,95,99]
count=0
key=67
b=0
e=len(to_find)-1
while b<=e:
m=(b+e)/2
count=count+1
if to_find[m] < key:
b=m+1
else:
e=m-1
if b== len(to_find) or to_find[b]!=key:
print "Index of the element not found: Element not in the list",-1
else:
print "Index of the element",to_find[b],"in the list is:",b
print count # this means log base 2 of count = no of elements of the list
|
if number > 1:
for itr in range(2, int(number/2)+1):
if (number % itr) == 0:
print(number, "is NOT a PRIME number")
break
else:
print(number, "is a PRIME number")
else:
print(number, "is NOT a PRIME number")
|
#Question4
def even(list):
a=[]
for i in list:
if (i % 2) == 0:
a.append(i)
return a
def odd(list):
b=[]
for i in list:
if (i % 2) != 0:
b.append(i)
return b
#Main
#l1=[30,40,22,33,22,11]
#l2=[40,30,10,99,53]
l1=[]
n = int(input("Enter number of elements in list 1 : "))
print("Enter", n ,"Elements of list 1:")
for i in range(0, n):
element = int(input())
l1.append(element)
print("List 1:",l1)
l2=[]
n = int(input("Enter number of elements in list 2 : "))
print("Enter", n ,"Elements of list 2:")
for i in range(0, n):
element = int(input())
l2.append(element)
print("List 2:",l2)
a=even(l1)
b=odd(l2)
l3=a+b
l3 = list(dict.fromkeys(l3))
print("\nResultant list:")
print(l3) |
__author__ = 'claireopila'
import string
import random
import math
import numpy as np
"""Make passwordswithout files"""
def makePassword1(password):
## this algorithm breaks up inputs into vowels and consonants by
## uppercase and lowercase, and numbers and punctuation
## inputs defined here
vowels = ['a', 'e', 'i', 'o', 'u']
cons = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', \
'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
vowelsUpper = ['A', 'E', 'I', 'O', 'U']
consUpper = ['B', 'C', 'D','F', 'G', 'H', 'J', 'K', \
'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z']
digits = string.digits
symbols = string.punctuation
## gets the length of the password inputh here
lenPass = len(password)
j = 0
newPass = [ ]
## creates a new password of equivalent length
while j < len(password):
## if the char in vowels,
##replace char with a newChar randomly selected from lowercase vowels
if password[j] in vowels:
newChar = random.choice(vowels)
## if the char in vowelsUpper,
##replace char with a newChar randomly selected from uppercase vowels
elif password[j] in vowelsUpper:
newChar = random.choice(vowelsUpper)
## if the char in cons
##replace char with a newChar randomly selected from lowercase consonants
elif password[j] in cons:
newChar = random.choice(cons)
## if the char in consUpper
##replace char with a newChar randomly selected from uppercase consonants
elif password[j] in consUpper:
newChar = random.choice(consUpper)
## if the char in digits
##replace char with a newChar randomly selected from digits
elif password[j] in digits:
newChar = random.choice(digits)
else:
##otherwise it is a symbol, replace with a rnadomly selected symbol
newChar = random.choice(symbols)
newPass.append(newChar)
j += 1
newPass = ''.join(newPass)
return newPass
def find_nearest(value):
letterFreq = np.array([0.0749, 0.0129, 0.0354, 0.0362, 0.1400, 0.0218, 0.0174, 0.0422, 0.0665, 0.0027, 0.0047, 0.0357,
0.0339, 0.0674, 0.0737, 0.0243, 0.0026, 0.0614, 0.0695, 0.0985, 0.0300, 0.0116, 0.0169, 0.0028,
0.0164, 0.000])
arrayIndices = np.where(np.logical_and(letterFreq >= (value - 0.02), letterFreq <= (value + 0.02)))
# print "arrayIndices", arrayIndices
# print "arrayindices", arrayIndices[0]
letterChoice = random.choice(arrayIndices[0])
return letterChoice
def makePassword2(password):
## this algorithm breaks up inputs into vowels and consonants by
## uppercase and lowercase, and numbers and punctuation
## inputs defined here
alphaFreq = [0.0749, 0.0129, 0.0354, 0.0362, 0.1400, 0.0218, 0.0174, 0.0422, 0.0665, 0.0027, 0.0047, 0.0357,
0.0339, 0.0674, 0.0737, 0.0243, 0.0026, 0.0614, 0.0695, 0.0985, 0.0300, 0.0116, 0.0169, 0.0028,
0.0164, 0.000]
lowerCase = string.lowercase
upperCase = string.uppercase
digits = string.digits
symbols = string.punctuation
## gets the length of the password inputh here
lenPass = len(password)
newPass = [ ]
## creates a new password of equivalent length
for char in password:
## if the char in vowels,
##replace char with a newChar randomly selected from lowercase vowels
if char in lowerCase:
numChar = ord(char)%97
letterFreq = alphaFreq[numChar]
## finds an index position of letterfreq array to use randomly selected from range of values close to the frequency fo letter in question
letterIndex= find_nearest(letterFreq)
letterIndex += 97
newChar = chr(letterIndex)
## if the char in vowelsUpper,
##replace char with a newChar randomly selected from uppercase vowels
elif char in upperCase:
numChar = ord(char)%65
letterFreq = alphaFreq[numChar]
## finds an index position of letterfreq array to use randomly selected from range of values close to the frequency fo letter in question
letterIndex= find_nearest(letterFreq)
letterIndex += 65
newChar = chr(letterIndex)
## if the char in digits
##replace char with a newChar randomly selected from digits
elif char in digits:
newChar = random.choice(digits)
else:
##otherwise it is a symbol, replace with a rnadomly selected symbol
newChar = random.choice(symbols)
newPass.append(newChar)
newPass = ''.join(newPass)
return newPass
# print makePassword2("passWord123")
# print makePassword2("may8fifth89")
def makePassword3(password):
## makes a new password by keeping all letters the same
## swaps out numbers for new numbers by adding 1
## swaps out punctuation by randomly selecting punctuation
letters = string.letters
digits = string.digits
punct = string.punctuation
newPass = []
for char in password:
## checks to see if the char is a digit, if so, adds 1 to it
if char in digits:
numChar = int(char)
numCharNext = random.choice(digits)
newChar = str(numCharNext)
## checks to see if the char is puncuation, if so, swaps out for a
## randomly selected punctuation
elif char in punct:
if char == "~":
newChar = "!"
else:
newChar = random.choice(punct)
else:
## if it is not a number or punctuation, keep the letter the same.
newChar = char
newPass.append(newChar)
newPass = "".join(newPass)
return newPass
def generateList(n, password):
## generates a list of passwords of size n, based on an input "password"
pwList = [ ]
digits = string.digits
while n > 0:
newPassword = makePassword3(password)
pwList.append(newPassword)
n -= 1
pwList.insert(int(random.choice(digits)), password)
for pw in pwList:
print pw
return pwList
#
generateList(10, "!Ciquser1")
"""Make Passwords with high prob file"""
def read_password_files(filename):
"""
Return a list of passwords in all the password file(s), plus
a proportional (according to parameter q) number of "noise" passwords.
"""
pw_list = [ ]
f = open(filename)
text = f.read()
f.close()
lines= text.split()
for line in lines:
pw_list.extend( line.split() )
# # add noise passwords
# pw_list.extend( noise_list(int(q*len(pw_list))) )
return pw_list
def make_password(L, tempPW):
"""
make a random password like those in given password list
"""
# start by choosing a random password from the list
# # save its length as k; we'll generate a new password of length k
# k = len(tempPW)
# print "tempPW", tempPW
# print "lentempPW", k
# # create list of all passwords of length k; we'll only use those in model
# L = [ pw for pw in pw_list if len(pw) == k ]
# print "list of same length password", L
k = len(tempPW)
nL = len(L)
print "nL", nL
# start answer with the first char of that random password
# row = index of random password being used
row = random.randrange(nL)
ans = L[row][:1] # copy first char of L[row]
# print "ans", ans
j = 1 # j = len(ans) invariant
while j < k:
LL = [ i for i in range(nL) if L[i][j-1]==ans[-1] ]
## find all words with the same char of the last char added to answer
## randomly choose the index position of one of these words
## Then, add the char in this word next to the last char used in ans
row = random.choice(LL)
print "row", row
ans = ans + L[row][j]
j = j + 1
return ans
pw_list = read_password_files("highProbPw.txt")
# print "make_passwords", make_password(pw_list)
def generate_passwords( n, pw_list ):
""" print n passwords and return list of them """
tempPW = random.choice(pw_list)
k = len(tempPW)
L = [ pw for pw in pw_list if len(pw) == k ]
ans = [ ]
for t in range( n ):
pw = make_password(L, tempPW)
# print "pw", pw
ans.append( pw )
for pw in ans:
print pw
return ans
# generate_passwords(10, pw_list)
|
# -*- coding: utf-8 -*-
# @Author: mithril
from __future__ import unicode_literals, print_function, absolute_import
def is_cjk(character):
""""
Checks whether character is CJK.
>>> is_cjk(u'\u33fe')
True
>>> is_cjk(u'\uFE5F')
False
:param character: The character that needs to be checked.
:type character: char
:return: bool
"""
return any([start <= ord(character) <= end for start, end in
[(4352, 4607), (11904, 42191), (43072, 43135), (44032, 55215),
(63744, 64255), (65072, 65103), (65381, 65500),
(131072, 196607)]
])
class CJKChars(object):
"""
An object that enumerates the code points of the CJK characters as listed on
http://en.wikipedia.org/wiki/Basic_Multilingual_Plane#Basic_Multilingual_Plane
This is a Python port of the CJK code point enumerations of Moses tokenizer:
https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/detokenizer.perl#L309
"""
# Hangul Jamo (1100โ11FF)
Hangul_Jamo = (4352, 4607) # (ord(u"\u1100"), ord(u"\u11ff"))
# CJK Radicals Supplement (2E80โ2EFF)
# Kangxi Radicals (2F00โ2FDF)
# Ideographic Description Characters (2FF0โ2FFF)
# CJK Symbols and Punctuation (3000โ303F)
# Hiragana (3040โ309F)
# Katakana (30A0โ30FF)
# Bopomofo (3100โ312F)
# Hangul Compatibility Jamo (3130โ318F)
# Kanbun (3190โ319F)
# Bopomofo Extended (31A0โ31BF)
# CJK Strokes (31C0โ31EF)
# Katakana Phonetic Extensions (31F0โ31FF)
# Enclosed CJK Letters and Months (3200โ32FF)
# CJK Compatibility (3300โ33FF)
# CJK Unified Ideographs Extension A (3400โ4DBF)
# Yijing Hexagram Symbols (4DC0โ4DFF)
# CJK Unified Ideographs (4E00โ9FFF)
# Yi Syllables (A000โA48F)
# Yi Radicals (A490โA4CF)
CJK_Radicals = (11904, 42191) # (ord(u"\u2e80"), ord(u"\ua4cf"))
# Phags-pa (A840โA87F)
Phags_Pa = (43072, 43135) # (ord(u"\ua840"), ord(u"\ua87f"))
# Hangul Syllables (AC00โD7AF)
Hangul_Syllables = (44032, 55215) # (ord(u"\uAC00"), ord(u"\uD7AF"))
# CJK Compatibility Ideographs (F900โFAFF)
CJK_Compatibility_Ideographs = (63744, 64255) # (ord(u"\uF900"), ord(u"\uFAFF"))
# CJK Compatibility Forms (FE30โFE4F)
CJK_Compatibility_Forms = (65072, 65103) # (ord(u"\uFE30"), ord(u"\uFE4F"))
# Range U+FF65โFFDC encodes halfwidth forms, of Katakana and Hangul characters
Katakana_Hangul_Halfwidth = (65381, 65500) # (ord(u"\uFF65"), ord(u"\uFFDC"))
# Supplementary Ideographic Plane 20000โ2FFFF
Supplementary_Ideographic_Plane = (131072, 196607) # (ord(u"\U00020000"), ord(u"\U0002FFFF"))
ranges = [Hangul_Jamo, CJK_Radicals, Phags_Pa, Hangul_Syllables,
CJK_Compatibility_Ideographs, CJK_Compatibility_Forms,
Katakana_Hangul_Halfwidth, Supplementary_Ideographic_Plane] |
#CALCULANDO OPERACIONES BASICAS
from tkinter import *
from tkinter import messagebox
from math import*
app = Tk()
app.title("OPERACIONES BASICAS")
app.geometry("600x200+200+200")
app.config(bg="pink")
def show_entry_fields():
print("REALIZADO POR: %s" % (e1.get()))
#PIDIENDO NUMEROS PARA LAS OPERACIONES AL USUARIO
Label(app, text="NOMBRE:").grid(row=0)
e1 = Entry(app)
e1.grid(row=0, column=1)
e1.delete(0,20)
ope_label = Label(app,text="INGRESE NUMERO 1:")
ope_label.grid(row=1,column=1)
ope_str = StringVar()
ope_entry = Entry(app,textvariable=ope_str)
ope_entry.grid(row=1,column=2)
ope_label1 = Label(app,text="INGRESE NUMERO 2:")
ope_label1.grid(row=2,column=1)
ope_str1 = StringVar()
ope_entry1 = Entry(app,textvariable=ope_str1)
ope_entry1.grid(row=2,column=2)
#FUNCIONES A CALCULAR
def suma ():
r=float(ope_entry.get())
r1=float(ope_entry1.get())
suma=r+r1
messagebox.showinfo("resultados","LA SUMA ES: %.2f"%suma)
ope_entry.delete(0,20)
ope_entry1.delete(0,20)
def resta ():
r=float(ope_entry.get())
r1=float(ope_entry1.get())
resta=r-r1
messagebox.showinfo("resultados","LA RESTA ES: %.2f"%resta)
ope_entry.delete(0,20)
ope_entry1.delete(0,20)
def mult ():
r=float(ope_entry.get())
r1=float(ope_entry1.get())
mult=r*r1
messagebox.showinfo("resultados","LA MULTIPLICACION ES: %.2f"%mult)
ope_entry.delete(0,20)
ope_entry1.delete(0,20)
def div ():
r=float(ope_entry.get())
r1=float(ope_entry1.get())
div=r/r1
messagebox.showinfo("resultados","LA DIVISION ES: %.2f"%div)
ope_entry.delete(0,20)
ope_entry1.delete(0,20)
#CREANDO BOTONES
suma = Button(app, text = "CALCULAR SUMA", command = suma,width=25)
suma.grid(row=4,column=2)
resta = Button(app, text = "CALCULAR RESTA", command = resta, width=25)
resta.grid(row=4,column=3)
mul = Button(app, text = "CALCULAR MULTIPLICACION", command = mult, width=25)
mul.grid(row=5,column=2)
div = Button(app, text = "CALCULAR DIVISION", command = div, width=25)
div.grid(row=5,column=3)
Button(app, text='Mostrar Nombre en consola',command=show_entry_fields,
width = 25).grid(row=0, column=3, sticky=W, pady=4)
app.mainloop()
|
import numpy as np
import math
#iteration counter: to count how many steps to reach the threshold value
i=0
def randompostive(x):
return np.multiply(np.random.random(),x)
# here iter(x) is x - f(x)/f'(x)
def iter(x):
f_x = math.tan(x)-math.cos(x);
df_x = 1+math.pow(math.tan(x),2)+math.sin(x);
return x - f_x/df_x
## NOTE: Inital generator, range:[0,5). Since we get smallest root from bisection around 1.57.
x_1 = 0
x_2 = randompostive(2);
### Setting the threshold epsilon
epsilon_ = math.pow(10,-15)
while abs(x_1-x_2) > epsilon_:
x_1 = x_2;
x_2 = iter(x_1);
i = i+1;
# x_2= 0.6662394324925153
print x_2
# i = 9
print i
|
ans=True
while ans:
print ("""=============================
PROGRAM SEDERHANA
1.Menghitung Waktu Tempuh
2.Delete a Student
3.Look Up Student Record
0.Exit/Quit
=============================""")
ans = input("Pilih pilihanmu: ")
if ans == "1":
waktutempuh=0.0
jarak=0.0
kecepatan=0.0
print("=============================")
print(" Menghitung Waktu Tempuh")
jarak = input("Masukan jarak (km): ")
jarak = float(jarak)
kecepatan = input("Masukan kecepatan (km/jam): ")
kecepatan = float(kecepatan)
waktutempuh = jarak/kecepatan
print("waktu tempuh:", waktutempuh,"jam")
print("")
elif ans == "2":
print("\n Student Deleted")
elif ans == "3":
print("\n Student Record Found")
elif ans == "0":
print("\n Goodbye")
break
elif ans != "":
print("\n Coba pilih yang ada di daftar!")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.