text stringlengths 37 1.41M |
|---|
# Program to return the sum of the numbers in the list
def sumList(nums):
count = 0
for i in nums:
count += i
return count
def main():
nums = [1, 2, 133]
print(sumList(nums))
main()
|
# c11ex05.py
# various list algorithms
def count(myList, x):
ans = 0
for item in myList:
if item == x:
ans = ans + 1
return ans
def isin(myList, x):
for item in myList:
if item == x:
return True
return False
def index(myList, x):
for i in range(len(myList)):
if myList[i] == x:
return i
# If not found, raise a value error
# an alternative would be to return -1
raise ValueError("x not in list")
def reverse(lst):
for i in range(len(lst)/2):
j = -(i+1)
lst[i], lst[j] = lst[j], lst[i]
def sort(lst):
# selection sort. See Chapter 13 for other examples.
for i in range(len(lst)-1):
# find min of remaining items
minpos = i
for j in range(i+1,len(lst)):
if lst[j] < lst[minpos]:
minpos = j
# swap min to front of remaining
lst[i], lst[minpos] = lst[minpos], lst[i]
|
# c13ex05.py
# recursive algorithm for base conversion
def baseConversion(num, base):
# PRE: num and base are integers with num >= 0 and base > 1
if num < base:
# base case is left most digit
print(num, end=' ')
else:
#remove last digit, recurse and then print last digit
lastDigit = num % base
baseConversion(num//base, base)
print(lastDigit, end=' ')
def main():
print()
print("Let's convert from base ten to another base.")
print()
n = int(input("What base ten integer shall we convert? (>=0 please) "))
b = int(input("To what base? (>=2 please) "))
print()
print("The digits of the new representation are:")
baseConversion(n,b)
print()
print()
main()
|
def fibo():
n = int(input("Enter a positive integer: "))
total = 0
i = 0
while i <= n:
if i % 2 != 0:
total += i
i += 1
print(total + 2 * n - 1)
fibo()
|
# c08ex11.py
# heating/colling degree-days
def main():
print("Heating and Cooling degree-day calculation.\n")
heating = 0.0
cooling = 0.0
tempStr = input("Enter an average daily temperature: ")
while tempStr != "":
temp = float(tempStr)
heating = heating + max(0, 60-temp)
cooling = cooling + max(0, temp-80)
tempStr = input("Enter an average daily temperature: ")
print("\nTotal heating degree-days", heating)
print("Total cooling degree-days", cooling)
if __name__ == '__main__':
main()
|
# c06ex08.py
# square roots
def nextGuess(guess, x):
return (guess + x/guess) / 2.0
def sqrRoot(x, iters):
guess = x / 2.0
for i in range(iters):
guess = nextGuess(guess, x)
return guess
def main():
x = float(input("Enter the value to take the root of: "))
n = int(input("Enter the number of iterations: "))
print("Square root is", sqrRoot(x, n))
main()
|
# c07ex12.py
# Date validator
from c07ex11 import isLeap
DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def isValidDate(month, day, year):
if 1 <= month <=12:
# month OK, check day
# determine last day of month
if month == 2:
if isLeap(year):
lastDay = 29
else:
lastDay = 28
else:
lastDay = DAYS_IN_MONTH[month]
# if day is also good, return True
if 1 <= day <= lastDay:
return True
# did not validate
return False
def main():
print("Date Validator\n")
month, day, year = input("Enter a date (mm/dd/yyyy): ").split("/")
if isValidDate(int(month), int(day), int(year)):
print("The date is valid.")
else:
print("The date is invalid.")
if __name__ == '__main__':
main()
|
# c11ex02.py
# A program to sort student information into GPA order.
from gpa import Student, makeStudent
def readStudents(filename):
infile = open(filename, 'r')
students = []
for line in infile:
students.append(makeStudent(line))
infile.close()
return students
def writeStudents(students, filename):
outfile = open(filename, 'w')
for s in students:
print("{0}\t{1}\t{2}".format(s.getName(), s.getHours(), s.getQPoints()),
file=outfile)
outfile.close()
def main():
print("This program sorts student grade information")
filename = input("Enter the name of the data file: ")
data = readStudents(filename)
sortBy = input("Enter field to sort on (gpa, name, or credits): ")
choice = sortBy[0].lower()
if choice == 'n':
print("Sorting by name.")
data.sort(key=Student.getName)
elif choice == 'c':
print("Sorting by credits hours")
data.sort(key=Student.getHours)
else:
print("Sorting by GPA.")
data.sort(key=Student.gpa)
filename = input("Enter a name for the output file: ")
writeStudents(data, filename)
print("The data has been written to", filename)
if __name__ == '__main__':
main()
|
# c13ex03.py
# A recursive palindrome checker
#
def isPalindrome(s):
# The base case
if len(s) < 2:
return True
elif not s[0].isalpha():
# ignore s[0] if non-letter
return isPalindrome(s[1:])
elif not s[-1].isalpha():
# ignore s[-1] if non-letter
return isPalindrome(s[:-1])
elif s[0].lower() != s[-1].lower():
#false if 1st and last don't match
return False
else:
# if first and last match then delete 1st and last
# and test middle section
return isPalindrome(s[1:-1])
def main():
print()
print(" Let's test a string to see if it is a palindrome.")
print(" I'll ignore spaces, punctuation and case differences.")
print()
theString = input("Enter a string to test: ")
print()
if isPalindrome(theString):
print("That IS a palindrome.")
else:
print("That is NOT a palindrome.")
print()
main()
|
# c13ex06.py
# digits in english
# global list of words
engDig = ["Zero","One","Two","Three","Four","Five",
"Six","Seven","Eight","Nine"]
def digitsToWords(num):
# base case is left most digit
if num < 10:
print(engDig[num], end=' ')
else:
currentDigit = num % 10
digitsToWords(num//10)
print(engDig[currentDigit], end=' ')
def main():
print()
print("Let's write out the digits of a number in words")
print()
x = int(input("Enter a positive integer: "))
print()
print("The digits of",x,"are:")
digitsToWords(x)
print()
print()
main()
|
import math
hydrogen = float(input("Enter the number of hydrogen atoms: "))
carbon = float(input("Enter the number of carbon atoms: "))
oxygen = float(input("Enter the number of oxygen atoms: "))
hydrogen = 1.00794 * hydrogen
carbon = 12.0107 * carbon
oxygen = 15.9994 * oxygen
print("The molecular weight of this comopund is: ", hydrogen + carbon + oxygen, "grams per mole")
|
# c10ex10.py
# Cube class
class Cube:
def __init__(self, side):
self.side = side
def getSide(self):
return self.side
def surfaceArea(self):
return 6 * self.side ** 2
def volume(self):
return self.side ** 3
def main():
print("This program computes the volume and surface area of a cube.\n")
r = float(input("Please enter the length of the cube's side: "))
myCube = Cube(r)
print("The surface area is", myCube.surfaceArea(), "square units.")
print("The volume is", myCube.volume(), "cubic units.")
if __name__ == '__main__':
main()
input("\nPress <Enter> to quit.")
|
import math
diameter = float(input("Enter the diameter of your pizza: "))
price = float(input("Enter the price of your pizza: "))
def areaOfPizza(diameter):
return math.pi * (diameter/2)**2
def costSquareInch(diameter, price):
return price / areaOfPizza(diameter)
def main():
print("The area of the pizza is %0.4f" % (areaOfPizza(diameter)))
print("The cost of square unit of pizza is %0.4f" % (costSquareInch(diameter, price)))
input("Press enter to quit")
main()
|
# c04ex09.py
# creates a rectangle
from graphics import *
import math
def main():
win = GraphWin("Rectangle!",500,500)
win.setCoords(0,0,10,10)
msg = Text(Point(5,1),"Click opposite corners of a rectangle").draw(win)
p1 = win.getMouse()
p1.draw(win)
p2 = win.getMouse()
rect = Rectangle(p1,p2)
rect.setWidth(2)
rect.draw(win)
length = abs(p2.getX()- p1.getX())
height = abs(p2.getY()- p1.getY())
area = length * height
perimeter = 2 * (length + height)
msg.setText("The perimeter is "+str(perimeter))
Text(Point(5,.5),"The area is "+str(area)).draw(win)
win.getMouse()
win.close()
main()
|
# c05ex07.py
# Caesar cipher (non-circular)
def main():
print("Caesar cipher")
print()
key = int(input("Enter the key value: "))
plain = input("Enter the phrase to encode: ")
cipher = ""
for letter in plain:
cipher = cipher + chr(ord(letter) + key)
print("Encoded message follows:")
print(cipher)
main()
|
#Given February 16, 2020
#Suppose an arithmetic expression is given as a binary tree.
#Each leaf is an integer and each internal node is one of '+', '−', '∗', or '/'.
#Given the root to such a tree, write a function to evaluate it.
#For example, given the following tree:
# *
# / \
# + +
# / \ / \
#3 2 4 5
#You should return 45, as it is (3 + 2) * (4 + 5).
#ArithmeticExpression is a tree containing an arithmetic expression
class ArithmeticExpression:
def __init__(self, value : str, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __str__(self):
def parse(node):
if node.isLeaf():
return node.value
else:
return '(' + parse(node.left) + ' ' + node.value + ' ' + parse(node.right) + ')'
#this string slice allows us to get rid of the outermost set of parentheses
return parse(self)[1:-1]
#this makes the base case less verbose
def isLeaf(self):
#leaf nodes are defined as numbers...
return self.left == None and self.right == None
#these two helpers helps us make trees without creating really long expressions
def attachLeftChild(self, node):
self.left = node
def attachRightChild(self, node):
self.right = node
if __name__ == '__main__':
#this allows us to use AE as another name for ArithmeticExpression since otherwise, it would be too long to use...
AE = ArithmeticExpression
a = AE('+', AE('2'), AE('3'))
print(a, '| 2 + 3')
b = AE('+')
b.attachLeftChild(AE('+', AE('2'), AE('7')))
b.attachRightChild(AE('5'))
print(b, '| (2 + 7) + 5')
c = AE('*', AE('7'))
c.attachRightChild(AE('/', AE('-', AE('*', AE('5'), AE('9')), AE('3')), AE('*', AE('8'), AE('7'))))
print(c, '| 7 * (((5 * 9) - 3) / (8 * 7))')
|
import random
import math
def remove(newrow,keep,discard):
vertex = newrow[0]
i =1
while(i<len(newrow)):
if((newrow[i] == keep)|(newrow[i] == discard)):
del(newrow[i])
else:
i=i+1
def replace(row2,replace_var):
delete_var = row2[0]
numofneigh = len(row2)
rows = len(arr)
k=1
i=0
j=0
while((k < numofneigh)&(i<rows)):
if(arr[i][0] == row2[k]):
#to avoid self loop
if(arr[i][0] == replace_var):
z = arr[i]
m = 1
while(m<len(z)):
if(z[m] == delete_var):
del(z[m])
else:
m = m+1
arr[i] = z
else:
z = arr[i]
m = 1
while(m<len(z)):
if(z[m] == delete_var):
z[m] = replace_var
break
else:
m = m+1
arr[i] = z
k = k+1
i = 0
else:
i = i+1
def contract(x,y):
row1 = arr[x]
row2 = arr[y]
#print("merging row %d into row %d" %(row2[0],row1[0]))
#print("combined row is")
newrow = row1 + row2
#print(newrow)
remove(newrow,row1[0],row2[0])
#print("new row after deleting %d" %row2[0])
#print(newrow)
if(x>y):
del(arr[y])
del(arr[x-1])
else:
del(arr[x])
del(arr[y-1])
arr.append(newrow)
#print("new array without removing neigh")
#print(arr)
replace(row2,row1[0])
#arr = [[1,2,3,4,5],[2,1,4,5],[3,1,4,6],[4,3,1,2,5,6],[5,2,4,1],[6,3,4]];
with open("kargerMinCut.txt","r") as f:
arr = [map(int,line.split()) for line in f ]
n = len(arr)
print n
n1 = int(math.ceil(n * n * math.log(n)))
print n1
n2 = 4
#print (arr)
mincut = n
while(n1 > 0):
#print("value of n1 is %d" %n1)
#arr = [[1,2,3,4,5],[2,1,4,5],[3,1,4,6],[4,3,1,2,5,6],[5,2,4,1],[6,3,4]];
with open("kargerMinCut.txt","r") as f:
arr = [map(int,line.split()) for line in f ]
n = len(arr)
while(n>2):
q = random.sample(range(0,n-1),1)
q1 = q[0]
#print ("value of first row %d " %q1)
w = arr[q1]
row = w[1:]
#print row
r = random.sample(row,1)
i = 0
while(i<n):
if(arr[i][0] == r[0]):
r1 = i
break
else:
i = i+1
#print r1
#print ("sending the index %d and %d" %(q1,r1))
contract(q1,r1)
#print(arr)
n = n-1
mincut1 = len(arr[0])-1
print ("mincut1 is %d" %mincut1)
if(mincut1<mincut):
mincut = mincut1
print("mincut is changed to %d" %mincut)
#print("Done")
n1 = n1-1
print("mincut is %d" %mincut)
|
def lb_to_kg(input1):
output=[]
print("Weight in Lb's:",input1)
for i in range(0,len(input1)):
i = round(input1[i]*(0.453592),2)
output.append(i)
return output
def string_alternative(input2):
x=[]
y=''
for i in input2:
x.append(i)
for i in range (0,len(x)):
if i%2 ==0:
y+=x[i]
return(y)
def file_prog():
file1= open("input_file.txt","r")
file2 = open("output_file.txt", "w")
if file1.mode =="r":
sentence = file1.read()
words=sentence.split("\n")
k=[]
for i in words:
z=[]
z=i.split()
for j in z:
k.append(j)
final_list=[]
for i in k:
counter1 = 0
for j in k :
if i.lower() == j.lower() and i not in final_list :
counter1+=1
if i not in final_list:
final_list.append(i)
if i in final_list and counter1 !=0:
r=str(i)+":"+str(counter1)
file2.write(r)
file2.write("\n")
if __name__ == "__main__" :
lines = []
while True:
line = input("enter weight in lbs: ")
if line:
lines.append(float(line))
else:
break
result1 = lb_to_kg(lines)
print("Weight in kg's:",result1)
input2=input("enter string: ")
result2 = string_alternative(input2)
print("Output string:",result2)
file_prog()
|
'''
Dynamic Programming(Tabularization)
There are N stairs, and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top (order does not matter).
Note:
Order does not matter means for n = 4 {1 2 1},{2 1 1},{1 1 2} are considered same.
Example 1:
Input: N = 4
Output: 3
Explanation: Three ways to reach at 4th stair.
They are {1, 1, 1, 1}, {1, 1, 2}, {2, 2}.
Example 2:
Input: N = 5
Output: 3
Explanation: Three ways to reach at 5th stair.
They are {1, 1, 1, 1, 1}, {1, 1, 2, 1} and
{1, 2, 2}.
Your Task:
You don't need to read or print anyhting. Your task is to complete the function nthStair() which takes N as input parameter and returns the total number of ways to reach at Nth stair.
Expected Time Complexity: O(N)
Expected Space Complexity: O(N)
Constraints:
1 <= N <= 1000000
'''
# Time complexity O(N2), sapce complexityO(N)
class Solution:
def nthStair(self,n):
dp = [0 for i in range(n+1)]
for i in range(1,3):
for j in range(1,n+1):
if dp[j]==0:
dp[j]+=1
continue
if j-i<0:
continue
dp[j]=max(dp[j-i],dp[j])+1
return dp[-1]
|
def reverse(S):
#Add code here
st=[]
for i in S:
st.insert(0,i)
ans = ""
for i in st:
ans+=i
return ans
|
# 당신은 택시기사이고, 어플로 손님을 매칭할 수 있다.
#50명의 승객과 매칭 기회가 있다. 이때 총 탑승 승객 수를 구하는 프로그램을 작성하시오.
#조건1: 승객별 운행 소요 시간은 5분~50분 사이의 난수로 정해진다.
#조건2: 당신은 소요 시간이 5분~15분 사이의 손님만 태울수 있다
from random import *
customers = range(1,51)
customers = list(customers)
num = 0
count = 0
for info in range(50):
minute = randrange(5,51)
num += 1
if 5 <= minute <= 15:
print("[O]"+str(num)+"번째 손님 (소요시간: "+str(minute)+")")
count += 1
else:
print("[ ]"+str(num)+"번째 손님 (소요시간: "+str(minute)+")")
print("총 탑승 승객: "+str(count)+"명")
|
// Calculate Factorial Example
number = int(input("Number : "))
factorial = 1
if number<0:
print("The factorial of negative numbers cannot be calculated.")
elif number == 0:
print("Result : 1")
else:
for i in range(1,number+1):
factorial = factorial * i
print("Result : ", factorial) |
'''
| Write a program that replaces all vowels in the with ‘* |
|---------------------------------------------------------|
| Using re module. |
'''
import re
string = input("Enter the string\n")
print(re.sub('[aeiouAEIOU]','*',string))
|
'''
| Write a program to read two strings and perform concatenation and comparison operations on it |
|-----------------------------------------------------------------------------------------------|
| We use the input() function to receive input from the user and print() function to print it |
'''
f1 = input("String 1\n")
f2 = input("String 2\n")
print(f1+f2)
|
"""
|-------------------------------------------|
| Problem 3:⦁ Write a program to find the |
| largest of three numbers |
|-------------------------------------------|
| Approach: |
| We use the max() function |
|-------------------------------------------|
"""
a = int(input("Number 1: \n"))
b = int(input("Number 2: \n"))
c = int(input("Number 3: \n"))
res = max([a,b,c])
print(f"The highest is {res}")
|
"""
|-------------------------------------------|
| Problem 4: Write a program to find whether|
| the year is a leap year or not. |
|-------------------------------------------|
| Approach: |
| First, check if the year is divisible by |
| 100. If so, check is the year is |
| divisible by 400. If not, simple division |
| by 4 is done |
|-------------------------------------------|
"""
year = int(input("Enter year: "))
print("Is the year leap?")
if year%100 == 0:
print(year%400 == 0)
else:
print(year%4 == 0)
|
"""
|-------------------------------------------|
| Problem 3:⦁ Write a program to find the |
| largest of three numbers |
|-------------------------------------------|
| Approach: |
| We use the max() function |
|-------------------------------------------|
"""
a = int(input("Number 1: \n"))
b = int(input("Number 2: \n"))
c = int(input("Number 3: \n"))
max = c
if (a > b and a > c):
max = a
elif (b > a and b > c):
max = b
print("The largest number is:", max) |
#!/usr/bin/python3
############################################################################################################################
#
#
# To Find the number of Characters, Words and Lines in test.txt as input file, and storing output in output.txt
#
#
##############################################################################################################################
#function to calculate the no of character
def no_of_characters():
global char_no
char_no=len(data)
#function to calculate the no of words
def no_of_words():
global word_no
word_no=len(data.split())
#function to calculate the no of lines
def no_of_lines():
global line_no
line_no=len(data.split('\n'))
def main():
global data
# Opening the file 'test.txt' in read mode(default)
with open("test.txt") as file:
#storing the contents of the file in 'data'
data = file.read()
no_of_characters()
no_of_words()
no_of_lines()
# Opening the file 'output.txt' in write mode(default)
print ("Characters:",char_no,"\nWords:",word_no,"\nLines:",line_no)
#initializing golbal variables to dummy values
data='temp'
char_no=0
word_no=0
line_no=0
main()
|
########################################################
#
# Program to perform CRUD operation on a table named
# "registration" in the database "student"
#
#######################################################
import mysql.connector
from mysql.connector import Error
import logging
# create the logging object
logging.basicConfig(level=logging.WARNING)
logger=logging.getLogger()
def connect():
''' To connect to the database '''
# conn to the database
conn = mysql.connector.connect(host='localhost',
database='student',
user='root',
password='wireless')
if conn.is_connected():
print('Connected to database')
# ask user for a choice of operations
choice=int(input("Enter your choice:\n1.Create\n2.Retrive\n3.Update\n4.Insert\n5.Delete\n6.Exit: "))
while(1):
if choice==1:
create(conn)
elif choice==2:
retrieve(conn)
elif choice==3:
update(conn)
elif choice==4:
insert(conn)
elif choice==5:
delete(conn)
else:
conn.close()
break
choice=int(input("\nEnter your choice:\n1.Create\n2.Retrive\n3.Update\n4.Insert\n5.Delete: "))
def retrieve(conn):
''' To get all the details in the table '''
#get the cursor object from the conn object
cursor=conn.cursor()
# create the query
query="select * from registration"
# execute the query and print
cursor.execute(query)
print (cursor.fetchall())
def update(conn):
''' To update the values in the table '''
# get the cursor object
cursor=conn.cursor()
# Ask the user for the Reg No whose data is to be changed
# and the changes to be made
choice='y'
while(choice=='y'):
reg_no=input("Enter reg.no whose value is to be updated: ")
value_to_be_updated=input("Enter the value to be updated , Fname,Lname or DOB")
new_value=input("Enter the new value")
# write the query as per the values as given by the user
if value_to_be_updated=='Fname':
query='update registration set Fname = %s where Reg_no= %s'
elif value_to_be_updated=="Lname":
query='update registration set Lname = %s where Reg_no= %s'
elif value_to_be_updated=="DOB":
query='update registration set DOB = %s where Reg_no= %s'
else:
print("\nYou have entred an invalid option\n")
args=(new_value,reg_no)
logger.info(query%args)
# execute the query and commit it
try:
cursor.execute(query,args)
conn.commit()
print ("\nValues updated")
choice=input("\nUpdate more values? y: ")
except Error as e:
print (e)
def delete(conn):
''' To delete the table '''
# get the cursor object
cursor=conn.cursor()
# write a query to delete the table
query="drop table registration"
logger.info(query)
# execute the query and commit it
try:
cursor=conn.cursor()
logger.debug("1")
cursor.execute(query)
conn.commit()
print("\nTable deleted\n")
except Error as e:
print (e)
finally:
cursor.close()
#conn.close()
def insert(conn):
''' To insert the values '''
# get the cursor object
cursor=conn.cursor()
# get the details of values to be added from the user
choice='y'
while(choice=='y'):
reg_no,fname,lname,dob=input("Enter Reg-no, fname, lname and dob: ").split()
try:
# write a query based on the values given by the user
query="insert into registration values(%s,%s,%s,%s)"
args=(reg_no,fname,lname,dob)
cursor.execute(query,args)
conn.commit()
print ("\nValues inserted\n")
choice=input("Add more values? y: ")
except Error as e:
print (e)
def create(conn):
''' Create the table '''
try:
# write the query
query="create table registration (Reg_no varchar(10),Fname varchar(10),Lname varchar(20),DOB varchar(20), PRIMARY KEY(Reg_no))"
logger.info(query)
# execute and commit the changes
cursor=conn.cursor()
cursor.execute(query)
print("Table created")
conn.commit()
except Error as e:
print (e)
finally:
cursor.close()
#conn.close()
connect() |
def main():
print("Enter the no")
numb=list(input())
# checking whether the input is a whole number
assert int(''.join(numb))>-1, 'Enter positive number'
sum=0
for i in numb:
sum=sum+pow((int(i)),len(numb))
if sum== int(''.join(numb)):
print ("Armstrong number")
else:
print ("Non Armstrong number")
main()
|
import sqlite3
connection = sqlite3.connect("addressbook.db")
print("Database opened successfully")
cursor = connection.cursor()
#delete
cursor.execute('''DROP TABLE Address;''')
connection.execute("create table Address (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT UNIQUE NOT NULL, address TEXT NOT NULL)")
print("Table created successfully")
connection.close()
|
from tkinter import *
master = Tk()
x = Entry()
x.pack(pady=10,padx=10)
x.insert(END, "a default value!")
def ok():
t = x.get()
print(t.capitalize())
def delt():
x.delete(0, END)
b = Button(master, text="ok", command=ok)
c = Button(master, text="delete", fg="red", command=delt)
b.pack()
c.pack()
master.mainloop() |
#-*- coding: utf-8 -*-
from collections import namedtuple
from collections import defaultdict
Grade = namedtuple('Grades',('score', 'weight'))
def fake():
pass
class Subject(object):
def __init__(self):
self._grade = []
self.count = 0
def Gen(self):
self.count += 1
return self.count
def Clear(self):
self.count = 0
def report_grade(self, score, weight):
index = (self.Gen(),) # Auto index tuple
tuples = Grade(score, weight) + index
self._grade.append(tuples)
def grade_recorder(self):
total, total_weight = 0, 0
for score, weight, _ in self._grade:
total += score * weight
total_weight += weight
return [total / total_weight, total_weight]
def Test(self):
self.grade = self._grade
print(self.grade)
class Year(object):
def __init__(self):
self._subjects = {}
def subject(self, name):
if name not in self._subjects:
print('Insert %s is complete!' % name)
self._subjects[name] = Subject() # All values in self._subjects are Subject class!
return self._subjects[name]
def average_grade(self):
Fscore, Ftotal_weight = 0, 0
for subject in self._subjects.values():
Fscore += subject.grade_recorder()[0] * subject.grade_recorder()[1]
Ftotal_weight += subject.grade_recorder()[1]
return Fscore / Ftotal_weight
def weight_input(weight):
if len(weight) == 3:
return weight
else:
raise ValueError()
class UniV(object):
def __init__(self):
self._years = {}
def year(self, level):
if level not in self._years:
print('Insert %s is complete!' % level)
self._years[level] = Year() # All values in self._years are Year class!
return self._years[level]
def average_grade(self, weight):
total = 0
for i, year in enumerate(self._years.values()):
total += year.average_grade() * weight[i]
return total / sum(weight) |
from datetime import datetime
from model.Despesa import Despesa
from linkedList.LinkedList import LinkedList
import locale
import time
import os
class TelaDespesas:
# Criando método para padronizar os dados em moeda real:
locale.setlocale(locale.LC_MONETARY, "pt_BR.UTF-8")
def __init__(self):
listaDespesa = LinkedList()
# Criando médoto para operacionalizar a lista encadeada:
def render(self, lista=LinkedList(), idsLista=0):
idDespesas = idsLista
# Opções do módulo das despesas financeiras:
opDespesas = "0"
while opDespesas != "4":
os.system("cls")
TelaDespesas.headerDespesas()
self.listar(lista)
TelaDespesas.menuDespesas()
TelaDespesas.footerDespesas()
opDespesas = input(" Digite uma opção (1..4): ")
# Opção para inserir dados na lista encadeada:
if opDespesas == "1":
valor, id = self.adicionarDados(idDespesas)
idDespesas = id
print(" Despesa cadastrada com sucesso!")
print()
lista.append(valor)
time.sleep(1)
os.system("cls")
TelaDespesas.headerDespesas()
self.listar(lista)
TelaDespesas.menuDespesas()
TelaDespesas.footerDespesas()
# Opção para remover dados da lista encadeada:
if opDespesas == "2":
print()
valor = int(input(" Digite o código a ser excluído: "))
resultado = self.deleteItem(lista, valor)
lista.remove(resultado)
os.system("cls")
TelaDespesas.headerDespesas()
self.listar(lista)
TelaDespesas.menuDespesas()
TelaDespesas.footerDespesas()
# Opções para gerar arquivo em PDF a partir dos dados da lista encadeda:
if opDespesas == "3":
print(" Gerar pdf...")
return lista, idDespesas
# Criando método para consultar dados da lista encadeada:
def listar(self, lista):
totalDespesas = 0
for item in lista:
if isinstance(item, Despesa):
val = locale.currency(item.getValor(), grouping=True)
print(" | |" + '\033[31m' + '{:^4}'.format(item.getId()) + '\x1b[0m' +
" | " + '\033[31m' + '{:<30}'.format(item.getNome()) + '\x1b[0m' +
" | " + '\033[31m' + '{:<20}'.format(item.getTipo()) + '\x1b[0m' +
" | " + '\033[31m' + '{:^10}'.format(str(item.getData())) + '\x1b[0m' +
" | " + '\033[31m' + '{:>19}'.format(val) + '\x1b[0m' + " | |")
print(" | +" + "-" * 5 +
"+" + "-" * 32 +
"+" + "-" * 22 +
"+" + "-" * 12 +
"+" + "-" * 21 + "+ |")
totalDespesas = totalDespesas + item.getValor()
print(" |" + " " * 70 + "TOTAL: " + '{:>20}'.format(locale.currency(totalDespesas, grouping=True)) + " |")
# Criando método para inserir dados na lista encadeada:
def adicionarDados(self, size):
id = size + 1
despesaObj = Despesa()
despesaObj.setId(id)
print()
despesaObj.setNome(input(" Despesa: "))
despesaObj.setTipo(input(" Tipo de despesa: "))
despesaObj.setValor(float(input(" Valor: ")))
despesaObj.setData(input(" Data (dd/mm/yyyy): "))
return despesaObj, id
# Criando método para remover dados da lista encadeada:
def deleteItem(self, lista, valor):
for item in lista:
if isinstance(item, Despesa):
if item.getId() == valor:
return item
# Criando método estático para o cabeçalho:
@staticmethod
def headerDespesas():
print()
print(" +" + "-" * 100 + "+")
print(" |" + '{:^100}'.format(" Controle Financeiro ") + "|")
print(" +" + "-" * 100 + "+")
print(" +" + '{:-^100}'.format(" Despesas ") + "+")
print(" |" + " " * 100 + "|")
print(" | +" + "-" * 5 +
"+" + "-" * 32 +
"+" + "-" * 22 +
"+" + "-" * 12 +
"+" + "-" * 21 + "+ |")
print(" | |" + '\033[31m' + '{:^4}'.format("ID") + '\x1b[0m' +
" | " + '\033[31m' + '{:^30}'.format("DESPESA") + '\x1b[0m' +
" | " + '\033[31m' + '{:^20}'.format("TIPO DE DESPESA") + '\x1b[0m' +
" | " + '\033[31m' + '{:^10}'.format("DATA") + '\x1b[0m' +
" | " + '\033[31m' + '{:^20}'.format("VALOR") + '\x1b[0m' + "| |")
print(" | +" + "-" * 5 +
"+" + "-" * 32 +
"+" + "-" * 22 +
"+" + "-" * 12 +
"+" + "-" * 21 + "+ |")
# Criando método estático para o menu:
@staticmethod
def menuDespesas():
print(" |" + " " * 100 + "|")
print(" |" + '{:^100}'.format("(1) Inserir (2) Excluir (3) Gerar PDF (4) Voltar") + "|")
print(" |" + " " * 100 + "|")
print(" +" + "-" * 100 + "+")
# Criando método estático para o rodapé:
@staticmethod
def footerDespesas():
print(" +" + "-" * 100 + "+")
data = datetime.now()
print(" |" + '{:^100}'.format("Aracaju (SE), " + str(data.strftime('%d/%m/%Y %H:%M'))) + "|")
print(" +" + "-" * 100 + "+")
|
import time
# Reference: https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/
# Reference: https://www.geeksforgeeks.org/kruskals-minimum-spanning-tree-algorithm-greedy-algo-2/
# class for Prim's algorithm
class PrimGraph:
def __init__(self, vertices):
self.vertices = vertices
self.graph = [[0 for col in range(vertices)] for row in range(vertices)]
# finds the vertex with minimum distance value from the set of vertices not included in the MST
def find_min_key(self, key, mst):
min = float("inf")
min_index = 0
for v in range(self.vertices):
if key[v] < min and mst[v] is False:
min = key[v]
min_index = v
return min_index
# function used to construct and print the MST using Prim's algorithm
def Prim(self):
key = [float("inf")] * self.vertices # set values of all vertices to infinity
parent = [None] * self.vertices # list to store the MST
key[0] = 0 # initialize vertex to 0 to start the algorithm
mst = [False] * self.vertices # boolean array
parent[0] = -1
# find the minimum key and add the corresponding endpoint to the mst set
for v in range(self.vertices):
u = self.find_min_key(key, mst)
mst[u] = True
for w in range(self.vertices):
if 0 < self.graph[u][w] < key[w] and mst[w] is False:
key[w] = self.graph[u][w]
parent[w] = u
# print the constructed mst
print("Edge\t\tWeight")
for i in range(1, self.vertices):
print(parent[i], " - ", i, "\t", self.graph[i][parent[i]])
# class for Kruskal's algorithm
class KruskalGraph:
def __init__(self, vertices):
self.vertices = vertices
self.graph = []
# add edge to the graph
def add_edge(self, u, v, w):
self.graph.append([u, v, w])
# find set of element
def find(self, prev, i):
if prev[i] == i:
return i
return self.find(prev, prev[i])
# computes union of two sets
def union(self, prev, rank, x, y):
root_x = self.find(prev, x)
root_y = self.find(prev, y)
if rank[root_x] < rank[root_y]:
prev[root_x] = root_y
elif rank[root_y] < rank[root_x]:
prev[root_y] = root_x
else:
prev[root_y] = root_x
rank[root_x] += 1
# function for Kruskal's algorithm
def Kruskal(self):
mst = [] # stores the MST
i = 0 # index for sorted edges
j = 0 # index for MST
# Sort the edges in the non-decreasing order of weights
self.graph = sorted(self.graph, key=lambda line: line[2])
prev = []
rank = []
# create V subsets with a single element
for v in range(self.vertices):
prev.append(v)
rank.append(0)
# no of edges to be considered = V-1
while j < self.vertices - 1:
u, v, w = self.graph[i]
i += 1
x = self.find(prev, u)
y = self.find(prev, v)
# if adding the edge doesn't create a cycle add to the MST, else discard it
if x != y:
j += 1
mst.append([u, v, w])
self.union(prev, rank, x, y)
# print the MST
print("Edges\t\tWeight")
for u, v, w, in mst:
print("{} - {}\t{}".format(u, v, w))
print("\n")
def main():
file = open("graph.txt", "r")
num_vertices = int(file.readline())
num_edges = int(file.readline())
print("PRIM'S ALGORITHM")
pg = PrimGraph(num_vertices)
for line in file:
u = int(line.split(" ")[0])
v = int(line.split(" ")[1])
w = float(line.split(" ")[2])
pg.graph[u][v] = w
pg.graph[v][u] = w
file.close()
start_prim = time.time_ns()
pg.Prim()
time_prim = (time.time_ns() - start_prim) / 10**6
print("KRUSKAL'S ALGORITHM")
file = open("graph.txt", "r")
num_vertices = int(file.readline())
num_edges = int(file.readline())
kg = KruskalGraph(num_vertices)
for line in file:
u = int(line.split(" ")[0])
v = int(line.split(" ")[1])
w = float(line.split(" ")[2])
kg.add_edge(u, v, w)
file.close()
start_kruskal = time.time_ns()
kg.Kruskal()
time_kruskal = (time.time_ns() - start_kruskal) / 10**6
print("Time takem by the Prim's algorithm is: {:.2f} ms".format(time_prim))
print("Time taken by Kruskal's algorithm for the same graph is: {:.2f} ms".format(time_kruskal))
if __name__ == '__main__':
main()
|
# function for demonstrating the insertion sort algorithm
def ins_sort(arr):
count = 0
# iterate through the length of the list
for i in range(1, len(arr)):
count += 1
key = arr[i]
j = i - 1
# Swap the elements in the list if the preceding element exceeds the succeeding element
while j >= 0 and key < arr[j]:
count += 1
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return count, arr
# Shell sort function that takes parameters as the array and the gap to consider (n)
def shell_sort(arr, n):
count = 0
# iterate throughout the length of the array beginning from the gap
for i in range(n, len(arr)):
count += 1
key = arr[i]
j = i
# h-sort the arrays
while j >= n and arr[j - n] > key:
count += 1
arr[j] = arr[j - n]
j -= n
arr[j] = key
return count, arr
def main():
arr = []
arr1 = []
# Reading the file and copying to a list
txt = input("Enter the file to open: ")
txt1 = open(txt, "r")
for k in txt1:
arr.append(int(k))
print("Input Data: ", arr)
print("\n")
count = count1 = count2 = count4 = count5 = 0
# calculate elapsed time
import time
start1 = time.time()
count, arr = shell_sort(arr, 7)
count1, arr = shell_sort(arr, 3)
count2, arr = ins_sort(arr)
stop1 = time.time()
# print("The sorted array is: ", arr)
txt2 = open(txt, "r")
for line in txt2:
arr1.append(int(line))
start2 = time.time()
count3, arr1 = shell_sort(arr1, 7)
count4, arr1 = shell_sort(arr1, 3)
count5, arr1 = shell_sort(arr1, 1)
stop2 = time.time()
# print("The sorted array is: ", arr1)
# print the results obtained
print("Number of comparisons for shell sort phase is: ", count + count1)
print("Number of comparisons for insertion sort phase is: ", count2, "\n")
print("COMPARISONS:")
print("Shell sort reverting to insertion sort: ", count + count1 + count2)
print("Shell sort all the way: ", count3 + count4 + count5)
print("PHYSICAL WALL CLOCK TIME:")
print("Shell sort reverting to insertion sort: ", (stop1 - start1), "s.")
print("Shell sort all the way: ", stop2 - start1, "s.")
if __name__ == '__main__':
main()
|
# Using a base class to initialize the id of the nodes and the size for the weighted quick union
class UF:
# referred the documentation for __init__ and self
def __init__(self, size):
self.id_no = list(range(size))
self.sz = list(range(size))
# Class quick find from the base class
# constructor to initialize the class
class QF(UF):
# for every node, create the id
def QF(self, n):
for i in range(0, len(self.id_no), 1):
self.id_no[i] = i
# check if the id is same for every node, which means the nodes are connected
def find(self, p, q):
return self.id_no[p] == self.id_no[q]
# if not connected, connect by changing id's of the nodes
def union(self, p, q):
id_p = self.id_no[p]
id_q = self.id_no[q]
for i in range(0, len(self.id_no), 1):
if self.id_no[i] == id_p:
self.id_no[i] = id_q
return p, q
# class quick union
class QU(UF):
# similar to quick find, create the id for the nodes
def QU(self, n):
for i in range(0, len(self.id_no), 1):
self.id_no[i] = i
# find the root for the nodes
def root(self, i):
while i != self.id_no[i]:
i = self.id_no[i]
return i
# check if the nodes are connected if the root node is the same
def find(self, p, q):
return self.root(p) == self.root(q)
# if not connected, connect the node by changing the node id to root id
def union(self, p, q):
a = self.root(p)
b = self.root(q)
self.id_no[a] = b
return p, q
# class weighted quick union
class WQU(UF):
# create the id's
def WQU(self, n):
for i in range(0, len(self.id_no), 1):
self.id_no[i] = i
def root(self, i):
while i != self.id_no[i]:
i = self.id_no[i]
return i
def find(self, p, q):
return self.root(p) == self.root(q)
def union(self, lst, p, q):
a = self.root(p)
b = self.root(q)
sz = list(range(len(lst)))
# use a size data structure to keep track of the height of the trees
if self.sz[a] < self.sz[b]:
self.id_no[a] = b
self.sz[b] += self.sz[a]
else:
self.id_no[b] = a
self.sz[a] += self.sz[b]
return p, q
def main():
count1 = count2 = count3 = 0
# Reading input from the input file
txt = input("Enter the text file: ")
txt1 = open(txt, "r")
# Create an empty list of lists to copy all the data from the text file
lst = []
# referred the documentation for the map() method
# mapping the string elements into an integer
for l in txt1:
lst.append(list(map(int, l.split())))
print("Input data: ", lst)
print("\n")
import time
f = QF(8192)
print("QUICK FIND")
start = time.time()
for [i, j] in lst:
count1 += 1
if not f.find(i, j):
print("The pairs for quick find are: ", f.union(i, j))
print("Time taken for the quick find algorithm is:", time.time() - start)
print("\n")
u = QU(8192)
print("QUICK UNION")
start = time.time()
for [i, j] in lst:
count2 += 1
if not u.find(i, j):
print("The pairs for quick union are: ", u.union(i, j))
# u.union(lst, i, j)
print("Time taken for the quick union algorithm is: ", time.time() - start)
print("\n")
w = WQU(8192)
print("WEIGHTED QUICK UNION")
start = time.time()
for [i, j] in lst:
count3 += 1
if not w.find(i, j):
print("The pairs for weighted quick union are: ", w.union(lst, i, j))
# w.union(lst, i, j)
print("Time taken for the weighted quick union algorithm is: ", time.time() - start)
print("\n")
if __name__ == '__main__':
main()
|
import re
with open("python_07.fasta","r") as f:
for line in f:
line=line.rstrip()
found=re.search(r">",line)
if found:
# print(line)
match=re.search(r">(\S+)",line)
if match:
print(match.group(1))
#group1 specifies everything inside the parentheses
# startMatch=match.start()
# endMatch=match.end()
# print(line[startMatch:endMatch])
|
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self, node=None):
self.head = node
def insert(self, value):
node = Node(value)
node.next = self.head
self.head = node
return self
def includes(self, value):
current = self.head
while current:
if current.value == value:
return True
current = current.next
return False
def __str__(self):
string = ""
current = self.head
while current:
string += f"{ {current.value} } -> "
current = current.next
string += f" None "
return string
def append(self, value):
new_node = Node(value)
if self.head is None:
self.head = new_node
return self
current = self.head
while current.next is not None:
current = current.next
current.next = new_node
return self
def insert_before(self, target, new_value):
new_node = Node(new_value)
if self.head is None:
return None
if self.head.value == target:
new_node.next = self.head
self.head = new_node
return self
current = self.head
while current is not None:
if current.next.value == target:
new_node.next = current.next
current.next = new_node
return self
current = current.next
print("Target not within list")
def insert_after(self, target, new_value):
new_node = Node(new_value)
if self.head is None:
return None
current = self.head
while current is not None:
if current.value == target:
new_node.next = current.next
current.next = new_node
return self
current = current.next
print("Target not within list")
def kth_from_the_end(self, k):
if k < 0:
return "K is negative"
if self.head is None:
return None
count = 0
current = self.head
while current:
count += 1
current = current.next
if count < k:
raise Exception("K is larger than linked list")
current = self.head
count = count - k
while count > 1:
current = current.next
count -= 1
return current.value
def zip_lists(ll1, ll2):
curr_1 = ll1.head
curr_2 = ll2.head
while curr_1 and curr_2:
list_1_next = curr_1.next
list_2_next = curr_2.next
curr_1.next = curr_2
curr_2.next = list_1_next
curr_1 = list_1_next
curr_2 = list_2_next
ll2.head = curr_2
return ll1
if __name__ == "__main__":
pass
|
left = {
"fond": "enamored",
"wrath": "anger",
"diligent": "employed",
"outfit": "garb",
"guide": "usher",
}
right = {"fond": "averse", "wrath": "delight", "diligent": "idle", "guide": "follow", "flow": "jam"}
def left_join(hashmap1, hashmap2):
result = []
values1 = list(hashmap1.values())
values2 = list(hashmap2.values())
keys1 = list(hashmap1.keys())
keys2 = list(hashmap2.keys())
for i in range(len(keys1)):
for j in range(len(keys2)):
print("i is: ", keys1[i])
print("j is: ", keys2[j])
if keys1[i] == keys2[j]:
to_append = [keys1[i], values1[i], values2[j]]
result.append(to_append)
to_append = [keys1[i], values1[i], "NULL"]
result.append(to_append)
return result
|
class Node:
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
class K_aryTree:
def __init__(self, root=None):
self.root = root
def pre_order(self):
pre_order_list = []
def traverse(root):
if root is None:
return "Empty"
pre_order_list.append(root.value)
traverse(root.left)
traverse(root.right)
traverse(self.root)
return pre_order_list
def fizz_buzz_tree(tree):
root = tree.root
tree_list = []
if root.value is None:
return "Empty"
def traverse(root):
if root is None:
return
if root.value % 3 == 0 and root.value % 5 == 0:
root.value = "FizzBuzz"
elif root.value % 3 == 0:
root.value = "Fizz"
elif root.value % 5 == 0:
root.value = "Buzz"
tree_list.append(root.value)
traverse(root.left)
traverse(root.right)
traverse(root)
return tree_list
if __name__ == "__main__":
tree = K_aryTree(Node(1))
tree.root.left = Node(4)
tree.root.right = Node(8)
tree.root.left.left = Node(15)
tree.root.left.right = Node(85)
tree.root.right.left = Node(42)
tree = K_aryTree(Node())
print(fizz_buzz_tree(tree))
|
####################################
# Author: Amber Lee #
# Email: cryptoboxcomics@gmail.com #
# Info: A choose-your-own #
# adventure game #
####################################
player_name = ""
player_health = 100
player_money = 50
player_species = "Human"
player_weapons = []
player_items = []
####################################
# Game Start! #
####################################
### Introduction ###
print()
print()
print(" ####################################################")
print(" # Hello! This is a choose-your-own-adventure game. #")
print(" # You are a hero trying to save your kingdom of #")
print(" # Kanbal from the evil King Rogsam. #")
print(" ####################################################")
print()
print()
while(player_name == ""):
player_name = input("What is your name, Hero? : ")
print()
print("Hi, " + player_name + "! You are our hero and savior! Please save the Kanbalese mountain people from the evil King Rogsam.")
print("You start off with no weapons or items, but if you make the right choices, you might survive.")
print()
# ---Section Author: <your name>--- #
print("You pass by a traveler who looks injured by the woods. What do you do?")
print("1. Ignore him")
print("2. Try to help him")
decision = input("Pick a number: ")
print()
if (decision == "1"):
print("You try to leave, but trip over a rock and hit your head!")
player_health = player_health - 10
print("Your health now: ")
print(player_health)
elif (decision == "2"):
print("He appreciates that you helped him, and he gives you a potion! A potion heals 20 health points.")
player_items.append("Potion")
print("Your items now: ")
print(player_items)
# ---section end--- #
# Section author: Oleg
print("The Kalbanese police stop you and tries to fine you for being outside during coronavirus!")
print("1. Run away")
print("2. Sign the ticket")
print()
decision = ""
while(decision == ""):
decision = input("Pick a number: ")
print()
if (decision == "1"):
print("You ran but police shoot you with rubber bullets")
player_health -= 10
print("Your health now: ")
print(player_health)
elif (decision == "2"):
print("You signed your ticket and got sent on you way with 10 ticket")
print("Now you need to hide and wait till it is safe to walk on the street")
player_money -= 10
print("Your money now: ")
print(player_money) |
fhand = open(input('Enter a filename (recommended mbox-short.txt): '))
count = (0)
for line in fhand:
print(line.upper()) |
from karel.stanfordkarel import *
def turn_around():
"""
Makes Karel rotate 180 degrees/
"""
turn_left()
turn_left()
def turn_right():
"""
Makes Karel rotate 90 degrees clockwise.
"""
turn_left()
turn_left()
turn_left()
def plant_garden():
"""
Pre-condition: Karel is at the bottom left corner of its world, facing north.
Post-condition: Karel is at the top left corner of its world, facing north.
Turns an entire world into a garden with every other row as a full row of
seeds, represented by beepers.
"""
place_row_and_return()
while front_is_clear():
move()
if front_is_clear():
move()
place_row_and_return()
def come_back_west():
"""
Pre-condition: Karel is at the far right edge of a row, facing east.
Post-condition: Karel is at the far left edge of a row, facing west.
Turns Karel around and brings it back to the start of a row.
"""
turn_around()
while front_is_clear():
move()
def place_row_and_return():
"""
Pre-condition: Karel is at the far left edge of a row, facing north.
Post-condition: Karel is at the far left edge of the same row, facing
north.
Fills an entire row with beepers, moving from left to right, and then
returns and faces north.
"""
turn_right()
make_beeper_row_better()
come_back_west()
turn_right()
def make_beeper_row_better():
"""
Pre-condition: Karel is at the far left edge of a row, facing east.
Post-condition: Karel is at the far right edge of a row, facing east.
Karel moves forward until it hits a wall,
placing beepers on each intersection where there
is not already a beeper.
"""
while front_is_clear():
if not on_beeper():
put_beeper()
move()
if not on_beeper():
put_beeper()
def main():
"""
Karel plants a garden by placing seeds (beepers) in
every other row. Some rows may already have seeds present.
"""
plant_garden()
if __name__ == "__main__":
execute_karel_task(main) |
"""
File: complement.py
-----------------------
This file should define a console program that prompts a user for
a strand of DNA and displays the complement of that strand of DNA.
Further details and output format can be found in the Assignment 2
handout.
"""
def build_complement(strand):
"""
This function takes in a DNA strand and returns the
complementary DNA strand, as defined by the base pair
matchings outlined in the Assignment 2 handout.
>>> build_complement("ATGCAAG")
'TACGTTC'
>>> build_complement("AAAA")
'TTTT'
"""
return ''
def main():
"""
Replace this comment with a more descriptive one.
Don't forget to delete the pass statement below.
"""
pass
if __name__ == "__main__":
main() |
from simpleimage import SimpleImage
def red_channel(filename):
"""
Creates an image for the given filename.
Changes the image as follows:
For every pixel, set green and blue values to 0
yielding the red channel.
Return the changed image.
"""
image = SimpleImage(filename)
for pixel in image:
pixel.green = 0
pixel.blue = 0
return image
def darker(filename):
"""
Makes the image darker by halving red,green,blue values.
Returns the changed image.
"""
# Demonstrate looping over all the pixels of an image,
# using pixel.xxx in the loop to change each pixel,
# int division, relative var updates.
image = SimpleImage(filename)
for pixel in image:
pixel.red = pixel.red // 2
pixel.green = pixel.green // 2
pixel.blue = pixel.blue // 2
# Could use += shorthand:
# pixel.blue //= 2
return image
def right_half(filename):
"""
Change and return the image:
make right half of the image
to be 50% as bright. Use int division
to compute where right half begins.
Properties reminder:
pixel.x pixel.y image.width image.height
Also try bottom half:
pixel.y >= image.height // 2
"""
image = SimpleImage(filename)
for pixel in image:
# if pixel is in right half of image
# (e.g. width is 100, right half begins at x=50)
if pixel.x >= image.width // 2:
pixel.red *= 0.5
pixel.green *= 0.5
pixel.blue *= 0.5
return image
def right_quarter(filename):
"""
As above, but do the lower right quarter.
Use "and" to combine 2 <= tests.
"""
image = SimpleImage(filename)
for pixel in image:
if (pixel.x >= image.width // 2 and
pixel.y >= image.height // 2):
pixel.red *= 0.5
pixel.green *= 0.5
pixel.blue *= 0.5
return image
def grayscale(filename):
"""
Change the image to be grayscale
using the "average" technique
and return it.
"""
image = SimpleImage(filename)
for pixel in image:
average = (pixel.red + pixel.green + pixel.blue) // 3
pixel.red = average
pixel.green = average
pixel.blue = average
return image
def curb_repair1(filename):
"""
Detect the red curb pixels, change them
to 180/180/180 gray.
This code does the gray setting,
but the hurdle factor needs to be adjusted.
Looks ok but not great.
"""
image = SimpleImage(filename)
for pixel in image:
average = (pixel.red + pixel.green + pixel.blue) // 3
if pixel.red >= average * 1.0:
pixel.red = 180
pixel.blue = 180
pixel.green = 180
return image
def curb_repair2(filename):
"""
Detect the red curb pixels, change them
to grayscale. The code here is complete:
factor is adjusted and grayscale is in.
This looks good!
"""
image = SimpleImage(filename)
for pixel in image:
average = (pixel.red + pixel.green + pixel.blue) // 3
if pixel.red >= average * 1.1:
pixel.red = average
pixel.blue = average
pixel.green = average
return image
def stop_leaves(front_filename, back_filename):
"""
Implement stop_leaves as described.
Detect red areas of stop sign.
Replace red pixels with pixels from corresponding x,y
from back image.
"""
image = SimpleImage(front_filename)
back = SimpleImage(back_filename)
for pixel in image:
average = (pixel.red + pixel.green + pixel.blue) // 3
if pixel.red >= average * 1.6:
# the key line:
pixel_back = back.get_pixel(pixel.x, pixel.y)
pixel.red = pixel_back.red
pixel.green = pixel_back.green
pixel.blue = pixel_back.blue
return image
def main():
"""
Run your desired photoshop functions here.
You should save the return value of the image and then
call .show() to visualize the output of your program.
"""
original_poppy = SimpleImage('images/poppy.png')
original_poppy.show()
original_dandelion = SimpleImage('images/dandelion.png')
original_dandelion.show()
redder_poppy = red_channel('images/poppy.png')
redder_poppy.show()
darker_poppy = darker('images/poppy.png')
darker_poppy.show()
right_half_poppy = right_half('images/poppy.png')
right_half_poppy.show()
right_quarter_poppy = right_quarter('images/poppy.png')
right_quarter_poppy.show()
grayscale_poppy = grayscale('images/poppy.png')
grayscale_poppy.show()
grayscale_dandelion = grayscale('images/dandelion.png')
grayscale_dandelion.show()
original_curb = SimpleImage('images/curb.png')
original_curb.show()
curb_repair_first = curb_repair1('images/curb.png')
curb_repair_first.show()
curb_repair_second = curb_repair2('images/curb.png')
curb_repair_second.show()
original_stop = SimpleImage('images/stop.png')
original_stop.show()
original_leaves = SimpleImage('images/leaves.png')
original_leaves.show()
stop_leaves_replaced = stop_leaves('images/stop.png', 'images/leaves.png')
stop_leaves_replaced.show()
if __name__ == '__main__':
main()
|
''' QUESTION:
Greedy person:
The owner of the shopping complex is a greedy person. The owner is very lazy to do anything and so felt lazy to count the number of digits in profit.
Also, he doesn't believe in anyone to assign that job. So he wants to make someone write a program to count the number of digits in the profit.
Can you make a program to calculate it?
Input Format : The input contains an integer n
Input Constraints : 1<=|n|<=10^7
Output Format : Print the result
Sample Input :
2342
Sample Output :
4
HINTS:
1 - When you divide a number by 10, the number of digits reduce by 1.
2 - Use a counter variable. Run a loop till N>0. In each iteration, divide N by 10 and increment the counter by 1.
3 - In python, you can handle the number as a string as well.
'''
# ANSWER:
x = input()
print(len(x))
|
import re
pattern = r's\S*'
string = 'smr tki yki smr ski' # 検索対象文字列
# 全て検索し、文字列リストを返す
result = re.findall(pattern, string)
print(result) # ['smr', 'smr', 'ski'] |
import time
starttime = time.clock()
a = []
for i in range(1,100):
if i % 3 ==0 and i % 5 == 0 :
a.append("fizzbuzz")
if i % 3 == 0 :
a.append("fizz")
elif i% 5 ==0 :
a.append("buzz")
else:
a.append(i)
print(a)
endtime = time.clock()
print("Duration {}".format(endtime - starttime)) |
#Ask the user to input the temperature
temp = input("Please enter the current temperature (°F): ")
#Convert the input string temperature to an integer
temp = int(temp)
#Set up the equality statement for the input temperature
if temp >= 70:
print ("No jacket required")
else:
print ("Wear a jacket")
|
import numpy as np
'''
TAKEN FROM UDACITY - ARTIFICIAL INTELLIGENCE FOR ROBOTICS, LESSON 2, SEBASTIAN THRUN
# Write a program that will iteratively update and
# predict based on the location measurements
# and inferred motions shown below.
#1D KALMAN FILTER
def update(mean1, var1, mean2, var2):
new_mean = float(var2 * mean1 + var1 * mean2) / (var1 + var2)
new_var = 1./(1./var1 + 1./var2)
return [new_mean, new_var]
def predict(mean1, var1, mean2, var2):
new_mean = mean1 + mean2
new_var = var1 + var2
return [new_mean, new_var]
measurements = [5., 6., 7., 9., 10.]
motion = [1., 1., 2., 1., 1.]
measurement_sig = 4.
motion_sig = 2.
mu = 0.
sig = 10000.
#Please print out ONLY the final values of the mean
#and the variance in a list [mu, sig].
# Insert code here
for i, m in enumerate(measurements):
mu, sig = update(mu, sig, m, measurement_sig)
mu, sig = predict(mu, sig, motion[i], motion_sig)
print [mu, sig]
#MULTIPLE DIMENSION KALMAN FILTER
def kalman_filter(x, P):
for n in range(len(measurements)):
# measurement update
measure_vec = matrix([[measurements[n]]])
error = measure_vec - H*x
S = H*P*H.transpose() + R
KG = P*H.transpose()*S.inverse()
x = x + (KG*error)
P = (I - KG*H)*P
# prediction
x = F*x + u
P = F*P*F.transpose()
return x,P
'''
def stateShapeTest(mat):
return mat.shape == np.zeros(4).shape
class KalmanFilter:
def __init__(self, dim_state, dim_measure, dim_control,
state_transition_mat, observation_mat,
init_state_estimate):
cov_error = np.identity(dim_state)*np.array([100]*dim_state) #set init covariance very high, because very uncertain
estimated_measurement_error = np.identity(dim_measure)*np.array([.3]*dim_measure)
init_state=np.zeros(dim_state)
self.state = init_state
self.control = np.identity(dim_control)
self.state_transition_mat = state_transition_mat
self.observation_mat = observation_mat
self.predicted_state = init_state
self.covariance = cov_error
self.estimated_measurement_error = estimated_measurement_error
self.error = []
self.covariance_to_measurement = []
self.previous_covariance = self.covariance
#The Kalman filter relies here on what knowledge it already has
def predict(self, control_vec=0):
if not self.control:
self.predicted_state = np.dot(self.state_transition_mat, self.state)
else:
self.predicted_state = self.state_transition_mat*self.state + self.control*control_vec
self.predicted_covariance = np.dot(np.dot(self.state_transition_mat, self.covariance),np.transpose(self.state_transition_mat))
#print "Predicted covariance: ", self.predicted_covariance
print "Predicted state: ", self.predicted_state
print "Predicted cov: \n", self.predicted_covariance
return self.predicted_state, self.predicted_covariance
#The Kalman filter updates its estimation framework using a new measurement
def correct(self, measurement_vec):
#this is known as the "innovation"
#print "obs mat: ", self.observation_mat
#print "pred state: ", self.predicted_state
self.error = self.observation_mat.dot(self.predicted_state)
self.error = measurement_vec - self.error
print "measurement: ", measurement_vec
print "error: ", self.error
self.covariance_to_measurement = np.squeeze(np.dot(np.dot(self.observation_mat,self.predicted_covariance),np.transpose(self.observation_mat))) + self.estimated_measurement_error
print "cov to meas: ", self.covariance_to_measurement
def update(self):
kalman_gain = np.dot(np.dot(self.covariance, np.transpose(self.observation_mat)),np.linalg.inv(self.covariance_to_measurement))
inter = np.squeeze((np.dot(kalman_gain,np.transpose(self.error))))
self.state = self.state + inter
print "State: ", self.state
self.covariance = np.dot((np.identity(self.predicted_covariance.shape[0]) - np.dot(kalman_gain,self.observation_mat)), self.covariance)
#print "Covariance: ", self.covariance
return self.state, self.covariance
dim_state = 4 #x,y,dx,dy
dim_measure = 2 #x,y
dim_control = 0 #no known controller
state_transition_mat = np.identity(4)
state_transition_mat[0,2] = 1 #these basically say, to get the next state from the current, add dx to x
state_transition_mat[1,3] = 1 #and dy to y
print "state trans: ", state_transition_mat
observation_mat = np.zeros((2,4))
observation_mat[0,0] = 1
observation_mat[1,1] = 1
init_state = np.array([0,0])
measured = init_state
k = KalmanFilter(dim_state, dim_measure, dim_control, state_transition_mat, observation_mat, init_state)
for i in range(100):
print "\niteration ", i
k.predict()
k.correct(measured)
k.update()
measured = measured + np.array([1,0]) + np.random.uniform(low=-.3, high=.3, size=(1,2))
#print "measured ", measured
#print k.state, "\n", k.covariance
|
from collections import deque
class DAG(object):
"""Directed Acyclic Graph"""
def __init__(self, nodes = None):
"""
Init the graph.
If nodes is given, it should be a mapping {node_id: {children}}
"""
self._nodes = nodes if nodes else {}
self._properties = {n: {} for n in nodes} if nodes else {}
self._eproperties = {}
def __contains__(self, arg):
"""Test existence of a node in the graph."""
return arg in self._nodes
def __len__(self):
"""Return the number of nodes in the graph."""
return len(self._nodes)
def __iter__(self):
"""Return an iterator for all the nodes in the graph."""
return self._nodes.__iter__()
def __eq__(self, other):
"""Equality between graphs, True if self is likely isomorphic to other. """
if len(self) != len(other):
return False
selfsort = self.topsort()
othersort = other.topsort()
# make sure each layer is the same size
selflayers = self.dist_layers(selfsort[0])
otherlayers = other.dist_layers(othersort[0])
if len(selflayers) != len(otherlayers):
return False
for layer in selflayers:
if layer not in otherlayers or len(selflayers[layer]) != len(otherlayers[layer]):
return False
# same number of leaves
if len(self.collect_leaves(selfsort[0])) != len(other.collect_leaves(othersort[0])):
return False
# same critical path length
if self.critical_path_length() != other.critical_path_length():
return False
return True
def __str__(self):
"""Return string representation of DAG."""
return str(self._nodes)
def transpose(self):
"""Return the transpose (reversed edges) of the graph as a new DAG."""
p = {n: set() for n in self}
for n in self._nodes:
for c in self.children(n):
p[c].add(n)
return DAG(p)
def in_degree(self, node):
"""The number of parents of some node."""
return len(self.parents(node))
def out_degree(self, node):
"""The number of children of some node."""
return len(self.children(node))
def set_edge_color(self, fr, to, val):
"""Set the color of the edge from fr to to."""
self.set_edge_property(fr, to, 'color', val)
def edge_color(self, fr, to, default = None):
"""Return the color of the edge from fr to to, default if undefined."""
return self.edge_property(fr, to, 'color', default)
def set_edge_label(self, fr, to, val):
"""Set the label of the edge from fr to to."""
self.set_edge_property(fr, to, 'label', val)
def edge_label(self, fr, to, default = None):
"""Return the label of the edge from fr to to, default if undefined."""
return self.edge_property(fr, to, 'label', default)
def set_edge_property(self, fr, to, prop, val):
"""Set property prop of edge from fr to to."""
if (fr,to) not in self._eproperties:
self._eproperties[(fr,to)] = {}
self._eproperties[(fr,to)][prop] = val
def set_edge_properties(self, fr, to, propertyDict):
"""Set properties from fr to to to the given propertyDict."""
self._eproperties[(fr,to)] = propertyDict.copy()
def edge_property(self, fr, to, prop, default=None):
"""Return property prop of edge from fr to to."""
return self._eproperties[(fr,to)].get(prop, default)
def edge_properties(self, fr, to):
"""Return a reference to a dict of the properties of the edge from fr to to."""
return self._eproperties.get((fr,to), {})
def set_property(self, node, prop, value):
"""Set some property of a node to given value."""
self._properties[node][prop] = value
def has_property(self, node, prop):
"""Return whether a node has some property defined."""
return prop in self._properties[node]
def property(self, node, prop, default = None):
"""Get property prop of some node, default if prop not defined for node."""
if prop not in self._properties[node] or not self._properties[node][prop]:
return default
return self._properties[node][prop]
def properties(self, node):
"""Return a reference to a dict of all the properties of a node."""
return self._properties[node]
def remove_node(self, node, parents = None):
"""Remove a node from the graph."""
if not parents:
parents = self.parents(node)
for parent in self.parents(node):
self.remove_child(parent, node)
del self._nodes[node]
del self._properties[node]
def contract(self, node, parent):
"""Contract parent node into node, labeling and coloring contracted edges."""
for p in self.parents(parent):
# parents of parent become parents of node
color = self.edge_color(p, parent, 'black')
label = self.edge_label(p, parent, '')
self.add_child(p, node)
self.set_edge_label(p, node, label)
self.set_edge_color(p, node, color)
for c in self.children(parent):
if c == node: continue
# children of parent become children of node
color = self.edge_color(parent, c, 'black')
label = self.edge_label(parent, c, '')
self.add_child(node, c)
self.set_edge_label(node, c, label)
self.set_edge_color(node, c, color)
self.remove_node(parent)
def add_node(self, node):
"""Add node to graph if it's not already there."""
if node not in self:
self._nodes[node] = set()
self._properties[node] = {}
def add_node_with_children(self, node, children):
"""
Add node to the graph with given iterable of children.
Adds children to the graph if they are not already there.
"""
self.add_node(node)
for child in children:
if child not in self:
self.add_node(child)
self.add_child(node, child)
def add_node_with_parents(self, node, parents):
"""
Add node to the graph with given iterable of parents.
Adds parents to the graph if they are not already there.
"""
self.add_node(node)
for parent in parents:
if parent not in self:
self.add_node(parent)
self.add_child(parent, node)
def add_child(self, node, child):
"""Add some child to some node; create child node if it does not exist."""
if child in self:
self._nodes[node].add(child)
if (node,child) not in self._eproperties:
self._eproperties[(node,child)] = {}
else:
self.add_node_with_parents(child, [node])
def add_parent(self, node, parent):
"""Add some parent to some node; create parent if it does not exist."""
self.add_child(parent, node)
def remove_child(self, node, child):
"""Remove child from set of children of node."""
self._nodes[node].discard(child)
def remove_all_children(self, node):
"""Remove all children of node."""
self._nodes[node] = set()
def remove_all_parents(self, node):
"""Remove all parents of node."""
for parent in self.parents(node):
self.remove_child(parent, node)
def children(self, node):
"""Return the set of children of some node."""
return self._nodes[node]
def parents(self, node):
"""
Return the set of parents of some node.
Use transpose and children instead if parents is called repeatedly.
"""
parents = set()
for p in self:
if node in self.children(p):
parents.add(p)
return parents
def bfs(self, start_node = None, visitor = lambda x: x):
"""
Perform a breadth-first search starting at start_node along parent -> children edges.
Call visitor(node) on each visited node in traversal order.
If start_node not given, visit all nodes.
Return a mapping of {visited nodes : distance from start}
"""
distances = {} # track visited nodes
while len(distances) < len(self._nodes):
break_first = bool(start_node)
if not break_first:
start_node = list(set(self._nodes).difference(set(distances.keys())))[0]
distances[start_node] = 0
que = deque([start_node])
while len(que) > 0:
current_id = que.popleft()
for child_id in self.children(current_id):
if child_id not in distances:
que.append(child_id)
distances[child_id] = distances[current_id] + 1
visitor(child_id)
if break_first: break
return distances
def dist_layers(self, start_node = None, visitor = lambda x:x):
"""
Return an inverse mapping of BFS distances.
Perform breadth-first search, but instead of returning a mapping of
node -> distance, return a mapping of distance -> {nodes}.
"""
distances = self.bfs(start_node, visitor)
layers = {}
for n in distances:
if distances[n] not in layers:
layers[distances[n]] = set()
layers[distances[n]].add(n)
return layers
def dfs(self, start_node = None, visitor = lambda x: x):
"""
Perform a depth-first search starting at start_node.
Travel along edges connecting parents to children and call
visitor(node) on each visited node.
If start_node not given, visit all nodes.
"""
history = set()
def visit(node):
if node not in history:
history.add(node)
for child in self.children(node):
visit(child)
visitor(node) # callback comes here
if not start_node:
while len(history) < len(self._nodes):
visit(list(set(self._nodes).difference(history))[0])
else:
visit(start_node)
def dfs_pred(self, start_node, predicate):
"""
Perform a depth-first search starting at start_node, calling predicate on each node visited.
If predicate is True, immediately return True.
Otherwise return False (predicate never is True).
"""
history = set()
# the flag needs to be reassignable, so we put it into a list
flag = [predicate(start_node) is True]
def visit(node):
# check for eureka and history
if node not in history and not flag[0]:
history.add(node)
for child in self.children(node):
visit(child)
flag[0] = predicate(node) is True
visit(start_node)
return flag[0]
def topsort(self):
"""Return a list representing a topological ordering of the graph's nodes."""
ordering = []
self.dfs(visitor = lambda x: ordering.append(x))
return ordering[::-1]
def collect_leaves(self, node_id):
"""Return a list of all leaves below node_id."""
leafs = []
def leaf_collector(node):
if self.out_degree(node) == 0:
leafs.append(node)
self.bfs(node_id, leaf_collector)
return leafs
def critical_path_length(self):
"""Return length of the longest path in the graph."""
nodes = self.topsort()
tpose = self.transpose()
pl = {}
for n in nodes:
# path work at node is work done at the node plus the maximum work on an incoming path
pl[n] = 1 + max([0]+[pl.get(p, 0) for p in tpose.children(n)])
return pl[nodes[-1]]
def dump_graph_dot(self, name='DAG', **kwargs):
"""
Return string of graph in .dot format.
All edge and node properties not prefixed with _ are included in the dot output.
kwargs are assumed to be graph-level attributes, like rankdir.
"""
output = ['node [fontname="%s",fontsize="%s"]' % ("sans-serif", "12")]
for i in self:
# node
output.append("%s [id=%s,%s]" % (i, '"%s"' % i, ','.join(['%s="%s"' % (k,v) for k, v in
self.properties(i).items() if not k.startswith('_')])))
for child in self.children(i):
# edges
output.append("%s -> %s [id=%s,%s]" % (i, child, '"%s->%s"' % (i, child),
','.join(['%s="%s"' % (k,v) for k, v in
self.edge_properties(i,child).items() if not k.startswith('_')])))
opts = '\n'.join(["%s=%s" % (k,v) for (k,v) in kwargs.items()])
output = 'digraph "%s" {\n%s\n%s}\n' % (name, opts, '\n'.join(output))
return output
|
def is_prime(x):
# check if x is prime
if x < 2:
return False
elif x == 2:
return True
else:
for i in range(2,int(x)):
rem = x % i
if rem == 0:
return False
else:
return True
def inputfac(num):
# return list of prime factors of num
primelist = []
nonlist = []
faclist = range(2,num+1)
for i in range(0,len(faclist)):
if is_prime(faclist[i]) == 1:
primelist.append(faclist[i])
else:
nonlist.append(faclist[i])
return primelist
def findfacs(maxi):
# find prime factors that occur more than once in producing solution
global primelist
primelist = inputfac(maxi)
rt = int(maxi**0.5)
prlst = filter(lambda x: x <= rt, primelist)
return prlst
prlst = findfacs(20)
def findpower(x,maxi):
# find what power those primes must be raised to
n = 1
while x ** n < maxi:
n += 1
return n-1
def multfacs(prlst,maxi):
# add the extra occurrences of those primes
multlist = []
for i in range(0,len(prlst)):
val = prlst[i]
j = findpower(val,maxi)-1
templist = [val] * j
multlist = multlist + templist
return multlist
toadd = multfacs(prlst,20)
allfactors = toadd + primelist
allfactors.sort()
# acquired a complete list of factors needed to find smallest product
def mult_it_out(allfactors):
total = 1
for i in range(0,len(allfactors)):
total = total * allfactors[i]
return total
anstot = mult_it_out(allfactors)
print anstot
|
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for i in range(2,x):
rem = x % i
if rem == 0:
return False
else:
return True
def findprimes(w,x):
primes = []
for i in range(w,x+1):
if is_prime(i) == 1:
primes.append(i)
return primes
def loopprimes(x):
prlst = findprimes(1,x)
newend = x
while len(prlst) < 10001:
newend += 200
primes = findprimes(newend-199,newend)
prlst = prlst + primes
return prlst
ans = loopprimes(100000)
print ans[10000]
|
# import pygame
# start drawing
# lines 8 - 21 displays pygame window
import pygame
import sys
BOARD_SIZE = WIDTH, HEIGHT = 640, 480
DEAD_COLOR = 0, 0, 0
ALIVE_COLOR = 0, 255, 255
class LifeGame:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode(BOARD_SIZE)
# ball = pygame.image.load('intro_ball.gif') //are images, but going to draw//
# ballrect = ball.get_rect()
def run(self):
circle_rect = pygame.draw.circle(self.screen, ALIVE_COLOR, (50, 50), 5, width=0)
print(type(circle_rect))
print(circle_rect)
# screen.blit(ball, ballrect)
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
self.screen.fill(DEAD_COLOR)
# screen.blit(ball, ballrect) # is where I'm going to put my rectangles
pygame.display.flip() ## blit to draw and flip to push it into memory
if __name__ == '__main__':
game = LifeGame()
game.run()
|
'''def ecrit():
a=-1
while(a<0):
a=input("donnez number positive a")
return (a)
def puissance(x,n):
if(n==0):
return(1)
else:
x=x*puissance(x,n-1)
return(x)
x=ecrit()
y=puissance(x,3)
print(x,y)'''
def saisi():
n=input("donnez n")
b=0
while(b<2)and(b>8):
b=int(input("donnez a"))
return (n,b)
print(saisi())
|
#fortune cookie bot
#before we start the programme, we ask python to get all the packages we need
#random allows us to pick a random fortune later
#time allows us to pause between outputs
#pyttsx3 is the package that does speech for us. We will ask it to start up and will close it down later
import random
import time
import pyttsx3
engine = pyttsx3.init()
#first, find out the user's name, then store the name in the variable "name"
#we tell the computer what to say aloud by using engine.say, then we tell it to go ahead and say it with engine.runAndWait()
engine.say("Hello! What is your name?")
print("Hello, what is your name?")
engine.runAndWait()
name = input()
#tell the user how many letters are in their name
print("Hello, " + name)
engine.say("Hello, " + name)
time.sleep(1)
print("Did you know you have " +str(len(name)) +" letters in your name?")
engine.say("Did you know you have " +str(len(name)) +" letters in your name?")
engine.runAndWait()
time.sleep(1)
print("...")
print("Oh, you did, huh?")
engine.say("Oh, you did, huh?")
engine.runAndWait()
time.sleep(1)
#creates a variable based on input and checks to see if it's yes or no
#then introduces the fortune with varying degrees of snark
engine.say("Ok, then. Do you want me to tell your fortune?")
engine.runAndWait()
fortune = input("Ok, then. Do you want me to to tell your fortune? ")
if fortune == "yes":
print("FANTASTIC, I love reading lyrics to people!!!!")
engine.say("fantastic, I love reading lyrics to people!")
engine.runAndWait()
time.sleep(3)
elif fortune == "no":
print("Listen here, bucko. I came here to chew gum and tell fortunes. And I'm fresh out of gum. So why don't you sit down and listen to your fortune, before I knock you down?")
engine.say("Listen here, bucko. I came here to chew gum and read lyrics from popular songs. And I'm fresh out of gum. So why don't you sit down and listen to your song lyric, before I knock you down?")
engine.runAndWait()
time.sleep(1)
while fortune not in ("yes", "no"):
engine.say("Answer yes or no, please, using only lower case letters. I'm not that smart a programme.")
engine.runAndWait()
fortune = input("Answer yes or no, please")
if fortune == "yes":
print("I'm so happy. I'm glad I understand you now.")
engine.say("I'm so happy. I'm glad I understand you now.")
engine.runAndWait()
time.sleep(2)
elif fortune == "no":
print("Right, you little squirt. You'll get your fortune whether you like it or not.")
engine.say("Right, you little squirt. You'll get your fortune whether you like it or not.")
engine.runAndWait()
time.sleep(1)
#looks for a fortune from a txt file called lines.txt and prints it out
#lines.txt needs to be in the same place this programme is stored
print("Ok, " + name)
engine.say("Ok, " + name)
engine.runAndWait()
print("I'm computing your fortune now.")
engine.say("I'm computing your fortune now.")
engine.runAndWait()
time.sleep(3)
print("(please imagine mystical noises)")
engine.say("(please imagine mystical noises)")
engine.runAndWait()
time.sleep(2)
#this is where the programme reads the file and picks a random line
fileobj = open('fortune.txt','r')
line = random.choice(fileobj.readlines())
fileobj.close()
print (line)
engine.say(line)
engine.runAndWait()
time.sleep(2)
#good manners
engine.say("Thanks for playing with me. It's someone else's turn now.")
engine.runAndWait()
print ("Thanks for playing with me. It's someone else's turn now.")
#we stop the speech package and exit the programme.
engine.stop()
time.sleep(7)
exit
|
class Solution:
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
for row in range(len(A)):
A[row] = A[row][::-1]
for col in range(len(A[row])):
A[row][col] ^= 1
return A
if __name__ == '__main__':
solution = Solution()
print (solution.flipAndInvertImage([[1,1,0],[1,0,1],[0,0,0]]))
print (solution.flipAndInvertImage([[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]])) |
class Solution:
def isToeplitzMatrix(self, matrix: 'List[List[int]]') -> 'bool':
for i in range(len(matrix) - 1):
for j in range(len(matrix[0]) - 1):
if matrix[i][j] != matrix[i + 1][j + 1]:
return False
return True
def main():
input = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
# Output: ["Alaska", "Dad"]
print(Solution().isToeplitzMatrix(input))
if __name__ == '__main__':
main()
|
from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
if len(nums) <= 0:
return 0
if len(nums) == 1:
return nums[0]
dp = [0]*len(nums)
for i, num in enumerate(nums):
dp[i] = max(dp[i-1] + num, num)
return max(dp)
def main():
# Example:1
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(Solution().maxSubArray(nums))
# Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
# Output: 6
# Explanation: [4,-1,2,1] has the largest sum = 6.
print('------------------------------')
# Example:2
nums = [1]
print(Solution().maxSubArray(nums))
# Input: nums = [1]
# Output: 1
print('------------------------------')
# Error case
nums = [5, 4, -1, 7, 8]
print(Solution().maxSubArray(nums))
Input: nums = [5, 4, -1, 7, 8]
Output: 23
if __name__ == '__main__':
main()
|
from typing import List
class Solution:
def lengthOfLastWord(self, s: str) -> int:
word_list = s.split()
return len(word_list[-1])
def main():
# Example:1
s = "Hello World"
print(Solution().lengthOfLastWord(s))
# Input: s = "Hello World"
# Output: 5
# Explanation: The last word is "World" with length 5.
print('------------------------------')
# Example:2
s = " fly me to the moon "
print(Solution().lengthOfLastWord(s))
# Input: s = " fly me to the moon "
# Output: 4
# Explanation: The last word is "moon" with length 4.
print('------------------------------')
# Error case
s = "luffy is still joyboy"
print(Solution().lengthOfLastWord(s))
# Input: s = "luffy is still joyboy"
# Output: 6
# Explanation: The last word is "joyboy" with length 6.
if __name__ == '__main__':
main()
|
class Solution:
def findLUSlength(self, a: str, b: str) -> int:
if a == b:
return False
return max(len(a), len(b))
def main():
print(Solution().findLUSlength("aba","cdc"))
# Output: 3
# Explanation: The longest uncommon subsequence is "aba" (or "cdc"),
# because "aba" is a subsequence of "aba",
# but not a subsequence of any other strings in the group of two strings.
if __name__ == '__main__':
main()
|
class Solution:
def findWords(self, words: 'List[str]') -> 'List[str]':
a = set('qwertyuiop')
b = set('asdfghjkl')
c = set('zxcvbnm')
ans = []
for word in words:
loWordList = set(word.lower())
if set(a) - (set(a) - set(loWordList)) == loWordList:
ans.append(word)
if set(b) - (set(b) - set(loWordList)) == loWordList:
ans.append(word)
if set(c) - (set(c) - set(loWordList)) == loWordList:
ans.append(word)
return ans
def main():
input = ["Hello", "Alaska", "Dad", "Peace"]
# Output: ["Alaska", "Dad"]
print(Solution().findWords(input))
if __name__ == '__main__':
main()
|
import random
import string
from words import words
def get_valid_word(words):
word = random.choice(words) # randomly select a word from words list
while '-' in word or ' ' in word:
word = random.choice(words)
return word
def hangman():
word = get_valid_word(words).upper()
word_letters = set(word) # letters in the word
alphabet = set(string.ascii_uppercase)
used_letters = set() # letters the user has guessed
# getting user input
while len(word_letters) > 0:
# letters used by user
print("You have used these letters: ", " ".join(used_letters))
# what is the current word being guessed
word_list = [letter if letter in used_letters else '-' for letter in word]
print("Current word: ", " ".join(word_list))
user_letter = input("Guess a letter: ").upper()
if user_letter in alphabet - used_letters:
used_letters.add(user_letter)
if user_letter in word_letters:
word_letters.remove(user_letter)
elif user_letter in used_letters:
print("You have already typed that letter. Please try again!")
else:
print("Invalid character. Please try again!")
num_guesses = len(used_letters)
print(f"Congratulations you have solve the puzzle for the word {word} and it only took {num_guesses} guesses!")
hangman()
|
class AbstractAngle(object):
__slots__ = ['atom1', 'atom2', 'atom3']
def __init__(self, atom1, atom2, atom3):
self.atom1 = atom1
self.atom2 = atom2
self.atom3 = atom3
def __eq__(self, object):
if ((self.atom1 == object.atom1 and
self.atom2 == object.atom2 and
self.atom3 == object.atom3)
or
(self.atom1 == object.atom3 and
self.atom2 == object.atom2 and
self.atom3 == object.atom1)):
return True
else:
return False
def __hash__(self):
return hash(tuple([self.atom1, self.atom2, self.atom3]))
|
a=input("enter the first number : ")
b=input("enter the second number : ")
print("the first number is", a.replace(a,b))
print("the second number is", b.replace(b,a))
|
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if n is 0:
return []
result = []
curr = ""
self.backtrack(result, n, curr, 0, 0)
return result
def backtrack(self, result, n, curr, op, cl):
if len(curr) is 2*n:
result.append(curr)
if op < n:
self.backtrack(result, n, curr + "(", op+1, cl)
if cl < op:
self.backtrack(result, n, curr + ")", op, cl+1)
|
# person3 = {'Name': 'Ford Prefect',
# 'Gender': 'Male',
# 'Occupation':'Researcher',
# 'Home Planet':'Not Earth'
# }
#
#
# print(person3['Gender'])
# person3['Age'] = 33
# print(person3['Age'])
found = {}
found['a'] = 0
found['e'] = 0
found['i'] = 0
found['o'] = 0
found['u'] = 0
print(found)
print(found)
for i in range(30):
found['e'] +=1
print(found)
|
#Cálculo de la potencia. Calcular a^n cuando n es potencia de 2
def calcularPotencia(a,n):
if n==2:
b=a
else:
b=calcularPotencia(a,n//2)
return b*b
def __main__():
print(calcularPotencia(5,4))
if __name__=="__main__":
__main__() |
import tkinter
from tkinter import *
from tkinter.ttk import *
import os
import sqlite3
conn=sqlite3.connect('My.project12.db')
window=Tk()
window.title("ACCOUNT LOGIN")
window.geometry('550x300')
#window.configure(background="orange")
#window.configure(highlightbackground="#d9d9d9")
#window.configure(highlightcolor="black")
global txt5
global txt6
global txt7
global txt8
global txt9
global txt10
global txt11
global txt12
global txt13
global txt14
global txt15
global txt16
global txt17
global txt18
global txt19
global txt20
global txt21
global txt22
global txt23
global txt24
global txt25
global txt26
global txt27
global txt28
global txt29
global combo1
global combo2
global combo3
global combo4
global combo5
global combo6
def clicked():
window = Tk()
window.geometry('550x300')
window.title("HOME PAGE")
root_menu = tkinter.Menu(window)
window.config(menu=root_menu)
def funcreg():
conn = sqlite3.connect('My.project5.db')
window = Tk()
window.title("REGISTRATION FORM")
window.geometry('550x300')
print("opened database connectivity")
# conn.execute('''CREATE TABLE EMPDATA1
# (ID INT PRIMARY KEY,
# NAME TEXT NOT NULL,
# EMAIL CHAR[50] NOT NULL,
# ADDRESS CHAR[50] NOT NULL,
# GENDER CHAR[50] NOT NULL,
# QUALIFICATION CHAR[50] NOT NULL,
# CITY TEXT NOT NULL,
# STATE TEXT NOT NULL);''')
print("TABLE CREATED SUCCESSFULLY")
name = StringVar()
email = StringVar()
address = StringVar()
gender = StringVar()
qualification = StringVar()
city = StringVar()
state = StringVar()
global txt1
global txt2
global txt3
global txt4
lb1 = Label(window, text="ID")
lb1.grid(column=0, row=0)
lb2 = Label(window, text="NAME")
lb2.grid(column=0, row=1)
lb3 = Label(window, text="EMAIL")
lb3.grid(column=0, row=2)
lb4 = Label(window, text="ADDRESS")
lb4.grid(column=0, row=3)
lb5 = Label(window, text="GENDER")
lb5.grid(column=0, row=4)
lb6 = Label(window, text="QUALIFICATION")
lb6.grid(column=0, row=5)
lb7 = Label(window, text="CITY")
lb7.grid(column=0, row=6)
lb8 = Label(window, text="STATE")
lb8.grid(column=0, row=7)
txt1=StringVar()
txt1 = Entry(window, width=30)
txt1.grid(column=1, row=0)
txt2 = Entry(window, width=30, textvariable=name)
txt2.grid(column=1, row=1)
txt3 = Entry(window, width=30, textvariable=email)
txt3.grid(column=1, row=2)
txt4 = Entry(window, width=30, textvariable=address)
txt4.grid(column=1, row=3)
combo1 = Combobox(window, textvariable=city)
combo1['values'] = (
"Amaravati ", "Itanagar", "Dispur", "Patna", "Raipur", "Panaji", "Gandhinagar", "Chandigarh", "Shimla",
"Srinagar",
"Ranchi", "Bengaluru", "Thiruvananthapuram", "Bhopal", "Mumbai", "Imphal", "Shillong", "Aizawl", "Kohima",
"Bhubaneswar", "Chandigarh", "Jaipur", "Gangtok", "Chennai", "Telangana", "Hyderabad", "Lucknow",
"Dehradun",
"Kolkata")
combo1.current(0)
combo1.grid(column=1, row=6)
combo2 = Combobox(window, textvariable=state)
combo2['values'] = (
"Andhra Pradesh", "Arunachal Pradesh", "Assam", "Bihar", "Chhattisgarh", "Goa", "Gujarat", "Haryana",
"Himachal Pradesh", "Jharkhand", "JAMMU & KASHMIR", "Karnataka", "Kerala", "Madhya Pradesh", "Maharashtra",
"Manipur", "Meghalaya", "Mizoram", "Nagaland", "Odisha", "Punjab", "Rajasthan", "Sikkim", "Tamil Nadu",
"Telangana",
"Tripura", "Uttar Pradesh", "Uttarakhand", "West Bengal")
combo2.current(0)
combo2.grid(column=1, row=7)
combo3 = Combobox(window, textvariable=qualification)
combo3['values'] = ("SSC", "HSC", "GRADUATE", "POST GRADUATE")
combo3.current(0)
combo3.grid(column=1, row=5)
combo4 = Combobox(window, textvariable=gender)
combo4['values'] = ("MALE", "FEMALE")
combo4.current(0)
combo4.grid(column=1, row=4)
global res1
global res2
global res3
res1 = txt1.get()
res2 = txt2.get()
res3 = txt3.get()
def clicked1():
print(txt1.get())
print(txt2.get())
print(txt3.get())
print(txt4.get())
print(combo4.get())
print(combo3.get())
print(combo1.get())
print(combo2.get())
conn.execute("INSERT INTO EMPDATA1 VALUES (" + txt1.get() + ",'" + txt2.get() + "','" + txt3.get() + "','" + txt4.get() + "' ,'" + combo4.get() + "','" + combo3.get() + "', '" + combo1.get() + "','" + combo2.get() + "');")
btn = Button(window, text="SUBMIT", command=clicked1)
btn.grid(column=1, row=8)
window.mainloop()
conn.commit()
conn.close()
def funcsel():
conn = sqlite3.connect('My.project13.db')
window = Tk()
window.title("COURSES SELECTION")
window.geometry('550x300')
print("opened database connectivity")
#conn.execute('''CREATE TABLE TBLCRS1
#(ID INT PRIMARY KEY,
#COURSENAME CHAR[50] NOT NULL,
#COURSESUBJECT CHAR[50] NOT NULL);''')
print("TABLE CREATED SUCCESSFULLY")
coursename = StringVar()
coursesubject = StringVar()
global res4
global res5
lb1 = Label(window, text="ID")
lb1.grid(column=0, row=0)
lb2 = Label(window, text="COURSENAME")
lb2.grid(column=0, row=1)
lb3 = Label(window, text="COURSESUBJECT")
lb3.grid(column=0, row=2)
txt5 = Entry(window, width=30, textvariable=id)
txt5.grid(column=1, row=0)
combo5 = Combobox(window, textvariable=coursename)
combo5['values'] = ("JAVA", "HTML", "PYTHON", "DATABASE", "CLOUD COMPUTING", ".NET")
combo5.current(0)
combo5.grid(column=1, row=1)
combo6 = Combobox(window, textvariable=coursesubject)
combo6['values'] = ("CORE JAVA", "ADVANCED JAVA", "HTML5", "PYTHON3", "AWS", "AZURE", "ASP.NET")
combo6.current(0)
combo6.grid(column=1, row=2)
res4 = combo5.get()
res5 = combo6.get()
def clicked2():
print(combo5.get())
print(combo6.get())
conn.execute("INSERT INTO TBLCRS1 VALUES (" + txt5.get() +" , '" + combo5.get() + "','" + combo6.get() + "');")
btn = Button(window, text="SUBMIT", command=clicked2)
btn.grid(column=1, row=3)
window.mainloop()
conn.commit()
conn.close()
def changepass():
conn = sqlite3.connect('My.project12.db')
window = Tk()
window.title("CHANGE PASSWORD FORM")
window.geometry('550x300')
# conn.execute('''CREATE TABLE TBLREG
# (USERNAME CHAR[50] PRIMARY KEY,
# PASSWORD CHAR[50] NOT NULL,
# NEW PASSWORD CHAR[50] NOT NULL);''')
username = StringVar()
password = StringVar()
lb1 = Label(window, text="USERNAME")
lb1.grid(column=0, row=0)
lb2 = Label(window, text="OLD PASSWORD")
lb2.grid(column=0, row=1)
lb2 = Label(window, text="NEW PASSWORD")
lb2.grid(column=0, row=2)
txt6 = Entry(window, width=30)
txt6.grid(column=1, row=0)
txt7 = Entry(window, width=30)
txt7.grid(column=1, row=1)
txt8 = Entry(window, width=30)
txt8.grid(column=1, row=2)
def clicked3():
conn.execute(
"INSERT INTO TBLCHGPASS VALUES ('" + txt6.get() + "' , '" + txt7.get() + "', '" + txt8.get() + "');")
btn = Button(window, text="SUBMIT", command=clicked3)
btn.grid(column=1, row=3)
window.mainloop()
conn.commit()
conn.close()
def funcrate():
conn = sqlite3.connect('My.project5.db')
window = Tk()
window.title("TRANSACTION FORM")
window.geometry('550x300')
#conn.execute('''CREATE TABLE TBLTRAN2
#(FEES INT NOT NULL,
#DISCOUNT INT NOT NULL,
#NET FEES INT NOT NULL);''')
global res6
global res7
global res8
lb1 = Label(window, text="FEES")
lb1.grid(column=0, row=0)
lb2 = Label(window, text="DISCOUNT")
lb2.grid(column=0, row=1)
lb3 = Label(window, text="NET FEES")
lb3.grid(column=0, row=3)
txt9 = Entry(window, width=30)
txt9.grid(column=1, row=0)
txt10 = Entry(window, width=30)
txt10.grid(column=1, row=1)
txt11 = Entry(window, width=30)
txt11.grid(column=1, row=3)
res6=txt9.get()
res7=txt10.get()
res8=txt11.get()
def calc():
print(txt9.get())
print(txt10.get())
print(txt11.get())
res = int(txt9.get()) - int(txt10.get())
txt11.insert(INSERT, res)
def clicked4():
conn.execute("INSERT INTO TBLTRAN2 VALUES (" + txt9.get() + " , " + txt10.get() + ", " + txt11.get() + ");")
btn = Button(window, text="CALCULATE", command=calc)
btn.grid(column=1, row=2)
btn = Button(window, text="SUBMIT", command=clicked4)
btn.grid(column=1, row=4)
window.mainloop()
conn.commit()
conn.close()
utility_menu = tkinter.Menu(root_menu)
root_menu.add_cascade(label="UTILITY", menu=utility_menu)
utility_menu.add_cascade(label="CHANGE PASSWORRD", command=changepass)
utility_menu.add_cascade(label="CALCULATION", command=funcrate)
utility_menu.add_separator()
utility_menu.add_cascade(label="EXIT", command=window.quit)
master_menu = tkinter.Menu(root_menu)
root_menu.add_cascade(label="MASTER", menu=master_menu)
master_menu.add_cascade(label="REGISTRATION", command=funcreg)
master_menu.add_cascade(label="COURSES", command=funcsel)
def functran():
conn = sqlite3.connect('My.project5.db')
window = Tk()
window.title("TRANSACTION FORM")
window.geometry('550x300')
# conn.execute('''CREATE TABLE EMPDATA1
# (FEES INT NOT NULL,
# DISCOUNT INT NOT NULL,
# NET FEES INT NOT NULL);''')
lb0 = Label(window, text="GET")
lb0.grid(column=0, row=0)
lb1 = Label(window, text="ID")
lb1.grid(column=0, row=1)
lb2 = Label(window, text="NAME")
lb2.grid(column=0, row=2)
lb3 = Label(window, text="EMAIL")
lb3.grid(column=0, row=3)
lb4 = Label(window, text="COURSENAME")
lb4.grid(column=0, row=4)
lb5 = Label(window, text="COURSESUBJECT")
lb5.grid(column=0, row=5)
lb6 = Label(window, text="FEES")
lb6.grid(column=0, row=6)
lb7 = Label(window, text="DISCOUNT")
lb7.grid(column=0, row=7)
lb8 = Label(window, text="NET FEES")
lb8.grid(column=0, row=8)
txt12 = Entry(window, width=30)
txt12.grid(column=1, row=1)
txt13 = Entry(window, width=30)
txt13.grid(column=1, row=2)
txt14 = Entry(window, width=30)
txt14.grid(column=1, row=3)
txt15 = Entry(window, width=30)
txt15.grid(column=1, row=4)
txt16 = Entry(window, width=30)
txt16.grid(column=1, row=5)
txt17 = Entry(window, width=30)
txt17.grid(column=1, row=6)
txt18 = Entry(window, width=30)
txt18.grid(column=1, row=7)
txt19 = Entry(window, width=30)
txt19.grid(column=1, row=8)
def pay():
window = Tk()
window.title("PAYMENT GATEWAY")
window.geometry('550x300')
def funcmon():
global login_success_screen
login_success_screen = Toplevel(window)
login_success_screen.title("PAYMENT SUCCESSFUL")
login_success_screen.geometry("150x100")
Label(login_success_screen, text="VISIT AGAIN").pack()
Button(login_success_screen, text="THANK YOU", command=delete_funcmon).pack()
def delete_funcmon():
login_success_screen.destroy()
def funcnet():
window = Tk()
window.title("NET BANKING")
window.geometry('350x350')
lb = Label(window)
lb.grid(column=0, row=0)
lb1 = Label(window, text="NAME")
lb1.grid(column=0, row=1)
lb = Label(window)
lb.grid(column=0, row=2)
lb2 = Label(window, text="BANK NAME")
lb2.grid(column=0, row=3)
lb = Label(window)
lb.grid(column=0, row=4)
lb3 = Label(window, text="ACCOUNT NO.")
lb3.grid(column=0, row=5)
lb = Label(window)
lb.grid(column=0, row=6)
lb4 = Label(window, text="IFSC NO.")
lb4.grid(column=0, row=7)
lb = Label(window)
lb.grid(column=0, row=8)
lb5 = Label(window, text="AMOUNT PAID")
lb5.grid(column=0, row=9)
lb = Label(window)
lb.grid(column=1, row=0)
txt20 = Entry(window, width=30)
txt20.grid(column=1, row=1)
lb = Label(window)
lb.grid(column=1, row=2)
txt21 = Entry(window, width=30)
txt21.grid(column=1, row=3)
lb = Label(window)
lb.grid(column=1, row=4)
txt22 = Entry(window, width=30)
txt22.grid(column=1, row=5)
lb = Label(window)
lb.grid(column=1, row=6)
txt23 = Entry(window, width=30)
txt23.grid(column=1, row=7)
lb = Label(window)
lb.grid(column=1, row=8)
txt24 = Entry(window, width=30)
txt24.grid(column=1, row=9)
lb = Label(window)
lb.grid(column=1, row=10)
btn2 = Button(window, text="TRANSFER", command=funcmon)
btn2.grid(column=1, row=11)
window.mainloop()
def funcdeb():
window = Tk()
window.title("DEBIT CARD")
window.geometry('550x300')
lb = Label(window)
lb.grid(column=0, row=0)
lb1 = Label(window, text="NAME")
lb1.grid(column=0, row=1)
lb = Label(window)
lb.grid(column=0, row=2)
lb2 = Label(window, text="BANK NAME")
lb2.grid(column=0, row=3)
lb = Label(window)
lb.grid(column=0, row=4)
lb3 = Label(window, text="CARD NO.")
lb3.grid(column=0, row=5)
lb = Label(window)
lb.grid(column=0, row=6)
lb4 = Label(window, text="CVV NO.")
lb4.grid(column=0, row=7)
lb = Label(window)
lb.grid(column=0, row=8)
lb5 = Label(window, text="AMOUNT PAID")
lb5.grid(column=0, row=9)
lb = Label(window)
lb.grid(column=1, row=0)
txt25 = Entry(window, width=30)
txt25.grid(column=1, row=1)
lb = Label(window)
lb.grid(column=1, row=2)
txt26 = Entry(window, width=30)
txt26.grid(column=1, row=3)
lb = Label(window)
lb.grid(column=1, row=4)
txt27 = Entry(window, width=30)
txt27.grid(column=1, row=5)
lb = Label(window)
lb.grid(column=1, row=6)
txt28 = Entry(window, width=30)
txt28.grid(column=1, row=7)
lb = Label(window)
lb.grid(column=1, row=8)
txt29 = Entry(window, width=30)
txt29.grid(column=1, row=9)
lb = Label(window)
lb.grid(column=1, row=10)
btn2 = Button(window, text="TRANSFER", command=funcmon)
btn2.grid(column=1, row=11)
window.mainloop()
lb = Label(window)
lb.pack()
btn1 = Button(window, text="NET BANKING", command=funcnet)
btn1.pack()
lb = Label(window)
lb.pack()
btn2 = Button(window, text="DEBIT CARD", command=funcdeb)
btn2.pack()
window.mainloop()
def detail():
txt12.insert(INSERT, res1)
txt13.insert(INSERT, res2)
txt14.insert(INSERT, res3)
txt15.insert(INSERT, res4)
txt16.insert(INSERT, res5)
txt17.insert(INSERT, res6)
txt18.insert(INSERT, res7)
txt19.insert(INSERT, res8)
btn = Button(window, text="DETAILS", command=detail)
btn.grid(column=1, row=0)
btn = Button(window, text="PAY", command=pay)
btn.grid(column=1, row=9)
window.mainloop()
conn.commit()
conn.close()
transaction_menu = tkinter.Menu(root_menu)
root_menu.add_cascade(label="TRANSACTION", menu=transaction_menu)
transaction_menu.add_cascade(label="TRANSACTION", command=functran)
window.mainloop()
def signup():
global register_screen
register_screen = Toplevel(window)
register_screen.title("Register")
window.geometry('550x300')
global username
global password
global username_entry
global password_entry
username = StringVar()
password = StringVar()
Label(register_screen, text="Please enter details below").pack()
Label(register_screen, text="").pack()
username_lable = Label(register_screen, text="Username * ")
username_lable.pack()
username_entry = Entry(register_screen, textvariable=username)
username_entry.pack()
password_lable = Label(register_screen, text="Password * ")
password_lable.pack()
password_entry = Entry(register_screen, textvariable=password, show='*')
password_entry.pack()
Label(register_screen, text="").pack()
Button(register_screen, text="Register",command = register_user).pack()
def login():
global login_screen
login_screen = Toplevel(window)
login_screen.title("Login")
window.geometry('550x300')
Label(login_screen, text="Please enter details below to login").pack()
Label(login_screen, text="").pack()
global username_verify
global password_verify
username_verify = StringVar()
password_verify = StringVar()
global username_login_entry
global password_login_entry
Label(login_screen, text="Username * ").pack()
username_login_entry = Entry(login_screen, textvariable=username_verify)
username_login_entry.pack()
Label(login_screen, text="").pack()
Label(login_screen, text="Password * ").pack()
password_login_entry = Entry(login_screen, textvariable=password_verify, show= '*')
password_login_entry.pack()
Label(login_screen, text="").pack()
Button(login_screen, text="Login", command = login_verify).pack()
# Implementing event on register button
def register_user():
username_info = username.get()
password_info = password.get()
file = open(username_info, "w")
file.write(username_info + "\n")
file.write(password_info)
file.close()
username_entry.delete(0, END)
password_entry.delete(0, END)
Label(register_screen, text="Registration Success").pack()
# Implementing event on login button
def login_verify():
username1 = username_verify.get()
password1 = password_verify.get()
username_login_entry.delete(0, END)
password_login_entry.delete(0, END)
list_of_files = os.listdir()
if username1 in list_of_files:
file1 = open(username1, "r")
verify = file1.read().splitlines()
if password1 in verify:
login_sucess()
else:
password_not_recognised()
else:
user_not_found()
def login_sucess():
global login_success_screen
login_success_screen = Toplevel(login_screen)
login_success_screen.title("Success")
login_success_screen.geometry("150x100")
Label(login_success_screen, text="Login Success").pack()
Button(login_success_screen, text="OK", command=clicked).pack()
# Designing popup for login invalid password
def password_not_recognised():
global password_not_recog_screen
password_not_recog_screen = Toplevel(login_screen)
password_not_recog_screen.title("Success")
password_not_recog_screen.geometry("150x100")
Label(password_not_recog_screen, text="Invalid Password ").pack()
Button(password_not_recog_screen, text="OK", command=delete_password_not_recognised).pack()
# Designing popup for user not found
def user_not_found():
global user_not_found_screen
user_not_found_screen = Toplevel(login_screen)
user_not_found_screen.title("Success")
user_not_found_screen.geometry("150x100")
Label(user_not_found_screen, text="User Not Found").pack()
Button(user_not_found_screen, text="OK", command=delete_user_not_found_screen).pack()
# Deleting popups
def delete_login_success():
login_success_screen.destroy()
def delete_password_not_recognised():
password_not_recog_screen.destroy()
def delete_user_not_found_screen():
user_not_found_screen.destroy()
lb = Label(window)
lb.pack()
btn1=Button(window,text="LOGIN",command=login)
btn1.pack()
lb = Label(window)
lb.pack()
btn2=Button(window,text="SIGN UP",command=signup)
btn2.pack()
window.mainloop()
conn.commit()
conn.close()
|
# Escreva um programa para aprovar o emprestimo bancario para a compra de uma casa. O programa vai perguntar o valor da casa, o salario do comprador e em quantos anos ele vai pagar
# Calcule o valor da prestação mensal sabendo que ela não pode exeder 30% do salario ou entãoo emprestimo será negado
valor = float(input('\nQual é o valor da casa?: R$'))
salario = float(input('Qual é o seu salario?: R$'))
ano = int(input('Em quantos anos a casa vai ser paga?: '))
presMensal = valor / (ano * 12)
print('\nR${:.2f}' .format(presMensal))
if(presMensal >= (salario * (30 / 100))):
print('Recusado')
elif(presMensal <= (salario * (30 / 100))):
print('Aprovado')
|
from datetime import date
year = date.today().year
age = int(input('Digite seu ano de nascimento: '))
age = year - age
if(age <= 9):
print('Mirim')
elif((age > 9) and (age <= 14)):
print('Infantil')
elif((age > 14) and (age <= 19)):
print('Junior')
elif((age > 19) and (age <= 20)):
print('Sênior')
else:
print('Master')
|
# Faça um programa que jogue par ou ímpar com o computador. O jogo só será interrompido quando o jogador perder, mostrando o total de vitórias consecutivas que ele conquistou no final do jogo
from random import randint
from time import sleep
c = 0
ppt = 'PEDRA, PAPEL, TESOURA'
print('-' * 30)
print(ppt.center(30))
print('-' * 30)
while True:
cpu = randint(1,3)
player = int(input('\nEscolha entre pedra(1), papel(2) e tesoura(3)'))
if(player == 1):
if(cpu == 1):
print('\nCPU diz: PEDRA')
print('EMPATE!')
elif(cpu == 2):
print('\nCPU diz: PAPEL')
print('Você perdeu...')
break
elif(cpu == 3):
print('\nCPU diz: TESOURA')
print('PARABENS!!! Você ganhou!')
c += 1
elif(player == 2):
if(cpu == 1):
print('\nCPU diz: PEDRA')
print('PARABENS!!! Você ganhou!')
c += 1
elif(cpu == 2):
print('\nCPU diz: PAPEL')
print('EMPATE!')
elif(cpu == 3):
print('\nCPU diz: TESOURA')
print('Você perdeu...')
break
elif(player == 3):
if(cpu == 1):
print('\nCPU diz: PEDRA')
print('Você perdeu...')
break
elif(cpu == 2):
print('\nCPU diz: PAPEL')
print('PARABENS!!! Você ganhou!')
c += 1
elif(cpu == 3):
print('\nCPU diz: TESOURA')
print('EMPATE!')
print(f'\nVocê ganhou {c} vezes') |
#Peça dois valores e escreva na tea o maior ou diga se os dois são iguais
n1 = int(input('Digite o primeiro numero: '))
n2 = int(input('Digite o segundo numero: '))
n = [n1, n2]
n.sort()
print('')
if(n[0] == n[1]):
print('Os numeros são iguais!')
else:
if(n[1] == n1):
print('O primeiro valor é maior!')
if(n[1] == n2):
print('O segundo valor é maior!') |
# Desenvolva um programa que leia duas notas de um aluno, calcule e mostre sua media
n1 = float(input('Nota 1: '))
n2 = float(input('Nota 2: '))
x = (n1 + n2) / 2
print('Media: {:.1f}' .format(x))
|
# Faça um programa que leia um número qualquer e mostre o seu fatorial
num = int(input('Digite um numero: '))
result = 1
print(f'Calculando {num}! = ', end='')
while(num != 0):
result = result * num
if(num == 1):
print(num, end=' = ')
print(result)
else:
print(num, end=' x ')
num = num - 1
|
# Desenvolva um programa que pergunte a distancia de uma viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por km para viagens de ate 200km e R$0,45 para viagens mais longas
km = int(input('quantos km teve a viagem: '))
if(km <= 200):
price = km * 0.5
elif(km > 200):
price = km * 0.45
print('O preço da viagem é R${:.2f}!' .format(price))
|
#Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre:
# A) Quantos números foram digitados.
# B) A lista de valores, ordenada de forma decrescente.
# C) Se o valor 5 foi digitado e está ou não na lista.
num = list()
print('\nDigite uma letra para parar')
print('-=-' * 10)
while True:
n = str(input('Digite um numero: '))
if(n.isnumeric()):
num.append(int(n))
elif(n.isalpha()):
print('-=-' * 10)
break
else:
print('-=-' * 10)
print('Tente de novo')
print('-=-' * 10)
if(5 in num):
val = 'Tem'
else:
val = 'Não tem'
num.sort(reverse=True)
print(f'Foram digitados {len(num)} numeros \nA lista de valores de forma decrecente {num} \n{val} um numero 5 na lista') |
# Converta uma temperatura de C° para F°
c = float(input('C° = '))
f = (c * 9/5) + 32
print('{}F°' .format(f)) |
# Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles
end = False
times = 0
add = 0
while(end == False):
n = int(input(f'Digite o {times + 1}° valor ou digite "0" pra terminar o programa: '))
if(n != 0):
add = add + n
times = times + 1
if((n == 0) and (times == 1)):
print(f'O numero foi adicionado {times} vez e o resultado é {add}')
end = True
elif(n == 0):
print(f'Os numeros foram adicionados {times} vezes e o resultado é {add}')
end = True |
# Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores ‘M’ ou ‘F’. Caso esteja errado, peça a digitação novamente até ter um valor correto
loop = True
while(loop == True):
gender = str(input('Qual é o seu sexo?(M, F): '))
if gender.lower() in('m', 'f'):
loop = False
else:
print('\nVocê colocou um valor invalido, tente de novo!\n')
loop = True |
# Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista. Caso o número já exista lá dentro, ele não será adicionado. No final, serão exibidos todos os valores únicos digitados, em ordem crescente
lnum = list()
print('Digite um numero para adicionalo na lista')
print('Digite alguma letra para parar')
print('-' * 30)
while True:
n = str(input('Digite um valor: '))
if(n.isnumeric()):
if(int(n) in lnum):
print('Esse numero já esta na lista')
elif(int(n) not in lnum):
lnum.append(int(n))
elif(n.isalpha()):
break
elif(n == ''):
print('Você não digitou nada')
elif(n.isalnum):
print('Você digitou uma letra e um numero')
lnum.sort()
print(' '.join(str(a) for a in lnum)) |
def has_even_neg_numbers(array):
neg_num = 0
for num in array[-3:]:
if num < 0:
neg_num = neg_num + 1
if neg_num == 0:
return None
if neg_num % 2 == 0
return -3
def solution(array):
sorted_array = sorted(array, key=lambda num: abs(num))
print(sorted_array)
while len(sorted_array) >= 3:
neg = has_even_neg_numbers(sorted_array[-3:])
if neg is None:
break
print(len(sorted_array), has_even_neg_numbers(sorted_array[-3:]))
sorted_array.pop(-1)
print(sorted_array)
return sorted_array[-3:-2][0] * sorted_array[-2:-1][0] * sorted_array[-1:][0]
assert(solution([-3, 1, 2, -2, 5, 6]) == 60)
assert(solution([2, -2, 2]) == -8)
assert(solution([-2, -2, 2]) == 8) |
from collections import deque
def solution(array, cycles):
if len(array) == 0:
return []
new_list = array
for _ in range(cycles):
queue = deque(new_list)
queue.appendleft(de.pop())
new_list = list(de)
return new_list |
from .factory import *
"""
This module handles taking an external file and parsing out youtube links.
This will be used on an extract of a bookmarks.html from mozilla.
"""
"https://www.youtube.com/watch?v=U18Ru3k5HrM"
def find_url(string):
count, url, array = 0, "", []
index = string.find("https://www.youtube.com/watch?v=")
url = string[index+32:index+43]
if index >= 0:
count += 1
array.append(url)
find_url(string[index+43:])
return count, array
def extract_links_from_file(input, output):
"""For each line in the input file, we need to find all the strings like
https://www.youtube.com/watch?v=%
where the % is an 11 char length string.
"""
count = 0
matches = []
with open(input, "r", encoding="utf-8") as file:
for line in file:
inner_count, inner_matches = find_url(line)
count += inner_count
matches.extend(inner_matches)
with open(output, "w+") as write_file:
for url in matches:
write_file.write(f"{url}\n")
with open(output, "r") as read:
lines = 0
for url in read:
lines += 1
print(f"Found {lines} unique urls")
if __name__ == "__main__":
extract_links_from_file("./resources/bookmarks.html", "./resources/output")
|
#!/usr/bin/env python
# coding: utf-8
# # 1. Conditional Basics
# In[73]:
# a. prompt the user for a day of the week, print out whether the day is Monday or not
input_day = input("Please type a day of the week: ")
if input_day.capitalize() == "Monday":
print("It is Monday")
else:
print("It is not Monday")
# In[75]:
# How to determine what day it is today?
import datetime
datetime.datetime.today()
datetime.datetime.today().weekday()
if datetime.datetime.today().weekday() == 0:
print("Today is Monday")
else:
print("Today is not Monday")
# In[76]:
# b. prompt the user for a day of the week, print out whether the day is a weekday or a weekend
user_day = input("Please type a weekday:")
weekday = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
weekend = ["Saturday", "Sunday"]
if user_day.capitalize() in weekday:
print("It is a Weekday")
elif user_day.capitalize() in weekend:
print("It is a Weekend")
else:
print("Invalid input")
# In[19]:
# c. create variables and make up values for
# the number of hours worked in one week
# the hourly rate
# how much the week's paycheck will be
# write the python code that calculates the weekly paycheck.
# You get paid time and a half if you work more than 40 hours
work_hours = 20
hourly_rate = 20
if 0 <= work_hours <= 40:
week_pay = work_hours * hourly_rate
elif 40 < work_hours <= 7*24:
week_pay = 40 * hourly_rate + (work_hours - 40) * hourly_rate * 1.5
elif work_hours > 7*24:
week_pay = "Are you from Mars?"
else:
week_pay = "You'd better start work"
print(week_pay)
# # 2. Loop Basics
# In[24]:
# a. While
# Create an integer variable i with a value of 5.
# Create a while loop that runs so long as i is less than or equal to 15
# Each loop iteration, output the current value of i, then increment i by one.
i = 5
while i <= 15:
print(i)
i += 1
# In[25]:
# Create a while loop that will count by 2's starting with 0 and ending at 100.
# Follow each number with a new line.
i = 0
while i <= 100:
print(i)
i += 2
# In[31]:
# Alter your loop to count backwards by 5's from 100 to -10.
i = 100
while i >= -10:
print(i)
i -= 5
# In[39]:
# Create a while loop that starts at 2, and displays the number squared on each line
# while the number is less than 1,000,000. Output should equal:
i = 2
while i <= 1000000:
print(i)
i = i * i
# In[41]:
# Write a loop that uses print to create the output shown below.
i = 100
while i >= 5:
print(i)
i -= 5
# In[19]:
# It is very convenient to generate arithmetic and geometric progression
i = 100
n = []
while i >= 5:
n.append(i)
i -= 5
print(n)
# In[58]:
# i. Write some code that prompts the user for a number,
# then shows a multiplication table up through 10 for that number.
num = int(input("Type in a : "))
for i in range (1,11):
print(f"{num} x {i} = {num*i}")
# In[11]:
# ii. Create a for loop that uses print to create the output shown below.
# use "1"*i to generate "111...", then conver it to int
for i in range(1,10):
print(int("1"*i)*i)
# C. break and continue
#
# i. Prompt the user for an odd number between 1 and 50. Use a loop and a break statement to continue prompting the user if they enter invalid input. Hint: use the isdigit method on strings so determine this. Use a loop and continue statement to output all the odd numbers between 1 and 50, except for the number the user entered.
# In[7]:
# Step 1: use WHILE to create a list of odd number between 1 and 50
odd_number = []
n = 1
while n < 50:
odd_number.append(n)
n += 2
print(odd_number) # list is correct
# In[ ]:
# Step 2: validate the input (user_input can be any data type: int, float, boolean, list, dict, etc.)
user_input = input("Enter an odd number between 1 and 50: ")
type(user_input) # No matter what the user input, the datatype that INPUT returns is str.
# In[122]:
# Test .isdigit()
# .isdigit() return flase if the string input is negative or a float
print("5".isdigit())
print("-5".isdigit())
print("4.5".isdigit())
# .isdecimal() returns false if the string input is negative or a float
print("5".isdecimal())
print("-5".isdecimal())
print("4.5".isdecimal())
# .isnumeric() also returns false if the string input is negative or a floast
print("5".isnumeric())
print("-5".isnumeric())
print("4.5".isnumeric())
# int() is a good tool to convert string to integer when the string input is "integer" but
# it returns ValueError when the string input is "float"
int("4")
# In[40]:
# Limited input vs. Unlimited input
# Limited input: the users are given 3 chances to enter the number.
user_input = input("Enter an odd number between 1 and 50: ")
for i in range(0,4):
if i == 3: # this is 4th time the user trys to input
print("Please call xxx-xxx-xxxx to regain the access")
break
if user_input.isdigit() == False or int(user_input) < 1 or int(user_input) >= 50 or int(user_input)%2 != 1:
print(f"Not Valid and {2-i} times left")
user_input = input("Enter an odd number between 1 and 50: ")
else:
print("Valid")
break
# In[12]:
# Unlimited input:
user_input = input("Enter an odd number between 1 and 50: ")
while user_input.isdigit() == False or int(user_input) < 1 or int(user_input) >= 50 or int(user_input)%2 != 1:
print("Not Valid")
user_input = input("Enter an odd number between 1 and 50: ")
# In[1]:
# Step 3: output all odd number between 1 and 50, except the number the user input
user_input = input("Enter an odd number between 1 and 50: ")
odd_number = []
n = 1
while n < 50:
odd_number.append(n)
n += 2
while user_input.isdigit() == False or int(user_input) < 1 or int(user_input) >= 50 or int(user_input)%2 != 1:
print("Not Valid")
user_input = input("Enter an odd number between 1 and 50: ")
for num in odd_number:
if num == int(user_input):
print(f"Yikes! Skipping number: {num}")
# continue
else:
print(f"Here is an odd number: {num}")
# d. The INPUT function can be used to prompt for input and use that input in your python code. Prompt the user to enter a positive number and write a loop that counts from 0 to that number. (Hints: first make sure that the value the user entered is a valid number, also note that the INPUT function returns a string, so you'll need to convert this to a numeric type.
# In[1]:
input_int = input("Please type in an positive integer: ")
while input_int.isdigit() == False:
input_int = input("Please type in an integer: ")
num_count = [n for n in range(0,int(input_int)+1)]
print(num_count)
# How about positive float, like 4.5?
# e. Write a program that prompts the user for a positive integer. Next write a loop that prints out the numbers from the number the user entered down to 1.
# In[51]:
input_int = input("Please type in an positive integer: ")
while input_int.isdigit() == False:
input_int = input("Please type in an integer: ")
num_count = [n for n in range(1,int(input_int)+1)]
num_count.reverse()
print(num_count)
# # Q3: Fizzbuzz
# One of the most common interview questions for entry-level programmers is the FizzBuzz test. Developed by Imran Ghory, the test is designed to test basic looping and conditional logic skills.
# In[53]:
# Write a program that prints the numbers from 1 to 100.
num = []
for i in range(1, 101):
num.append(i)
print(num)
# You can also use list comprehension
# In[57]:
# For multiples of three print "Fizz" instead of the number
user_input = input("Please tyep in a number: ")
if user_input.isdigit() and (int(user_input)%3 == 0):
print("Fizz")
else:
print("invalid")
# In[59]:
# For the multiples of five print "Buzz".
user_input = input("Please tyep in a number: ")
if user_input.isdigit() and (int(user_input)%5 == 0):
print("Buzz")
else:
print("invalid")
# In[60]:
# For numbers which are multiples of both three and five print "FizzBuzz".
user_input = input("Please tyep in a number: ")
if user_input.isdigit() and (int(user_input)%3 == 0) and (int(user_input)%5 == 0):
print("FizzBuzz")
else:
print("invalid")
# # Q4: Display a table of powers.
# In[9]:
# Use TRY EXCEPT for the string input validation
# type(int("float or contains string")) returns ValueError
try:
user_input = int(input("What number would you like to go up to?"))
print()
print("Here is your table!")
print()
except ValueError:
print("Invalid entry.")
# Calculate the squares and cubes of the input and put them in a list
filed_names = ["number", "squared", "cubed"]
# print(data_list) # valid
print("number| squared| cubed")
print("-"*20)
for i in range(0,user_input):
print('{:<6}|'.format(f"{(i+1)}"),'{:<7}|'.format(f"{(i+1)**2}"),'{:<7}'.format(f"{(i+1)**3}"))
print()
# Add continuing prompting
do_it_again = input("Do you want to continue? Please type Y/N")
if do_it_again == "Y":
user_input = input("Pleaese enter a numerical grade: ")
user_input = int(user_input)
# In[18]:
# Use WHILE LOOP to combine them together
user_input = "Y"
while user_input == "Y":
user_input = int(input("What number would you like to go up to?"))
print("number| squared| cubed")
print("-"*20)
for i in range(0,user_input):
print('{:<6}|'.format(f"{(i+1)}"),'{:<7}|'.format(f"{(i+1)**2}"),'{:<7}'.format(f"{(i+1)**3}"))
print()
user_input = (input("Do you want to continue? Please type Y/N"))
# # Q5: Convert given number grades into letter grades
# In[ ]:
#Prompt the user for a numerical grade from 0 to 100.
num_grade = input("Pleaese enter a numerical grade: ") #valid
num_grade = int(num_grade)
# Display the corresponding letter grade
if 88 <= num_grade <=100:
print("A")
elif 80 <= num_grade <=87:
print("B")
elif 67 <= num_grade <=79:
print("C")
elif 60 <= num_grade <= 66:
print("D")
elif 0 <= num_grade <= 59:
print("F")
# Prompt the user to continue
do_it_again = input("Do you want to continue? Please type Y/N")
if do_it_again == "Y":
num_grade = input("Pleaese enter a numerical grade: ")
num_grade = int(num_grade)
# In[57]:
# Use the LOOP to make the continuing prompting
num_grade = input("Pleaese enter a numerical grade: ")
num_grade = int(num_grade)
if 88 <= num_grade <=100:
print("A")
elif 80 <= num_grade <=87:
print("B")
elif 67 <= num_grade <=79:
print("C")
elif 60 <= num_grade <= 66:
print("D")
elif 0 <= num_grade <= 59:
print("F")
do_it_again = input("Do you want to continue? Please type Y/N")
while do_it_again == "Y":
num_grade = input("Pleaese enter a numerical grade: ")
num_grade = int(num_grade)
if 88 <= num_grade <=100:
print("A")
elif 80 <= num_grade <=87:
print("B")
elif 67 <= num_grade <=79:
print("C")
elif 60 <= num_grade <= 66:
print("D")
elif 0 <= num_grade <= 59:
print("F")
do_it_again = input("Do you want to continue? Please type Y/N")
# In[19]:
# Simplify the coding:
num_grade = "Y"
while num_grade == "Y":
num_grade = input("Pleaese enter a numerical grade: ")
num_grade = int(num_grade)
if 88 <= num_grade <=100:
print("A")
elif 80 <= num_grade <=87:
print("B")
elif 67 <= num_grade <=79:
print("C")
elif 60 <= num_grade <= 66:
print("D")
elif 0 <= num_grade <= 59:
print("F")
num_grade = input("Do you want to continue? Please type Y/N")
# # Q6: Create a list of dictionaries where each dictionary represents a book that you have read. Each dictionary in the list should have the keys title, auther and genre. Loop through the list and print out information about each book.
# # Prompt the user to enter a genre, then loop through your books list and print out the titles of all the books in that genre.
# In[56]:
# create a list of dicts
book_shelf = [
{"title": "President of America",
"auther": "Jon Roper",
"genre": "history"},
{"title": "Marketer's Toolkit",
"auther": "Richard Luecke",
"genre": "economy"},
{"title": "Probability for Risk Management 2",
"auther": "Hassett Stewart",
"genre": "math"},
]
for i in range(0,3):
print(book_shelf[i])
# Prompt the user to enter a genre
enter_genre = input("Please enter a genre:")
# Loop through your books list and print out the titles of all the books in that genre
for i in range(0,3):
if enter_genre == book_shelf[i]["genre"]:
print(book_shelf[i]["title"])
else:
continue
|
import threading
import time
import random
semaphore = threading.Semaphore(0) # 创建信号量
def producer():
global item
time.sleep(3)
item = random.randint(1, 1000)
print("product : 生产 %s." % item)
semaphore.release()
def consumer():
print("consumer : 挂起")
semaphore.acquire()
print("consumer : 消费 %s." % item)
threads = []
for i in range(0, 2):
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer)
t1.start()
t2.start()
threads.append(t1)
threads.append(t2)
for t in threads:
t.join()
|
# you can add imports but you should not rely on libraries that are not already provided in "requirements.txt #
from collections import deque
import copy
def breadth_first_search(stack):
flip_sequence = []
# --- v ADD YOUR CODE HERE v --- #
visited = deque()
deq = deque()
traverse = []
counter = 0
seq = deque()
start_node = stack.copy()
visited.appendleft(start_node)
deq.append(start_node)
seq.append(counter)
while deq:
s = deq.pop()
seq.pop()
if s.check_ordered() == True:
print(s.order)
print(s.orientations)
traverse.append(counter)
print(seq)
for idx, val in enumerate(s.order):
node = s.copy()
node.flip_stack(idx+1)
counter = idx+1
if node not in visited:
new_seq = []
visited.append(node)
deq.append(node)
new_seq.append(counter)
seq.append(new_seq)
flip_sequence = traverse
return flip_sequence
# ---------------------------- #
def depth_first_search(stack):
flip_sequence = []
# --- v ADD YOUR CODE HERE v --- #
s = stack.copy()
stk = []
stk.append(s)
visited = deque()
path = []
seq = []
counter = 0
traverse = []
while (len(stk)):
s = stk[-1]
stk.pop()
if s.check_ordered() == True:
print(s.order)
print(s.orientations)
traverse.append(counter)
for idx, val in enumerate(s.order):
node = s.copy()
node.flip_stack(idx+1)
counter = idx+1
if node not in visited:
visited.appendleft(node)
new_seq = []
new_seq.append(counter)
seq.append(new_seq)
stk.append(node)
flip_sequence = traverse
return flip_sequence
# ---------------------------- #
|
import random
count = 0
f = open("highscore.txt", "r")
currentHigh = int(f.read())
f.close()
guessed = False
print("The current high score is: {}".format(currentHigh))
difficulty = int(input("What do you want the difficulty to be (Number)"))
guessNumber = random.randint(0,difficulty+1)
while (guessed == False):
guess = int(input("What's your guess \n"))
count += 1
if (guess == guessNumber):
guessed = True
elif (guess < guessNumber):
print("Higher")
elif (guess > guessNumber):
print("Lower")
elif(count == "50"):
break
if(count != 50):
print("congrats!")
if((50 - count) * difficulty > currentHigh):
f = open("highscore.txt", "w")
f.write(str((50 - count) * difficulty))
f.close()
print("You got a new high score of {}!".format((50-count)*difficulty))
else:
print("You lost...")
f = open("highscore.txt", "w")
f.write(str(currentHigh))
f.close()
|
import numpy as np
import matplotlib.pyplot as plt
### Uncomment each section and play with the variables marked as hyper-parameters
###
###grid search and random search
'''
n_search = 10 #hyperparameter #how many values should we search
x_plot = np.linspace(0.001, 2.5, 400)
y_plot = (np.sin(10*np.pi*x_plot)/(2*x_plot)) + (x_plot-1)**4 #function we are optimizing
x = np.arange(0.001, 2.5, 2.5/n_search) #grid search
#x = np.random.rand(10)*2.5 #random search
y = (np.sin(10*np.pi*x)/(2*x)) + (x-1)**4
min_ind = np.argmin(y) #index of minimum value of y
min_y = y[min_ind] #minimum value of y
min_x = x[min_ind] #value of x for minimum value of y
print('Lowest Y of',min_y, 'occurs at X', min_x)
plt.figure()
plt.plot(x_plot, y_plot)
plt.scatter(x, y, c='b')
plt.scatter([min_x], [min_y], c='r')
plt.show()
'''
###gradient descent with known equation
'''
def my_function(x, deriv=False):
if deriv:
return (-np.sin(10*np.pi*x)/(2*x**2)) + 4*(x-1)**3 + (5*np.pi*np.cos(10*np.pi*x))/x
else:
return (np.sin(10*np.pi*x)/(2*x)) + (x-1)**4
learning_rate = 0.001 #hyperparameter #controls the size of the steps you take
steps = 10 #hyperparameter#number of steps to take
x_plot = np.linspace(0.001, 2.5, 400)
y_plot = my_function(x_plot)
plt.ion()
plt.figure()
plt.plot(x_plot, y_plot)
new_x = (np.random.rand()*2)+0.001
for i in range(steps):
current_x = new_x
current_y = my_function(current_x)
current_deriv = my_function(current_x, deriv=True)
new_x = current_x - learning_rate*current_deriv
#final position of search is plotted in red
plt.scatter([current_x], [current_y], c='r' if i==steps-1 else 'b')
'''
###gradient descent without known equation
###we can sample from the function but we cant model it mathematically
'''def my_function(x):
#pretend we dont know this equation
return (np.sin(10*np.pi*x)/(2*x)) + (x-1)**4
learning_rate = 0.001 #hyperparameter #controls the size of the steps you take
steps = 10 #hyperparameter #number of steps to take
epsilon = 0.001 #hyperparameter #step size for calculating gradient, lower is better
x_plot = np.linspace(0.001, 2.5, 400)
y_plot = my_function(x_plot)
plt.ion()
plt.figure()
plt.plot(x_plot, y_plot)
plt.show()
new_x = (np.random.rand()*2)+0.001
for i in range(steps):
current_x = new_x
current_y = my_function(current_x)
#current_deriv = my_function(current_x, deriv=True)
test_x = current_x + epsilon
test_y = my_function(test_x)
current_deriv = (test_y-current_y) / epsilon
new_x = current_x - learning_rate*current_deriv
#final position of search is plotted in red
plt.scatter([current_x], [current_y], c='r' if i==steps-1 else 'b')
'''
###gradient descent with momentum
'''
def my_function(x, deriv=False):
if deriv:
return (-np.sin(10*np.pi*x)/(2*x**2)) + 4*(x-1)**3 + (5*np.pi*np.cos(10*np.pi*x))/x
else:
return (np.sin(10*np.pi*x)/(2*x)) + (x-1)**4
learning_rate = 0.001 #hyperparameter #controls the size of the steps you take
steps = 10 #hyperparameter #number of steps to take
momentum_decay = 0.8 #hyperparameter #controls how much previous gradients contribute to the current step
x_plot = np.linspace(0.001, 2.5, 400)
y_plot = my_function(x_plot)
plt.ion()
plt.figure()
plt.plot(x_plot, y_plot)
plt.show()
new_x = (np.random.rand()*2)+0.001
current_momentum = 0
for i in range(steps):
current_x = new_x
current_y = my_function(current_x)
current_deriv = my_function(current_x, deriv=True)
current_momentum = (momentum_decay*current_momentum) + learning_rate*current_deriv
new_x = current_x - current_momentum
#final position of search is plotted in red
plt.scatter([current_x], [current_y], c='r' if i==steps-1 else 'b')
'''
|
# STAT/CS 287
# HW 01
#
# Name: Cecily Page
# Date: September 11 2018
import urllib.request
from os import path
from string import punctuation
import collections
import operator
def words_of_book():
"""Download `A tale of two cities` from Project Gutenberg. Return a list of
words. Punctuation has been removed and upper-case letters have been
replaced with lower-case.
"""
# DOWNLOAD BOOK:
url = "http://www.gutenberg.org/files/98/98.txt"
req = urllib.request.urlopen(url)
charset = req.headers.get_content_charset()
raw = req.read().decode(charset)
# PARSE BOOK
raw = raw[750:] # The first 750 or so characters are not part of the book.
# Loop over every character in the string, keep it only if it is NOT
# punctuation:
exclude = set(punctuation) # Keep a set of "bad" characters.
list_letters_noPunct = [ char for char in raw if char not in exclude ]
# Now we have a list of LETTERS, *join* them back together to get words:
text_noPunct = "".join(list_letters_noPunct)
# (http://docs.python.org/3/library/stdtypes.html#str.join)
# Split this big string into a list of words:
list_words = text_noPunct.strip().split()
# Convert to lower-case letters:
list_words = [ word.lower() for word in list_words ]
return list_words
def read_file_by_word(file_path: str):
with open(file_path, 'r') as file_name:
list_words = file_name.read().split()
return list_words
def use_cashed(file_path):
if path.exists(file_path):
list_words = read_file_by_word(file_path)
return list_words
else:
with open(file_path, 'w') as file:
for word in words_of_book():
file.write(word + ' ')
return words_of_book()
def count_most_common(word_list):
all_words = {}
for word in word_list:
if word not in all_words:
all_words[word] = 1
elif word in all_words:
all_words[word] += 1
sorted_word_count = sorted(list(all_words.items()), key=lambda x: x[1], reverse=True)
return sorted_word_count
word_list = use_cashed('tale_of_two_cities.txt')
word_count = count_most_common(word_list)
### 3.2
most_used_words = word_count[:100]
print(most_used_words)
### 3 bonus
print(collections.Counter(word_list))
|
# Understanding
# * can we count
# solution: build count var
# * ONE pass, not FIRST pass
# sol: setup for the one pass
# turns out ^^^ was incorrect :grin:
# c
# [h/1] [2] [3] [4] [5] [6] [7] [t/8]
# m
# m = c // 2 + 1
# when (count reaches tail || next == null)
# return m
# class Node:
# def __init__(self, value):
# self.value = value
# self.next = None
# def __len__(self):
# # come back here later
# return self.length
# def findMiddle(self, value):
# count = 0
# middle = 0
# while self.next != None:
# # track current node
# count += 1
# middle = (count // 2) + 1
# return middle
# f = Node(8)
# print(f.findMiddle)
# How do you reverse a singly linked list without recursion?
# You may not store the list, or it’s values, in another data structure.
# track original tail
# make current head into tail
# increment the list, moving each next to head
# stop if current head = original tail
# !
# [h/1] [2] [3] [4] [5] [6] [7] [t/8]
# [h/5] [4] [3] [2] t
# !
# [h/1] [2] [3] [4] [5] [6] [7] [t/8]
# [h/2] [1] [3] [4] [5] [6] [7] [t/8]
# [h/3] [2] [1] [4] [5] [6] [7] [t/8]
# [h/7] [6] [5] [4] [3] [2] [1] [t/8]
# [h/7] [6] [5] [4] [3] [2] [1] [t/8]
# when you get to the original tail, make orig tail current head and current head to next
class Shoe():
def __init__(self, node=None):
# self.value = value
self.next = None
self.head = node
self.tail = node
def walk():
# var for current_tail
# var for original_tail
current_head = self.head
original_head = self.head
original_tail = self.tail
while self.next != original_tail
# make current_node the new_head
|
name=input("enter your name:")
surname=input("enter your surname:")
deneme=3
failed=0
while True:
if deneme==0:
print("please try again later..")
break
if name=="Yusuf" and surname=="Volkan":
print("Welcome {} {}".format(name,surname))
deneme-=1
break
if name=="Yusuf" and surname!="Volkan":
print("Soyadınızı doğru giriniz lütfen..")
deneme-=1
elif name!="Yusuf" and surname=="Volkan":
print("İsminiz yanlış, lütfen isminizi doğru giriniz..")
deneme-=1
else:
print("isminiz ve soyadınız yanlış....")
deneme-=1
"""
DERSLER
1.MAT
2.kimya
3.software
4.biology
5.fizik
"""
ders1=input("ders1 seçiniz:")
ders2=input("ders2 seçiniz:")
ders3=input("ders3 seçiniz:")
ders4=input("ders4 seçiniz:")
ders5=input("ders5 seiçini:")
dersler=[ders1,ders2,ders3,ders4,ders5]
print("seçtiğiniz dersler:",dersler)
midterm=0
final=0
project=0
while True:
midterm_grade=int(input("midterm notunuzu giriniz:"))
midterm=midterm_grade*0.3
print("midterm orlamanız is:",midterm)
final_grade=int(input("final notunuz:"))
final=final_grade*0.5
print("final ortalamanız:",final)
project_grade=int(input("proje puanınınz:"))
project=project_grade*0.2
print("proje ortalamanız:",project)
notlar={"midterm":midterm_grade,"final":final_grade,"proje":project_grade}
print(notlar)
grades=midterm+final+project
print(grades)
if grades>=90:
print("AA")
elif 90>grades>70:
print("bb")
elif 70>grades>50:
print("cc")
elif 30<grades<50:
print("dd")
else:
print(" YOU FAILED!! 'FF' ")
|
def is_palindrome(n):
return str(n) == str(n)[::-1]
largest = 0
for n in range(100,1000):
for m in range(100,1000):
number = n * m
if is_palindrome(number) and number > largest:
largest = number
print largest
|
print("Happy 2021!!!")
# variables
secret_of_life = 42
gst_percentage = 0.07
# BMI Calculator
weight = float(input("Please enter your weight in kg"))
height = float(input("Please enter your height in metres"))
bmi = weight / (height * height)
if bmi < 18.5:
print("underweight")
# else if bmi < |
# Programming Exercise 2-3
#
# Program to convert area in square feet to acres.
# This program will prompt a user for the size of a tract in square feet,
# then use a constant ratio value to calculate it value in acres
# and display the result to the user.
# Variables to hold the size of the tract and number of acres.
# be sure to initialize these as floats
acrenumber = 0.0
feet = float(0)
# Constant for the number of square feet in an acre.
SQUAREFOOT = 0.0000229568411
# Get the square feet in the tract from the user.
# you will need to convert this input to a float
squarefeet = input("Enter the number of square feet: ")
squarefeet = float(squarefeet)
# Calculate the number of acres.
acres = squarefeet*SQUAREFOOT
# Print the number of acres.
# remember to format the acres to two decimal places
output = "The number of acres is %.5f. Good effort, mate." % acres
print(output)
|
#WRITE YOUR CODE IN THIS FILE
def greaterThan (x,y):
if x > y:
return True
else:
return False
print(greaterThan(52, 2))
def lessThan (x,y):
if x < y:
return True
else:
return False
print(lessThan(52, 2))
def equalTo (x,y):
if x == y:
return True
else:
return False
print(equalTo(52, 2))
def greaterOrEqual (x,y):
if x > y:
return True
elif x == y:
return True
else:
return False
print(greaterOrEqual(2, 2))
def lessOrEqual (x,y):
if x < y:
return True
elif x == y:
return True
else:
return False
print(lessOrEqual(2, 2)) |
"""
- 숫자 야구
해당하는 케이스를 확인하는 작업이 필요
remove 해서 남은 원소 파악하기
그러나 remove를 하면 인덱스가 조정이 된다는 사실을 인지하고
remove 후 인덱스를 옮겨야함
"""
from itertools import permutations
num_list = list(permutations([1, 2, 3, 4, 5, 6, 7, 8, 9], 3))
N = int(input())
# asdf = []
for _ in range(N):
test, s, b = [int(x) for x in input().split()]
test = tuple(int(x) for x in str(test))
x_cnt = 0 # remove를 하고나서 건너뛰는 원소를 놓치지 않기 위함, "#"로 확인가능
for i in range(len(num_list)):
s_cnt, b_cnt = 0, 0
i -= x_cnt
# asdf.append((i, num_list[i]))
for j in range(3):
if test[j] in num_list[i]:
if test[j] == num_list[i][j]:
s_cnt += 1
else:
b_cnt += 1
if s_cnt != s or b_cnt != b:
num_list.remove(num_list[i])
x_cnt += 1
# print(asdf)
print(len(num_list))
"""
for _ in range(N):
test, s, b = [int(x) for x in input().split()]
test = tuple(int(x) for x in str(test))
for num in num_list:
s_cnt, b_cnt = 0, 0
for i in range(3):
if test[i] in num:
if test[i] == num[i]:
s_cnt += 1
else:
b_cnt += 1
if s_cnt != s or b_cnt != b:
num_list.remove(num)
print(len(num_list))
"""
|
"""
- 절댓값 힙
힙에 넣을 때 크기만 필요하지만 출력시 부호를 고려해야 하므로
힙은 tuple을 원소로 가질 수 있음을 이용하여 tuple에 부호를 넣기
"""
import sys # input으로 했더니 틀림...
import heapq
input = sys.stdin.readline
N = int(input().rstrip())
heap = []
for _ in range(N):
num = int(input().rstrip())
if num != 0:
heapq.heappush(
heap, (abs(num), 1 if num > 0 else -1)
) # Heap elements can be tuples.
else:
try:
elem = heapq.heappop(heap)
print(elem[0] * elem[1])
except IndexError: # If the heap is empty, IndexError is raised.
print(0)
|
#Peter Tran
#1104985
#this program calculates stock transactions
#input
stockName = input("Enter Stock name: ");
numShares = int(input("Enter Number of shares: "));
purchasePrice = float(input("Enter Purchase price: "));
salePrice = float(input("Enter Selling price: "));
brokerCommission = float(input("Enter Commision: " ));
#calc
purchaseCost = numShares*purchasePrice;
saleAmount = numShares*salePrice;
brokerPurchaseCommission = purchaseCost*brokerCommission;
brokerSaleCommission = saleAmount*brokerCommission;
#output
print("You purchased and sold stock from " + stockName);
print("The amount of money you paid is ${:12,.2f}".format(purchaseCost));
print("The amount of commission paid to broker for purchase is ${:12,.2f}".format(brokerPurchaseCommission));
print("The amount of money you sold for is ${:12,.2f}".format(saleAmount));
print("The amount of commission paid to broker for sale is ${:12,.2f}".format(brokerSaleCommission));
print("The profit/loss is ${:12,.2f}".format(saleAmount - brokerSaleCommission - purchaseCost - brokerPurchaseCommission));
##run1
##Enter Stock name: Kaplack, Inc.
##Enter Number of shares: 10000
##Enter Purchase price: 33.92
##Enter Selling price: 35.92
##Enter Commision: 0.04
##You purchased and sold stock from Kaplack, Inc.
##The amount of money you paid is $ 339,200.00
##The amount of commission paid to broker for purchase is $ 13,568.00
##The amount of money you sold for is $ 359,200.00
##The amount of commission paid to broker for sale is $ 14,368.00
##The profit/loss is $ -7,936.00
##
##
##Press enter to quit the program
##run2
##Enter Stock name: Apple
##Enter Number of shares: 100
##Enter Purchase price: 35.23
##Enter Selling price: 155.97
##Enter Commision: 0.07
##You purchased and sold stock from Apple
##The amount of money you paid is $ 3,523.00
##The amount of commission paid to broker for purchase is $ 246.61
##The amount of money you sold for is $ 15,597.00
##The amount of commission paid to broker for sale is $ 1,091.79
##The profit/loss is $ 10,735.60
##
##
##Press enter to quit the program
##run3
##Enter Stock name: Jagex Ltd.
##Enter Number of shares: 15
##Enter Purchase price: 11.99
##Enter Selling price: 5.99
##Enter Commision: 0.04
##You purchased and sold stock from Jagex Ltd.
##The amount of money you paid is $ 179.85
##The amount of commission paid to broker for purchase is $ 7.19
##The amount of money you sold for is $ 89.85
##The amount of commission paid to broker for sale is $ 3.59
##The profit/loss is $ -100.79
##
##
##Press enter to quit the program
##run4
##Enter Stock name: Microfirm
##Enter Number of shares: 253
##Enter Purchase price: 25.23
##Enter Selling price: 28.19
##Enter Commision: 0.05
##You purchased and sold stock from Microfirm
##The amount of money you paid is $ 6,383.19
##The amount of commission paid to broker for purchase is $ 319.16
##The amount of money you sold for is $ 7,132.07
##The amount of commission paid to broker for sale is $ 356.60
##The profit/loss is $ 73.12
##
##
##Press enter to quit the program
##run5
##Enter Stock name: Amazone
##Enter Number of shares: 10000
##Enter Purchase price: 12.30
##Enter Selling price: 144.29
##Enter Commision: 0.09
##You purchased and sold stock from Amazone
##The amount of money you paid is $ 123,000.00
##The amount of commission paid to broker for purchase is $ 11,070.00
##The amount of money you sold for is $1,442,900.00
##The amount of commission paid to broker for sale is $ 129,861.00
##The profit/loss is $1,178,969.00
##
##
##Press enter to quit the program
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.