text
stringlengths 37
1.41M
|
---|
# Srijana Shrestha
# 1918305
word = input()
for x in word:
word = word.replace('i', '1')
word = word.replace('m', 'M')
word = word.replace('a', '@')
word = word.replace('s', '$')
word = word.replace('o', '.')
print(word+'q*s')
|
import math
def main():
# Escribe tu código abajo de esta línea
pass
a = int(input("Da el valor de a:"))
b = int(input("Da el valor de b:"))
c = int(input("Da el valor de c:"))
if ((b**2)-4*a*c) < 0:
print ("Raices Complejas")
elif a == 0 and b == 0:
print ("No tiene solucion")
elif a == 0 and b != 0:
x3 = -c/ b
print (x3)
else:
x1 = (-b + math.sqrt(b**2-(4*a*c))) / (2*a)
x2 = (-b-math.sqrt((b**2-(4*a*c))))/(2*a)
print(x1)
print(x2)
if __name__ == '__main__':
main()
|
def firstrun():
return "success"
def computecirclearea(radius):
return radius * radius * 3.14159
def firstandlast(inputlist):
return inputlist[0], inputlist[len(inputlist) - 1]
def timedates(date1, date2):
# date input formate MMDDYYYY
daydiff = 0
if date1[2] == date2[2]:
if date1[0] == date2[0]:
daydiff = (date2[1] - date1[1])
if date1[2] != date2[2]:
daydiff = 365 * (date2[2] - date1[2])
return daydiff
|
from PIL import Image, ImageTk
import tkinter as tk
width = 600
size = 300
def show_entry_fields():
print("hello")
root = tk.Tk()
root.title('EuroTrip 2019 Photo Labeller')
root.geometry("900x400")
root.resizable(0,0)
img = Image.open("lim.jpg")
img = img.resize((width,size))
tkimage = ImageTk.PhotoImage(img)
bbb = tk.Label(root, image=tkimage) #have to put imageTK into a label - then insert the label onto the grid
w = tk.Label(root, text="Museum\nPlanetarium\n\nSUN 19TH MAY\n\tMilan Linate Airport")
w1 = tk.Label(root, text="TAG")
w2 = tk.Label(root, text="Author")
but = tk.Button(root, text='Add Data', command=show_entry_fields)
e1 = tk.Entry(root)
e2 = tk.Entry(root)
w.grid(row=0, column=2)
w2.grid(row=0, column=3)
w1.grid(row=1, column=3)
e1.grid(row=0, column=5)
e2.grid(row=1, column=5)
bbb.grid(row=0, column=6, rowspan=6, columnspan=12)
but.grid(row=3,column=5)
root.mainloop()
|
# --------------
# Importing header files
import numpy as np
# Path of the file has been stored in variable called 'path'
#New record
new_record=[[50, 9, 4, 1, 0, 0, 40, 0]]
#Code starts here
data=np.genfromtxt(path,delimiter=",",skip_header=1)
census = np.concatenate((data,new_record),axis=0)
# --------------
#Code starts here
import numpy as np
age = census[:,0]
print(age)
max_age = np.max(age)
print(max_age)
min_age = np.min(age)
print(min_age)
age_mean = np.mean(age)
print(age_mean)
age_std = np.std(age)
print(age_std)
# --------------
#Code starts here
import numpy as np
race_0 = census[census[:,2]==0]
race_1 = census[census[:,2]==1]
race_2 = census[census[:,2]==2]
race_3 = census[census[:,2]==3]
race_4 = census[census[:,2]==4]
len_0 =len(race_0)
len_1 =len(race_1)
len_2 =len(race_2)
len_3 =len(race_3)
len_4 =len(race_4)
race_list=[len_0, len_1,len_2, len_3, len_4]
#Storing the race with minimum length into a variable
minority_race=race_list.index(min(race_list))
# --------------
#Code starts here
import numpy as np
senior_citizens = census[census[:,0]>60]
#print(senior_citizens)
working_hours_sum = senior_citizens.sum(axis=0)[6]
print(working_hours_sum)
senior_citizens_len = len(senior_citizens)
avg_working_hours = working_hours_sum/senior_citizens_len
print(avg_working_hours)
# --------------
#Code starts here
import numpy as np
high = census[census[:,1]>10]
low = census[census[:,1]<=10]
avg_pay_high = high.mean(axis=0)[7]
avg_pay_low = low.mean(axis=0)[7]
|
import unittest
from leetcode.problems.lc0083_remove_duplicates_from_sorted_list import LC0083_Remove_Duplicates_from_Sorted_List
from leetcode.common.listnode import ListNode
class LC0083_Remove_Duplicates_from_Sorted_List_Tests(unittest.TestCase):
def test_LC0083_Remove_Duplicates_from_Sorted_List_00(self):
lc = LC0083_Remove_Duplicates_from_Sorted_List()
head = None
actual = lc.deleteDuplicates(head)
self.assertIsNone(actual)
def test_LC0083_Remove_Duplicates_from_Sorted_List_01(self):
lc = LC0083_Remove_Duplicates_from_Sorted_List()
head = ListNode.create([1, 1, 2])
actual = lc.deleteDuplicates(head)
expected = [1, 2]
self.assertEqual(expected, actual.toList())
def test_LC0083_Remove_Duplicates_from_Sorted_List_02(self):
lc = LC0083_Remove_Duplicates_from_Sorted_List()
head = ListNode.create([1, 1, 2, 3, 3])
actual = lc.deleteDuplicates(head)
expected = [1, 2, 3]
self.assertEqual(expected, actual.toList())
def test_LC0083_Remove_Duplicates_from_Sorted_List_03(self):
lc = LC0083_Remove_Duplicates_from_Sorted_List()
head = ListNode.create([1, 1, 1])
actual = lc.deleteDuplicates(head)
expected = [1]
self.assertEqual(expected, actual.toList()) |
import unittest
from leetcode.problems.lc0015_three_sum import LC0015_Three_Sum
class LC0015_Three_Sum_Tests(unittest.TestCase):
def test_LC0015_Three_Sum_01(self):
lc = LC0015_Three_Sum()
nums = [-1, 0, 1, 2, -1, -4]
actual = lc.threeSum(nums)
expected = [
[-1, -1, 2],
[-1, 0, 1]
]
self.assertEqual(expected, actual)
def test_LC0015_Three_Sum_02(self):
lc = LC0015_Three_Sum()
nums = []
actual = lc.threeSum(nums)
expected = [
]
self.assertEqual(expected, actual)
def test_LC0015_Three_Sum_03(self):
lc = LC0015_Three_Sum()
nums = [0]
actual = lc.threeSum(nums)
expected = [
]
self.assertEqual(expected, actual)
def test_LC0015_Three_Sum_04(self):
lc = LC0015_Three_Sum()
nums = [-2, 0, 0, 2, 2]
actual = lc.threeSum(nums)
expected = [
[-2, 0, 2]
]
self.assertEqual(expected, actual)
|
import unittest
from leetcode.common.treenode import TreeNode
from leetcode.problems.lc0101_symmetric_tree import LC0101_Symmetric_Tree
class LC0101_Symmetric_Tree_Tests(unittest.TestCase):
def test_LC0101_Symmetric_Tree_00(self):
lc = LC0101_Symmetric_Tree()
root = TreeNode(1)
actual = lc.isSymmetric(root)
self.assertTrue(actual)
def test_LC0101_Symmetric_Tree_01(self):
lc = LC0101_Symmetric_Tree()
root = TreeNode.create('1,2,2,3,4,4,3')
actual = lc.isSymmetric(root)
self.assertTrue(actual)
def test_LC0101_Symmetric_Tree_02(self):
lc = LC0101_Symmetric_Tree()
root = TreeNode.create('1,2,2,null,3,null,3')
actual = lc.isSymmetric(root)
self.assertFalse(actual)
|
import unittest
from leetcode.problems.lc0031_next_permutation import LC0031_Next_Permutation
class LC0031_Next_Permutation_Tests(unittest.TestCase):
def test_LC0031_Next_Permutation_01(self):
lc = LC0031_Next_Permutation()
nums = [1, 2, 3]
lc.nextPermutation(nums)
expected = [1, 3, 2]
self.assertEqual(expected, nums)
def test_LC0031_Next_Permutation_02(self):
lc = LC0031_Next_Permutation()
nums = [3, 2, 1]
lc.nextPermutation(nums)
expected = [1, 2, 3]
self.assertEqual(expected, nums)
def test_LC0031_Next_Permutation_03(self):
lc = LC0031_Next_Permutation()
nums = [1, 1, 5]
lc.nextPermutation(nums)
expected = [1, 5, 1]
self.assertEqual(expected, nums)
def test_LC0031_Next_Permutation_04(self):
lc = LC0031_Next_Permutation()
nums = [1, 5, 8, 4, 7, 6, 5, 3, 1]
lc.nextPermutation(nums)
expected = [1, 5, 8, 5, 1, 3, 4, 6, 7]
self.assertEqual(expected, nums)
def test_LC0031_Next_Permutation_09(self):
lc = LC0031_Next_Permutation()
nums = [1]
lc.nextPermutation(nums)
expected = [1]
self.assertEqual(expected, nums)
def test_LC0031_Next_Permutation_10(self):
lc = LC0031_Next_Permutation()
nums = [1, 2]
lc.nextPermutation(nums)
expected = [2, 1]
self.assertEqual(expected, nums)
|
#! /usr/bin/python
a = 10
b = input();
c = a+b;
#print('Sum of two number = {0}'.format(c));
print c
|
#! /usr/bin/python
dict ={};
dict['one'] = "This is one";
dict[2] = "This is two";
tinydict ={'Name':'John',"code":6363,'Dep':"Sale"};
print dict['one'];
print dict[2];
print tinydict;
print tinydict.keys();
print tinydict.values();
|
sum_odd=0
sum_even=0
total=0
# sum of 1st 100 even integers
for number in range(2,101, 2):
sum_even += number
print(f"Sum of 1st 100 even numbers is :{sum_even}")
# sum of 1st odd integers
for number in range(1,101,2):
sum_odd += number
print(f"Sum of 1st 100 odd numbers is:{sum_odd}")
# sum of 1st 100 integers
for number in range(1, 101):
total += number
print(f"Sum of 1st 100 numbers is :{total}")
|
import os
import art
def sum1(n1,n2):
return n1+n2
def substract(n1,n2):
if n1>n2:
return n1-n2
else:
n2-n1
def multiply(n1,n2):
return n1*n2
def divide(n1,n2):
if n2==0:
return "invalid can not be divided by 0"
else:
return n1/n2
operator={
"+":sum1,
"-":substract,
"*": multiply,
"/": divide
}
def calc():
print(art.logo)
f_number=float(input("What's the first number?:"))
more="yes"
while more =="yes":
for symbol in operator:
print (symbol)
operator_input=input("Pick an operation: ")
s_number=float(input("What's the next number?:"))
function=operator[operator_input]
result=function(f_number,s_number)
print(f"result is :{result}")
more =input(f"'yes' to continue calculating with {result}, or type 'no' to start a new calculation\n").lower()
if more=="yes":
f_number=result
else:
os.system("clear")
calc()
calc()
|
import random
from art import logo
import os
import time
def Black_jack():
start_game=input("Do you want to play a game of Blackjack? Type 'yes' or 'no'").lower()
user_score=0
dealer_score=0
user_deck=list()
dealer_deck=list()
counter=1
while start_game=="yes":
print(logo)
while start_game=="yes":
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
def score_calc(deck,score):
user_number=random.randint(0,len(cards)-1)
deck.append(cards[user_number])
score=sum(deck)
if 11 in deck and score>12:
deck.remove(11)
deck.append(1)
score=sum(deck)
return deck,score
if counter==1:
for _ in range(0,2):
user_deck,user_score=score_calc(deck=user_deck,score=user_score)
dealer_deck,dealer_score=score_calc(deck=dealer_deck,score=dealer_score)
else:
user_deck,user_score=score_calc(deck=user_deck,score=user_score)
dealer_deck,dealer_score=score_calc(deck=dealer_deck,score=dealer_score)
print(f"dealer deck :{dealer_deck[0]}")
print(f"user deck {user_deck} and score :{user_score}")
counter=2
if user_score<21 and dealer_score<21:
start_game=input("Do you want to play a game of Blackjack? Type 'yes' or 'no'").lower()
if start_game=="no":
if dealer_score<15:
dealer_deck,dealer_score=score_calc(deck=dealer_deck,score=dealer_score)
if dealer_score<user_score or dealer_score>21:
print(f"user deck {user_deck} and score :{user_score}")
print(f"dealer deck {dealer_deck} and score :{dealer_score}")
print("You win")
start_game="no"
time.sleep(5)
os.system("clear")
Black_jack()
else :
print(f"user deck {user_deck} and score :{user_score}")
print(f"dealer deck {dealer_deck} and score :{dealer_score}")
print("you lose")
start_game="no"
time.sleep(5)
os.system("clear")
Black_jack()
else:
if dealer_score<user_score:
print(f"user deck {user_deck} and score :{user_score}")
print(f"dealer deck {dealer_deck} and score :{dealer_score}")
print("You win")
start_game="no"
time.sleep(5)
os.system("clear")
Black_jack()
else :
print(f"user deck {user_deck} and score :{user_score}")
print(f"dealer deck {dealer_deck} and score :{dealer_score}")
start_game="no"
print("you lose")
time.sleep(5)
os.system("clear")
Black_jack()
elif (dealer_score>21 and user_score>21) or(dealer_score==user_score) :
print(f"user deck{user_deck}and score :{user_score}")
print(f"dealer deck{dealer_deck}and score :{dealer_score}")
print("Draw")
start_game="no"
time.sleep(5)
os.system("clear")
Black_jack()
elif user_score==21 :
print(f"user deck {user_deck} and score :{user_score}")
print(f"dealer deck {dealer_deck} and score :{dealer_score}")
print("You Win")
start_game="no"
time.sleep(5)
os.system("clear")
Black_jack()
elif dealer_score<21 :
print(f"user deck {user_deck} and score :{user_score}")
print(f"dealer deck {dealer_deck} and score :{dealer_score}")
print("You Lose")
start_game="no"
time.sleep(5)
os.system("clear")
Black_jack()
elif dealer_score>21 :
print(f"user deck {user_deck} and score :{user_score}")
print(f"dealer deck {dealer_deck} and score :{dealer_score}")
print("You win")
start_game="no"
time.sleep(5)
os.system("clear")
Black_jack()
elif dealer_score==21 or user_score>21:
print(f"user deck{user_deck}and score :{user_score}")
print(f"dealer deck{dealer_deck}and score :{dealer_score}")
print("You lose")
start_game="no"
time.sleep(5)
os.system("clear")
Black_jack()
Black_jack()
|
from art_High_Low import logo,vs
from game_data import data
import random
import os
score=0
game_over=True
a_dic={
'name': "sarthak",
'follower_count': 0,
'description': 'xyxy ',
'country': 'India '
}
b_dic={
'name': "sarthak",
'follower_count': 0,
'description': 'xyxy ',
'country': 'India '
}
def randomvalue():
index=random.randint(0,len(data)-1)
dic={
'name': "sarthak",
'follower_count': 0,
'description': 'xyxy ',
'country': 'India '
}
dic=data[index]
return dic
def winner(Input):
global a_dic,b_dic
global score
if (a_dic['follower_count']>b_dic['follower_count'] and Input=="a") or(a_dic['follower_count']<b_dic['follower_count'] and Input=="b") :
os.system("clear")
score=score+1
a_dic=b_dic
print(f"You're right! Current score: {score}.")
return score
else:
os.system("clear")
print(f"Sorry, that's wrong. Final score: {score}")
score=0
return score
a_dic=randomvalue()
while game_over:
print(logo)
print(f"Compare A:{a_dic['name']},{a_dic['description']},from {a_dic['country']}.")
print(vs)
b_dic=randomvalue()
print(f"Compare B:{b_dic['name']},{b_dic['description']},from {b_dic['country']}.")
user_input=input("Who has more followers? Type 'A' or 'B': ").lower()
score=winner(user_input)
if score==0:
game_over=False
|
#!/usr/bin/env python
# coding: utf-8
# In[5]:
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, items):
self.items.insert(0,items)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def show(self):
return self.items
def menu() :
print("\n\nchoose: 1 >> counter 1 to get customer. \tchoose: 2 >> counter 2 to get customer\t3. >> custorme waiting,and 4 > quit\n\n\n")
queue_j = Queue()
while True :
menu()
fn_input = int(input("Waiting for customer : "))
customer_waiting = queue_j.size()
if fn_input == 1 :
if customer_waiting > 0 :
dequeue = queue_j.dequeue()
print("Customer ({}) com to counter 1 : ".format(dequeue))
customer_waiting -= 1
print("Number of waiting customer : {}".format(customer_waiting))
print("Waiting customer >>> ",queue_j.show())
else:
print("Number of waiting customer : {}".format(customer_waiting))
print("No one waiting")
elif fn_input == 2 :
if customer_waiting > 0 :
dequeue = queue_j.dequeue()
print("Customer ({}) com to counter 2 : ".format(dequeue))
customer_waiting -= 1
print("Number of waiting customer : {}".format(customer_waiting))
print("Waiting customer >>> ",queue_j.show())
else:
print("Number of waiting customer : {}".format(customer_waiting))
print("No one waiting")
elif fn_input == 3 :
queue_input = input("Enter customer name >>>").strip()
queue_j.enqueue(queue_input)
print("Number of waiting customer : {}".format(customer_waiting))
print("Waiting customer >>> ",queue_j.show())
else :
break
# In[ ]:
|
import numpy as np
from Particle3D import Particle3D
def Find_potential_energy(particle1, particle2):
"""
Method to return the gravitational potential energy between two objects
Potential energy is given by Ep = -Gm1m2/r
:param particle1: Particle3D instance
:param partcile2: Particle 3D insatnce
:return: The potential energy between two particles
"""
r12 = Particle3D.particle_separation(particle1, particle2)
rscalar = np.linalg.norm(r12)
G = 6.67408E-11 # Gravitational constant
potential_energy = (-G*particle1.mass*particle2.mass)/rscalar
return potential_energy
def Find_kinetic_energy(particle1):
"""
Method to return the kinetic energy of an object,
Kinetic energy is given by Ek = 0.5mv^2
:param particle1: Particle3D instance
:return: The kinetic energy of the particle
"""
kinetic_energy = 0.5*particle1.mass*(np.linalg.norm(particle1.velocity)**2)
return kinetic_energy
def Find_force_vector(particle1, particle2):
"""
Method to return the force due to gravity as a vector between two objects.
Force is given by F = (Gm1m2/r^2)rhat
Where rhat is the unit vector between the two objects.
:param particle1: particle3D instance
:param partcile2: particle 3D instance
:return: force between particle1 and particle2 as a numpy array
"""
r12 = Particle3D.particle_separation(particle1, particle2) # displacement between the particles, a vector
rscalar = np.linalg.norm(r12) # distance between the particles, a scalar
rhat = r12/rscalar # unit vector
G = 6.67408E-11 # Gravitational constant
force = -((G*particle1.mass*particle2.mass)/(rscalar**2))*rhat
return force
def Find_all_forces(lst):
"""
A method to calculate the forces on each object due to every other object using the Find_Force_Vector function.
:param lst: a list of Particle3D objects
:return: a list of numpy arrays, where each array is the total force acting on the body of that indexing
"""
all_total_forces = [] # forces acting on each particle
all_individual_forces = [] # will be a list of lists of the forces acting on a particle from each other particle, or a zero if not needed
for i in range(0, len(lst)):
individualforces = [] # list to go into list of lists
totalforce = np.array([0,0,0])
for j in range(0,len(lst)):
# ie particle and itself
if j == i :
individualforces.append(0)
# Calculate force between the particles
elif j > i:
added = Find_force_vector(lst[i],lst[j])
totalforce = totalforce + added
individualforces.append(added)
# use Newton's third law as force has already been calculated for the other particle
elif j < i:
totalforce = totalforce - all_individual_forces[j][i]
individualforces.append(0)
all_individual_forces.append(individualforces)
all_total_forces.append(totalforce)
return all_total_forces
def Update_velocity(lst,force_lst,dt):
"""
A method to update the velocities of particles stored in a list.
:param lst: a list containing Particle3D instances
:param force_lst: a list of the forces acting on each object
:param dt: timestep as float
:return: the updated list of velocities which are numpy arrays
"""
updated_lst = []
for i in range(0, len(lst)):
lst[i].leap_velocity(dt,force_lst[i]) #calculating updated velocity of particle
updated_lst.append(lst[i])
return updated_lst
def Update_position(lst,force_lst,dt):
"""
A method to update the position of particles in a list.
:param lst: a list containing Particle3D instances
:param force_lst: a list of the forces acting on each object
:param dt: timestep as float
:return: the updated list of positions which are numpy arrays
"""
updated_position_lst = []
for i in range(0, len(lst)):
updated_position_lst.append(lst[i].leap_pos2nd(dt,force_lst[i]))
return updated_position_lst
def Calculate_total_energy(lst):
"""
A method to calculate the total energy of the system due to particle pair interactions (potential energies) and their kinetic energies,
using the functions Find_kinetic_energy and Find_potential_energy.
:param lst: a list containing Particle3D instances representing the system
:return: 3-tuple of floats, (total energy, kinetic energy, potential energy)
"""
total_energy = 0
potential_energy = 0
kinetic_energy = 0
for l in lst:
add_kin = Find_kinetic_energy(l)
kinetic_energy += add_kin
total_energy += add_kin # adds kinetic energy of each particle3D to total energy
for i in range(lst.index(l) + 1, len(lst)):
add_pot = Find_potential_energy(l,lst[i])
potential_energy += add_pot
total_energy += add_pot # adds potential between that particle and each further particle in lst to total energy
return total_energy,kinetic_energy,potential_energy
|
#!/usr/bin/env python
# coding: utf-8
# In[2]:
# importing important libraries
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import pandas as pd
import seaborn as sns
from matplotlib.pyplot import figure, show
# In[3]:
#reading the csv file or dataset
file = pd.read_csv(sys.argv[1], error_bad_lines=False);
# In[4]:
#dropping all columns where all entries are missing values
file.dropna(axis=1, how='all',inplace=True)
# In[5]:
file.head()
# In[5]:
with PdfPages('visualization-output.pdf') as output_pdf:
#2a. The number of students applied to different technologies.
file['Areas of interest'].value_counts().plot(kind='bar')
plt.title('No of students who applied for different technologies')
plt.ylabel('No of students')
plt.xlabel('Technologies')
output_pdf.savefig(bbox_inches="tight",pad_inches=2)
plt.close()
#2b. The number of students applied for Data Science who knew ‘’Python” and who didn’t.
df1=file[file['Areas of interest']=='Data Science ']
import seaborn as sns
sns.countplot(df1['Programming Language Known other than Java (one major)']=='Python')
plt.title('The number of students applied for Data Science who knew ‘’Python” and who didn’t')
plt.xlabel("Python language known")
plt.ylabel("Student in Data Science")
output_pdf.savefig(bbox_inches="tight",pad_inches=2)
plt.close()
#2c. The different ways students learned about this program.
file['How Did You Hear About This Internship?'].value_counts().plot(kind='bar')
plt.title('The different ways students learned about this program')
plt.xlabel("The Different Ways")
plt.ylabel("No of Student")
output_pdf.savefig(bbox_inches="tight",pad_inches=2)
plt.close()
#2d. Students who are in the fourth year and have a CGPA greater than 8.0.
df2=file[file['Which-year are you studying in?']=='Fourth-year']
sns.countplot(df2['CGPA/ percentage']>=8.0)
plt.title('Student in fourth year having CGPA greater than 8')
plt.xlabel("CGPA/Percentage greater than 8")
plt.ylabel("Student in Fourth Year")
output_pdf.savefig(bbox_inches="tight",pad_inches=2)
plt.close()
#2e.Students who applied for Digital Marketing with verbal and written communication score greater than 8.
df3 = file.loc[(file['Areas of interest'] == 'Digital Marketing ') &
(file['Rate your verbal communication skills [1-10]'] > 8) &
(file['Rate your written communication skills [1-10]'] > 8)]
fig,ax = plt.subplots(figsize = (15,7))
ax.set_ylabel('Number of Students')
ax.set_xlabel('pointer rating')
comm_counts = df3['Rate your written communication skills [1-10]'].value_counts()
verbal_counts = df3['Rate your verbal communication skills [1-10]'].value_counts()
sns.lineplot(x= comm_counts.index, y = comm_counts.values,ax = ax,label = 'Written Communication rating')
sns.lineplot(x = verbal_counts.index, y = verbal_counts.values,ax =ax,label = 'Verbal communication rating')
plt.title("Students who applied for Digital Marketing with verbal and written communication score greater than 8")
output_pdf.savefig(bbox_inches="tight",pad_inches=2)
plt.close()
#2f.Year-wise and area of study wise classification of students
df5 = file[['Which-year are you studying in?', 'Major/Area of Study']]
fig,ax = plt.subplots(figsize = (20,10))
df5.groupby(['Major/Area of Study', 'Which-year are you studying in?']) ['Which-year are you studying in?'].value_counts().unstack(0).plot.barh(ax=ax,rot = 0)
plt.title(' Year-wise and area of study wise classification of students')
output_pdf.savefig(bbox_inches="tight",pad_inches=2)
plt.close()
#2g.City and college wise classification of students.
df6=file[['City','College name']]
fig,ax = plt.subplots(figsize = (25,15))
df6.groupby(['City', 'College name']) ['College name'].value_counts().unstack(0).plot.bar(ax=ax)
plt.title('City and college wise classification of students. ')
output_pdf.savefig(bbox_inches="tight",pad_inches=2)
plt.close()
#2h.Plot the relationship between the CGPA and the target variable.
sns.stripplot(x="Label", y="CGPA/ percentage",hue="Label",data=file)
plt.title(' CGPA and the target variable')
output_pdf.savefig(bbox_inches="tight",pad_inches=2)
plt.close()
##2i.Plot the relationship between the Area of Interest and the target variable.
major_df1=file.groupby(['Areas of interest','Label'])['Areas of interest'].size()[lambda x: x < 1000]
fig,ax = plt.subplots(figsize = (15,7) )
major_df1 = major_df1.to_frame()
major_df1.unstack().plot.bar(ax =ax)
plt.title("Area of Interest and the target variable ")
output_pdf.savefig(bbox_inches="tight",pad_inches=2)
plt.close()
#2j.Plot the relationship between the year of study, major, and the target variable
major_df=file.groupby(['Major/Area of Study','Which-year are you studying in?','Label'])['Major/Area of Study'].size()[lambda x: x < 1000]
fig,ax = plt.subplots(figsize = (15,7) )
major_df = major_df.to_frame()
major_df.unstack().plot.bar(ax =ax)
plt.title(" year of study, major and the target variable")
output_pdf.savefig(bbox_inches="tight",pad_inches=2)
plt.close()
# In[ ]:
|
#!/usr/bin/python3
def print_sorted_dictionary(a_dictionary):
for item in sorted(a_dictionary):
print("{}: {}".format(item, a_dictionary[item]))
|
#!/usr/bin/python3
""" module urllib """
import requests
import sys
""""
script that fetches an url
"""
if __name__ == "__main__":
if len(sys.argv) == 2:
response = requests.post('http://0.0.0.0:5000/search_user',
data={'q': sys.argv[1]}).json()
if response:
if response.get('id') and response.get('name'):
print("[{}] {}".format(response.get('id'),
response.get('name')))
else:
print('Not a valid JSON')
else:
print('No result')
else:
print('No result')
|
#!/usr/bin/python3
import numpy as np
"""
Matrix multiplication
Attributes: m_a(matrix): first matrix m_b(matrix): second matrix
Return result(matrix)
"""
def lazy_matrix_mul(m_a, m_b):
"""
Multiply two matrix m_a * m_b
"""
if not isinstance(m_a, list):
raise TypeError("m_a must be a list")
if not isinstance(m_b, list):
raise TypeError("m_b must be a list")
if m_a == [[]] or m_a == []:
raise ValueError("m_a can't be empty")
if m_b == [[]] or m_b == []:
raise ValueError("m_b can't be empty")
for i in range(len(m_a)):
if len(m_a[0]) is not len(m_a[i]):
raise TypeError("each row of m_a must be of the same size")
for j in range(len(m_a[i])):
if not isinstance(m_a[i][j], (int, float)):
raise TypeError("m_a should contain only integers or floats")
for i in range(len(m_b)):
if len(m_b[0]) is not len(m_b[i]):
raise TypeError("each row of m_b must be of the same size")
for j in range(len(m_b[i])):
if not isinstance(m_b[i][j], (int, float)):
raise TypeError("m_b should contain only integers or floats")
if len(m_a) < len(m_b):
result = [[0 for x in range(len(m_a[0]))] for y in range(len(m_a))]
else:
result = [[0 for x in range(len(m_b[0]))] for y in range(len(m_b))]
try:
result = np.dot(m_a,m_b)
except ValueError:
print("m_a and m_b can't be multiplied")
return result
|
#!/usr/bin/python3
"""
matrix_divided: divide all elements of a matrix
Attributes: matrix(list): list of int, div(int): number used to divide
Return: new matrix
"""
def matrix_divided(matrix, div):
"""
function: divide list of integer
"""
mustbeint = "matrix must be a matrix (list of lists) of integers/floats"
new_matrix = []
new_matrix = list(map(list, matrix))
if not isinstance(div, (int, float)):
raise TypeError("div must be a number")
elif div == 0:
raise ZeroDivisionError("division by zero")
for i in range(len(matrix)):
if len(matrix[i]) is not len(matrix[0]):
raise TypeError("Each row of the matrix must have the same size")
for j in range(len(matrix[i])):
if not isinstance(matrix[i][j], (int, float)):
raise TypeError(mustbeint)
new_matrix[i][j] = round((new_matrix[i][j] / div), 2)
return (new_matrix)
|
class DQueue:
def __init__(self):
self.dequeue = []
def isEmpty(self):
return self.dequeue == []
def addBegin(self, item):
self.dequeue.insert(0,item)
def addEnd(self, item):
self.dequeue.append(item)
def remBegin(self):
self.dequeue.pop(0)
def remEnd(self):
self.dequeue.pop()
def displayDQueue(self):
print(self.dequeue)
|
#!/usr/bin/env python
# coding: utf-8
# In[33]:
def cal_kg():
"""
kg를 파운드(lb)로 변환해주는 함수
"""
kg = float(input("kg? >>>"))
lb = float(2.20462 * kg)
print(lb, "lb")
# In[35]:
def cal_lb():
"""
파운드(lb)를 kg으로 변환해주는 함수
"""
lb = float(input("lb? >>>"))
kg = float(0.453592 * lb)
print(kg, "kg")
# In[ ]:
# In[ ]:
|
"""
Problem 1. Maximim Index - level medium
Given an array A of positive integers.
The task is to find the maximum of j - i
subjected to the constraint of A[i] <= A[j].
EX1
34 8 10 3 2 80 30 33 1
A[1] = 8
A[7] = 33
therefore the answer is 7-1 = 6
Look at other numbers.
A[0]= 34 that is the max so no bueno.
A[2] = 10
A[6] = 33
this proposed answer would be 6-2 = 4.
"""
def problem1(some_arr):
pass |
'''
joaquim coleciona filmes no computador, mas quer gravar alguns em cd,
precisar organizar sua lista por ordem alfabetica e gravar os cinco
primeiros. (mae, vida, nos, eli, vidro, resgate, close, o poço, fragmentado, parasita).
'''
import time
filmes = ['mae', 'vida', 'nos', 'eli', 'vidro', 'resgate',
'close', 'o poco', 'fragmentado', 'parasita']
gravados = []
cont = 0
print('-'*5, 'Lista de Filmes', '-'*5)
for f in sorted(filmes):
cont += 1
print(cont, '-', f)
if cont <= 5:
gravados.append(f)
print('-'*5, '5 primeiros filmes', '-'*5)
print('Iniciando gravação dos seguintes filmes')
cont = 0
for g in sorted(gravados):
cont += 1
print(cont, '-', g)
print('Gravando...')
for l in range(1, 101):
print(l, '%')
time.sleep(1)
print('Gravação concluída.')
|
# coding: utf-8
# In[47]:
def tuple_sort():
inp1=["PHP","Exercises","Backend"]
'''counting the length of each input'''
len_inp1=[len(inp1[0]),len(inp1[1]),len(inp1[2])]
'''converting into tuple'''
new_inp1=list(zip(len_inp1,inp1))
'''sorting using first key'''
new_inp1.sort(key=lambda new_inp1:new_inp1[0])
return new_inp1[2]
print(tuple_sort())
|
#!/usr/bin/env python
#####################################################################################################
# Code Developed by Raja Chellappan
# Student ID: 200716420
# Queen Mary University of London
# Square Size Generator is used to create a random value using Python.random.uniform() function
# for the size of the square every 20 seconds
# the length of the side of the square should be random real number between 0.05 and 0.20
#####################################################################################################
import rospy
import random
from ar_week10_test.msg import square_size
#########################################################################################################
def square_size_generator():
#Topic initialization
pub = rospy.Publisher('size', square_size, queue_size=0)
#New Node initialization
rospy.init_node('square_size_generator', anonymous=True)
#Generate every 20 seconds (0.05hz = 20s)
rate = rospy.Rate(0.05)
msg = square_size()
while not rospy.is_shutdown():
#Generate random real number between 0.05 and 20
msg.size = random.uniform(0.05, 0.20)
rospy.loginfo(msg)
pub.publish(msg)
rate.sleep()
#########################################################################################################
#########################################################################################################
if __name__ == '__main__':
try:
square_size_generator()
except rospy.ROSInterruptException: #Exception Handling
pass
#########################################################################################################
|
import numpy as np
import matplotlib.pyplot as pl
import csv
import math
import pandas as pd
# Linear Regression Model
class LinearRegression:
def __init__(self):
self.W = None
def predict(self,X):
y_predict = X.dot(self.W)
return y_predict
def L1Cost(self, X, y_target,reg):
cost = 0.0
N,M = X.shape
grads = np.ones(self.W.shape)
scores = X.dot(self.W)
cost = np.sum(np.abs(scores - y_target))/N + reg * np.sum(self.W*self.W)
mask = np.ones(y_target.shape)
mask[(scores-y_target)<0] = -1
grads = X.T.dot(mask)/N + 2*self.W*reg
return cost, grads
def L2Cost(self, X, y_target,reg):
cost = 0.0
N,M = X.shape
grads = np.ones(self.W.shape)
scores = X.dot(self.W)
cost = np.sum(np.square(scores - y_target))/N + reg * np.sum(self.W*self.W)
grads = 2*X.T.dot(scores - y_target)/N + 2*self.W*reg
return cost, grads
def L3Cost(self, X, y_target,reg):
cost = 0.0
N,M = X.shape
grads = np.ones(self.W.shape)
scores = X.dot(self.W)
cost = np.sum(np.abs(np.power(scores - y_target,3)))/N + reg * np.sum(self.W*self.W)
mask = 3*np.square(scores-y_target)
mask[(scores-y_target)<0] *= -1
grads = X.T.dot(mask)/N + 2*self.W*reg
return cost, grads
def train(self,X_train, y_target,X_test,y_test, cost_function="L2",epochs=2000, learning_rate=0.0000001,lr_decay = 1,reg = 0.0):
N,M = X_train.shape
self.W = np.random.randn(M)
old_cost = 0.0
"""
costfunction = self.L3Cost
if cost_function == "L1":
costfucntion = self.L1Cost
#print("Selected L1")
elif cost_function == "L2":
costfucntion = self.L2Cost
#print("Selected L2")
elif cost_function == "L3":
costfucntion = self.L3Cost
#print("Selected L3")
"""
for i in range(epochs):
if(cost_function == "L1"):
cost, dW = self.L1Cost(X_train,y_target,reg)
if(cost_function == "L2"):
cost, dW = self.L2Cost(X_train,y_target,reg)
if(cost_function == "L3"):
cost, dW = self.L3Cost(X_train,y_target,reg)
self.W = self.W - learning_rate*dW
if(math.fabs(old_cost-cost) < 0.01):
break;
if i%100 == 0:
learning_rate *= lr_decay
#print("\nAccuracy after %d epochs : %f\n" %(i,np.sqrt(np.sum(np.square(self.predict(X_test)-y_test))/N)) )
print("Cost difference after %d epochs : %f" %(i,np.abs(cost-old_cost)) )
old_cost = cost
# Load Data and create Training and Test data
#
filename = 'kc_house_data.csv'
data = pd.read_csv(filename)
X_y = data.as_matrix().astype('float')
N,M = X_y.shape
X = X_y[:,0:M-1]
y_target = X_y[:,M-1]
print("Shape of X : ",X.shape)
print("Shape of y_target : ",y_target.shape)
# Split data into train and test data
#
size_of_train = int(N*0.8)
X_train = X[0:size_of_train]
X_test = X[size_of_train:N]
y_train = y_target[0:size_of_train]
y_test = y_target[size_of_train:N]
print("Shape of X_train : ", X_train.shape)
print("Shape of X_test : ", X_test.shape)
print("Shape of y_train : ", y_train.shape)
print("Shape of y_test : ", y_test.shape)
# Data Preprocessing
# Zero centering and Normalizing data
X_mean = np.mean(X_train,axis=0)
X_max = np.max(X_train,axis=0)
X_min = np.min(X_train,axis=0)
X_train -= X_mean
X_std = np.std(X,axis=0)
#X /= (X_max-X_min)
X_train /=X_std
X_test -= X_mean
X_test /= X_std
# append a column of ones to X
N,M = X_train.shape
X_temp = np.ones((N,M+1))
M += 1
X_temp[:,1:M] = X_train
X_train = X_temp
N,M = X_test.shape
X_temp = np.ones((N,M+1))
M += 1
X_temp[:,1:M] = X_test
X_test = X_temp
model = LinearRegression()
model.train(X_train,y_train,X_test,y_test,cost_function="L1",epochs=10000,learning_rate=0.05)
print(np.sqrt(np.sum(np.square(model.predict(X_test)-y_test))/N))
j = 0.05
lr_list = []
rmse_linear = []
rmse_sq = []
rmse_cubic = []
for i in range(20):
model.train(X_train,y_train,X_test,y_test,cost_function="L1",epochs=10000,learning_rate=j)
print("Model Parameters L1 with %.12f lr: "%(j),model.W)
rmse_linear.append(np.sqrt(np.sum(np.square(model.predict(X_test)-y_test))/N))
model.train(X_train,y_train,X_test,y_test,cost_function="L2",epochs=10000,learning_rate=j)
print("Model Parameters L2 with %.12f lr: "%(j),model.W)
rmse_sq.append(np.sqrt(np.sum(np.square(model.predict(X_test)-y_test))/N))
model.train(X_train,y_train,X_test,y_test,cost_function="L3",epochs=10000,learning_rate=j)
print("Model Parameters L3 with %.12f lr: "%(j),model.W)
rmse_cubic.append(np.sqrt(np.sum(np.square(model.predict(X_test)-y_test))/N))
lr_list.append(j)
j /= 2
pl.semilogx(lr_list,rmse_linear,'-',label="L1")
pl.semilogx(lr_list,rmse_sq,'-',label="L2")
pl.semilogx(lr_list,rmse_cubic,'-',label="L3")
pl.xlabel("learning rate")
pl.ylabel("RMSE")
pl.title("RMSE-Performance of various cost fucntions vs learning rates")
pl.legend()
pl.show()
"""
cost_data_reg1 = np.array(model.train(X_train,y_train,X_test,y_test,reg=0.1))
print("\nRMSE with regularization 0.1: %f\n" %(np.sqrt(np.sum(np.square(model.predict(X_test)-y_test))/N)) )
cost_data_reg2 = np.array(model.train(X_train,y_train,X_test,y_test,reg=0.2))
print("\nRMSE with regularization 0.2: %f\n" %(np.sqrt(np.sum(np.square(model.predict(X_test)-y_test))/N)) )
cost_data_reg3 = np.array(model.train(X_train,y_train,X_test,y_test,reg=0.3))
print("\nRMSE with regularization 0.3: %f\n" %(np.sqrt(np.sum(np.square(model.predict(X_test)-y_test))/N)) )
pl.plot(range(cost_data.shape[0]),cost_data,'-',label="No Reg")
pl.plot(range(cost_data_reg1.shape[0]),cost_data_reg1,'-',label="Reg 0.1")
pl.plot(range(cost_data_reg2.shape[0]),cost_data_reg2,'-',label="Reg 0.2")
pl.plot(range(cost_data_reg3.shape[0]),cost_data_reg3,'-',label="Reg 0.3")
pl.title("cost vs epochs")
pl.legend()
pl.show()
"""
|
import math
def ln():
x=int(input("Value?"))
ln=math.log(x)
print(ln)
|
import math
def sec():
x=int(input("Angle in Radian or Degree?Press 1 for radian,press 2 for degree"))
if x==1:
a=float(input("Enter Angle in Radian"))
b=1/math.cos(a)
print(b)
elif x==2:
a = float(input("Enter Angle in Degree"))
c=a*(0.0174)
b = 1/math.cos(c)
print(b)
else:
print("Press 1 or 2")
|
num2 = input('Please enter a length: ')
print('User has entered', num2)
num3 = input('Please enter a breath: ')
print('User has entered', num3)
if num2==num3:
print("its is a square")
else:
print("its is a rectangle")
|
if __name__ == '__main__':
N = int(raw_input())
a = [];
while N > 0:
s = raw_input().split(' ')
if s[0] == "insert":
(i,v) = (int(s[1]),int(s[2]))
a.insert(i,v)
elif s[0] == "remove":
v = int(s[1])
if a.count(v):
a.remove(v)
elif s[0] == "append":
v = int(s[1])
a.append(v)
elif s[0] == "sort":
a.sort()
elif s[0] == "reverse":
a.reverse()
elif s[0] == "pop":
a.pop()
elif s[0] == "print":
print str(a)
N-=1; |
from geometry import Vector, normalize_angle
from math import atan2, pi
from bzrc import Command
"""A controller for a single tank. This used to be in the agent, but I wanted to clean up the agent code a tad so I made its own class"""
class TankController(object):
def __init__(self, tank):
self.prev_speed_error = 0
self.prev_angle_error = 0
self.tank = tank
self.targetX = 0
self.targetY = 0
self.target = 0
def hasValidTarget(self):
if self.target == 0:
return False
else:
return self.target.isAlive()
"""Returns the tanks direction of movment in polar coordinates. It uses the tank x and y velocity to do so"""
def getCurrentDirectionInPolar(self):
vx = self.tank.vx
vy = self.tank.vy
#the follow statement prevents divide by zero errors
if vx == 0 and vy == 0:
return 0
elif vx == 0 and 0 < vy:
return pi/2
elif vx == 0 and vy < 0:
return 3*pi/2
else:
return atan2(vy,vx)
def getFireCommand(self):
""" index, speed, angle, shoot"""
return Command(self.tank.index, 0, 0, True)
def updateTarget(self, targetCont):
self.target = targetCont
self.targetX, self.targetY = self.target.getTargetPosAtNextInterval()
def getTargetingCommand(self):
yDiff = self.targetY - self.tank.y
xDiff = self.targetX - self.tank.x
target_angle = atan2(yDiff, xDiff)
curTankAngle = self.getCurrentDirectionInPolar()
angleDiff = target_angle - curTankAngle
if abs(angleDiff + 2*pi) < abs(angleDiff):
angleDiff = angleDiff + 2*pi
elif abs(angleDiff - 2*pi) < abs(angleDiff):
angleDiff = angleDiff - 2*pi
angleVel = angleDiff
#TODO depending on how we get the angle and speed, convert these to a command
if 1 < angleVel:
angleVel = 1
elif angleVel < -1:
angleVel = -1
elif angleVel == 'nan':
angleVel = 0
""" index, speed, angle, shoot"""
return Command(self.tank.index, .5, angleVel, True)
"""Returns the tanks direction of movment in polar coordinates. It uses the tank x and y velocity to do so"""
def getCurrentDirectionInPolar(self):
vx = self.tank.vx
vy = self.tank.vy
#the follow statement prevents divide by zero errors
if vx == 0 and vy == 0:
return 0
elif vx == 0 and 0 < vy:
return pi/2
elif vx == 0 and vy < 0:
return 3*pi/2
else:
return atan2(vy,vx)
|
# Fri, 3 Sep 2021
# Task 13
# Reading and writing csv file
import csv
def viewData():
with open("D:\\College\\SEM 5\\Implant Training\\Git\\AI-ML-Inplant-Training\\Temp.csv", "rt") as f:
for lines in csv.reader(f):
print(lines)
def addData():
with open("D:\\College\\SEM 5\\Implant Training\\Git\\AI-ML-Inplant-Training\\Temp.csv", "a", newline='') as f:
lisToWrite = []
lisToWrite.append(input("Enter Details :\n\t Employee Id : "))
lisToWrite.append(input("\t Name : "))
lisToWrite.append(input("\t Department : "))
lisToWrite.append(input("\t Salary : "))
lisToWrite.append(input("\t Experience : "))
w = csv.writer(f)
w.writerow(lisToWrite)
def main():
ch = int(input("Press\n1. View Data\n2. Add Student\n3. Exit\n\tSelect : "))
if ch == 1:
viewData()
main()
elif ch == 2:
addData()
main()
elif ch == 3:
exit()
else:
print("Invalid Choice !!!")
main()
main() |
# Mon, 23 Aug 2021
# Task 8.1
# Take input from user and find out sum and average of 0 to that number.
i =0
sum = 0
n = int(input("\nEnter number : "))
while i <= n :
sum+= i
i += 1
print("------------------------------------------")
print(f"\nSum of numbers from 0 to {n} = {sum} ")
print(f" & Average = {sum/n}")
print("------------------------------------------")
# Task 8.2
# Take a number as input and print multiplication table of that number using while loop.
print("\nTable of ", n)
i = 0
while i <= 10 :
print(f"{n} * {i} = {i*n}")
i += 1
print("------------------------------------------")
# Task 8.3
# Writr a program to find factorial using while loop.
fact = 1
i = 1
while i <= n :
fact *= i
i += 1
print(f"\n Factorial of {n} : ", fact)
print("------------------------------------------") |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
A=8
B=30
print("Operator Relasional")
print("-------------------")
print("A= 8 dan B= 30")
print("1. A == B bernilai ",A == B)
print("2. A != B bernilai ",A != B)
print("3. A > B bernilai ",A > B)
print("4. A < B bernilai ",A < B)
print("5. A >= B bernilai ",A >= B)
print("6. A <= B bernilai ",A <= B)
print("")
print("Operator Logika")
print("-------------------")
print("1. True or True bernilai ",True or True)
print("2. True or False bernilai ",True or False)
print("3. False or True bernilai ",False or True)
print("4. False or False bernilai ",False or False)
print("1. True and True bernilai ", True and True)
print("2. True and False bernilai ", True and False)
print("3. False and True bernilai ", False and True)
print("4. False and False bernilai ", False and False)
print("not True bernilai", not True)
print("not False bernilai", not False)
# In[ ]:
# abs(X)
X = int(input("X ="))
if X<0:
X=-X
print("X =",X)
# In[2]:
# mencetak bilangan terbesar dari 2 buah bilangan
B1=int(input("Bilangan Pertama = "))
B2=int(input("Bilangan Kedua = "))
print("Bilangan Terbesar adalah ",end="")
if B1>B2:
print(B1)
else:
print(B2)
# In[8]:
# mencetak bilangan terbesar dari 3 buah bilangan
B1=int(input("Bilangan Pertama = "))
B2=int(input("Bilangan Kedua = "))
B3=int(input("Bilangan Ketiga = "))
print("Bilangan Terbesar adalah ",end="")
if B1>B2:
if B1>B3:
print(B1)
else:
print(B3)
elif B2>B3:
print(B2)
else:
print(B3)
# In[10]:
# mencetak bilangan terbesar dari 5 buah bilangan
B1=int(input("Bilangan Pertama = "))
B2=int(input("Bilangan Kedua = "))
B3=int(input("Bilangan Ketiga = "))
B4=int(input("Bilangan Keempat = "))
B5=int(input("Bilangan Kelima = "))
print("Bilangan Terbesar adalah ",end="")
B=B1
if B<B2:B=B2
if B<B3:B=B3
if B<B4:B=B4
if B<B5:B=B5
print(B)
# In[11]:
# mencetak bilangan terbesar dan terkecil dari 5 buah bilangan
B1=int(input("Bilangan Pertama = "))
B2=int(input("Bilangan Kedua = "))
B3=int(input("Bilangan Ketiga = "))
B4=int(input("Bilangan Keempat = "))
B5=int(input("Bilangan Kelima = "))
print("Bilangan Terbesar adalah ",end="")
B=B1
if B<B2:B=B2
if B<B3:B=B3
if B<B4:B=B4
if B<B5:B=B5
print(B)
print("Bilangan Terkecil adalah = ",end="")
B=B1
if B>B2:B=B2
if B>B3:B=B3
if B>B4:B=B4
if B>B5:B=B5
print(B)
# In[13]:
# mencetak bilangan terbesar dan terkecil dari 5 buah bilangan
# dengan mnegunakan 2 variable bantuan BB dan Bk
B1=int(input("Bilangan Pertama = "))
B2=int(input("Bilangan Kedua = "))
B3=int(input("Bilangan Ketiga = "))
B4=int(input("Bilangan Keempat = "))
B5=int(input("Bilangan Kelima = "))
BB=B1
BK=B1
if BB<B2:
BB=B2
elif BK>B2:
BK=B2
if BB<B3:
BB=B3
elif BK>B3:
BK=B3
if BB<B4:
BB=B4
elif BK>B4:
BK=B4
if BB<B5:
BB=B5
elif BK>B5:
BK=B5
print("Bilangan Terbesar adalah",BB)
print("Bilangan Terkecil adalah",BK)
# In[3]:
Pembilang=int(input("Pembilang = "))
Penyebut=int(input("Penyebut = "))
if Penyebut==0:
if Pembilang==0:
print("Tidak Terdefinisi")
else:
print("∞")
else:
print(Pembilang,"/", Penyebut,"/",Pembilang/Penyebut)
# In[7]:
#persamaan kuadrat ax2 + bx +c = 0
#import module math
import math
#input koeisien dengan keyboard
a = int(input('Masukkan Nilai A = '))
b = int(input('Masukkan Nilai B = '))
c = int(input('Masukkan Nilai C = '))
#menghitung diskrimanan D
D = (b**2)-(4*a*c)
D = int(D)
if D==0:
x=-b/2*a
print("Dua Akar yang Sama",x)
elif D<0:
print("Angka Imanginer")
else:
x1=(-b+math.sqrt(D))/2*a
x2=(-b-math.sqrt(D))/2*a
print("x1=",x1)
print("x2=",x2)
# In[14]:
#persamaan linier
# a1 x + b1 y = c1
# a2 x + b2 y = c2
A1=int(input("A1 = "))
B1=int(input("B1 = "))
C1=int(input("C1 = "))
A2=int(input("A2 = "))
B2=int(input("B2 = "))
C2=int(input("C2 = "))
DA=A1*B2-A2*B1
if DA==0:
DC=A1*C2-A2*C1
if DC==0:
print("Banyak jawaban atau ∞")
else:
print("Tidak memiliki jawaban")
else:
x=(C1*B2-C2*B1)/DA
y=(A1*C2-A2*C1)/DA
print("x=",x)
print("y=",y)
# In[9]:
#
# In[ ]:
|
from math import sqrt
from aocframework import AoCFramework
class Day(AoCFramework):
test_cases = ()
def go(self):
raw = self.raw_puzzle_input
raw_split = self.linesplitted
class Point():
x=0
y=0
vel_x=0
vel_y=0
def __init__(self,x,y,vel_x,vel_y):
self.x=x
self.y=y
self.vel_x=vel_x
self.vel_y=vel_y
def move(self):
self.x+=self.vel_x
self.y+=self.vel_y
return (self.x,self.y)
def __repr__(self):
return f"Point @ ({self.x},{self.y}) >>> ({self.vel_x,self.vel_y})"
points = []
for line in raw_split:
splitted_line=line.split(',')
pointx = int(splitted_line[0][-6:].strip())
pointy=int(splitted_line[1][1:7].strip())
pointvelx=int(splitted_line[1][-2:].strip())
pointvely=int(splitted_line[2][1:3].strip())
points.append(Point(pointx,pointy,pointvelx,pointvely))
point_positions={}
def distance(x1, y1, x2, y2):
return sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
for i in range(20000):
next_positions = [point.move() for point in points]
point_positions[i]={'pos':next_positions}
max_x=max(point.x for point in points)
max_y=max(point.y for point in points)
min_x=min(point.x for point in points)
min_y=min(point.y for point in points)
point_positions[i]['max_distance']=distance(min_x,min_y,max_x,max_y)
if point_positions[i]['max_distance']<70:
for y in range(min_y, max_y + 1):
for x in range(min_x,max_x+1):
point_at_pos = any(point.x==x and point.y==y for point in points)
print('X' if point_at_pos else ' ',end='')
print('')
print('')
# print(min_x,min_y,max_x,max_y,distance(min_x,min_y,max_x,max_y))
distances = [point_position['max_distance'] for point_position in point_positions.values()]
min_distance = min(distances)
print(min_distance)
Day() |
#===================
#==collections
#===================
#-----defaultdict
from collections import defaultdict
ice_cream = defaultdict(lambda: 'Vanilla')
ice_cream['Sarah'] = 'Chunky Monkey'
print(ice_cream['Sarah'])
# Chunky Monkey
print(ice_cream['Joe'])
# Vanilla
#=====================
#==json file
#=====================
#--------read
with open(path, 'r') as f:
print(f"readin from {path}...")
print(json.load(f))
#--------write
with open(path, 'w') as f:
print(f"writing to {oath}...")
json.dump(json_data, f, indent=2) |
# TODO Aula 04: https://www.youtube.com/watch?v=3ohzBxoFHAY&list=PL-osiE80TeTsqhIuOqKhwlXsIBIdSeYtc&index=5
class Employee:
percent = 1.04
def __init__(self, name, lastname, sal):
self.name = name
self.lastname = lastname
self.sal = sal
self.email = '{}.{}@prop.com'.format(name, lastname)
def fullname(self):
return '{} {}'.format(self.name, self.lastname)
def apply_raise(self):
self.sal = int(self.sal * self.percent)
# Métodos Especiais
def __repr__(self):
return "Employee({}, {}, {})".format(self.name, self.lastname, self.sal)
def __str__(self):
return '{}: {}'.format(self.fullname(), self.email)
def __add__(self, other):
return self.sal + other.sal
emp_1 = Employee('Jef', 'Melo', 70000)
emp_2 = Employee('Jon', 'Car', 50000)
# print(repr(emp_1))
# print(repr(emp_1))
# print(emp_1.__repr__())
# print(emp_1.__str__())
print(emp_1 + emp_2)
|
import math
import unittest
def calcCircumfrence(r):
return r*2*math.pi
class TestMyCode(unittest.TestCase):
def test_circumfrence(self):
actual = calcCircumfrence(5)
self.assertEqual(actual, 31.41592653589793)
def test_calcCircumfrenceZero(self):
actual = calcCircumfrence(0)
self.assertEqual(actual,0)
def test_circumfrenceInvalid(self):
self.assertRaises(calcCircumfrence("Frank"))
def myfunc(self): #Note that this will not run without being explicitly called because it does not begin with "test"
return "Hello"
unittest.main() |
first_num = int (input ("first num >"))
second_num = int (input ("second num >"))
for number in range(first_num,second_num + 1):
found_prime = True
for i in range(2, number-1):
if number % i == 0 :
print ( number , "is not a prime number")
found_prime = False
break
if found_prime == True :
print ( number , "is a prime number") |
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
XEntre = True if (Q[0] >= P[0] and Q[0]<=P[2]) or ((Q[2] >= P[0] and Q[2]<=P[2])) else False
YEntre = True if (Q[1] >= P[1] and Q[1]<=P[3]) or ((Q[3] >= P[1] and Q[3]<=P[3])) else False
XEntre = XEntre or (True if (P[0] >= Q[0] and P[0]<=Q[2]) or ((P[2] >= Q[0] and P[2]<=Q[2])) else False)
YEntre = YEntre or (True if (P[1] >= Q[1] and P[1]<=Q[3]) or ((P[3] >= Q[1] and P[3]<=Q[3])) else False)
print("1" if XEntre and YEntre else "0")
|
R1 = list(map(int,input().split()))
R2 = list(map(int,input().split()))
A1 = R1[0]*R1[1]
A2 = R2[0]*R2[1]
if A1>A2:
R = "Primeiro"
elif A1 == A2:
R = "Empate"
else:
R = "Segundo"
print(R) |
#http://marathoncode.blogspot.com/2012/03/numeros-primos-iii.html
#https://tiagomadeira.com/2007/06/crivo-de-eratostenes/
def crivo_erastostenes(N,crivo):
crivo[1]=True
for i in range(1,N+1):
if not crivo[i]:
j = 2
while i*j<=N:
crivo[i*j] = True
j+=1
return crivo
N = int(input())
crivo = list(range(0,N+1))
crivo = [False] * (N + 1)
#print(crivo)
crivo = crivo_erastostenes(N,crivo)
for i in range(1,N+1):
if not crivo[i]:
print(i, end=' ') |
V = []
#V[0] = Quantidade de posições
#V[1] = Posição do Disco Voador
#V[2] = Posição do Avião
for i in range(3):
V.append(int(input()))
if V[0] == V[1]:
Resp = V[2]
elif V[0] == V[2]:
Resp = V[1]
else:
Resp = V[0]
print(Resp) |
# 函数input()让用户可以输入一些信息,等待python存储后方便使用
message = input("Tell me something , and I will repeat it to you : ")
print(message)
# 在提示用户输入的是否可以提示用户输入的数据类型
name = input("Please enter your name : ")
print("Hello ! " + name)
# 用 += 创建多行字符串
prompt = "If you tell us who you are ,we can personalize the message you see ."
prompt += "\nWhat is your first name ?"
name = input(prompt)
print("\nHello , " + name + "!")
# 使用int()获取数字输入
age = input("How old are you ?")
age = int(age)
# 指明年龄的类型是数值,将str()转化为int()
print(age)
height = input("How tall are you , in inches?")
height = int(height)
if height >= 36:
print("\nYou are tall enough to ride!")
else:
print("\nYou will be able to ride when you are a little older")
# 求模运算符 % 是一个很有用的工具,他将两个数相除并返回余数
a = 4 % 3
a = float(a)
print(a)
# 利用求模运算符判断是否余数为0,偶数整除的话返回余数为0
numble = input("Enter a numble ,and I will tell you if it is even or odd: ")
numble = int(numble)
if numble % 2 == 0:
print("The numble is even")
else:
print("The numble is odd")
# while循环
couning_numble = 1
while couning_numble <= 5:
print(couning_numble)
couning_numble += 1
# 让用户选择何时退出
# 定义一个退出值,当用户输入的不是这个值,程序接着运行
prompt = "\nTell me something and i will repeat it back to you "
prompt = "\nEnter 'quit' to end the program"
message = ""
while message != 'quit':
message = input(prompt)
print(message)
# 发现quit输入的是否并没有正确被停止程序
# 接下来进行修改
prompt = "\nTell me something and i will repeat it back to you "
prompt += "\nEnter 'quit' to end the program"
message = ""
while message != 'quit':
message = input(prompt)
# 以上是判断输入的条件,只要控制输入quit后停止输出就可以
if message != 'quit':
print(message)
else:
# 使用break立刻退出while循环
break
# 使用标志
prompt = "\nTell me something and i will repeat it back to you "
prompt += "\nEnter 'quit' to end the program"
message = ""
active = True
# 其中active 为程序是否执行的标志
while active:
message = input(prompt)
if message != 'quit':
print(message)
else:
active = False
# 在while 中使用break 和 coutinue 控制程序运行
curent_numble = 0
while curent_numble < 10:
curent_numble += 1
if curent_numble % 2 == 0:
continue
# coutinue 表示符合条件的话回到while接着执行
else:
print(curent_numble)
# 使用while循环处理列表和字典
uncomfirme_users = ['alice', 'brain', 'candace']
comfirme_users = []
while uncomfirme_users:
comfirme_user = uncomfirme_users.pop()
print("Verifying user : " + comfirme_user.title())
comfirme_users.append(comfirme_user)
print("\nThe following users have been comfirmed :")
for user in comfirme_users:
print("\t\t\t" + user.title())
# 删除包含特定值的所有列表元素
# 先用for 循环去筛选
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
for pet in pets:
if pet == 'cat':
pets.remove(pet)
print(pets)
# 要注意 pop只是弹出需要的列表元素,原列表并不会发生改变
# 用while语法筛选
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
# 与for循环不同,while循环将筛选和循环一起完成 ,取消中间变量pet,更加简洁
pets.remove('cat')
print(pets)
# 使用用户输入来填充字典
responds = {}
polling_active = True
while polling_active:
name = input("\nWhat is your name ?")
respond = input("Which mountain would you like to cilmb someday")
responds[name] = respond
repeat = input("\nWould you like to lat another person respond?(Yes/No) ")
repeat = repeat.title()
if repeat == 'No':
polling_active = False
print("\n----Poll Resule----")
print(name + " Would like to climb " + respond + ".")
|
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
# for语句的格式问题,注意缩进
# 条件测试
# python 是个根据条件测试的值为true还是false来决定是否执行if后面的语句
# python在考虑值是否相等时,会检查大小写,如何检查是否相等时不用考虑大小写得使用lower() ,upper()和title()方法
# 用"=="来询问是否相等,用"!="来询问是否不相等,如果回答是true则接着执行下面的语句
age = 18
if age == 18:
print(True)
else:
print(False)
age = 18
if age != 20:
print(True)
print("That is not the correct answer, Please try again !")
else:
print(False)
# 检查多个条件,用and链接两个删选条件
age_0 = 22
age_1 = 38
if age_0 >= 22 and age_1 <= 38:
print(True)
else:
print(False)
# 检查多个条件,用or链接两个删选条件
if age_0 >= 22 or age_1 != 38:
print(True)
else:
print(False)
# 检查特定值是否包含在列表中
# 要判断是否包含在列表中,可使用关键字in(if '字符串' in list[])
request_toppings = ['mushrooms', 'onions', 'pineapple']
if 'onions' in request_toppings:
print(True)
else:
print(False)
if 'beef' in request_toppings:
print(True)
else:
print(False)
# 要判断是否不包含在列表中,可使用关键字in(if '字符串' not in list[])
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(user.title() + ", you can post a response if you wish.")
# 布尔表达式
# 布尔表达式的结果要么是True,要么是False,常用于记录条件
game_active = True
can_edit = False
# if的高级形式,if elif else
age = 20
if age < 15:
print("Your admission cost is $0 ")
elif age < 30:
print("Your admission cost is $5")
else:
print("Your admission cost is $10")
# 视条件可采用多个elif 结构
# 测试多个条件,采用一系列的if语句,各个if语句之间相互独立
request_toppings = ['mushroonms', 'extra cheese']
for request in request_toppings:
if request in request_toppings:
print("adding " + request.title())
# 使用if语句处理列表
request_toppings = ['mushrooms', 'green papers', 'extra cheese']
for request in request_toppings:
print("Adding " + request.title() + ".")
print("\nFinished making your pizza")
# 确认列表为空,用if list[]: 判断列表元素是否为空。
request_toppings = ['mushrooms', 'green papers', 'extra cheese']
if request_toppings:
for request in request_toppings:
print("Adding " + request.title() + ".")
else:
print("\nAre you sure want a plain pizza ?")
print("\nFinished making your pizza.")
|
import os
from multiprocessing import Pool, Manager
def copy_file(q, file_name, old_file_name, new_file_name):
# print("copying from %s to %s: %s" % (old_file_name, new_file_name, file_name))
old_f = open(old_file_name + '/' + file_name, 'rb')
content = old_f.read()
old_f.close()
new_f = open(new_file_name + '/' + file_name, 'wb')
new_f.write(content)
new_f.close()
q.put(file_name)
def print_bar(copied, file_num):
print('\r', end='')
for i in range(int(50 * copied / file_num)):
print("*", end='')
print("%.2f%%" % (copied * 100 / file_num), end='')
def main():
# 获取要拷贝的文件夹名
old_folder_name = input("Please enter the old folder name: ")
# 获取要创建的文件夹名
new_folder_name = input("Please enter the new folder name: ")
# 创建新文件夹,存在则pass
try:
os.mkdir(new_folder_name)
except:
pass
# 获取要文件夹中的所有文件名 listdir()
file_names = os.listdir(old_folder_name)
# 创建进程池
po = Pool(5)
# 如果用进程池,则要用Manage()中的Queue()
q = Manager().Queue()
# 向进程池中添加copy任务
for file_name in file_names:
po.apply_async(copy_file, args=(q, file_name, old_folder_name, new_folder_name))
po.close()
# po.join()
# 子进程开始复制文件
file_num = len(file_names)
copied = 0
while copied < file_num:
file_name = q.get()
# print("copy complete: %s" % file_name)
copied += 1
print_bar(copied, file_num)
print('\n')
if __name__ == "__main__":
main()
|
#Opcion 1 para pedir un dato desde teclado en consola
print("Ingresa un dato: ")
n = input()
#Las opciones de mostrar el dato obtenido desde teclado
print("El dato ingresado fue: " + n)
print("El dato ingresado fue:", n)
print(f"El dato ingresado fue: {n}")
#Opcion 2 para pedir un dato desde teclado en consola
nombre = input("Ingresa tu Nombre: ")
print("El nombre ingresado fue: " + nombre) |
#LAS TUPLAS PUEDEN SER USADAS PARA CUANDO NO QUIERA QUE SE MODIFIQUE ALGUN DATO ESPECIFICADO DESDE LA CREACION DEL MISMO
ejemplo = ([40, 2], "Cincuenta", 23, "Doce")
print(ejemplo[0])
ejemplo2 = ("solo un dato en la tupla",) #Si solo se quiere un elemento dentro de la tupla se debe poner una coma al final
# para que la variable sea detectada como una tupla
print(ejemplo2, type(ejemplo2)) |
def sumar(a, b):
return a + b
def restar(a, b):
return a - b
def multiplicar(a, b):
return a * b;
num1 = input("Num1: ")
num2 = input("Num2: ")
print("Opciones\n1.- Sumar\n2.- Restar\n3.- Multiplicar")
operaciones = {'1': sumar, '2': restar, '3': multiplicar}
seleccion = input('Escoge una: ')
try:
resultado = operaciones[seleccion](int(num1), int(num2))
print(resultado)
except:
print("Esa no vale")
|
#EN JAVA SERIA indexOf()
cadena = "Alvarado"
#PIDE SI ES QUE SE ENCUENTRA ESA LETRA PARA DEVOLVER TRUE
print('A' in cadena)#Devuelve un true o un false si esta letra se encuentra o no dentro de la anterior cadena
#PIDE QUE ESTA LETRA NO SE ENCUENTRA PARA DEVOLVER TRUE
print('o' not in cadena)
#OPERADORES DE IDENTIDAD --> son las comparaciones de distintos tipos de atributos (variables)
#is y is not
a = 10
b = 10
print(b is complex)#Devuelve false o true si es que es igual al tipo de variable que le indicamos
|
from auxiliares import Auxiliares
class TablaLL(Auxiliares):
"""Clase para la creacion y despliegue de la tabla LL(1)
utilizando los metodos contenidos en la clase padre Auxiliares"""
def __init__(self, archivo):
"""Se recibe el nombre del archivo y se pasa a la clase padres"""
super(TablaLL, self).__init__(archivo)
self.leer_archivo()
self.num_filas = len(self.no_terminales)
self.num_colum = len(self.terminales)
self.tabla = [[None] * self.num_colum for i in range(self.num_filas)]
def construir_tabla(self):
"""Implementacion del algoritmo para el
llenado de la tabla"""
produccion_num = 1
for clave, valor in self.gramatica.items():
for produccion in valor.get("producciones"):
primeros = self.primero(produccion)
for a in primeros:
if a != "e":
self.agregar_elemento(clave, a, produccion_num)
if "e" in primeros:
siguientes = self.siguiente(clave)
for c in siguientes:
self.agregar_elemento(clave, c, produccion_num)
produccion_num += 1
def agregar_elemento(self, A, a, num):
"""Metodo que agrega un elemento a la tabla"""
i = self.no_terminales.get(A)
j = self.terminales.get(a)
if self.tabla[i][j] is None:
self.tabla[i][j] = set()
self.tabla[i][j].add(num)
def mostrar_tabla(self):
"""Metodo que muestra la tabla"""
print("Tabla LL(1):")
print(" ", end="")
for t in self.terminales.keys():
print(t, end="\t")
print("")
for f, n in zip(self.tabla, self.no_terminales.keys()):
for c in f:
print(c, end="\t")
print(n)
|
# 예외 (exception) -> 통상적으로 에러
# 예외 발생 -> 프로그램이 비정상적으로 처리됨
# 예외 처리 -> 발생된 예외를 처리하는 것이 아니고 정상종료 하도록 유도
# 예외 처리 방법
# 예외클래스(계층구조)를 제공해서 처리, (파이썬 문서(python.org) 에서 hierarchy 볼 수 있음 (library reference))
# try ~ except 문장
# finally 문
# 1. 예외 발생
n1 = 10
n2 = n1/5
#n2 = n1/0 # 실행시키면 에러 발생 (ZeroDivisionError: division by zero)
print("실행결과:", n2)
print("정상종료")
print("#"+"-"*20+"#")
# 2. 예외 처리 (try ~ except)
try:
n1 = 10
#n2 = n1/2
n2 = n1/0
print("실행결과:", n2)
# ZeroDivisionError 의 hierarchy
# Exception > ArithmeticError > ZeroDivisionError
except ZeroDivisionError as e: # 해당하는 에러종류를 써줘야 함. (정확하게 종류를 써주는 것이 좋음)
# except ArithmeticError as e: # hierarchy 에서 상위는 사용가능 (다형성)
# except Exception as e: # hierarchy 에서 상위는 사용가능 (다형성)
# except TabError as e: # hierarchy 가 완전 다르기 때문에 동작안됨
print("예외처리 코드", e)
# except:
# print("예외처리 코드")
print("정상종료")
print("#"+"-"*20+"#")
# 3. 예외 처리 (try ~ except, finally)
try:
n1 = 10
#n2 = n1/2
n2 = n1/0
print("실행결과:", n2)
# ZeroDivisionError 의 hierarchy
# Exception > ArithmeticError > ZeroDivisionError
except ZeroDivisionError as e: # 해당하는 에러종류를 써줘야 함. (정확하게 종류를 써주는 것이 좋음)
print("예외처리 코드", e)
finally:
print("finally : 반드시 수행")
print("finally : 파일, DB 입출력(외부자원)의 close 작업") # 예외동작을 하든 안하든 동작되는 코드에는 외부자원을 사용하는 부분의 close 작업을 넣어준다.
print("정상종료")
print("#"+"-"*20+"#")
# 4. 예외 처리 (try ~ except, finally, 서로 다른 exception 이 있는 경우)
# 명시적으로 각각 예외처리를 하고 마지막에는 전체 예외에 대한 처리를 넣어준다.
try:
n1 = 10
#n2 = n1/2
n2 = n1/0
print("실행결과:", n2)
except ZeroDivisionError as e: # 해당하는 에러종류를 써줘야 함. (정확하게 종류를 써주는 것이 좋음)
print("예외처리 코드", e)
except IndexError as e:
print("예외처리 코드", e)
except Exception as e:
print("예외처리 코드", e)
finally:
print("finally : 반드시 수행")
print("finally : 파일, DB 입출력(외부자원)의 close 작업") # 예외동작을 하든 안하든 동작되는 코드에는 외부자원을 사용하는 부분의 close 작업을 넣어준다.
print("정상종료")
print("#"+"-"*20+"#")
# 5. finally 문 사용 (except 없이)
# except 없이 try finally 만 사용할 수 있음
# 반드시 수행해야 하는 작업만 수행하겠다는 의미
print("프로그램 시작")
try:
n = 10 / 2
print("결과값", n)
finally:
print("finally : 반드시 수행")
print("정상종료")
print("#"+"-"*20+"#")
# 6. 사용자 정의 예외
# 지금까지는 예외를 시스템이 발생시킴
# 사용자가 명시적으로 예외 발생시키고 처리 가능
# 사용자가 명시적으로 예외 발생시칸다는 것은 시스템이 발생시킨다는 의미. 즉, 문법적으로는 문제가 없음
# 개발자가 만든 프로그램에서 개발자가 지정한 특정 조건에 위배되었을 경우 강제적으로 예외 발생함
# raise 예외클래스명(mesg) -> 자바는 throw 예외클래스명(mesg)
# 사용자 정의 예외클래스
class UserException(Exception): # 반드시 Exception 클래스를 상속받아야 함
def __init__(self, mesg):
self.mesg = mesg
#
import random
def randomValue():
n = random.randrange(0, 2)
print("6. 랜덤값 :", n)
if n == 0:
# 사용자 정의 예외클래스 이용
raise UserException("랜덤값이 0: 예외발생") # 클래스이름(값). 즉, 객체 생성과 동일
# 기존 예외 이용 가능
# raise ZeroDivisionError("랜덤값이 2: 예외발생") # 클래스이름(값). 즉, 객체 생성과 동일
print("6. 프로그램 시작")
try:
randomValue()
except ZeroDivisionError as e:
print("6. 예외처리 코드", e)
except UserException as e:
print("6. 예외처리 코드", e)
else: # 예외가 발생하지 않았을때를 위해서 'else'를 사용할 수 있다.
print("6. 예외발생 안함")
print("6. 정상종료")
print("#"+"-"*20+"#")
# 7. 시스템이 발생시킨 예외를 사용자 정의 예외로 처리하는 방법
# 시스템이 발생한 에러 -> 영문자 에러 메시지가 출력됨
# 시스템이 발생한 에러 -> 사용자 정의 예외로 하여 한글로 된 에러 메시지 출력
# 사용자 정의 예외클래스
class UserException(Exception): # 반드시 Exception 클래스를 상속받아야 함
def __init__(self, mesg):
self.mesg = mesg
#
def calc():
try:
n1 = 10
n2 = n1 / 0
print("7. 실행결과:", n2)
except ZeroDivisionError as e:
raise UserException("0으로 나눔: 예외발생")
print("7. 프로그램 시작")
try:
calc()
except UserException as e:
print("7. 예외처리 코드", e)
print("7. 정상종료")
print("#"+"-"*20+"#")
# 8. 사용자 정의 예외의 예제
# 랜덤값 생성하여 생성된 값이 특정값이면 예외 발생
# 사용자 정의 예외클래스
class UserException(Exception): # 반드시 Exception 클래스를 상속받아야 함
# def __init__(self, mesg):
# self.mesg = mesg
def __init__(self):
super().__init__("Check User Exception")
#
import random
def randomValue():
n = random.randrange(0, 2)
print("8. 랜덤값 :", n)
if n == 1:
# 사용자 정의 예외클래스 이용
raise UserException # 클래스이름(값). 즉, 객체 생성과 동일
print("8. 프로그램 시작")
try:
randomValue()
except UserException as e:
print("8. 예외처리 코드", e)
else: # 예외가 발생하지 않았을때를 위해서 'else'를 사용할 수 있다.
print("8. 예외발생 안함")
print("8. 정상종료")
print("#"+"-"*20+"#")
|
# while
n = 1
while n < 6 :
print("hello")
n += 1
print("end")
print("#"+"-"*20+"#")
# while 중첩
n = 1
while n < 4 :
m = 1
while m < 3:
print(str(n) + " " + str(m))
m += 1
n += 1
print("end")
print("#"+"-"*20+"#") |
def add_comp(num):
if num <= 3:
return 0
else:
comp_num_sum = 0
for n in range(3, num+1):
for m in range(2, n):
if (n % m) == 0:
comp_num_sum += n
break
return comp_num_sum
list_to_test = [2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 50]
for num in list_to_test:
print("The sum of all composite numbers <= {} is ".format(num) + str(add_comp(num))) |
def piramide_for():
lenght = int(input('Hoe groot? '))
for i in range(lenght+1):
print('*' * i)
for i in range(lenght):
print('*' * (lenght-i))
def piramide_while():
lenght = int(input('Hoe groot? '))
count = 1
while count < lenght:
print('*' * count)
count += 1
while count > 0:
print('*' * count)
count -= 1
piramide_for()
piramide_while()
#print(f'{mystring:>{size}}') |
def fibonaci(index):
if index == 0:
return 1
elif index == 1:
return 1
else:
return fibonaci(index-1) + fibonaci(index-2)
print(fibonaci(40)) |
#!/usr/bin/env python
#coding: utf-8
'''------------------------------------------------------------------------
> File Name: insertion_sort.py
> Author: Hat_Cloud
> Mail: [email protected]
> Created Time: 2014-11-20 14:23
------------------------------------------------------------------------'''
def InsertionSort(A):
for j in range(1, len(A)):
key = A[j]
i = j - 1
while i >= 0 and A[i] > key:
A[i + 1] = A[i]
i = i - 1
A[i + 1] = key
return A
B = [5,2,4,6,1,3]
print InsertionSort(B)
|
"""
Displays an image pyramid
"""
from skimage import data
from skimage.util import img_as_ubyte
from skimage.color import rgb2gray
from skimage.transform import pyramid_gaussian
import napari
import numpy as np
# create pyramid from astronaut image
astronaut = data.astronaut()
base = np.tile(astronaut, (3, 3, 1))
pyramid = list(
pyramid_gaussian(base, downscale=2, max_layer=3, multichannel=True)
)
pyramid = [
np.array([p * (abs(3 - i) + 1) / 4 for i in range(6)]) for p in pyramid
]
print('pyramid level shapes: ', [p.shape for p in pyramid])
with napari.gui_qt():
# add image pyramid
napari.view_image(pyramid, is_pyramid=True)
|
from gates import NAND, NOR, OR, AND, XOR, NOT
# function to take input
def take_input():
# take input as string, and split it on basis of white spaces
return input('Enter two numbers: (Enter with empty string to exit)').split()
# validate if there are 2 and only 2 elements entered
def validate_count(nums):
if len(nums) == 2:
return True
else:
print('Error in input format. Enter again.')
return False
# validate if the entered numbers are actually integers
def validate_int(nums):
try:
# try casting them to ints. if success, returns true from next line
int(nums[0]) and int(nums[1])
return True
except:
# if can't be casted to int, exception will occur
print('The numbers are not integers.')
return False
# validate if the numbers entered are within range of (0 to 255)
def validate_size(nums):
# checking if both the numbers are within rangee
if 0 <= int(nums[0]) <= 255 and 0 <= int(nums[1]) <= 255:
return True
else:
# print the error message
print('The integer is out of bounds (0-255)')
return False
def is_valid(nums):
# return true if all validation rules are satisfied
return validate_count(nums) and validate_int(nums) and validate_size(nums)
# function that adds two bits, along with carry
def add_bits(a, b, cin):
# simulating the bit-adder
# refer to bit_adder.png
m = XOR(a, b)
x = NAND(m, cin)
y = OR(m, cin)
s = AND(x, y)
n = AND(a, b)
p = AND(m, cin)
r = NOR(n, p)
cout = NOT(r)
return (s, cout)
# function that returns binary representation of a number
def get_bin_string(num):
# get binary value of num as string
s = "{0:b}".format(num)
# since we need exactly 8 bits in both numbers
# create new list and
# apppend 0s in front if there are less than 8 bits
binstr = ['0']*(8 - len(s))
# after that append every bits in s to binstr
for ch in s:
binstr.append(ch)
# at this point, binstr will be exactly have 8 bits
# return a string joining the bits in the list binstr
return ''.join(binstr)
# function that adds two bytes
def add_bytes(a, b):
# get binary representation of the numbers in 8 bits
num1 = get_bin_string(a)
num2 = get_bin_string(b)
# initializing carry-in as 0 initially
cin = 0
# list that will store the bits after
res = []
# for every bits in the binary representation (equivalently, every column in addition)
for i in range(1, 8+1):
# take out individual bits from bit-string, as integers, starting from the last (hence, -i)
bit1 = int(num1[-i])
bit2 = int(num2[-i])
# add the bits, get sum and carry-out
s, cout = add_bits(bit1, bit2, cin)
# carry-in for next column will be carry-out for this column
cin = cout
# insert the sum bit at the very beginning
res.insert(0, str(s))
# add the final carry in the result string too. (if the result is required to be 8 bits strictly, delete this line)
res.insert(0, str(cin))
# create a bit-string by joining the bits in the list
res = ''.join(res)
# return the integer value when the bit-string is parsed as binary-string.
return int(res, 2)
# if this file is run as main program
if __name__ == "__main__":
# take the numbers input
nums = take_input()
# while there is something entered,
while nums:
# check if what user entered is valid
if is_valid(nums):
# convert the input numbers from string into integers
num1 = int(nums[0])
num2 = int(nums[1])
# calculate the result of byte addition
result = add_bytes(num1, num2)
# print the result
print('The sum of the numbers is:', result)
# take input for next instance
nums = take_input()
# loop exits once nums is empty
|
import re
# 验证手机号是否正确
phone_pat = re.compile(r'^1[3-9]\d{9}$')
name_pat = re.compile(r'^Simle[A-Z]{6}$')
class Student():
def __init__(self):
self.list1 = []
def menu(self):
while True:
user = int(input("北京格林豪泰酒店\n1.登记保存\n2.退出\n输入:"))
if user == 1:
#验证手机号
phone = input('请输入您的手机号:')
name = input("请输入您的姓名:")
res1 = re.search(name_pat, name)
res = re.search(phone_pat,phone)
if res and res1:
continue
else:
print("格式错误,重新输入")
self.list1.append(phone)
self.list1.append(name)
for i in self.list1:
str(i)
print(" ")
f = open("2.txt", "a")
f.write(i)
f.close()
print("保存成功")
elif user == 3:
print("感谢您来格林豪泰!")
break
xm = Student()
xm.menu() |
from rgfunc import *
def printEmp(employees):
n = 1
for name in employees:
print n, ": ", name.fullname()
n +=1
br()
def new_emp(Employee,employees):
br()
print "Enter New Employees Details"
employee = Employee(raw_input("Enter new employee's frist name: "))
employee.lastname = raw_input("Enter new employee's last name: ")
employee.city = raw_input("Enter name of city: ")
employee.country = raw_input("Enter name of country: ")
employee.day = get_int("Enter the date of birth: ")
employee.month = get_int("Enter the month of birth: ")
employee.year = get_int("Enter the year of birth: ")
employees.append(employee)
br()
def det_emp(employee):
br()
stline()
print employee.fullname()
stline()
br()
print "First Name: ",employee.name
print "Last Name: ",employee.lastname
print "City: ",employee.city
print "Country: ",employee.country
print "Date of Birth:",employee.dateofbirth()
br()
def vd_emp(employees):
if len(employees) == 0:
br()
print "Empty - nothing to View"
br()
else:
br()
printEmp(employees)
vd_empl = get_int("choose employee to vew details: ")
br()
det_emp(employees[vd_empl-1])
def list_emp(employees):
if len(employees) == 0:
br()
print "Empty - nothing to View"
br()
else:
br()
printEmp(employees)
def del_emp(employees):
if len(employees) == 0:
br()
print "Empty - nothing to Delete"
br()
else:
printEmp(employees)
stline()
del_name = raw_input("Which employee you want to delete: ")
try:
del_name = int(del_name)
del employees[del_name-1]
printEmp(employees)
stline()
br()
except:
br()
print "Invalid Input"
br()
def srch_emp(employees):
listName = []
num = []
br()
sr_name = raw_input("Enter name of employee you want to search: ")
br()
no = 1
for name in employees:
if sr_name.lower() == name.name.lower():
listName.append(name.fullname())
num.append(no)
no +=1
if len(listName) == 0:
br()
print "Nothing Found, Try Again"
br()
else:
n= 1
for name in listName:
print num[n-1] , ": " ,name
n +=1
br()
def edit_emp(employees):
pass
if __name__ == "__main__":
print "Error-Invalid File to Run- Please Run main.py."
exit()
|
class Superhero(object):
def __init__(self, name):
self.powers = set()
self.name = name
self.gender = ""
self.super_friends = set()
self.evil_enemies = set()
self.sidekicks = set()
self.weaknesses = set()
self.lair = ""
self.biological_parents = tuple()
def fight(self):
pass
def get_powers(self):
return self.powers
def add_power(self, new_power):
self.powers.add(new_power)
def remove_power(self, power_to_remove):
self.powers.remove(power_to_remove)
def __str__(self):
power_output = ""
for power in self.get_powers():
power_output += power + ","
return "{} the superhero with the powers: {}".format(self.name, power_output[0:-1])
|
import numpy as np
# Write a function that takes as input a list of numbers, and returns
# the list of values given by the softmax function.
def softmax(L):
expL = np.exp(L)
sum_expL = sum(expL)
result = []
for i in expL:
result.append(i * 1.0/sum_expL)
print(result)
return result
L = [-1,0,1]
softmax(L)
# Note: The function np.divide can also be used here, as follows:
# def softmax(L):
# expL = np.exp(L)
# return np.divide (expL, expL.sum()) |
# -*- coding:UTF-8 -*-
#! /usr/bin/python3
# 赋值运算符
a = 1
print("初值:",a)
a += 3
print("加3:",a)
a -= 9
print("减9:",a)
a *= 8
print("乘8:",a)
a /= 2
print("除2:",a)
a //= 3
print("整除3:",a)
a **= 4
print("4次方:",a)
a %= 2
print("余2:",a)
|
# -*- coding:UTF-8 -*-
#! /usr/bin/python3
list_a = list(range(5,10))
it = iter(list_a)
print(next(it))
print(next(it))
for a in it:
print(a,end=' ')
del it
import sys
list_b = range(4)
it = iter(list_b)
while 1:
try:
print(next(it))
except StopIteration:
sys.exit()
|
# -*- coding:UTF-8 -*-
#! /usr/bin/python3
def dprint(str):
print(str)
# return
def fun_1(x):
x += 1
return x
def fun_2(x):
x = [x,[123,12,1]]
print('函数内a:', x)
return x
def fun_3(x):
x.append([1,2,3,4])
print('函数内a:',x)
return b
dprint("1") # return 存在与否尚无影响
a = 10
b = fun_1(a)
print('由于a属于不可变型,函数不会改变a的值',b,' ',a)
a = [10,11]
b = fun_2(a) # 输入变量未改变
print(b);print(a)
a = [10,11]
b = fun_3(a) # 输入变量已改变
print('函数外a:',a,'函数外b:',b) |
"""
T1 and T2 are two very large binary trees, with T1 much bigger than T2. Create an algorithm
to determine if T2 is a subTree of T1.
A tree T2 is a subtree of T1 if there exists a node n in T1 such that the substree of n
is identical to T2. That is, if you cut off the tree at node n, the two trees would be
identical.
"""
if __name__ == '__main__':
|
"""
There are three types of edits that can be performed on strings:
insert a character, remove a character, or replace a character.
Given two strings, write a function to check if they are one edit
(or zero edits) away.
EXAMPLE
pale, ple -> true
pales, pale -> true
pale, bale -> true
pale, bake -> false
"""
def isoneoperationaway(a, b):
l = max(len(a), len(b))
if a == b:
return True
if len(a) == len(b):
for i in range(l):
if a[i] != b[i]:
arrA = list(a)
arrB = list(b)
arrA[i] = arrB[i]
return arrA == arrB
else:
c = 0
for i in range(l):
if i < len(a):
c ^= ord(a[i])
if i < len(b):
c ^= ord(b[i])
return chr(c).isalpha()
if __name__ == '__main__':
print("isoneoperationaway 'le', 'pale' {0}".format(isoneoperationaway('le', 'pale')))
print("isoneoperationaway 'pale', 'ale' {0}".format(isoneoperationaway('pale', 'ale')))
print("isoneoperationaway 'pales', 'pale' {0}".format(isoneoperationaway('pales', 'pale')))
print("isoneoperationaway 'pale', 'bale' {0}".format(isoneoperationaway('pale', 'bale')))
print("isoneoperationaway 'pale', 'bake' {0}".format(isoneoperationaway('pale', 'bake')))
print("... 'california', 'nevada' {0}".format(isoneoperationaway('california', 'nevada')))
print("... 'a', 'aaaaa' {0}".format(isoneoperationaway('a', 'aaaaa')))
print("... 'pale', 'pale' {0}".format(isoneoperationaway('pale', 'pale')))
|
"""
Given two strings, write a method to decide if one is a permutation of the other.
"""
def ispermutation(a, b):
i = 0
j = 0
for c in a:
i += ord(c)
for c in b:
j += ord(c)
return i == j and len(a) == len(b)
if __name__ == '__main__':
print("Is Permutation: aab, baa {0}".format(ispermutation('aab', 'baa')))
print("Is Permutation: aaa, ijk {0}".format(ispermutation('aaa', 'ijk')))
|
def findMax(arr):
do_pick = [0]*len(arr)
do_not_pick = [0]*len(arr)
do_pick[0] = arr[0]
#do_pick = 2
for i in range(1, len(arr)):
do_pick[i] = do_not_pick[i-1] + arr[i]
do_not_pick[i] = max(do_not_pick[i-1], do_pick[i-1])
return do_pick[-1]
if __name__ == '__main__':
arr = [3,2,3,2]
print(findMax(arr))
|
"""
Given a string, write a function to check if it is a permutation of a palindrome.
A palindrome is a word or phrase that is the same forwards and backwards. A
permutation is a rearrangement of letters. The palindrome does not need to be
limited to just dictionary words
EXAMPLE
Input: Tact Coa
Output True (permutations: "taco cat", "atco cta", etc.)
"""
def ispermutation(s):
map = {}
for c in s.lower().replace(' ', ''):
map[c] = map.get(c, 0) + 1
print(map)
numOfOddNum = 0
for key in map.keys():
if map[key]%2 == 1:
numOfOddNum += 1
if numOfOddNum > 1:
return False
return True
if __name__ == '__main__':
print('Is Palindrome Permutation: Tact Coa {0}'.format(ispermutation('Tact Coa')))
|
import RPi.GPIO as GPIO
import time
''' This is the initialization for GPIO stuff '''
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
''' This is the setup for every motor on the robot '''
GPIO.setup(17, GPIO.OUT)
motor_1 = GPIO.PWM(17, 50)
motor_1.start(3)
''' This is the code for the robot '''
while True:
duty_cycle = raw_input('Duty Cycle: ')
motor_1.ChangeDutyCycle(float(duty_cycle))
print 'Duty Cycle set to ', duty_cycle
|
import nltk
# 使用nltk工具对以下句子的词性标注
text = nltk.word_tokenize('the lawyer questioned the witness about the revolver')
str = nltk.pos_tag(text)
print("Answer 1 : ")
print(str)
print("\n------------------------------------------------\n")
print("Answer 2 : ")
# 测试答案
grammar = nltk.CFG.fromstring("""
S -> NP VP
VP -> VBD NP | VBD NP PP
PP -> IN NP
NP -> DT NN | DT NN PP
DT -> "the" | "a"
NN -> "boy" | "dog" | "rod"
VBD -> "saw"
IN -> "with"
""")
words = nltk.word_tokenize('the boy saw the dog with a rod')
tags = nltk.pos_tag(words)
rd_parser = nltk.RecursiveDescentParser(grammar)
for tree in rd_parser.parse(words):
print()
print(tree) |
def dict_to_arr(x):
import numpy as np
if isinstance(next(iter(x)), tuple):
n = max([i for (i, j) in x.keys()]) + 1
m = max([j for (i, j) in x.keys()]) + 1
y = np.zeros((n, m), dtype=int)
for i in range(n):
for j in range(m):
y[i, j] = x.get((i, j), -1)
else:
n = max([i for i in x.keys()]) + 1
y = np.zeros((n, 1), dtype=int)
for i in range(n):
y[i] = x.get(i, -1)
return y
def is_permutation(x, n=None):
''' is `x` a permutation of {0, 1, ..., `n` - 1}?'''
if n == None:
n = len(x)
elif len(x) != n:
return False
s = set(x)
if len(s) != n:
return False
for i in range(n):
if i not in s:
return False
return True
def generate_even_permutations(n):
if n == 1:
return [[0]]
ans = [x + [n - 1] for x in generate_even_permutations(n - 1)]
odd_perms = generate_odd_permutations(n - 1)
for perm in odd_perms:
for i in range(n - 1):
new_perm = perm + [perm[i]]
new_perm[i] = n - 1
ans.append(new_perm)
return ans
def generate_odd_permutations(n):
if n == 1:
return []
ans = [x + [n - 1] for x in generate_odd_permutations(n - 1)]
even_perms = generate_even_permutations(n - 1)
for perm in even_perms:
for i in range(n - 1):
new_perm = perm + [perm[i]]
new_perm[i] = n - 1
ans.append(new_perm)
return ans
def generate_all_permutations(n):
return generate_even_permutations(n) + generate_odd_permutations(n)
def combine_permutations(first_perm, second_perm):
assert is_permutation(first_perm)
assert is_permutation(second_perm)
assert len(first_perm) == len(second_perm)
n = len(first_perm)
perm = [0] * n
for i in range(n):
perm[i] = second_perm[first_perm[i]]
assert is_permutation(perm, n)
return perm
def permutation_of_permutations(permutations, perm):
n = len(permutations)
assert perm in permutations
perm_to_idx = {tuple(perm): i for i, perm in enumerate(permutations)}
ans = [-1] * n
for j in range(n):
perm_src = permutations[j]
perm_dest = combine_permutations(first_perm=perm, second_perm=perm_src)
ans[j] = perm_to_idx[tuple(perm_dest)]
assert is_permutation(ans, n)
return ans
|
class Solution:
def findMin(self, nums: List[int]) -> int:
return self.binarySearch(nums, 0, len(nums) - 1)
def binarySearch(self, nums, a, b):
if nums[a] <= nums[b]:
return nums[a]
mid = (a + b) // 2
if a < mid < b and nums[mid] < nums[mid - 1] and nums[mid] < nums[mid + 1]:
return nums[mid]
elif mid == b and nums[mid] < nums[mid - 1]:
return nums[mid]
if nums[mid] > nums[b]:
return self.binarySearch(nums, mid + 1, b)
return self.binarySearch(nums, a, mid - 1)
|
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
sign = 1
if x < 0:
sign = -1
x = abs(x)
rev = int(str(x)[::-1])
if rev > 2**31 - 1 or rev*sign < -2**31:
return 0
return rev * sign
|
class Solution:
def toLowerCase(self, string):
"""
:type str: str
:rtype: str
"""
ret = []
for c in string:
cascii = ord(c)
ret.append(chr(cascii + 32) if 65 <= cascii <= 95 else c)
return ''.join(ret)
# Python Easy Way
# class Solution:
# def toLowerCase(self, string):
# """
# :type str: str
# :rtype: str
# """
# return string.lower()
|
for x in list(range(0,100)):
output = ""
if(x % 3 == 0):
output += 'Fizz'
if(x % 5 == 0):
output += 'Buzz'
if(output == ""):
output += str(x)
print(output) |
def merge(A,B):
(C,m,n) = ([], len(A), len(B))
(i,j) = (0,0)
while i+j < m+n:
if i == m:
C.append(B[j])
j = j + 1
elif j == n:
C.append(A[i])
i = i + 1
elif A[i] <= B[j]:
C.append(A[i])
i = i + 1
elif A[i] > B[j]:
C.append(B[j])
j = j + 1
return(C)
def mergesort(A,left,right):
print(left, right)
if right - left <= 1:
return(A[left:right])
if right - left > 1:
mid = (left+right)//2
L = mergesort(A,left,mid)
R = mergesort(A,mid,right)
N = merge(L,R)
print(L, R, N)
return(N)
|
"""
A command-line controlled coffee maker.
"""
import sys
import load_recipes as rec
"""
Implement the coffee maker's commands. Interact with the user via stdin and print to stdout.
Requirements:
- use functions
- use __main__ code block
- access and modify dicts and/or lists
- use at least once some string formatting (e.g. functions such as strip(), lower(),
format()) and types of printing (e.g. "%s %s" % tuple(["a", "b"]) prints "a b"
- BONUS: read the coffee recipes from a file, put the file-handling code in another module
and import it (see the recipes/ folder)
There's a section in the lab with syntax and examples for each requirement.
Feel free to define more commands, other coffee types, more resources if you'd like and have time.
"""
"""
Tips:
* Start by showing a message to the user to enter a command, remove our initial messages
* Keep types of available coffees in a data structure such as a list or dict
e.g. a dict with coffee name as a key and another dict with resource mappings (resource:percent)
as value
"""
# Commands
EXIT = "exit"
LIST_COFFEES = "list"
MAKE_COFFEE = "make" #!!! when making coffee you must first check that you have enough resources!
HELP = "help"
REFILL = "refill"
RESOURCE_STATUS = "status"
commands = [EXIT, LIST_COFFEES, MAKE_COFFEE, REFILL, RESOURCE_STATUS, HELP]
# Coffee examples
ESPRESSO = "espresso"
AMERICANO = "americano"
CAPPUCCINO = "cappuccino"
# Resources examples
WATER = "water"
COFFEE = "coffee"
MILK = "milk"
# Coffee maker's resources - the values represent the fill percents
RESOURCES = {WATER: 100, COFFEE: 100, MILK: 100}
"""
Example result/interactions:
I'm a smart coffee maker
Enter command:
list
americano, cappuccino, espresso
Enter command:
status
water: 100%
coffee: 100%
milk: 100%
Enter command:
make
Which coffee?
espresso
Here's your espresso!
Enter command:
refill
Which resource? Type 'all' for refilling everything
water
water: 100%
coffee: 90%
milk: 100%
Enter command:
exit
"""
#print("I'm a simple coffee maker")
#print("Press enter")
#sys.stdin.readline()
#print("Teach me how to make coffee...please...")
def status():
print("water: " + RESOURCES[WATER].__str__() + "%")
print("coffee: " + RESOURCES[COFFEE].__str__() + "%")
print("milk: " + RESOURCES[MILK].__str__() + "%")
def refill():
print("Which resource?")
resource = sys.stdin.readline().strip()
if resource == WATER:
RESOURCES[WATER] = 100
elif resource == COFFEE:
RESOURCES[COFFEE] = 100
elif resource == MILK:
RESOURCES[MILK] = 100
elif resource == "all":
RESOURCES[WATER] = 100
RESOURCES[COFFEE] = 100
RESOURCES[MILK] = 100
print("water: " + RESOURCES[WATER].__str__() + "%")
print("coffee: " + RESOURCES[COFFEE].__str__() + "%")
print("milk: " + RESOURCES[MILK].__str__() + "%")
def make_coffee():
print("Which coffee?")
coffee_type = sys.stdin.readline().strip()
recipe = rec.get_recipes(coffee_type)
if coffee_type == "cappuccino":
if RESOURCES[WATER] >= 5:
RESOURCES[WATER] = RESOURCES[WATER] - int(recipe[0])
if RESOURCES[COFFEE] >= 10:
RESOURCES[COFFEE] = RESOURCES[COFFEE] - int(recipe[1])
if RESOURCES[MILK] >= 10:
RESOURCES[MILK] = RESOURCES[MILK] - int(recipe[2])
elif coffee_type == "espresso":
if RESOURCES[WATER] >= 5:
RESOURCES[WATER] = RESOURCES[WATER] - int(recipe[0])
if RESOURCES[COFFEE] >= 10:
RESOURCES[COFFEE] = RESOURCES[COFFEE] - int(recipe[1])
RESOURCES[MILK] = RESOURCES[MILK] - int(recipe[2])
elif coffee_type == "americano":
if RESOURCES[WATER] >= 10:
RESOURCES[WATER] = RESOURCES[WATER] - int(recipe[0])
if RESOURCES[COFFEE] >= 10:
RESOURCES[COFFEE] = RESOURCES[COFFEE] - int(recipe[1])
RESOURCES[MILK] = RESOURCES[MILK] - int(recipe[2])
print("Here is your {}!:)".format(coffee_type))
def list():
print("americano, {}, {}".format("cappuccino", "espresso"))
def main():
print("Enter command")
while 1:
read_input = sys.stdin.readline().strip()
if read_input == EXIT:
print("Have a nice day!:3")
break
elif read_input == RESOURCE_STATUS:
status()
elif read_input == REFILL:
refill()
elif read_input == LIST_COFFEES:
list()
elif read_input == HELP:
list()
elif read_input == MAKE_COFFEE:
make_coffee()
if __name__ == "__main__":
main()
|
class introduce:
def __init__(self, name, sex, height, weight):
self.name = name
self.sex = sex
self.height = height
self.weight = weight
def info(self):
print(f'이름:{self.name}')
print(f'성별:{self.sex}')
print(f'키:{self.height}')
print(f'몸무게:{self.weight}')
name1 = input('무슨 이름? : ')
sex1 = input('성별이 뭐야? : ')
height1 = input('키는 몇이야? : ')
weight1 = input('몸무게는 몇이야? : ')
introduce1 = introduce(name1, sex1, height1, weight1)
introduce1.info() |
# Given a string,write a function to check if it is a permutation of a palindrome
# Example :
# tact coa
# Output : true(permutations : 'taco cat','atco cta' etc)
class PalindromePerm:
def palindromePerm(self,str):
# Join string together
# str1 = str.replace(" ","")
str1 = "".join(str.split())
print(str1)
countAlphabet = {}
count=0
for char in str1:
if char in countAlphabet:
countAlphabet[char]+=1
else:
countAlphabet[char]=1
print(countAlphabet)
for k,v in countAlphabet.items():
if v%2!= 0:
count+=1
if count>1:
return False
return True
if __name__ == '__main__':
obj = PalindromePerm()
str = input('Enter the string to check : ')
print(obj.palindromePerm(str)) |
# Deep copy
print('Exemplo de DEEP COPY')
lista = [ 1, 2, 3 ]
nova = lista.copy()
nova.append(4)
print(lista)
print(nova)
# COPY
print('Exemplo de COPY')
lista2 = [ 3, 2, 1 ]
nova2 = lista2
nova2.append(0)
print(lista2)
print(nova2)
|
import pygame
grid = [[0 for x in range(3)] for y in range(3)] #Esta sentencia crea las 3 tuplas
for row in grid:
print(row)
print("\n")
grid[0][2]="X"
grid[0][0]="X"
grid[0][1]="X"
for item in grid:
print(item)
print("\n")
grid2 = [["X" for x in range(3)] for y in range(3)] #Esta sentencia crea las 3 tuplas
for item in grid2:
print(item)
print("\n")
"""def gamewin_check(grid1):
grid = [[[x][y] for x in range(3)] for y in range(3)] #Esta sentencia crea las 3 tuplas
for item in gamewinlist:
gamewinlist_1 = [grid1[item[0]],grid1[item[1]],grid1[item[2]]]
if gamewinlist_1 == ['X','X','X'] or gamewinlist_1 == ['O','O','O']:
gamewincheck = True
break
else:
gamewincheck = False
return gamewincheck
print(gamewin_check(grid))"""
|
import requests
from bs4 import BeautifulSoup
import csv
# sets up for scrape
scrape_soup = requests.get('https://en.wikipedia.org/wiki/List_of_United_States_cities_by_population')
info = BeautifulSoup(scrape_soup.text, 'html.parser')
#Finds the table containing all the information about Amecican cities
table_info = info.find('table', style="text-align:center")
print(len(table_info))
#this finds the table elements for cities
rows = table_info.findAll('tr')
#creates a writable csv file
with open('city_info.csv', 'w', newline='') as new_file:
csv_writer = csv.writer(new_file)
#header for the csv file
csv_writer.writerow(['rank', 'City', 'State', '2018 estimate', '2010 Census', 'Change', '2016 land area(mi)', '2016 land area(km^2)', '2016 population density(mi)', '2016 population density(km^2)', 'Location'])
for row in rows:
data = row.findAll('td')
datas = [i.text.strip( ) for i in data]
csv_writer.writerow(datas)
#this for loop goes into the different links and finds more
#information about the top 5 ranked cities
count = 1;
#loops through the top 5 cities and their hyperlinks
for x in range(1,6):
count_string = str(count)
city_name = rows[x].a
city_links =city_name['href']
# debuging
print(city_links)
find_gdp = requests.get('https://en.wikipedia.org'+city_links)
city_info = BeautifulSoup(find_gdp.text, 'html.parser')
#finds the table containing information about the city
city_table = city_info.find('table')
tables = city_table.findAll('tr')
# writes the information about the city into a seperate csv file
with open('city_info' +count_string+'.csv', 'w', newline='') as new_file:
csv_writer = csv.writer(new_file)
city = []
for table in tables:
get_th = table.findAll('th')
get_td = table.findAll('td')
get = [i.text.strip() for i in get_th]
city.append(get)
gets = [i.text.strip() for i in get_td]
city.append(gets)
csv_writer.writerow(city)
del city[:]
#debuging
print(count_string)
print(count)
count = count + 1
# can comment out all print statements. they are just used check if program is running
|
#Autor: Jose Heinz Moller Santos
#Descripción: Este programa es para calcular el IMC de las personas.
#calcular IMC:
def calcularElIMC(peso,estatura):
indiceMasa=peso/(estatura**2)
return indiceMasa
def main():
peso=float(input("Introduzca su peso en kg:"))
estatura=float(input("Introduzca su estatura en metros:"))
if peso or estatura <= 0:
print("ERROR")
print(" ")
IMC=float(calcularElIMC(peso,estatura))
if IMC<18.5:
print("Estas de bajo peso")
elif 25>=IMC>=18.5:
print("Estas normal")
elif IMC>25:
print("Visite medico, estas obeso")
main() |
number = int(input("пожалуйста,введите целое число число\n"))
max = 0
while number > 0:
box = number%10
number = number//10
if max < box:
max = box
print(f'наибольшая цифра в числе - {max}')
|
class counter:
c = 0
def __init__(self,n): int
self.c = n
cc = counter(2) : counter
print cc.c
|
"""=============================================================================
Ex3: Hypothesis testing
Câu 3: P-test và T-test
Cho 2 bộ dữ liệu phụ thuộc nhau như sau:
np.random.seed(11)
before = stats.norm.rvs(scale=30, loc=250, size=100)
after = before + stats.norm.rvs(scale=5, loc=-1.25, size=100)
a) Tạo dataframe chứa before, after, và change = after - before.
b) Áp dụng t-test để kiểm định H0: 'The mean are equal', với alpha = 0.05
============================================================================="""
import numpy as np
import pandas as pd
import scipy.stats as stats
print('=======================================================================')
print('*** a) Đọc dữ liệu. ***')
print('=======================================================================')
np.random.seed(11)
# Dữ liệu tại thời điểm t(i)
before = stats.norm.rvs(scale=30, loc=250, size=100)
# Dữ liệu tại thời điểm t(i+1)
after = before + stats.norm.rvs(scale=5, loc=-1.25, size=100)
df = pd.DataFrame({"before":before, "after":after, "change":after-before})
print(df.head())
print('Số liệu thống kê:\n', df.describe())
print('------------------------------------------')
print('Các giả thuyết kiểm định ')
print(' H0: Mean_1 = Mean_2 ')
print(' Ha: Mean_1 <> Mean_2 ')
print('------------------------------------------')
alpha = .05
confidence_level = 1 - alpha
t, p = stats.ttest_rel(df.before, df.after)
##------------------------------------------------------------------------------
print('\n**** Phương pháp CRITICAL VALUE (giá trị tới hạn)')
##------------------------------------------------------------------------------
df = len(df.before) - 1
critical = stats.t.ppf(confidence_level, df)
print(' - critical value = %.4f, statistic = %.4f' % (critical, t))
if (abs(t) >= critical):
print(' Bác bỏ H0 ==> Mean_1 <> Mean_2')
else:
print(' KHÔNG bác bỏ H0 ==> Mean_1 = Mean_2')
##------------------------------------------------------------------------------
print('\n**** Phương pháp TRỊ SỐ p (p-value) ----')
##------------------------------------------------------------------------------
print(' - alpha = %.2f, p = %.5f' % (alpha, p))
if (p <= alpha):
print(' Bác bỏ H0 ==> Mean_1 <> Mean_2')
else:
print(' KHÔNG bác bỏ H0 ==> Mean_1 = Mean_2')
|
# -*- coding: utf-8 -*-
"""=============================================================================
Ex5: SPARSE MATRIX
Câu 3:
a) Tạo ma trận thưa thớt ngẫu nhiên S(5,5) với mật độ density = 0.25
b) Chuyển S thành full matrix A
c) Tạo ma trận thưa thớt ngẫu nhiên S1(5,5) với mật độ density = 0.25
và item khác 0 sẽ bằng 1
d) Chuyển S1 thành full matrix A1
e) Trực quan hóa S, S1
============================================================================="""
import scipy.sparse as sparse
import scipy.stats as stats
import numpy as np
import matplotlib.pyplot as plt
## a) create sparse matrix with density 0.25
np.random.seed(42) # set random seed to repeat
S = sparse.random(5, 5, density = 0.25)
print(S)
## b) Convert the sparse matrix to a full matrix
A = S.toarray()
print("Sử dụng toarray: ", A)
plt.spy(S)
# create sparse matrix with density 0.25
# link: https://cmdlinetips.com/2019/02/how-to-create-random-sparse-matrix-of-specific-density/
""" Ngầm định, các giá trị sẽ được tạo theo uniform distribution trong [0, 1)
Tham số data_rvs dùng để chỉ định phân phối cho các giá trị được tạo ra
"""
""" Trường hợp 1: Chỉ lấy giá trị (nhị phân) trong tập hợp {0, 1}
"""
S1 = sparse.random(5, 5, density = 0.25, data_rvs = np.ones)
print(S1)
A1 = S1.toarray()
plt.spy(S1)
""" Trường hợp 2: Normal distribution
Mean = 3 và Standard deviation = 1
"""
rvs = stats.norm(loc = 3, scale = 1).rvs
S1 = sparse.random(5, 5, density = 0.25, data_rvs = rvs)
print("Normal distribution: ", S1)
A1 = S1.toarray()
plt.spy(S1)
""" Trường hợp 3: Poisson distribution
Mean = 10
"""
rvs = stats.poisson(15, loc = 10).rvs
S1 = sparse.random(5, 5, density = 0.25, data_rvs = rvs)
print("Poisson distribution: ", S1)
A1 = S1.toarray()
plt.spy(S1)
|
vowels = 'aeiou'
vowels += vowels.upper()
print(vowels)
for _ in range(5):
string = input('Enter a string: ')
for v in vowels:
string = string.replace(v, '')
print(string)
|
# range object iteration
total = 0
for i in range(0, 100):
print(i)
total += i
print('total:', total)
# list object iteration
fruits = ['apple', 'banana', 'grapes', 'orange']
for f in fruits:
print(f)
# double variable iteration
fruits = ['apple', 'banana', 'grapes', 'orange']
for index, fruit in enumerate(fruits):
print('index: {}\tfruit: {}'.format(index, fruit))
prices = {
'apple': 5,
'banana': 1,
'grapes': 3,
'orange': 2
}
for key, value in prices.items():
print('fruit: {}\tprice: {}'.format(key, value))
# anonymous for loop
for _ in range(5):
print('hello!')
# single-line
import random
nums = [random.randint(0, 10) for _ in range(10)]
print(nums)
unicode = {num: chr(num) for num in range(128)}
print(unicode)
|
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Brennan
#
# Created: 09/09/2015
# Copyright: (c) Brennan 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
def binsearch(InputListInt, search):
right = len(InputList)
left = 0
previous_centre = -1
if search < InputList[0]:
return -1
while 1:
centre = (left + right) / 2
candidate = InputList[centre]
if search == candidate:
return centre
if centre == previous_centre:
return - 2 - centre
elif search < candidate:
right = centre
else:
left = centre
previous_centre = centre
InputList = []
# Counter
x = 0
UserInput = raw_input("Enter a value (int)")
InputList.append(UserInput)
InputListInt = [int(f) if f.isdigit() else f for f in InputList]
InputListInt.sort()
x += 1
while x !=5:
UserInput = raw_input("Enter a value (int)")
InputList.append(UserInput)
InputListInt = [int(f) if f.isdigit() else f for f in InputList]
InputListInt.sort()
x += 1
print (InputListInt)
else:
search = raw_input("What number are you looking for?")
binsearch(InputList, search)
print binsearch(InputListInt, search)
|
#-------------------------------------------------------------------------------
# Name: Virtual Pet
# Purpose:
#
# Author: Brennan
#
# Created: 08/09/2015
# Copyright: (c) Brennan 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
class VirtualPet:
"""A class to simulate a virtual pet that you can play with
>>>VirtualPet()
VirtualPetType"""
def __init__(self):
"""Virtual Pet Constructor
define the attributes first"""
self.Name = "Poop"
self.LifeRemaining = 25
self.HowClean = 10
self.Fed = 10
self.Entertained = 10
self.Happiness = (self.LifeRemaining + self.HowClean + self.Fed + self.Entertained)
self.Alive = True
def setName(self, newName):
"""Gives the virtual pet a name
>>>setName("Felix")
Felix"""
self.Name = newName
def getName(self):
return self.Name
def toString(self):
info = "This pet is called " + self.Name + "and he has " + str(self.Fed) + " food points."
return info
def Feed(self, foodstuff, points):
"""A method to feed the Pet
>>>Feed("XL Bacon Double Cheese Burger", 10)
NoneType"""
self.Fed += points
return ("This pet has just eaten a dank "+ foodstuff)
def getFed(self):
return self.Fed
def getHappiness(self, Name):
self.Happiness = (self.LifeRemaining + self.HowClean + self.Fed + self.Entertained)
if self.Happiness > 50:
return ("I am very happy! :D:D:D:D:D:D:D")
elif self.Happiness > 35:
return ("Meh need more dank memes...")
elif self.Happiness > 10:
return ("TOO many damn pepes in the comment section... >:(")
else:
return (Name + " Has signed out.")
def isAlive(self):
if self.Happiness < 0:
self.Alive = False
|
#-------------------------------------------------------------------------------
# Name: Blackjack
# Purpose:
#
# Author: cnys
#
# Created: 09/09/2015
# Copyright: (c) cnys 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
from Deck import Deck
from Card import Card
from BlackJackHand import Hand
def main():
#make a temporary object
deck = Deck()
hand = Hand()
deck.shuffle()
#print deck.toString()
card1 = Card("","")
card1 = deck.drawNext()
hand.AddCard(card1)
print hand.toString()
card1 = deck.drawNext()
hand.AddCard(card1)
print hand.toString()
total = hand.totalValue()
print "Your hand is worth " + str(total)
if __name__ == '__main__':
main()
|
print("SUMA DE IMPARES EN UN RANGO DADO")
def rango1(): #funcion para el rango si en caso el usuario elije solo uno
d1 = int(input("Inicio de rango: "))
d2 = int(input("Fin de rango: "))
a = 0
for i in range(d1,d2+1):
if i%2 != 0: #este if verifica si el numero en i en el rango, es par o impar, osea divisible o no entre 2
a = a+i #variable que va guardando cada numero impar del rango
print("Suma de impares: ",a) #se imprime la variable a, con el dato final osea la suma de todos los impares que fue guardando
def rango1y2():
a = 0 #variable a que me ira guardando los impares del rango 1
b = 0 #variable b que me ira guardando los impares del rango 2
#AQUI SE PIDEN LOS RANGOS, DESDE EL PRIMER DATO AL ULTIMO DATO DE ESTOS SEGUN ELIJA EL USUARIO
d1 = int(input("Inicio de rango 1: "))
d2 = int(input("Fin de rango 1: "))
d3 = int(input("Inicio de rango 2: "))
d4 = int(input("Fin de rango 2: "))
for i in range(d1,d2+1): #for que verifica los datos del rango 1
if i%2 != 0:
a = a+i
print("Caso 1: ",a) #aqui se imprime sa suma de los impares del rango 1
for i in range(d3,d4+1): #for que verifica los datos del rango 2
if i%2 != 0:
b = b+i
print("Caso 2: ",b) #aqui se imprime la suma de los impares del rango 2
cp = int(input("Ingrese el numero de casos de prueba (Maximo 2) "))
while cp > 0: #mientras la opcion sea mayor a 0 sino, el programa acabara
if cp == 1:
rango1() #si la opcion es 1 llamo a la funcion del rango 1
cp = int(input("Ingrese el numero de casos de prueba (Maximo 2) "))
elif cp == 2:
rango1y2() # si es dos llamo a la funcion donde esta el rango 1 y 2
cp = int(input("Ingrese el numero de casos de prueba (Maximo 2) "))
elif cp >2:
print("MAXIMO 2 CASOS!")
cp = int(input("Ingrese el numero de casos de prueba (Maximo 2) "))
else:
break
|
# *** 5 || 15 dono se divisiable hai ya nahi ***
# num=int(input("enter a number"))
# if num%5==0 and num%15==0:
# print("number is divisible by 5 and 15")
# else:
# print(" number is not divisible by 5 and 15") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.