text
stringlengths
37
1.41M
from tkinter import * import csv weight = [] numquestions = 0 num = 0 y = 0 question = 0 choise = 0 numchoice = 0 arr = [] responses = [] trash = [] n = 0 j = 0 root = Tk() root.withdraw() # Responses: These are the responses to the question. Stored as a location in memory v = IntVar() current_window = None with open('test.csv') as csvfile: readCSV = csv.reader(csvfile, skipinitialspace=True, delimiter=',') arr = list(readCSV) # v gets inserted into num. This will add to the response list def userresponce(num): global responses responses.append(num) # insert def num_of_choices(list): length = len(list) length -= 1 return length numquestions = len(arr) def weight_list(list): #void global weight for x in range(0, len(list)): n = list[x][3] weight.append(n) weight_list(arr) def hello(): print("hello!") menubar = Menu(root) menubar.add_command(label="Hello", command=hello) menubar.add_command(label="Quit", command=root.quit) def previous(): print("Previous!") def replace_window(root): # Destroy current window, create new window global current_window if current_window is not None: current_window.destroy() current_window = Toplevel(root) # if the user kills the window via the window manager, # exit the application. current_window.wm_protocol("WM_DELETE_WINDOW", root.destroy) return current_window counter = 0 def new_window(): global counter counter += 1 window = replace_window(root) window.config(menu=menubar) window.geometry("500x300+0+0") window.title("IRAT") # Label: This is where the questions will go def label_creation(): #count = Label(window, text=counter) #count.grid(row=1, column=1, pady=25) global n if (n <= len(weight)): question = Label(window, text=arr[n][0], font=32) question.grid(row=0, column=0, sticky=W, pady=25) n += 1 label_creation() def radio_creation(): global j vcount = 0 rcount = 1 #choice = ["One", "Two", "Three"] if (n <= len(weight)): for x in range(1, num_of_choices(arr[j])): Radiobutton(window, text=arr[j][x], font=16, variable=v, value=vcount).grid(row=rcount, column=0, sticky=W) vcount += 1 rcount += 1 j += 1 radio_creation() btnNext = Button(window, text="Next", command=new_window, height=1, width=10) btnNext.grid(row=9, column=2, pady=40) btnPrevious = Button(window, text="Previous", command=previous, height=1, width=10) btnPrevious.grid(row=9, column=0, pady=40) global responses global v temp = v.get() userresponce(temp) def score_math(wlist, rlist): wt = 0 rt = 0 length = len(wlist) for x in range(0, length): wt += int(wlist[x]) # print(wt) for x in range(0, length): rt += int(wlist[x]) * int(rlist[x]) final = rt / wt print(final, "/", 10) # score_math(weight, responses) if (n < len(weight)): window = new_window() root.mainloop() score_math(weight, responses)
__author__ = 'brianlawney' class Reaction(object): """ This class holds all the components of a reaction- the constitutive species, rate constants, the direction of reaction """ def __init__(self, reactants, products, fwd_k, rev_k=None, is_bidirectional=False): """ :param reactants: A list of Reactant instances :param products: :param fwd_k: :param rev_k: :param is_bidirectional: :return: """ self._reactant_list = reactants self._product_list = products self._fwd_k = fwd_k self._rev_k = rev_k self.is_bidirectional = is_bidirectional def get_reactants(self): return self._reactant_list def get_products(self): return self._product_list def get_fwd_k(self): return self._fwd_k def get_rev_k(self): return self._rev_k def is_bidirectional_reaction(self): return self.is_bidirectional def get_all_species(self): """ A set of the symbols (Strings) :return: """ species_set = set() for r in self._reactant_list: species_set.add(r.symbol) for r in self._product_list: species_set.add(r.symbol) return species_set def reactant_str(self): return '+'.join([' %s ' %x for x in self._reactant_list]) def product_str(self): return '+'.join([' %s ' %x for x in self._product_list]) def as_string(self): reactant_str = '+'.join([' %s ' %x for x in self._reactant_list]) product_str = '+'.join([' %s ' %x for x in self._product_list]) direction = '<-->' if self.is_bidirectional else '-->' s = reactant_str + direction + product_str s += ',%s' % self._fwd_k if self._rev_k is not None: s += ',%s' % self._rev_k else: s += ',0' return s def __str__(self): reactant_str = '+'.join([' %s ' %x for x in self._reactant_list]) product_str = '+'.join([' %s ' %x for x in self._product_list]) if self._rev_k is not None: return '%s <--%s, %s--> %s' % (reactant_str, self._rev_k, self._fwd_k, product_str) else: return '%s --%s--> %s' % (reactant_str, self._fwd_k, product_str) class ReactionElement(object): def __init__(self, symbol, coefficient, verbose_name=''): self.symbol = symbol self.coefficient = coefficient self.verbose_name = verbose_name def __str__(self): s = '' if self.coefficient > 1: s = '%s*' % self.coefficient s += self.symbol return s def __eq__(self, other): return (self.symbol == other.symbol) & (self.coefficient == other.coefficient) class Reactant(ReactionElement): def __init__(self, symbol, coefficient, verbose_name=''): super(Reactant, self).__init__(symbol, coefficient, verbose_name) class Product(ReactionElement): def __init__(self, symbol, coefficient, verbose_name=''): super(Product, self).__init__(symbol, coefficient, verbose_name)
from sys import argv, exit import csv if len(argv) != 3: print("missing command-line argument") exit(1) #open file datafile = open(argv[1], "r") checkfile = open(argv[2], "r") #read database into dict database = csv.DictReader(datafile) dna_sequence = checkfile.readline() #store keys keys = database.fieldnames #1st key is name maxi = len(keys) - 1 length = len(dna_sequence) #declare list with number of keys occurence = [0] * maxi #counting largest consequtive STR sequences and store in list for i in range(maxi): temp = 0 r = len(keys[i + 1]) j = 0 while j < (length - r + 1): if dna_sequence[j: j+r ] == keys[i + 1]: temp += 1 j += r else: if temp > occurence[i]: occurence[i] = temp j += 1 temp = 0 #searching in dictionaries and show name if found for row in database: found = True for i in range(maxi): if (int(row[keys[i + 1]]) == occurence [i]) and i == (maxi - 1) and found == True: print(row["name"]) datafile.close() checkfile.close() exit(0) elif int(row[keys[i + 1]]) != occurence [i]: #if different from database toggle to false found = False print("No match") #close file datafile.close() checkfile.close() exit(1)
#!/usr/bin/env python def parseSize(text): prefixes = { 'b': 1, 'k': 1024, 'ki': 1024, 'kb': 1024, 'm': 1024 * 1024, 'mb': 1024 * 1024, 'g': 1024 * 1024 * 1024, 'gb': 1024 * 1024 * 1024 } num = "" text = str(text).strip() while text and text[0:1].isdigit() or text[0:1] == '.': num += text[0] text = text[1:] num = float(num) letter = text.strip().lower() return num * (prefixes[letter] if letter in prefixes else 1) for test in ('1024K', '1.0 K', '1.5M', '12 M', '12', '12kb', ' 123.421 Kb ', '1GB', 42, '42b'): print test, '\r\t\t', parseSize(test)
from math import sqrt suma = 0 def fibonacci(a): ans = int(1/sqrt(5)*((1+sqrt(5))/2)**a-1/sqrt(5)*((1-sqrt(5))/2)**a) return ans i=0 while fibonacci(i)<4000000: if fibonacci(i)%2==0: suma = suma + fibonacci(i) i += 1 print(suma)
# Write a function that asks the user for a string containing multiple words. Print back # to the user the same string, except with the words in backwards order. def reverseV1(w): return ' '.join(w.split()[::-1]) def reverseV2(x): y = x.split() result = [] for word in y: result.insert(0,word) return " ".join(result) def reverseV3(x): y = x.split() return " ".join(reversed(y)) def reverseV4(x): y = x.split() y.reverse() return " ".join(y) # test code test = input("Enter a sentence: ") print(reverseV1(test)) print(reverseV2(test)) print(reverseV3(test)) print(reverseV4(test))
# Find an element in a list using binary search. def find(orderedList, elementToFind): startIndex = 0 endIndex = len(orderedList) - 1 found = False while startIndex <= endIndex and not found: middleIndex = (startIndex + endIndex) // 2 if orderedList[middleIndex] == elementToFind: found = True else: if elementToFind < orderedList[middleIndex]: endIndex = middleIndex - 1 else: startIndex = middleIndex + 1 return found if __name__=="__main__": l = [2, 4, 6, 8, 10] print(find(l, 5)) print(find(l, 10)) print(find(l, -1)) print(find(l, 2))
import plotly.express as px import pandas as pd class Plot(): def __init__(self, dfResult, a, b, gridInfo): self.modelDf = dfResult self.a = a self.b = b self.gridInfo = gridInfo def print_title(self): start = str(self.gridInfo[0]) end = str(self.gridInfo[1]) step = str(self.gridInfo[2]) return "Linear function ( y = " + str(self.a) + "x + " + str(self.b) + ") from: "+ start + "up untill to: " + end + "with a step of: " + step def plot(self): fig = px.scatter(self.modelDf, x="x", y="y", trendline="ols") return fig
# 11.6 Write a test program that prompts the user to enter two 3 by 3 matrices and displays their product # Sample Input [1 2 3 4 5 6 7 8 9] [0 2 4 1 4.5 2.2 1.1 4.3 5.2] # Multiply two matrices def multiplyMatrix(a, b): n = len(a) c = [[0] * n for i in range(n)] for row in range(n): for column in range(n): total = 0 for j in range(len(a[row])): total += a[row][j] * b[j][column] c[row][column] = total return c # Create a matrix def createMatrix(s, n): numbers = [float(x) for x in s] # Convert items to numbers m = [[0] * n for i in range(n)] j = 0 for row in range(len(m)): for column in range(len(m[row])): m[row][column] = numbers[j] j += 1 return m # Print a matrix def printMatrix(m): for row in range(len(m)): for column in range(len(m[row])): print(round(m[row][column], 1), end = " ") print() print() def main(): # n by n matrix n = 3 # Read numbers as a string from the console and create a matrix of n by n s1 = input("Enter matrix1: ").split() # Extract items from the string a = createMatrix(s1, n) s2 = input("Enter matrix2: ").split() # Extract items from the string b = createMatrix(s2, n) print("The matrices are added as follows:") c = multiplyMatrix(a, b) printMatrix(a) print(" * ") printMatrix(b) print(" = ") printMatrix(c) main()
# 10.2 Write a program that reads a list of integers and displays them in the reverse order # in which they were read. # Sample Input [2 5 6 4 3 23 43] # Create a list of integers def createList(): # Read numbers as a string from the console s = input("Enter integers: ") items = s.split() # Extract items from the string myList = [eval(x) for x in items] # Convert items to numbers return myList # Return the list # Display the list of integers in reverse order def displayReverseList(myList): myList.reverse() # Reverse the list for i in myList: print(i, end = " ") def main(): # Create a list of n integers myList = createList() # Print the list in reverse order print("The list in reverse order:") displayReverseList(myList) main() # Call the main function
# 2.22 Write a program to prompt the user to enter the number of years and # displays the population after that many years # Prompt the user to enter the number of years numberOfYears = eval(input("Enter the number of years: ")) # Constants CURRENT_POPULATION = 312032486 BIRTH_RATE = 7 DEATH_RATE = 13 NEW_IMMIGRANT_RATE = 45 # Compute total seconds in a year with 365 days secondsPerYear = 365 * 24 * 60 * 60 # Compute births per year birthsPerYear = secondsPerYear / BIRTH_RATE # Compute deaths per year deathsPerYear = secondsPerYear / DEATH_RATE # Compute new immigrants per year newImmigrantsPerYear = secondsPerYear / NEW_IMMIGRANT_RATE # Compute change in population per year annualPopulationChange = birthsPerYear - deathsPerYear + newImmigrantsPerYear # Compute population and print the result population = CURRENT_POPULATION + numberOfYears * annualPopulationChange print("The population in", numberOfYears, "years is", round(population))
# 2.7 Write a program that prompts the user to enter the minutes (e.g., 1 billion), # and displays the number of years and days for the minutes # Sample Input[1000000000] # Prompt the user to enter minutes totalMinutes = eval(input("Enter the number of minutes: ")) # Compute minutes per day minutesPerDay = 24 * 60 # Compute minutes per year minutesPerYear = 365 * minutesPerDay # Compute number of years numberOfYears = totalMinutes // minutesPerYear # Compute number of days remaining remainingDays = (totalMinutes % minutesPerYear) // minutesPerDay # Display result print(totalMinutes, "minutes is approximately", numberOfYears, "years and", remainingDays, "days")
# 3.6 Write a program that draws a triangle, square, pentagon, hexagon, and octagon import turtle # Import turtle module # Draw a triangle with bottom side parallel to x-axis turtle.setheading(60) # Set the turtle’s heading to 60 degrees turtle.pensize(3) # Set pen thickness to 3 pixels turtle.penup() turtle.goto(-200, -50) turtle.pendown() turtle.begin_fill() # Begin to fill color in the shape turtle.color("red") turtle.circle(40, steps = 3) # Draw a triangle turtle.end_fill() # Fill the shape # Draw a square with bottom side parallel to x-axis turtle.setheading(45) # Set the turtle’s heading to 45 degrees turtle.penup() turtle.goto(-100, -50) turtle.pendown() turtle.begin_fill() # Begin to fill color in the shape turtle.color("blue") turtle.circle(40, steps = 4) # Draw a square turtle.end_fill() # Fill the shape # Draw a pentagon with bottom side parallel to x-axis turtle.setheading(36) # Set the turtle’s heading to 36 degrees turtle.penup() turtle.goto(0, -50) turtle.pendown() turtle.begin_fill() # Begin to fill color in the shape turtle.color("green") turtle.circle(40, steps = 5) # Draw a pentagon turtle.end_fill() # Fill the shape # Draw a hexagon with bottom side parallel to x-axis turtle.setheading(30) # Set the turtle’s heading to 30 degrees turtle.penup() turtle.goto(100, -50) turtle.pendown() turtle.begin_fill() # Begin to fill color in the shape turtle.color("yellow") turtle.circle(40, steps = 6) # Draw a hexagon turtle.end_fill() # Fill the shape # Draw a octagon with bottom side parallel to x-axis turtle.setheading(22.5) # Set the turtle’s heading to 22.5 degrees turtle.penup() turtle.goto(200, -50) turtle.pendown() turtle.begin_fill() # Begin to fill color in the shape turtle.color("purple") turtle.circle(40, steps = 8) # Draw a octagon turtle.end_fill() # Fill the shape turtle.hideturtle() # Make the turtle invisible turtle.done()
# 5.36 Revise the Rock Scissor Paper program to let the user play continuously until either the user # or the computer wins more than two times. import random # Import random module # Initialize the number of user and computer wins userWins = 0 computerWins = 0 # Check condition and proceed while userWins <= 2 and computerWins <= 2: # Prompt the user for input user = eval(input("Enter scissor (0), rock (1), paper (2): ")) # Compute user choice if user == 0: userChoice = "scissor" elif user == 1: userChoice = "rock" elif user == 2: userChoice = "paper" else: print("Incorrect choice!") # Report incorrect choice continue # Generate a random choice for computer computer = random.randint(0, 2) # Compute computer choice if computer == 0: computerChoice = "scissor" elif computer == 1: computerChoice = "rock" elif computer == 2: computerChoice = "paper" # Check the choices and display result if userChoice == computerChoice: print("The computer is " + computerChoice + ". You are " + userChoice + " too. It is a draw.") elif userChoice == "scissor": if computerChoice == "rock": print("The computer is " + computerChoice + ". You are " + userChoice + ". Computer won.") computerWins += 1 else: print("The computer is " + computerChoice + ". You are " + userChoice + ". You won.") userWins += 1 elif userChoice == "rock": if computerChoice == "paper": print("The computer is " + computerChoice + ". You are " + userChoice + ". Computer won.") computerWins += 1 else: print("The computer is " + computerChoice + ". You are " + userChoice + ". You won.") userWins += 1 else: if computerChoice == "scissor": print("The computer is " + computerChoice + ". You are " + userChoice + ". Computer won.") computerWins += 1 else: print("The computer is " + computerChoice + ". You are " + userChoice + ". You won.") userWins += 1 print("Computer Score:", computerWins,"User Score:", userWins)
# 10.26 Write a test program that prompts the user to enter two sorted lists and # displays the merged list # Sample Inputs [1 5 16 61 111], [2 4 5 6] def merge(list1, list2): list3 = [] while len(list1) and len(list2): if list1[0] > list2[0]: list3.append(list2.pop(0)) else: list3.append(list1.pop(0)) if len(list1): while len(list1): list3.append(list1.pop(0)) elif len(list2): while len(list2): list3.append(list2.pop(0)) for i in list3: print(i, end = " ") def main(): # Read numbers as a string from the console s1 = input("Enter list1: ") items = s1.split() # Extract items from the string myList1 = [eval(x) for x in items] # Convert items to numbers # Read numbers as a string from the console s2 = input("Enter list2: ") items = s2.split() # Extract items from the string myList2 = [eval(x) for x in items] # Convert items to numbers # Display the merged list print("The merged list is", end = " ") merge(myList1, myList2) main() # Call the main function
# 5.30 Write a program that prompts the user to enter the year and first day of the year, # and displays the first day of each month in the year on the console # Prompt the user for inputs year, firstDayOfYear = eval(input("Enter the year and first day of the year(e.g 2016, 3): ")) # Check if the given year is a leap year if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0): isLeapYear = True else: isLeapYear = False # Compute the first day number for each month and display result for i in range(1, 13): if i == 1: dayNumber = firstDayOfYear month = "January" numberOfDaysInMonth = 31 else: dayNumber = (firstDayOfYear + numberOfDaysInMonth) % 7 if i == 2: month = "February" # Check for leap year and set number of days accordingly if isLeapYear: numberOfDaysInMonth += 29 else: numberOfDaysInMonth += 28 elif i == 3: month = "March" numberOfDaysInMonth += 31 elif i == 4: month = "April" numberOfDaysInMonth += 30 elif i == 5: month = "May" numberOfDaysInMonth += 31 elif i == 6: month = "June" numberOfDaysInMonth += 30 elif i == 7: month = "July" numberOfDaysInMonth += 31 elif i == 8: month = "August" numberOfDaysInMonth += 31 elif i == 9: month = "September" numberOfDaysInMonth += 30 elif i == 10: month = "October" numberOfDaysInMonth += 31 elif i == 11: month = "November" numberOfDaysInMonth += 30 else: month = "December" numberOfDaysInMonth += 31 # Compute day from day number if dayNumber == 0: day = "Sunday" elif dayNumber == 1: day = "Monday" elif dayNumber == 2: day = "Tuesday" elif dayNumber == 3: day = "Wednesday" elif dayNumber == 4: day = "Thursday" elif dayNumber == 5: day = "Friday" else: day = "Saturday" # Display result print(month, "1", year, "is", day)
# 5.35 Write a program to find four perfect numbers less than 10,000. # Compute the perfect numbers less than 10000 and display result print("The four perfect integers less than 10000 are: ", end = "") for i in range(1, 10000): sumOfDivisors = 0 n = i // 2 for j in range(1, n + 1): if i % j == 0: sumOfDivisors = sumOfDivisors + j; if sumOfDivisors == i: print(i, end = " ")
# 8.3 Write a program that prompts the user to enter a password and displays valid password # if the rules are followed or invalid password otherwise. # Sample Inputs [43GRfdf], [dR#t3dT#], [dRt3dT210], [dkTw3dsP] # Check if password is valid def checkPassword(p): if isLengthValid(p) and isCharValid(p) and isNumberOfDigitsValid(p): return "Valid Password" else: return "Invalid Password" # Check length of password criteria def isLengthValid(p): if len(p) >= 8: return True else: return False # Check number of digits password criteria def isNumberOfDigitsValid(p): length = len(p) count = 0 # Count number of digits for i in range(0, length): if 48 <= ord(p[i]) <= 57: count += 1 if count >= 2: return True else: return False # Check digits and alphabets password criteria def isCharValid(p): length = len(p) for i in range(0, length): if (48 <= ord(p[i]) <= 57) or (65 <= ord(p[i]) <= 90) or (97 <= ord(p[i]) <= 122): if i == length - 1: return True else: continue else: return False def main(): # Prompt the user for inputs password = input("Enter a password: ") # Display result print(checkPassword(password)) main() # Call the main function
# 6.5 Write a test program that prompts the user to enter three numbers # and invokes the function to display them in increasing order # Sorts the numbers in increasing order and displays result def displaySortedNumbers(num1, num2, num3): for i in range(1, 3): if num1 > num2: num1, num2 = num2, num1 # swap num1 and num2 if num2 > num3: num2, num3 = num3, num2 # swap num2 and num3 print("The sorted numbers are", num1, num2, num3) def main(): number1, number2, number3 = eval(input("Enter three numbers: ")) # Prompt the user for input displaySortedNumbers(number1, number2, number3) main() # Call the main function
class Vertex: def __init__(self, vNum): self.mVertices = {} for i in range(vNum): self.mVertices[i+1] = list() def AddEdge(self, u, v): self.mVertices[u].append(v) self.mVertices[v].append(u) def neighbors(self, u): return [neighbour for neighbour in self.mVertices[u]] n = int(input()) graph = Vertex(n) k = int(input()) for _ in range(k): st = input().split() if st[0] == '1': graph.AddEdge(int(st[1]), int(st[2])) elif st[0] == '2': print(*graph.neighbors(int(st[1])))
class Queue: def __init__(self): self.mItems = [] def empty(self): return len(self.mItems) == 0 def push(self, item): self.mItems.append(item) print('ok') def pop(self): return self.mItems.pop(0) def front(self): return self.mItems[0] def __len__(self): return len(self.mItems) def clear(self): self.mItems = [] print('ok') def exit(self): print('bye') que = Queue() while True: try: st = input().split() except: break if st[0] == 'push': que.push(int(st[1])) elif st[0] == 'pop': print(que.pop()) elif st[0] == 'front': print(que.front()) elif st[0] == 'size': print(len(que)) elif st[0] == 'clear': que.clear() else: que.exit() break
""" Реалізуйте підпрограми сортування масиву. """ N = 10000 # Кількість елементів масиву. # Використовується у головній програмі для генерування # масиву з випадкових чисел def bubble_sort(array): """ Сортування "Бульбашкою" :param array: Масив (список однотипових елементів) """ n = len(array) for pass_num in range(n - 1, 0, -1): for i in range(pass_num): if array[i] > array[i + 1]: array[i], array[i + 1] = array[i + 1], array[i] def bubble_sort_optimized(array): """ Модификований алгоритм сортування "Бульбашкою" :param array: Вхідний масив даних, що треба відсортувати. """ n = len(array) for pass_num in range(n - 1, 0, -1): c = True for i in range(pass_num): if array[i] > array[i + 1]: c = False array[i], array[i + 1] = array[i + 1], array[i] if c: break def selection_sort(array): """ Сортування вибором :param array: Масив (список однотипових елементів) :return: None """ n = len(array) for i in range(n - 1, 0, -1): maxpos = 0 for j in range(1, i + 1): if array[maxpos] < array[j]: maxpos = j array[i], array[maxpos] = array[maxpos], array[i] def insertion_sort(array): """ Сортування вставкою :param array: Масив (список однотипових елементів) :return: None """ n = len(array) for index in range(1, n): currentValue = array[index] position = index while position > 0: if array[position - 1] > currentValue: array[position] = array[position - 1] else: break position -= 1 array[position] = currentValue
#------------------------------------------------------------------------------- # Name: Exercise 7 # Purpose: Convert degrees minutes to decimal degrees # Decimal Degrees = degrees + (minutes/60) + (seconds/3600) # add 0 after number # Author: chengjiaqi sun # # Created: 10/09/2019 # Copyright: (c) cheng 2019 # Licence: <your licence> #------------------------------------------------------------------------------- deg = 95 min = 25 sec = 5 decimaldeg = deg + min / 60.0 + sec/3600.0 print str (deg) + ":" + str (min) + ":" + str (sec) +" = " + "%.8f" % decimaldeg
import csv def writeCSV(FN): with open(FN,mode='a',encoding='utf-8',newline="") as fn: fw=csv.writer(fn,delimiter=',',quoting=csv.QUOTE_NONNUMERIC) data=['aaa',40,60] fw.writerow(data) data1=[['bbb',3,5],['ccc',55,333]] fw.writerows(data1) def readCSV(FN): with open(FN, mode='r', encoding='utf-8', newline="") as fn: fr=csv.reader(fn) for i in fr: print('{}'.format(i)) def readCsvDict(FN): with open(FN, mode='r', encoding='utf-8', newline="") as fn: fr=csv.DictReader(fn) for i in fr: print('{}'.format(i)) if __name__ == '__main__': filename = '/python/File/fire.csv' #writeCSV(filename) #readCSV(filename) readCsvDict(filename)
#The Fibonacci sequence is defined by the recurrence relation: #Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. #The 12th term, F12, is the first term to contain three digits. #What is the index of the first term in the Fibonacci sequence to contain 1000 digits? def FibonacciNumber(n): #n number of digits a = 1 b = 0 i = 1 while len(str(a)) != n: a, b = a +b, a i += 1 return i final = FibonacciNumber(1000) print(final)
#Nombre: Iago Brian Lorenzana Reyes #Carrera: Informática #Materia: Desarrollo de Aplicaciones Web #Ejercicio o práctica: 2.2 - practicando condicionales complejas python fecha=input("Fecha (formato'dia, DD/MM') :") #Declaramos variables con sus diferentes propiedades y formatos como en el caso de diasemana, dianro, mesnro fecha=fecha.lower() diasemana=fecha[0:fecha.find(',')] dianro=int(fecha[fecha.find(' ')+1:fecha.find('/')]) mesnro=int(fecha[fecha.find('/')+1:]) if dianro>31 or mesnro>12: print("Fecha incorrecta") else: if diasemana in "lunes,martes,miércoles":#Empiezan las condiciones y apartir de cada respuesta obtendremos un diferente resultado de promedio respuesta=input("¿Se tomaron exámenes? S/N: ")#En caso de que sea una entrada de texto que no esté en la condición sólo mostrará un error if respuesta.lower()=="s": aprobados=int(input("Cantidad de aprobados: ")) reprobados=int(input("Cantidad de reprobados: ")) print("Porcentaje de aprobados: ", (aprobados*100)/(aprobados+reprobados) ,"%") elif diasemana == "jueves": asistencia=int(input("Porcentaje de asistencia: "))#En caso de que sea jueves o viernes se verificará la asistencia si es mayor a 50 mandará un mensaje de asistirá la mayoría if asistencia>50: print("Asistió la mayoría") else: print("No asistió la mayoría") elif diasemana == "viernes": #En este elif si la condición es viernes y si el día es el primero o el mes primero o septimo dará el mensaje de Comienzo de nuevo ciclo if dianro==1 and (mesnro==1 or mesnro==7): print("Comienzo de nuevo ciclo") alumnos=int(input("Cantidad de alumnos: "))#Asignamos la cantidad de alumnso cómo el arancel por alumno y así calcularemos el ingreso total multiplicando la cantidad de alumnos por el arancel y se mostrará al final el ingreso total arancel=float(input("Arancel: $")) print("Ingreso total: $", alumnos*arancel) else: print("Fecha incorrecta") print("Fin del programa")
def invest(amount, rate, time): print("principle amount: ${}".format(amount)) print("annual rate of return: {}".format(rate)) for n in range(1,time+1): amount= amount*(1+rate) print("year {}: ${}".format(n,amount)) print("") invest(100,.05, 8) invest(2000, .025, 5)
""" picture.py Author: John Warhold Credit: dan Assignment: Use the ggame library to "paint" a graphical picture of something (e.g. a house, a face or landscape). Use at least: 1. Three different Color objects. 2. Ten different Sprite objects. 3. One (or more) RectangleAsset objects. 4. One (or more) CircleAsset objects. 5. One (or more) EllipseAsset objects. 6. One (or more) PolygonAsset objects. See: https://github.com/HHS-IntroProgramming/Standards-and-Syllabus/wiki/Displaying-Graphics for general information on how to use ggame. See: http://brythonserver.github.io/ggame/ for detailed information on ggame. """ from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset # add your code here \/ \/ \/ blueviolet = Color(0x8a2be2, 1.0) hotpink = Color(0xff69b4, 1.0) Aquamarine =Color(0x7fffd4, 1.0) brown = Color(0xcd5c5c, 1.0) green = Color(0x00ff7f, .5) thist = Color(0xd8bfd8, 1.0) thinline = LineStyle(1, hotpink) rec = RectangleAsset(169,169, thinline, Aquamarine) poly = PolygonAsset([(500,400), (669,400), (584.5, 350), (500, 400)], thinline, blueviolet) circ = CircleAsset(67, thinline, hotpink) rek = RectangleAsset(50,100, thinline, brown) lol = CircleAsset(100, thinline, green) rrr = EllipseAsset(75,25, thinline, thist) rekt = RectangleAsset(50,100, thinline, brown) sup = EllipseAsset(50,25, thinline, thist) we = EllipseAsset(75,50, thinline, thist) rtr = EllipseAsset(75,25, thinline, thist) Sprite(rec, (500, 400)) Sprite(poly) Sprite(circ, (67,67)) Sprite(rek, (800,469 )) Sprite(lol, (825,390)) Sprite(rrr, (500,200)) Sprite(rekt, (559,468)) Sprite(sup, (700, 130)) Sprite(we, (900, 200)) Sprite(rtr, (200,169)) # add your code here /\ /\ /\ myapp = App() myapp.run()
# -*- coding: utf-8 -*- import math def cifrar(): mensajeACifrar = input('Ingresa tu mensaje a cifrar') llave = input('Ingresa un numero entero para la llave') lallave = int(llave) if len(mensajeACifrar)>lallave: mensajeCifrado = encriptando(lallave, mensajeACifrar) print("") print("") print(f'Su mensaje descifrado es:\n {mensajeCifrado}') else: print("") print("La llave es mayor que el numero de caracteres que tiene tu mensaje que quieres cifrar") print("porfavor introduce una llave que sea menor a el numero de caracteres que tiene el mensaje que quieres cifrar") print("") print("") cifrar() print("") print("") print("Si deseas volver al menu principal escribe si") volver=input("Si deseas repetir la programa escribe cualquier otra cosa") vol=volver.upper() print("") print("") if vol=="SI": menu() else: cifrar() def encriptando(llave, mensaje): mensajeCifrado = [''] * llave for columnas in range(llave): puntero = columnas while puntero < len(mensaje): mensajeCifrado[columnas] += mensaje[puntero] puntero += llave return ''.join(mensajeCifrado) if __name__ == '__cifrar__': cifrar() def descifrar(): mensajaDescifrar = input('Ingresa tu mensaje a descifrar') llave = input('Ingresa el numero de la llave') laLlave = int(llave) if len(mensajaDescifrar)>laLlave: texto = desencriptar(laLlave, mensajaDescifrar) print("") print("") print(f'Su mensaje descifrado es:\n {texto}') else: print("") print("") print("La llave que escribiste es mayor a el numero de caracteres que tiene tu mensaje que quieres descifrar") print("Si deseas continuar con esa llave tu mensaje no sera desencriptado") respuesta=input('Escribe "si" si quieres continuar o "no" si quieres volver al menu principal') res=respuesta.upper() if res=="SI": print("") print("") texto = desencriptar(laLlave, mensajaDescifrar) print(f'Su mensaje descifrado es:\n {texto}') else: print("") print("") menu() print("") print("") print("Si deseas volver al menu principal escribe si") volver=input("Si deseas repetir la programa escribe cualquier otra cosa") vol=volver.upper() print("") print("") if vol=="SI": menu() else: descifrar() def desencriptar(llave, mensaje): numColumnas = math.ceil(len(mensaje) / llave) numFilas = llave cajas = (numColumnas * numFilas) - len(mensaje) caracteres = [''] * numColumnas columnas = 0 filas = 0 for symbol in mensaje: caracteres[columnas] += symbol columnas += 1 if (columnas == numColumnas) or (columnas == numColumnas - 1 and filas >= numFilas - cajas): columnas = 0 filas += 1 return ''.join(caracteres) if __name__ == '__descifrar__': descifrar() def menu(): try: print("Hola que tal aqui podras cifrar o descifrar un codigo con el metodo de transpocision") print("Escribe 1 si quieres cifrar o 2 si quieres descifrar\n1. Cifrar\n2. Descifrar") opc=int(input()) if opc==1: cifrar() elif opc ==2: descifrar() except: print("") print("") #print("Vaya parece que a sucedido un error por favor lee las indicaciones") print("Porfavor escribe un valor valido") print("") print("") menu() menu()
''' Rusty DeGarmo Professor Payne Intro to Programming with Python 7 May 2021 ''' #The purpose of this program is to utilize file management techniques #import the OS library import os #Ask the user for their desired directory with a prompt variable promptDir = "\nWhat is the path of the directory that you want to go to? " userDir = input(promptDir) #create space print() #check to see if the directory exists if os.path.isdir(userDir): #Ask the user for the name of the file with a prompt variable and #add the user's directory and file to work with the file in the #correct directory promptFile = "\nWhat is the name of the file you want to write to? " userFile = f"{userDir}/{input(promptFile)}" promptName = "\nWhat is your name? " userName = input(promptName) promptAddress = "\nWhat is your address? " userAddress = input(promptAddress) promptPhone = "\nWhat is your phone number? " userPhone = input(promptPhone) #create space print() #I got an error that access was denied because I had the file open. #Check to see if the file is open. Is there another reason that I #would get an access denied error? This only seemed to happen when I #had the file open in Word. When I opened the file in Notepad I didn't #seem to get this error. Can you explain that? try: #open the file to write to it with open(userFile, 'w') as fileHandle: fileHandle.write(f"{userName}, {userAddress}, {userPhone}") #open the file again to read it and print the contents with open(userFile) as fileHandle: userData = fileHandle.read() print("Verify that the information you entered is all correct: ") print(userData) print() except: print("Make sure that you don't have the file open!\n") else: print("That is not a valid directory") # py rdegarmo-filemanagement.py
import numpy, matplotlib.pyplot as plt from neuralNetwork import neuralNetwork # nodes and learning rate input_layer = 784 hidden_layer = 100 # Optimal is 200, but it takes considerably longer to train and the % difference is about 1% output_layer = 10 learning_rate = 0.1 # Instance of neural network nn = neuralNetwork(input_layer, hidden_layer, output_layer, learning_rate) # Loading training dataset - this code is for the small sample # training_data_file = open("mnist_dataset/mnist_train_100.csv", 'r') # training_data_list = training_data_file.readlines() # training_data_file.close() # Loading training dataset - this code is for the big sample. You need to unzip the full data sets training_data_file = open("mnist_dataset\mnist_full_dataset\mnist_train.csv", 'r') training_data_list = training_data_file.readlines() training_data_file.close() # TRAINING - Epochs are the naming standard for iterative trainings # We set the epoch = 2; which means that we will perform two training # sessions with the same training list of values, which means that the # training time will double. epochs = 5 for epoch in range(epochs): # Neural Network training - iteration through all data sets for entry in training_data_list: all_values = entry.split(',') # For the NN to work, we need the values to be in the range from 0.01 to 0.99 scaled_inputs = (numpy.asfarray(all_values[1:]) / 255.0*0.99) + 0.01 # The targeted values: they start at the beginning of each data set (for example, # the first number in the data set is 5, therefore the values afterward correspond # to the number 5. targets = numpy.zeros(output_layer) + 0.01 # the target value we mentioned before. it will allocate the number 0.99 in the array targets[int(all_values[0])] = 0.99 nn.train(scaled_inputs, targets) pass # Neural Network testing - same as before, but we expect the correct result as output # from the NN. This time, we load the test data for the test process # This code is for the small data set sample # test_data_file = open("mnist_dataset/mnist_test_10.csv", 'r') # test_data_list = test_data_file.readlines() # test_data_file.close() # This code is for the big data set sample. You need to unzip the full data sets test_data_file = open("mnist_dataset\mnist_full_dataset\mnist_test.csv", 'r') test_data_list = test_data_file.readlines() test_data_file.close() # Score card gives points to check how well the NN has performed score_card = [] # Iterate through each test for entry in test_data_list: all_values = entry.split(',') correct_answer = int(all_values[0]) print("The expected value is " + all_values[0]) # scaling the test inputs and querying them test_outputs = nn.query((numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01) # Chosen result of the NN in the test outputs answer = numpy.argmax(test_outputs) print("Neural Network answered:", answer) # Checking whether the result is correct or not if answer == correct_answer: # adding one point to the score card score_card.append(1) else: # if the NN is mistaken, we add a 0 to the score card score_card.append(0) pass # This code displays the number in order to see how does it look like. # NOTE: USE IT JUST WITH THE SMALL SAMPLES # image_array = numpy.asfarray(all_values[1:]).reshape((28,28)) # plt.imshow(image_array, cmap='Greys', interpolation='None') # plt.show() # Calculate the accuracy of the Neural Network accuracy = (numpy.sum(score_card) / len(score_card)) * 100.0 print("The Neural Network accuracy is:", accuracy, "%")
""" 一般进行接口测试时,每个接口的传参都不止一种情况,一般会考虑正向、逆向等多种组合。所以在测试一个接口时通常会编写多条case,而这些case除了传参不同外,其实并没什么区别。 这个时候就可以利用ddt来管理测试数据,提高代码复用率。 ※但要注意:正向和逆向的要分开写※ 安装:pip install ddt 四种模式:第一步引入的装饰器 @ ddt;导入数据的 @ data;拆分数据的 @ unpack;导入外部数据的 @ file_data """ # 一、读取元组数据 # 一定要和单元测试框架一起用 import unittest, os from ddt import ddt, data, unpack, file_data '''NO.1单组元素''' @ddt class Testwork(unittest.TestCase): @data(1, 2, 3) def test_01(self, value): # value用来接收data的数据 print(value) if __name__ == '__main__': unittest.main() # 结果: # 1 # 2 # 3 '''NO.2多组未分解元素''' @ddt class Testwork(unittest.TestCase): @data((1, 2, 3), (4, 5, 6)) def test_01(self, value): print(value) if __name__ == '__main__': unittest.main() # 结果: # (1, 2, 3) # (4, 5, 6) '''NO.3多组分解元素''' @ddt class Testwork(unittest.TestCase): @data((1, 2, 3), (4, 5, 6)) @unpack # 拆分数据 def test_01(self, value1, value2, value3): # 每组数据有3个值,所以设置3个形参 print(value1) if __name__ == '__main__': unittest.main() # 结果: # 1 # 2 # 3 # 4 # 5 # 6 # ############################################################# # 二、读取列表数据 import unittest, os from ddt import ddt, data, unpack, file_data '''NO.1单组元素和多组元素未分解都一样,下面看嵌套,考眼力了~''' @ddt class Testwork(unittest.TestCase): @data([{'name': 'lili', 'age': 12}, {'sex': 'male', 'job': 'teacher'}]) # @unpack def test_01(self, a): print(a) if __name__ == '__main__': unittest.main() # 结果: # [{'name': 'lili', 'age': 12}, {'sex': 'male', 'job': 'teacher'}] # ※上面结果可以看出:无法运用到requests数据请求中,所以不是很实用※ '''NO.2多组元素分解''' @ddt class Testwork(unittest.TestCase): @data([{'name': 'lili', 'age': 12}, {'sex': 'male', 'job': 'teacher'}]) @unpack def test_01(self, a, b): print(a, b) if __name__ == '__main__': unittest.main() # 结果: # {'name': 'lili', 'age': 12} # {'sex': 'male', 'job': 'teacher'} # ※拆分后的运行结果,不带有[],拆分是将列表中的2个字典拆分,所以有2个数据※ ############################################################## # 3、读取字典数据 import unittest, os from ddt import ddt, data, unpack, file_data '''※字典的读取比较特殊,因为在拆分的时候,形参和实参的key值要一致,否则就报错※''' '''NO.1单组数据''' @ddt class Testwork(unittest.TestCase): @data({'name': 'lili', 'age': '16'}, {'sex': 'female', 'job': 'nurser'}) # @unpack def test_01(self, a): print(a) if __name__ == '__main__': unittest.main() # 结果: # {'name': 'lili', 'age': '16'} # {'sex': 'female', 'job': 'nurser'} # ※以上运行的结果数据,就可以用来作为requests的请求参数 # ~!※ '''NO.2多数据拆分,重点来了''' @ddt class Testwork(unittest.TestCase): @data({'name': 'lili', 'age': '16'}, {'name': 'female', 'age': 'nurser'}) @unpack def test_01(self, name, age): print(name, age) if __name__ == '__main__': unittest.main() # 结果: # lili 16 # female nurser # ※重点来了:首先结果展示的数据是字典里的value,没有打印key的值;其次 @ data里的数据key值和def方法里的形参 # 名称一定要一致,否则,打印的时候,就会报莫名的参数错误,这里就不做展示,爱学习的同学可以尝试一下 # ~!※ #################################################################### # 4、读取文件数据 import unittest, os from ddt import ddt, data, unpack, file_data '''数据格式必须为json,且必须为双引号的键值对形式,如果不是json格式,有列表等其它格式嵌套的话,无论是 否有@unpack,形参和参数数量都要和key值相等''' @ddt class testwork(unittest.TestCase): testdata = [{'a': 'lili', 'b': 12}, {'a': 'sasa', 'b': 66}] @data(*testdata) # @unpack def test_01(self, value): print(value) @file_data(os.getcwd() + '/jsonll.txt') def test_02(self, value2): print(value2) if __name__ == '__main__': unittest.main() # 结果: # {'a': 'lili', 'b': 12} # {'a': 'sasa', 'b': 66} # nick # male # 29
# Debug all errrors found in this program so that the output result is displayed correctly to the user import random user = input("choose your weapon!") comp = random.choice(['rock','paper','scissors']) print('user (you) chose:', user) print('comp (me) chose:', comp) if (user == 'rock' and comp == 'paper'): print('YOU LOSE!') if (user == 'rock' and comp == 'scissors'): print('YOU WIN!') if (user == 'rock' and comp == 'rock'): print('TIE') if (user == 'paper' and comp == 'rock'): print('YOU LOSE!') if (user == 'paper' and comp == 'rock'): print('YOU WIN!') if (user == 'paper' and comp == 'paper'): print('TIE') if (user == 'scissors' and comp == 'rock'): print('YOU LOOSE!') if (user == 'scissors' and comp == 'paper'): print('YOU WIN!') if (user == 'scissors' and comp == 'scissors'): print('TIE')
# -*-coding:utf-8-*- # created by HolyKwok 201610414206 # practice1-4 # rooster -> 5, hen -> 3, 3chicks -> 1 # ¥100 -> 100 sum_ = 100 # the sum of hens, roosters and chicks cost = 100 price_rooster = 5 # each rooster costs 5 price_hen = 3 # eaach hen costs 3 one4chick = 3 # 3 chicks costs 1 for rooster in range(sum_ // price_rooster + 1): # number of rooster no more than 25 for hen in range(sum_ // price_hen + 1): # number of hen no more than 33 chick = sum_ - rooster - hen if chick % one4chick == 0 and (price_rooster * rooster + price_hen * hen + chick / one4chick) == cost: # 3 chicks -> 1 and cost = 100 print("rooster:{}, hen:{}, chick:{}".format(rooster, hen, chick)) else: pass
def Sorte(T): return T[0] def Mini(A,p): R=[] for i in range(len(A)): a=abs(p-A[i]) t=[a,A[i]] R.append(t) R.sort(key=Sorte) return R[0][1] Request=[98, 67, 78, 30, 10, 45, 180, 20, 150, 35] position=60 movef=0 c=position l=len(Request) for i in range(l): movef=movef+abs(c-Request[i]) c=Request[i] print("First Come First Serve:") print("No. of moves is",movef,"ns") print() #SSTF p=position moves=0 for i in range(l): a=Mini(Request,p) moves=moves+abs(p-a) p=a Request.pop(Request.index(a)) print("Shortest Seek Time First:") print("No. of moves is",moves,"ns") print() if(moves>movef): print("First Come First Serve is better") elif(moves<movef): print("Shortest Seek Time First is better") else: print("Both are equally better in this case")
#esse ("inf")O primeiro cria um número infinito, o segundo cria um número que não é um número "Not a Number" #aqui declaramos variaveis para o funcionamento como continuar, maior, menor, a quantidade de numeros que digitei. maior = -float("inf") menor = float("inf") continuar ="sim" quantos_numeros = 0 #esse while faz a pergunta da condição de continuar até o usuario dizer que não quer mais, e comprara dentro dos if se o numero é maior ou menor. while continuar == "sim": numero = int(input("digite um numero\n")) continuar = (input("deseja continuar\n")) if numero < menor: menor = numero if numero > maior: maior = numero quantos_numeros +=1 soma = maior = menor media = soma/quantos_numeros print("menor", menor) print("maior", maior) print("media", media)
# This python script reads a 28x22 PNG image representing a game level # and outputs a sequence of data that represents the game map # NOTE: white = background, black = wall # other colors are ignored (might be used to mark objects) from PIL import Image img = Image.open("map.png") level_map = [[0x80 for i in range(22)] for j in range(32)] pixels = img.load() black = (0, 0, 0) # first we process the map for j in range(22): for i in range(28): c = pixels[i, j] if c == black: level_map[i+2][j] = 0x85 # then we adjust the tiles for j in range(22): for i in range(2, 30): if level_map[i][j] != 0x80: c = 0 if (j > 0) and (level_map[i][j-1] != 0x80): c = c + 1 if (i < 28) and (level_map[i+1][j] != 0x80): c = c + 2 if (j < 21) and (level_map[i][j+1] != 0x80): c = c + 4 if (i > 0) and (level_map[i-1][j] != 0x80): c = c + 8 if (c == 2) or (c == 8) or (c == 10): level_map[i][j] = 0x82 - i%2 elif (c == 1) or (c == 4) or (c == 5): level_map[i][j] = 0x84 - j%2 # finally, print the layout for j in range(22): print "dm ", for i in range(32): print hex(level_map[i][j]), if i < 31: print ",", else: print
#The main goal of the program is to convert NPR to AUD or AUD TO NPR. Aud = 12345678 ConvertedAud= Aud*80.61 Npr= 12345678 ConvertedNpr = Npr/80.61 print "The AUD converted is : %f" %ConvertedAud # %f is a formatter for FLOAT hence the ConvertedToNpr will not show print "The NPR converted is :%d " %ConvertedNpr
for a in range(1, 400): for b in range(1, 400): c = (1000 - a - b) #condition (iii) if a < b < c: if a * a + b * b == c * c: product_abc = a * b * c print("the product abc is,",product_abc)
# https://docs.python.org/3/howto/sockets.html # https://stackoverflow.com/questions/8627986/how-to-keep-a-socket-open-until-client-closes-it # https://stackoverflow.com/questions/10091271/how-can-i-implement-a-simple-web-server-using-python-without-using-any-libraries import socket def create_server(): server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: server_socket.bind(('localhost', 9000)) server_socket.listen(5) while True: (client_socket, address) = server_socket.accept() rd = client_socket.recv(5000).decode() pieces = rd.split("\n") if len(pieces) > 0: print(pieces[0]) data = "HTTP/1.1 200 OK\r\n" data += "Content-Type: text/html; charset=utf-8\r\n" data += "\r\n" data += "<html><body>Hello World</body></html>\r\n\r\n" client_socket.sendall(data.encode()) client_socket.shutdown(socket.SHUT_WR) except KeyboardInterrupt: print("\nShutting down...\n") except Exception as exc: print("Error:\n") print(exc) server_socket.close() print('Access http://localhost:9000') if __name__ == '__main__': create_server()
import time import random def print_pause(message_to_print, pause=2): print(message_to_print) time.sleep(2) def valid_input(prompt, options): while True: response = input(prompt).lower() for option in options: if option == response: return response print_pause("Sorry I don't understand.") def intro(): print_pause("You find yourself in self isolation at home in a " "once bustling city.") print_pause("There is a lethal virus spreading and has been " "terrifying all those in its path.") print_pause("The mass panic caused by this invisible threat " "has caused a shortage of basic supplies.") print_pause("You must now venture into the world for the most " "essential supply, toilet paper!") print_pause("You stand in the foyer of your home.") def outside(items, color, material): print_pause("You cautiously open the front door.") if "mask" in items and "gloves" in items: print_pause("You put on your " + color + " bandana, " "covering your nose and mouth.") print_pause("And you slip on the " + material + " gloves.") print_pause("You're ready to go to the store!") print_pause("Congrats you win!") play_again(items, color, material) else: print_pause("Something doesn't feel right, like " "you're forgeting something.") response = valid_input("Do you want to go back inside? " "(yes/no)\n", ["yes", "no"]) if response == "yes": print_pause("Good call.") front_door(items, color, material) elif response == "no": print_pause("Oh no! You forgot an important piece of your PPE!") print_pause("You have been infected with the virus...") print_pause("Sorry you lose.") play_again(items, color, material) def bedroom(items, color, material): print_pause("You go upstairs to your bedroom.") if "mask" in items: print_pause("It looks like you have everything you need from in here.") print_pause("You return to the foyer.") front_door(items, color, material) else: print_pause("Upon entering the room you pick up " "your " + color + " bandana from the dresser.") print_pause("This can be used as a mask and that is important " "piece for venturing out into public!") items.append("mask") print_pause("You return to the foyer.") front_door(items, color, material) def kitchen(items, color, material): print_pause("You walk to your kitchen.") if "gloves" in items: print_pause("It looks like you have everything you need from in here.") print_pause("You return to the foyer.") front_door(items, color, material) else: print_pause("After searching the cabinets you find " "your " + material + " gloves under the sink.") print_pause("You'll definitely need these to avoid touching " "an infected surface.") items.append("gloves") print_pause("You return to the foyer.") front_door(items, color, material) def front_door(items, color, material): print_pause("Where do you want to go?") response = valid_input("Enter 1 to leave the house.\n" "Enter 2 to go to the bedroom.\n" "Enter 3 to go to the kitchen.\n", ["1", "2", "3"]) if response == "1": outside(items, color, material) elif response == "2": bedroom(items, color, material) elif response == "3": kitchen(items, color, material) def play_again(items, color, material): print_pause("GAME OVER") response = valid_input("Would you like to play " "again? (yes/no)\n", ["yes", "no"]) if response == "yes": print_pause("Great, let's go again!") items.clear() play_game() elif response == "no": print_pause("Okay, goodbye!") def play_game(): items = [] colors = ["red", "blue", "green", "black", "orange", "purple"] gloves = ["leather", "latex", "rubber", "suede"] color = random.choice(colors) material = random.choice(gloves) intro() front_door(items, color, material) if __name__ == "__main__": play_game()
# Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition. # The binary number returned should be a string. def add_binary(a,b): #your code here binarySum = a + b binaryResult = bin(binarySum) binaryLast1 = binaryResult.replace('b','') return binaryLast1[1 : : ]
def factorial(n): if n==1: return n else: return n*factorial(n-1) f=factorial(5) print(f)
# program to calculate area of basic geometrical shapes print("Launching Area Calculator") shape = raw_input("Enter one of the options listed: \n 1.S for square \n 2.R for Rectangle \n 3.C for circle \n 4.T for triangle \n") if shape.upper() == "S": sideSquare = float(raw_input("Enter the value of side of the square:")) areaSquare = sideSquare ** 2 print "Area of the Square is :%s" %(areaSquare) elif shape.upper() == "R": rectLen = float(raw_input("Enter the length of the rectangle:")) rectBreadth = float(raw_input("Enter the breadth of the rectangle:")) areaRect = rectLen * rectBreadth print areaRect elif shape.upper() == "C": radius=float(raw_input("Enter the radius of the circle:")) areaCircle=float( (3.14159 * (radius **2))) print areaCircle elif shape.upper() == "T": base = float(raw_input("Enter the base value of the triangle:")) height = float(raw_input("Enter the height of the triangle:")) areaTri = float(0.5*base*height) print "Area of Triangle: %s" %(areaTri) else: print("Invalid Option! Please choose one of the above:") print("Exiting Program!")
import collections def reverse_json(obj=None): """ Given a dict, reverse the order of the elements inside the dict :param obj: a dict, e.g. “{A:1, B:1, C:1, D:1, E:1}” :return: the dict with the elements reversed """ if obj is None: return {} # extract the keys from the dict reversed_keys = [*obj] # reverse their order reversed_keys.reverse() # create the object that will be returned by the function out = collections.OrderedDict() # iterate through each element of the dict to generate the output for k in reversed_keys: # if the element is another dict, recursively call this function if isinstance(obj[k], dict): out[k] = reverse_json(obj[k]) continue # otherwise store it in the ordered dict out[k] = obj[k] # return result return out
import smtplib host="smtp.gmail.com" port=587 username="[email protected]" password="password" from_email = username to_list=[ "[email protected]"] email_conn=smtplib.SMTP(host,port) #make connect email_conn.ehlo() #test whether the connect is ready email_conn.starttls() #enables upgrading otherwise plaintext communication between clients and mail servers, to encrypted communication. email_conn.login(username,password) #login email_conn.sendmail(from_email, to_list, "hello there this is an email message")#send email ,which's format like from "from_email" to "to_list" with text "hello there there" email_conn.quit() #disconnect from smtplib import SMTP ABC = SMTP(host, port) ABC.ehlo() ABC.starttls() ABC.login(username, password) ABC.sendmail(from_email, to_list, "Hello there this is an email message") ABC.quit() from smtplib import SMTP, SMTPAuthenticationError, SMTPException pass_wrong = SMTP(host, port) pass_wrong.ehlo() pass_wrong.starttls() try: pass_wrong.login(username, "wrong_password") pass_wrong.sendmail(from_email, to_list, "Hello there this is an email message") except SMTPAuthenticationError: print("Could not login") except: print("an error occured") pass_wrong.quit()
# Python code to demonstrate working of iskeyword() # In programming, a keyword is a "reserved word" by the language which convey a special meaning to the interpreter. # It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet. # Keywords in Python: Python language also reserves some of keywords that convey special meaning. # Knowledge of these is necessary part of learning this language. Below is list of keywords registered by python. # importing "keyword" for keyword operations # Python in its language defines an inbuilt module "keyword" which handles certain operations related to keywords. # A function "iskeyword()" checks if a string is keyword or not. Returns true if a string is keyword, else returns false. import keyword # initializing strings for testing s = "for" s1 = "geeksforgeeks" s2 = "elif" s3 = "elseif" s4 = "malika" s5 = "assert" s6 = "shambhavi" s7 = "True" s8 = "False" s9 = "Yash" s10 = "akash" s11 = "break" s12 = "ashty" s13 = "lambda" s14 = "suman" s15 = "try" s16 = "vaishnavi" # checking which are keywords if keyword.iskeyword(s): print (s + " is a python keyword") else: print (s + " is not a python keyword") if keyword.iskeyword(s1): print (s1 + " is a python keyword") else: print (s1 + " is not a python keyword") if keyword.iskeyword(s2): print (s2 + " is a python keyword") else: print (s2 + " is not a python keyword") if keyword.iskeyword(s3): print (s3 + " is a python keyword") else: print (s3 + " is not a python keyword") if keyword.iskeyword(s4): print (s4 + " is a python keyword") else: print (s4 + " is not a python keyword") if keyword.iskeyword(s5): print (s5 + " is a python keyword") else: print (s5 + " is not a python keyword") if keyword.iskeyword(s6): print (s6 + " is a python keyword") else: print (s6 + " is not a python keyword") if keyword.iskeyword(s7): print (s7 + " is a python keyword") else: print (s7 + " is not a python keyword") if keyword.iskeyword(s8): print (s8 + " is a python keyword") else: print (s8 + " is not a python keyword") if keyword.iskeyword(s9): print (s9 + " is a python keyword") else: print (s9 + " is not a python keyword") if keyword.iskeyword(s10): print (s10 + " is a python keyword") else: print (s10 + " is not a python keyword") if keyword.iskeyword(s11): print (s11 + " is a python keyword") else: print (s11 + " is not a python keyword") if keyword.iskeyword(s12): print (s12 + " is a python keyword") else: print (s12 + " is not a python keyword") if keyword.iskeyword(s13): print (s13 + " is a python keyword") else: print (s13 + " is not a python keyword") if keyword.iskeyword(s14): print (s14 + " is a python keyword") else: print (s14 + " is not a python keyword") if keyword.iskeyword(s15): print (s15 + " is a python keyword") else: print (s15 + " is not a python keyword") if keyword.iskeyword(s16): print (s16 + " is a python keyword") else: print (s16 + " is not a python keyword") # printing all keywords at once using "kwlist()" print ("The list of keywords is : ") print (keyword.kwlist)
from sklearn.datasets import load_iris from sklearn import tree from sklearn.naive_bayes import GaussianNB irisData = load_iris() print("==IRIS DATASET==") print(irisData) print("Type of irisData is:", type(irisData)) print() # Explore Features in DataSet print("===IRIS DATA FEATURES===") print(irisData.data) print() # Explore Target in DataSet print("===IRIS DATA TARGET===") print(irisData.target) print() # Explore Target NAMES in DataSet print("===IRIS DATA TARGET NAMES===") print(irisData.target_names) # 1. Create the Model model = GaussianNB() # 2. Training the Model model.fit(irisData.data, irisData.target) # Lets Test The Model with a Sample Input # inputData = [5.5, 2.3, 4.0, 1.3] # predictedTarget = model.predict([inputData]) # print(predictedTarget) inputData1 = [5.5, 2.3, 4.0, 1.3] inputData2 = [5.43, 3.90, 1.15, 0.32] predictedTargets = model.predict([inputData1, inputData2]) print(predictedTargets)
l = int(input("enter of low:")) u = int(input('enter of high:')) for num in range(l,u+1): if num>1: for i in range(2,num): if(num%i)==0: break else: print(num)
sum = -1 for x in range(0, 9**5*6): x_str = str(x) temp_sum = 0 for i in x_str: temp_sum += int(i)**5 if temp_sum == x: sum += x print(sum)
from tkinter import * class Gui(Tk): def __init__(self): super().__init__() # set window attributes self.title("Tickets") # add components self.__add_heading_label() self.__add_instruction_label() self.__add_tickets_entry() self.__add_buy_button() def __add_heading_label(self): self.heading_label= Label() self.heading_label.grid(row=0, column=0) self.heading_label.configure(font="Arial 14", text="Buy tickets", padx=50) def __add_instruction_label(self): self.instruction_label= Label() self.instruction_label.grid(row=1, column=0, sticky=W) self.instruction_label.configure(font="Arial 10", text="How many tickets do you need") def __add_tickets_entry(self): self.tickets_entry= Entry() self.tickets_entry.grid(row=2, column=0, sticky=W+S+E+N) self.tickets_entry.configure(text="", font="Arial 10") def __add_buy_button(self): #create self.buy_button=Button() self.buy_button.grid(row=3, column=0) #style self.buy_button.configure(text="Buy", font="Arial 9", width=16, height=1) #events self.buy_button.bind("<ButtonRelease-1>", self.__buy_button_clicked) def __buy_button_clicked(self, event): no_of_tickets =int (self.tickets_entry.get()) if (no_of_tickets == 1): messagebox.showinfo("Purchased!", "You have purchased the tickets!") elif no_of_tickets >1 : messagebox.showinfo("Purchased","You have purchased"+str(no_of_tickets)+ "tickets!") else: messagebox.showinfo("Error","You have entered an invalid number of tickets!")
def under(msg): """ This function creates a message and underneath converts it to * input: msg-string output: metin-string """ metin = "" metin = metin + msg metin = metin + "\n" metin = metin + len(msg)*"*" return metin def over(msg): metin2 = "" metin2 = metin2 + len(msg)*"*" metin2 = metin2 + "\n" metin2 = metin2 + msg return metin2 def both(msg): metin ="" metin = metin + len(msg)*"*" metin = metin + "\n" metin = metin + msg metin = metin + len(msg)*"*" return metin def grid(msg,size): metin = "" for number in range(0,size): metin = metin + (len(msg)*"*"+" ")*size metin = metin + "\n" metin = metin +msg+(size-1)*(" | "+msg) metin = metin + "\n" metin = metin +(len(msg)*"*"+" ")*size return metin
print("What type of adventure you like") user_answer = input() if ((user_answer == "scary") or (user_answer == "short")): print("Entering the dark forest") elif ((user_answer == "safe") or (user_answer == "long")): print("Taking the safe route!") else: print("Not sure which route to take.")
def abc(x): if x==0: return 0 return x+abc(x-1) while True: n=int(input("n: ")) print("suma primelor n cifre este : ",abc(n))
import sys, re import csv, json def main(): if len(sys.argv) != 3: print 'python course_csv_to_json.py <csv_file> <out_json_file>' return 0 fname = sys.argv[1] f = open(fname) data_arr = [] courseReader = csv.reader(f, delimiter=',', quotechar='"') for split_line in courseReader: hours = re.sub('[^0-9-]*', '', split_line[4]) hours_list = map(lambda x: int(x), hours.split('-')) difficulty = int(re.sub('[^0-9]*', '', split_line[5])) line_dict = {'time':split_line[0].lower(), 'major':split_line[1].lower(), 'grade':split_line[3].lower(), 'hours':hours_list, 'difficulty':difficulty} data_arr.append(line_dict) f.close() out_f = open(sys.argv[2], 'w') json.dump(data_arr, out_f) out_f.close() if __name__ == "__main__": main()
a=[float(i) for i in input().split()] area_tri=0.5*a[0]*a[2] area_circle=(3.14159*a[2]*a[2]) area_trip=0.5*a[2]*(abs(a[1]+a[0])) area_sq=a[1]*a[1] area_rec=a[0]*a[1] print("TRIANGULO:",format(area_tri,'0.3f')) print("CIRCULO:",format(area_circle,'0.3f')) print("TRAPEZIO:",format(area_trip,'0.3f')) print("QUADRADO:",format(area_sq,'0.3f')) print("RETANGULO:",format(area_rec,'0.3f'))
# -*- coding: utf-8 -*- import math import os ## Question1 : aire d'un rectangle (longueur x largeur) def rectangle(longueur,largeur): return (longueur*largeur) print("Aire du rectangle : " + str(rectangle(25,5))) ## Question 2 : aire d'un cylindre (2 x π x rayon x hauteur) def cylindre(rayon, hauteur): return (2*math.pi*rayon*hauteur) print("Aire du cylindre : " + str(cylindre(8,12))) ## Question 3 : conversion en chiffre Romain def convertChiffreRomain(i): result = '' if (i < 4): for x in range(i) : result = result + 'I' if (i == 4): result = 'IV' if (i == 5): result = 'V' if (i > 5 and i < 9) : result = 'V' for x in range(i-5) : result = result + 'I' if (i == 9): result = 'IX' if (i == 10): result = 'X' return result # retourne le chiffre Romain print("3 en chiffre Romain : " + convertChiffreRomain(3)) print("4 en chiffre Romain : " + convertChiffreRomain(4)) print("7 en chiffre Romain : " + convertChiffreRomain(7)) print("9 en chiffre Romain : " + convertChiffreRomain(9)) print("10 en chiffre Romain : " + convertChiffreRomain(10)) ## Question 4 : Générer un répertoire par commune (code INSEE) communes_insee = [85001,85003,85004,85005] def generateInseeDir(path): # Tester l'existence du dossier passé en paramètre if (os.path.exists(path) == False): os.mkdir(path) # Création du dossier si il n'existe pas for code_insee in communes_insee: if (os.path.exists(path+"\\"+str(code_insee)) == False): os.mkdir(path+"\\"+str(code_insee)) return 'Création des répértoires par commune terminée' print(generateInseeDir("C:\\FORMATION\\20210201")) ## Question 5 : Générer 50 répertoires (1-50) def generateNumberDir(path): if (os.path.isdir(path) == False): os.mkdir(path) for x in range(1,51): if (os.path.exists(path+"\\"+str(x)) == False): os.mkdir(path+"\\"+str(x)) return 'Création des 50 répertoires terminée' print(generateNumberDir("C:\\FORMATION\\20210201")) ## Question 6 : liste des fichiers + taille ==> fichier texte def readDir(path, outputFile): fw = open(outputFile, 'w') # Ouverture du fichier texte en ecriture listdir = os.listdir(path) print(listdir) # Boucler sur les répertoires et fichiers for fileOrDirectory in listdir: if (os.path.isfile(path + "\\"+ fileOrDirectory)): fw.write(fileOrDirectory + " : " + str(os.path.getsize(path + "\\"+ fileOrDirectory)) + " octet") if (os.path.getsize(path + "\\"+ fileOrDirectory) > 0): fw.write("s") fw.write("\n") fw.close() readDir('C:\\WINDOWS', 'C:\\FORMATION\\listerep.txt')
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np bilateral = pd.read_csv('data/bilateralmigrationmatrix20130.csv', index_col='From country', thousands=',') # histogram of migrants nonzero_values = bilateral.values.flatten() nonzero_values = nonzero_values[nonzero_values != 0] plt.hist(np.log(nonzero_values), bins=100) plt.ylabel('occurences') plt.xlabel('migrants - log scale') plt.show() # most emigrated to print bilateral.sum(axis=0).nlargest(11) # most emigrated from print bilateral.sum(axis=1).nlargest(11) # what are the countries bulgarians emigrate to? print bilateral.loc['Bulgaria'].nlargest(11) # here is how to plot pie charts of the 10 largest countries to emigrate to or from # bilateral.loc['United Kingdom'].nlargest(11).tail(10).plot.pie() # use population as predictor wdi_data = pd.read_csv('data/wdi_data_2013.csv', index_col = 'Unnamed: 0') population = wdi_data[wdi_data['Indicator Name'] == 'Population, total'] population.set_index('Country Name', inplace=True) emigration_to = bilateral.sum(axis=0).to_frame('emigration_to') emigration_from = bilateral.sum(axis=1).to_frame('emigration_from') # plot emigration to with population merged = population.merge(emigration_to, left_index=True, right_index=True, how='inner') merged = merged.merge(emigration_from, left_index=True, right_index=True, how='inner') merged['log_population'] = np.log(merged['2013']) merged['log_imigration'] = np.log(merged.emigration_to + 1) merged['log_emigration'] = np.log(merged.emigration_from + 1) log_indicators = ['log_population', 'log_emigration', 'log_imigration'] pop_plot = sns.pairplot(merged[log_indicators][merged.isnull().any(axis=1) == 0]) pop_plot.savefig('scatter-plot-population') # use gdp per capita PPP adjusted as predictor wdi_data = pd.read_csv('data/wdi_data_2013.csv', index_col = 'Unnamed: 0') gdp = wdi_data[wdi_data['Indicator Name'] == 'GDP per capita, PPP (current international $)'] gdp.set_index('Country Name', inplace=True) emigration_to = bilateral.sum(axis=0).to_frame('emigration_to') emigration_from = bilateral.sum(axis=1).to_frame('emigration_from') # plot emigration to with population merged = gdp.merge(emigration_to, left_index=True, right_index=True, how='inner') merged = merged.merge(emigration_from, left_index=True, right_index=True, how='inner') merged['log_gdp'] = np.log(merged['2013']) merged['log_emigration_to'] = np.log(merged.emigration_to + 1) merged['log_emigration_from'] = np.log(merged.emigration_from + 1) log_indicators = ['log_gdp', 'log_emigration_to', 'log_emigration_from'] pop_plot = sns.pairplot(merged[log_indicators][merged.isnull().any(axis=1) == 0]) pop_plot.savefig('scatter-plot-gdp') size_corrected = np.log(bilateral.values+1) size_corrected -= size_corrected.mean(axis=0) size_corrected = size_corrected.T size_corrected -= size_corrected.mean(axis=0)
#! /usr/bin/python3.7 # Map It # this program searches for the address given as a bash argument. # if no arguments given, it will copy from the clipboard. # this is an example for the "webbrowser" module. import webbrowser import pyperclip import sys address = 'https://www.google.com/maps/place/' if len(sys.argv) == 1: address += pyperclip.paste() else: address = address + '+'.join(sys.argv[1:]) webbrowser.open(address)
import collections # Named Tuples color = collections.namedtuple('Color', ['hue', 'saturation', 'luminosity']) p = color(170, 0.1, 0.6) if p.saturation >= 0.5: print('Whew, that is bright!') if p.luminosity >= 0.5: print('Wow, that is light!')
#! /usr/bin/python3.7 import logging ''' instead of using print() for logging, we can use this module. when deleting logging print() calls we can accidentally remove a valid print() call. instead, we use logging and we can disable all logs with this function: ''' # logging.disable(level=logging.DEBUG) logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') logging.debug('Start of program') def factorial(n): logging.debug('Start of factorial(%s)' % n) total = 1 for i in range(1, n + 1): total *= i logging.debug('i is ' + str(i) + ', total is ' + str(total)) logging.debug('End of factorial(%s)' % n) return total print(factorial(5)) logging.debug('End of program')
import logging from abc import abstractmethod from . import Input class DelayedSwitch(Input): """A class for using a switch with a delay """ async def _on_input(self, command, seat): """DelayedSwitch input functionality :param command: Command from game engine :type command: dict :param seat: Robot seat :type seat: int """ if "state" not in command or "delay" not in command: logging.warning("Received invalid command for DelayedSwitch") return try: val = str(command["state"]) if val != "up" and val != "down": logging.warn("Button command not <up|down>") return delay = int(command["delay"]) await self.set_state(val, delay, seat) except (ValueError, TypeError): logging.warn( "Could not convert command for Button into bool: %s" % command["state"] ) @abstractmethod async def set_state(self, state, delay, seat): """Set switch to 'up' or 'down' state after a user implemented delay :param state: 'up' or 'down' :type state: str :param delay: User implemented delay amount in seconds :type delay: float :param seat: Robot seat :type seat: int """ pass async def reset(self, seat): """DelayedSwitch reset functionality Defaults to setting the switch state to up :param seat: Robot seat :type seat: int """ self.set_state("up", 0, seat) def get_name(self): """Returns the name of the input :return: name of the input :rtype: str """ return "delayedButton"
""" kruskal_mst.py Compute a minimum spanning forest using Kruskal's algorithm. The KruskalMST class represents a data type for computing a * minimum spanning tree in an edge-weighted graph. * The edge weights can be positive, zero, or negative and need not * be distinct. If the graph is not connected, it computes a minimum * spanning forest, which is the union of minimum spanning trees * in each connected component. The weight() method returns the * weight of a minimum spanning tree and the edges() method * returns its edges. * * This implementation uses Krusal's algorithm and the * union-find data type. * The constructor takes Theta(E log E) time in * the worst case. * Each instance method takes Theta(1) time. * It uses Theta(E) extra space (not including the graph). """ import heapq from graphs.edge import Edge from graphs.edge_weighted_graph import EdgeWeightedGraph from queue import Queue from unionfind.uf import UF class KruskalMST: FLOATING_POINT_EPSILON = 1E-12 _weight = 0 _mst = Queue() def __init__(self, g: EdgeWeightedGraph): self._pq = list() # min priority queue in ascending order of Edge weights for e in g.edges(): heapq.heappush(self._pq, e.item) uf = UF(g.get_V()) # 1. Consider edges in ascending order of edge weight (sort weights). # 2. Add the next Edge, e, to tree, _mst, unless doing so would create a cycle. while self._pq and self._mst.qsize() < g.get_V() - 1: e = heapq.heappop(self._pq) v = e.either() w = e.other(v) if not uf.connected(v, w): # no cycle because v-w are not in the same set uf.union(v, w) # merge sets containing v-w to add v-w to _mst self._mst.put(e) self._weight += e.weight() assert self.__check(g) def edges(self): return self._mst.queue def weight(self): return self._weight def __check(self, g): total = 0.0 for e in self.edges(): total += e.weight() if abs(total - self.weight()) > KruskalMST.FLOATING_POINT_EPSILON: print(f'Weight of edges does not equal weight(): {total} vs {self.weight()}') return False uf = UF(g.get_V()) # check that it is acyclic for e in self.edges(): v = e.either() w = e.other(v) if uf.find(v) == uf.find(w): print(f'not a forest') return False uf.union(v, w) # check that it is a spanning forest for e in g.edges(): v = e.item.either() w = e.item.other(v) if uf.find(v) != uf.find(w): print(f'not a spanning forest') return False # check that it is a minimal spanning forest (cut optimality conditions) for e in self.edges(): uf = UF(g.get_V()) for f in self._mst.queue: x = f.either() y = f.other(x) if f != e: uf.union(x, y) for f in g.edges(): x = f.item.either() y = f.item.other(x) if uf.find(x) != uf.find(y): if f.item.weight() < e.weight(): print(f'Edge {f} violates cut optimality conditions') return False return True def __repr__(self): return f'<{self.__class__.__name__}(_pq={self._pq}, weight={self.weight()}, _mst={self._mst.queue})>' def main(): with open("../resources/tinyEWG.txt", ) as f: values = "".join(f.readlines()).splitlines() V, E = int(values[0]), int(values[1]) g = EdgeWeightedGraph(V) for line in values[2:]: vertices = line.split(' ') v, w, weight = int(vertices[0]), int(vertices[1]), float(vertices[2]) e = Edge(v, w, weight) g.add_edge(e) print(g) mst = KruskalMST(g) print(mst) if __name__ == '__main__': main()
# Bubble sort # O(n**2) def bubble_sort(array): is_sorted = False n = len(array) - 1 while not is_sorted: is_sorted = True for i in range(n): j = i + 1 if array[i] > array[j]: swap(array, i, j) is_sorted = False n -= 1 return array def swap(array, i, j): array[i], array[j] = array[j], array[i] def main(): array = [8, 5, 7, 2, 10] print(bubble_sort(array)) if __name__ == '__main__': main()
""" allow_filter.py The AllowFilter class provides a client for reading in an allow_list * of words from a file; then, reading in a sequence of words from standard input, * printing out each word that appears in the file """ from search.p_set import SET class AllowFilter: @staticmethod def run(*args): allow_list, word_file = args[0], args[1] st = SET() with open(allow_list) as f: for word in f.read().split(' '): # print(word) st.add(word) print() with open(word_file) as f1: for word in f1.read().split(' '): print(word) if st.contains(word): print(word) print(st) def main(): allow_list = "../resources/list.txt" word_file = "../resources/tiny_tale.txt" AllowFilter.run(allow_list, word_file) if __name__ == '__main__': main()
""" suffix_array.py A data type that computes the suffix array of a string. The SuffixArray class represents a suffix array of a string of * length n. * It supports the selecting the ith smallest suffix, * getting the index of the ith smallest suffix, * computing the length of the longest common prefix between the * ith smallest suffix and the i-1st smallest suffix, * and determining the rank of a query string (which is the number * of suffixes strictly less than the query string). * * This implementation uses a nested class Suffix to represent * a suffix of a string (using constant time and space) * The index and length operations takes constant time * in the worst case. * The lcp operation takes time proportional to the * length of the longest common prefix. * The select operation takes time proportional * to the length of the suffix and should be used primarily for debugging. * """ class SuffixArray: def __init__(self, text): n = len(text) self._suffixes = [SuffixArray._Suffix()] * n for i in range(n): self._suffixes[i] = SuffixArray._Suffix(text, i) self._suffixes.sort() class _Suffix: def __init__(self, text=None, index=None): self.text = text self.index = index def length(self): return len(self.text) - self.index def char_at(self, i): return self.text[self.index + i] def __lt__(self, other): n = min(self.length(), other.length()) for i in range(n): if self.char_at(i) < other.char_at(i): return True return False def __gt__(self, other): n = min(self.length(), other.length()) for i in range(n): if self.char_at(i) > other.char_at(i): return True return False def __eq__(self, other): n = min(self.length(), len(other)) for i in range(n): if self.char_at(i) == other[i]: return True return False def __repr__(self): return f'<{self.__class__.__name__}(text={self.text}, index={self.index})>' def __str__(self): return self.text[self.index] def length(self): return len(self._suffixes) def index(self, i): if i < 0 or i >= len(self._suffixes): raise AttributeError(f'i cannot be less than 0 or greater than or equal to length of {self._suffixes}') return self._suffixes[i].index def lcp(self, i): # the length of the longest common prefix of the i-th smallest suffix if i < 1 or i >= len(self._suffixes): raise AttributeError(f'i {i} must be between 1 and {len(self._suffixes)}') return self.__lcp_suffix(self._suffixes[i], self._suffixes[i - 1]) def __lcp_suffix(self, s, t): n = min(s.length(), t.length()) for i in range(n): if s.char_at(i) != t.char_at(i): return i return n def select(self, i): if i < 0 or i >= len(self._suffixes): raise AttributeError(f'i {i} must be between 1 and {len(self._suffixes)}') return self._suffixes[i] def rank(self, query): lo, hi = 0, len(self._suffixes) - 1 while lo <= hi: mid = (hi + lo) // 2 cmp = self.__compare(query, self._suffixes[mid]) if cmp < 0: hi = mid - 1 elif cmp > 0: lo = mid + 1 else: return mid return lo def __compare(self, query, suffix): n = min(len(query), suffix.length()) for i in range(n): if query[i] < suffix.char_at(i): return -1 if query[i] > suffix.char_at(i): return 1 return len(query) - suffix.length() def __repr__(self): return f'<{self.__class__.__name__}(_suffixes={self._suffixes})>' def main(): s = 'ABRACADABRA!' suffix = SuffixArray(s) print(suffix) print('i ind lcp rnk select') print('--------------------') for i in range(len(s)): index = suffix.index(i) ith = f'{s[index: min(index + 50, len(s))]}' assert s[index:] == suffix.select(i) rank = suffix.rank(s[index]) if i == 0: print(f'{i}, {index}, "-", {rank}, {ith}') else: lcp = suffix.lcp(i) print(f'{i}, {index}, {lcp}, {rank}, {ith}') if __name__ == '__main__': main()
""" /****************************************************************************** * Performs a series of computational experiments. * Execution: - * Dependencies: - ******************************************************************************/ """ from Percolation import Percolation import random import math class PercolationStats: """ :param T: The number of times a computation experiment runs. :type T: int. :param N: elements {0} through {N-1} for an N-by-N grid. :type N: int. """ def __init__(self, N: int, T: int): """ Perform T independent experiments on an N-by-N grid. :param T: The number of times a computation experiment runs. :type T: int. :param N: elements {0} through {N-1} for an N-by-N grid. :type N: int. """ if N < 1 or T < 1: raise ValueError('N and T must be > 0.') self.t = T self.N = N self.threshold = [self.calc_threshold(N) for _ in range(self.t)] def calc_threshold(self, n: int) -> float: """ Find threshold value p*, probability the system will percolate. :param n: n the value. :return: threshold value. :rtype: float. """ counter = 0 i, j = None, None perc = Percolation(n) while not perc.percolates(): i = random.randint(0, n-1)+1 j = random.randint(0, n-1)+1 print(f'i: {i}\nj: {j}') if not perc.is_open(i, j): counter += 1 perc.open(i, j) return counter / (n * n) def mean(self) -> float: """ Sample mean of percolation threshold. :return: mean. :rtype: float. """ _sum = 0 for i in range(len(self.threshold)): _sum += self.threshold[i] return _sum / self.t def stddev(self) -> float: """ Sample standard deviation of percolation threshold. :return: standard deviation. :rtype: float. """ m = self.mean() _sum = 0 for i in range(len(self.threshold)): _sum += (self.threshold[i] - m) * (self.threshold[i] - m) if self.t == 1: return float('nan') return _sum / (self.t - 1) def confidence_low(self) -> float: """ Low endpoint of 95% confidence interval. :return: low endpoint. :rtype: float. """ return self.mean() - (1.96 * self.stddev()) / (math.sqrt(self.t)) def confidence_high(self) -> float: """ High endpoint of 95% confidence interval. :return: high endpoint. :rtype: float. """ return self.mean() + (1.96 * self.stddev()) / (math.sqrt(self.t)) def __repr__(self): return f'<PercolationStats(threshold={self.threshold}, T={self.t}, N={self.N})>' def main(): stats = PercolationStats(4, 20) print(stats) print(f'mean = {stats.mean()}') print(f'stddev = {stats.stddev()}') print(f'95% confidence interval = {stats.confidence_low()}, {stats.confidence_high()}') if __name__ == '__main__': main()
""" flow_edge.py Capacitated edge with a flow in a flow network. The FlowEdge class represents a capacitated edge with a * flow in a FlowNetwork. Each edge consists of two integers * (naming the two vertices), a real-valued capacity, and a real-valued * flow. The data type provides methods for accessing the two endpoints * of the directed edge and the weight. It also provides methods for * changing the amount of flow on the edge and determining the residual * capacity of the edge. """ import math class FlowEdge: FLOATING_POINT_EPSILON = 1E-10 def __init__(self, v=0, w=0, capacity=0.0): if v < 0: raise AttributeError('vertex index must be a nonnegative integer') if w < 0: raise AttributeError('vertex index must be a nonnegative integer') if not capacity >= 0.0: raise AttributeError('Edge capacity must be non-negative') self._v = v self._w = w self._capacity = capacity self._flow = 0.0 def tail(self): return self._v def head(self): return self._w def capacity(self): return self._capacity def flow(self): return self._flow def other(self, vertex): if vertex == self._v: return self._w elif vertex == self._w: return self._v else: raise AttributeError('Invalid endpoint') def residual_capacity_to(self, vertex): if vertex == self._v: return self._flow # backward edge elif vertex == self._w: # forward edge return self._capacity - self._flow else: raise AttributeError('Invalid endpoint') def add_residual_flow_to(self, vertex, delta): if not delta >= 0.0: raise AttributeError('Delta must be non-negative') if vertex == self._v: self._flow -= delta # backward edge elif vertex == self._w: self._flow += delta # forward edge else: raise AttributeError('Invalid endpoint') # round flow to 0 or capacity if within floating-point precision if abs(self._flow) <= self.FLOATING_POINT_EPSILON: self._flow = 0 if abs(self._flow - self._capacity) <= self.FLOATING_POINT_EPSILON: self._flow = self._capacity if not self._flow >= 0.0: raise AttributeError('flow is negative') if not self._flow <= self._capacity: raise AttributeError('flow exceeds capacity') def __str__(self): return f'{self._v}->{self._w} {self._flow}/{self._capacity}' def __repr__(self): return f'<{self.__class__.__name__}(' \ f'_v={self._v}, ' \ f'_w={self._w}, ' \ f'_capacity={self._capacity},' \ f'_flow={self._flow})>' def main(): e = FlowEdge(12, 23, 4.56) print(e) if __name__ == '__main__': main()
# Bruteforce substring search # Time complexity # Worst case Theta(N * M) def str_search(pattern, text): """ if pattern exists in text, return index where pattern starts. :param pattern: string pattern :param text: string text :returns: index of where pattern starts """ N, M = len(text), len(pattern) i = 0 while i <= N-M: j = 0 while j < M: if text[i + j] != pattern[j]: break j += 1 if j == M: return i i += 1 return N def str_search_two(pattern, text): """ if pattern exists in text, return index where pattern starts. :param pattern: string pattern :param text: string text :returns: index of where pattern starts """ N, M = len(text), len(pattern) i, j = 0, 0 while i < N and j < M: if text[i] == pattern[j]: j += 1 else: i -= j j = 0 i += 1 if j == M: return i - M else: return N def main(): print(str_search('ADACR', 'ABACADABRAC')) print(str_search('IN', 'VINCENT')) print(str_search_two('ADACR', 'ABACADABRAC')) print(str_search_two('IN', 'VINCENT')) if __name__ == '__main__': main()
""" digraph.py The Digraph class represents a directed graph of vertices * named 0 through V - 1. * It supports the following two primary operations: add an edge to the digraph, * iterate over all of the vertices adjacent from a given vertex. * It also provides * methods for returning the indegree or outdegree of a vertex, * the number of vertices V in the digraph, * the number of edges E in the digraph, and the reverse digraph. * Parallel edges and self-loops are permitted. * * This implementation uses an adjacency-lists representation, which * is a vertex-indexed array of Bag objects. * It uses Theta(E + V) space, where E is * the number of edges and V is the number of vertices. * All instance methods take Theta(1) time. (Though, iterating over * the vertices returned by adj(int) takes time proportional * to the outdegree of the vertex.) * Constructing an empty digraph with V vertices takes * Theta(V) time constructing a digraph with E edges * and V vertices takes Theta(E + V) time. * """ from graphs.graph import Graph from graphs.bag import Bag from collections import deque, defaultdict class Digraph: def __init__(self, v): """ Initializes an empty graph with V vertices and 0 edges. :param v: the number of vertices """ if v < 0: raise ValueError('Number of vertices must be non-negative') self.V = v self.E = 0 self._indegree = [0 for _ in range(v)] self.adj = defaultdict(Bag) for v in range(v): self.adj[v] = Bag() def get_V(self): """ :returns: the number of vertices in this graph """ return self.V def get_E(self): """ :returns: the number of edges in this graph """ return self.E def _validate_vertex(self, v): """ Throw a ValueError exception if 0 <= v < V :param v: vertex v """ if v < 0 or v >= self.V: raise ValueError(f'vertex {v} is not between 0 and {self.V - 1}') def add_edge(self, v, w): self._validate_vertex(v) self._validate_vertex(w) self.adj[v].add(w) self.get_indegree()[w] += 1 self.E += 1 def adj_vertices(self, v): """ Returns the vertices adjacent to the vertex {v} :param v: v the vertex :returns: the vertices adjacent to vertex {v} """ self._validate_vertex(v) return self.adj[v] def get_indegree(self): return self._indegree def indegree(self, v=0): self._validate_vertex(v) return self._indegree[v] def get_outdegree(self): return self.outdegree() def outdegree(self, v=0): self._validate_vertex(v) return self.adj[v].size() def reverse(self): reverse = Digraph(self.get_V()) for v in range(self.get_V()): for w in self.adj_vertices(v): reverse.add_edge(w.item, v) return reverse def __repr__(self): return f'<{self.__class__.__name__}(' \ f'V={self.get_V()}, ' \ f'E={self.get_E()}, ' \ f'adj={self.adj})>' def main(): g = Digraph(4) print(g) g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 3) print(g) print(g.get_V()) print(f'adjacent vertices of 2 are: {g.adj_vertices(2)}') print(f'indegree of 2 is: {g.indegree(2)}') print(f'outdegree of 2 is: {g.outdegree(2)}') if __name__ == '__main__': main()
""" doubling_ratio.py * The DoublingRatio class provides a client for measuring * the running time of a method using a doubling ratio test. """ import random as r from fundamentals.stopwatch import StopWatch from fundamentals.three_sum import ThreeSum class DoublingRatio: MAXIMUM_INTEGER = 1000000 @staticmethod def time_trial(n): a = [r.uniform(-DoublingRatio.MAXIMUM_INTEGER, DoublingRatio.MAXIMUM_INTEGER) for _ in range(n)] timer = StopWatch() ThreeSum.count(a) return timer.elapsed_time() def main(): prev = DoublingRatio.time_trial(125) n = 250 while True: time = DoublingRatio.time_trial(n) print(f'{n} {time} {time/prev if prev != 0 else prev}') prev = time n += n if __name__ == '__main__': main()
""" hash_table.py. @description The hash_table.py module defines a class, HashTable. @author Vincent Porta. #------------------------------------------------- Time complexity in big O notation. # Algorithm Average Worst case # Space O(n) O(n) # Search O(1) O(n) # Insert O(1) O(n) # Delete O(1) O(n) #------------------------------------------------- """ class HashTable: def __init__(self, length=10): self.length = length self.array = [[] for i in range(length)] def hash(self, key): length = len(self.array) return hash(key) % length def add(self, key, value): # if self.is_full(): # return index = self.hash(key) if self.array[index] is not None: for kvp in self.array[index]: if kvp[0] == key: kvp[1] = value break else: self.array[index].append([key, value]) else: self.array[index] = [] self.array[index].append([key, value]) def get(self, key): index = self.hash(key) if self.array[index] is None: raise KeyError() else: for kvp in self.array[index]: if kvp[0] == key: return kvp[1] raise KeyError() def is_full(self): items = 0 for item in self.array: if item is not None: items += 1 return items > len(self.array) // 2 def double(self): ht2 = HashTable(length=len(self.array) * 2) for i in range(len(self.array)): if self.array[i] is None: continue for kvp in self.array[i]: ht2.add(kvp[0], kvp[1]) self.array = ht2.array def __repr__(self): return f"<HashTable(array={self.array})>" def __setitem__(self, key, value): self.add(key, value) def __getitem__(self, key): return self.get(key) def __contains__(self, key): i = hash(key) % len(self.array) print(i) for j in range(len(self.array[i])): if self.array[i][j][0] == key: return True return False def __iter__(self): yield from self.array def main(): hm = HashTable() print(hm) hm.add(0, 'vincent') hm['foo'] = 'bar' hm.add(1, 'bob') # hm.add(2, 'bert') hm.add(3, 'jerry') print(hm) print() for kvp in hm: print(kvp) if 'foo' in hm: print('exists')
""" pqueues.py A generic queue. * The pqueues class represents a first-in-first-out (FIFO) * queue of generic items. * It supports the usual enqueue and dequeue * operations, along with methods for peeking at the first item, * testing if the queue is empty, and iterating through the items in FIFO order. * This implementation uses a singly linked list with a static nested class for linked-list nodes * The enqueue, dequeue, peek, size, and is-empty operations all take constant time in the worst case. """ class Queue: class _Node: def __init__(self, _item=None, _next=None): self._item = _item self._next = _next def __repr__(self): return f"<_Node(_item={self._item}, _next={self._next})>" def __init__(self): self._first = None self._last = None self._n = 0 def is_empty(self): return self._first == None def size(self): return self._n def peek(self): if self.is_empty(): raise Exception('No such element') return self._first._item def enqueue(self, item): old_last = self._last self._last = Queue._Node() self._last._item = item self._last._next = None if self.is_empty(): self._first = self._last else: old_last._next = self._last self._n += 1 def dequeue(self): if self.is_empty(): raise Exception('pqueues underflow') item = self._first._item self._first = self._first._next self._n -= 1 if self.is_empty(): self._last = None return item def __repr__(self): return f"<Queue(first={self._first}, last={self._last}, n={self._n})>" def __iter__(self): current = self._first while current is not None: yield current._item current = current._next def main(): queue = Queue() queue.enqueue('A') queue.enqueue('B') queue.enqueue('C') print(queue) # queue.dequeue() print(queue) print(queue.peek()) print(queue.size()) for i in queue: print(i.first._item) if __name__ == '__main__': main()
""" doubling_test.py * The DoublingTest class provides a client for measuring * the running time of a method using a doubling test. """ import random as r from fundamentals.stopwatch import StopWatch from fundamentals.three_sum import ThreeSum class DoublingTest: MAXIMUM_INTEGER = 1000000 @staticmethod def time_trial(n): a = [r.uniform(-DoublingTest.MAXIMUM_INTEGER, DoublingTest.MAXIMUM_INTEGER) for _ in range(n)] timer = StopWatch() ThreeSum.count(a) return timer.elapsed_time() def main(): n = 250 while True: time = DoublingTest.time_trial(n) print(f'{n} {time}') n += n if __name__ == '__main__': main()
""" directed_cycle_x.py Find a directed cycle in a digraph, using a nonrecursive, queue-based * algorithm. Runs in O(E + V) time. """ from collections import deque from graphs.digraph import Digraph class DirectedCycleX: _cycle = None def __init__(self, g): self._g = g self._marked = [False for _ in range(g.get_V())] self._edge_to = [0 for _ in range(g.get_V())] # indegrees of remaining vertices indegree = [g.indegree(v) for v in range(g.get_V())] # initialize queue to contain all vertices with indegree = 0 queue = deque() for v in range(g.get_V()): if indegree[v] == 0: queue.appendleft(v) while queue: v = queue.pop() for w in g.adj_vertices(v): indegree[w.item] -= 1 if indegree[w.item] == 0: queue.appendleft(w) # there is a directed cycle in subgraph of vertices with indegree >= 1 edge_to = [0 for _ in range(g.get_V())] root = -1 # any vertex with indegree >= -1 for v in range(g.get_V()): if indegree[v] == 0: continue else: root = v for w in g.adj_vertices(v): if indegree[w.item] > 0: edge_to[w.item] = v if root != -1: visited = [False for _ in range(g.get_V())] while not visited[root]: visited[root] = True root = edge_to[root] self._cycle = deque() # stack v = root while v != root: self._cycle.append(v) v = edge_to[v] self._cycle.append(root) assert self.__check() def get_g(self): return self._g def get_cycle(self): return list(self._cycle) def cycle(self): return self.get_cycle() def has_cycle(self): return self.get_cycle() is not None def __check(self): if self.has_cycle(): first, last = -1, -1 for v in self.cycle(): if first == -1: first = v last = v if first != last: print(f'cycle begins with {first} and ends with {last}') return False return True def __repr__(self): return f'<{self.__class__.__name__}(\n' \ f'g={self.get_g()}, \n' \ f'cycle={self.get_cycle()}\n' \ def main(): g = Digraph(13) with open("../resources/tinyDG.txt", ) as f: for line in f.readlines(): vertices = " ".join(line.splitlines()).split(' ') if len(vertices) < 2: continue else: v1, v2 = int(vertices[0]), int(vertices[1]) g.add_edge(v1, v2) finder = DirectedCycleX(g) print(finder) if finder.has_cycle(): print('Directed cycle') for v in finder.get_cycle(): print(f'{v} ', end="") print() else: print('No directed cycle') if __name__ == '__main__': main()
# Binary Search Trees # Height: the height of a BST - avg: O(log n) - worst: O(n) # Operation on BST # S. No. Operation Average Case Worst Case # 1 Contains/Search O(log n) O(n) # 2 Minimum O(log n) O(n) # 3 Maximum O(log n) O(n) # 4 Predecessor O(log n) O(n) # 5 Successor O(log n) O(n) # 6 Insert O(log n) O(n) # 7 Delete O(log n) O(n) # Traversing # Use Inorder Traversal when dealing with a binary tree because it allows us to print the values in order """ B / \ A C """ # Inorder # left, then root, then right # A, B, C # Preorder # root, then left, then right # Postorder # left, then right, then root # Level Order # root level, child level, and so on from collections import deque class Node: def __init__(self, value=None, left=None, right=None): self.value = value self.left = left self.right = right self.size = 0 def disconnect(self): self.left = None self.right = None self.parent = None def __lt__(self, other): return self.value < other.value def __gt__(self, other): return self.value > other.value def __eq__(self, other): return self.value == other.value # def compare_to(self, other): # if self < other: return -1 # elif self > other: return 1 # else: return 0 def __repr__(self): return "<Node value = %s, left = %s, right = %s > " % (self.value, self.left, self.right) class BST: def __init__(self, root=None): self.root = root def get_root(self): return self.root def set_root(self, value): self.root = Node(value) def insert(self, value): def _insert(node, value): if node is None: return Node(value) elif value == node.value: return None elif value < node.value: node.left = _insert(node.left, value) node.parent = self.root elif value > node.value: node.right = _insert(node.right, value) node.parent = self.root return node self.root = _insert(self.root, value) return self.root is not None def contains(self, value): def _contains(node, value): return ( False if node is None else _contains(node.left, value) if value < node.value else _contains(node.right, value) if value > node.value else True ) return _contains(self.root, value) def rank(self, value): if value is None: return "argument to rank() is None" return self._rank(value, self.root) def _rank(self, value, node): if node is None: return 0 # -1 if node.value > value. 1 if node.value < value. 0 if equal. _cmp = self._compare_to(node.value, value) if _cmp < 0: return self._rank(value, node.left) elif _cmp > 0: return 1 + self._size(node.left) + self._rank(value, node.right) else: return self._size(node.left) def search(self, value): def _search(node, value): return ( "None such node" if node is None else _search(node.left, value) if value < node.value else _search(node.right, value) if value > node.value else node.value ) return _search(self.root, value) def minimum(self): return self._minimum(self.root).value def _minimum(self, node): if node.left is None: return node return self._minimum(node.left) # alternative iterative approach: # current = node # if current is None: return -1 # while current.left is not None: # current = current.left # return current def maximum(self): return self._maximum(self.root).value def _maximum(self, node): if node.right is None: return node return self._maximum(node.right) def predecessor(self, value): """ Returns the largest key in the BST less than or equal to value ie "floor." If the left subtree of node x is non-empty, then the successor of x is just the rightmost node in x‘s left subtree. If the left subtree of node x is empty and x has a successor y, then y is the lowest ancestor of x whose right child is also an ancestor of x. """ def _predecessor(node, value): if node.left is not None: return self._maximum(node.left) y = node.parent while y is not None and node == y.left: node = y y = y.parent return y return _predecessor(self.root, value) def successor(self, value): """ Returns the smallest key in the BST greater than or equal to value ie "ceiling." If the right subtree of node x is non-empty, then the successor of x is just the leftmost node in x‘s right subtree. If the right subtree of node x is empty and x has a successor y, then y is the lowest ancestor of x whose left child is also an ancestor of x. """ def _successor(node, value): if node.right is not None: return self._minimum(node.right) y = node.parent while y is not None and node == y.right: node = y y = y.parent return y return _successor(self.root, value) def _compare_to(self, node_value, value): _cmp = None if node_value < value: _cmp = 1 elif node_value > value: _cmp = -1 else: _cmp = 0 return _cmp def delete(self, value): if value is None: return "calls delete() with a null key" self.root = self._delete(self.root, value) def _delete(self, node, value): if node is None: return None _cmp = self._compare_to(node.value, value) if _cmp < 0: node.left = self._delete(node.left, value) elif _cmp > 0: node.right = self._delete(node.right, value) else: if node.right is None: return node.left if node.left is None: return node.right t = node node = self._minimum(t.right) node.right = self._delete_min(t.right) node.left = t.left return node def delete_min(self): if self.is_empty(): return "BST underflow" self.root = self._delete_min(self.root) def _delete_min(self, node): if node.left is None: return node.right node.left = self._delete_min(node.left) # node.size = self._size(node.left) + self._size(node.right) + 1 return node def delete_max(self): if self.is_empty(): return "BST underflow" self.root = self._delete_max(self.root) def _delete_max(self, node): if node.right is None: return node.left node.right = self._delete_max(node.right) # node.size = self._size(node.left) + self._size(node.right) + 1 return node def is_empty(self): return self.size() == 0 def size(self): return self._size(self.root) def _size(self, node): if node is None: return 0 return 1 + self._size(node.left) + self._size(node.right) def height(self): return self._height(self.root) def _height(self, node): if node is None: return -1 return 1 + max(self._height(node.left), self._height(node.right)) def min_depth(self): return self._min_depth(self.root) def _min_depth(self, node): if node is None: return -1 if node.left is None and node.right is None: return 1 if node.left is None: return self._min_depth(node.right) + 1 if node.right is None: return self._min_depth(node.left) + 1 return min(self._min_depth(node.left), self._min_depth(node.right)) + 1 def find_depth_of_node(self, value): return self._find_depth_of_node(self.root, value) def _find_depth_of_node(self, node, value): if not node: raise ValueError('Tree must contain a root value.') if node.value == value: return 0 return 1 + min(self._find_depth_of_node(node.left, value), self._find_depth_of_node(node.right, value)) def is_bst(self): def _is_bst(root, min_value, max_value): if root is None: return True if min_value < root.value < max_value \ and _is_bst(root.left, min_value, root.value) \ and _is_bst(root.right, root.value, max_value): return True else: return False return _is_bst(self.root, float('-inf'), float('inf')) # def _height(node): # if node is None: return 0 # left_height = _height(node.left) # right_height = _height(node.right) # if left_height == -1 or right_height == -1 or abs(left_height - right_height) > 1: # return -1 # return 1 + max(_height(node.left), _height(node.right)) # return _height(self.root) != -1 # Traversals def inorder(self, node): if node: self.inorder(node.left) print(node.value) self.inorder(node.right) return def preorder(self, node): if node: print(node.value) self.preorder(node.left) self.preorder(node.right) return def postorder(self, node): if node: self.postorder(node.left) self.postorder(node.right) print(node.value) return def level_order(self): """ Print Nodes level by level. """ keys = deque() queue = deque() queue.append(self.root) while queue: x = queue.popleft() if x is None: continue keys.append(x.value) queue.append(x.left) queue.append(x.right) return keys def __str__(self): return '<BST(root = %s)>' % (self.root) def main(): t = BST() # t.set_root(5) t.insert(10) t.insert(5) t.insert(1) t.insert(6) t.insert(14) t.insert(12) t.insert(16) print(t) print('search', t.search(50)) print('size', t.size()) print('contains', t.contains(10)) print('inorder', t.inorder(t.root)) print('pre order', t.preorder(t.root)) print('post orde r', t.postorder(t.root)) print('level order', t.level_order()) print('minimum', t.minimum()) print('maximum', t.maximum()) # print('delete', t.delete(5)) print('predecessor', t.predecessor(10)) print('successor', t.successor(10)) print('height', t.height()) print('is_BST()', t.is_bst()) # print('delete_min', t.delete_min()) # print('delete_max', t.delete_max()) print('size', t.size()) print('rank', t.rank(8)) print(t) main()
""" red_black_bst.py A symbol table implemented using a left-leaning red-black BST. Invariants: 1. No node has two red links connected to it. 2. Every path from root to null/None link has the same number of BLACK links 3. RED links lean left. The put, get, contains, remove, minimum, maximum operations each take Θ(log n) time in the worst case, where n is the number of key-value pairs in the symbol table. The size, and is-empty operations take Θ(1) time. The keys methods take O(log n + m) time, where m is the number of keys returned by the iterator. Construction takes Θ(1) time. This is the 2-3 version. """ class RedBlackBST: RED: bool = True BLACK: bool = False class Node: def __init__(self, key, val, size, color=None, left=None, right=None): self._key = key self._val = val self._color = color self._size = size self._left = left self._right = right def __lt__(self, other): return self._key < other.key def __gt__(self, other): return self._key > other.key def __eq__(self, other): return self._key == other.key def __repr__(self): return f'<Node(key={self._key}, ' \ f'val={self._val}, ' \ f'size={self._size}, ' \ f'color={self._color}, ' \ f'left={self._left}, ' \ f'right={self._right})>' def __init__(self): self.TNULL = RedBlackBST.Node('', 0, 1, False) self.root = self.TNULL def __is_red(self, x: Node): if x is None: return False return x._color == self.RED def __size(self, x: Node): if x is None: return 0 return x._size def size(self): return self.__size(self.root) def is_empty(self): return self.root is None def get(self, key): if key is None: raise ValueError('argument to get() is None') return self.__get(self.root, key) def __get(self, x, key): while x is not None: if key < x.key: x = x.left elif key > x.key: x = x.right else: return x.val return None def put(self, key, val): if key is None: raise ValueError('first argument to put() is None') if val is None: self.delete(key) return self.root = self.__put(self.root, key, val) self.root._color = self.BLACK # assert self.check() def __put(self, h, key, val): if h is None: return RedBlackBST.Node(key, val, 1, self.RED) if key < h.key: h.left = self.__put(h.left, key, val) elif key > h.key: h.right = self.__put(h.right, key, val) else: h.val = val if self.__is_red(h.right) and not self.__is_red(h.left): h = self.rotate_left(h) if self.__is_red(h.left) and self.__is_red(h.left._left): h = self.rotate_right(h) if self.__is_red(h.left) and self.__is_red(h.right): # print(f'h {h}') self.flip_colors(h) h.size = self.__size(h.left) + self.__size(h.right) + 1 return h def contains(self, key): return self.get(key) is not None def delete__min(self): if self.is_empty(): raise ValueError('BST underflow') if not self.__is_red(self.root.left) and not self.__is_red(self.root.right): self.root.color = self.RED self.root = self.__delete_min(self.root) if not self.is_empty(): self.root.color = self.BLACK def __delete_min(self, h): if h.left is None: return None if not self.__is_red(h.left) and not self.__is_red(h.left.left): h = self.__move_red_left(h) h.left = self.__delete_min(h.left) return self.__balance(h) def delete_max(self): if self.is_empty(): raise ValueError('BST underflow') # if both children of root are black, set root to red if not self.__is_red(self.root.left) and not self.__is_red(self.root.right): self.root.color = self.RED self.root = self.__delete_max(self.root) if not self.is_empty(): self.root.color = self.BLACK def __delete_max(self, h): if self.__is_red(h.left): h = self.rotate_right(h) if h.right is None: return None if not self.__is_red(h.left) and not self.__is_red(h.right.left): h = self.__move_red_right(h) h.right = self.__delete_max(h.right) return self.__balance(h) def delete(self, key): if key is None: raise ValueError('argument to delete() is None') if not self.contains(key): return # if both children of root are black, set root to red if not self.__is_red(self.root.left) and not self.__is_red(self.root.right): self.root.color = self.RED self.root = self.__delete(self.root, key) if not self.is_empty(): self.root.color = self.BLACK def __delete(self, h, key): if key < h.key: if not self.__is_red(h.left) and not self.__is_red(h.left.left): h = self.__move_red_left(h) h.left = self.__delete(h.left, key) else: if self.__is_red(h.left): h = self.rotate_right(h) if key == h.key and h.right is None: return None if not self.__is_red(h.right) and not self.__is_red(h.right.left): h = self.__move_red_right(h) if key == h.key: x = self.__min(h.right) h.key = x.key h.val = x.val h.right = self.__delete_min(h.right) else: h.right = self.__delete(h.right, key) return self.__balance(h) def rotate_right(self, h): x = h.left h.left = x.right x.right = h x.color = x.right.color x.right.color = self.RED x.size = h.size h.size = self.__size(h.left) + self.__size(h.right) + 1 return x def rotate_left(self, h): x = h.right h.right = x.left x.left = h x.color = x.left.color x.left.color = self.RED x.size = h.size h.size = self.__size(h.left) + self.__size(h.right) + 1 return x def flip_colors(self, h): h.color = not h.color h.left.color = not h.left.color h.right.color = not h.right.color def __move_red_left(self, h): self.flip_colors(h) if self.__is_red(h.right.left): h.right = self.rotate_right(h.right) h = self.rotate_left(h) self.flip_colors(h) return h def __move_red_right(self, h): self.flip_colors(h) if self.__is_red(h.left.left): h = self.rotate_right(h) self.flip_colors(h) return h def __balance(self, h): if self.__is_red(h.right): h = self.rotate_left(h) if self.__is_red(h.left) and self.__is_red(h.left.left): h = self.rotate_right(h) if self.__is_red(h.left) and self.__is_red(h.right): self.flip_colors(h) h.size = self.__size(h.left) + self.__size(h.right) + 1 return h def height(self): return self.__height(self.root) def __height(self, x): if x is None: return -1 return 1 + max(self.__height(x.left), self.__height(x.right)) def min(self): if self.is_empty(): raise ValueError('calls min() with empty symbol table') return self.__min(self.root).key def __min(self, x): if x.left is None: return x else: return self.__min(x.left) def max(self): if self.is_empty(): raise ValueError('calls max() with empty symbol table') return self.__max(self.root).key def __max(self, x): if x.right is None: return x else: return self.__max(x.right) def floor(self, key): """ Returns the largest key in the symbol table less than or equal to key i.e. Predecessor """ if key is None: raise ValueError('argument to floor() is None') if self.is_empty(): raise ValueError('calls floor() with empty symbol table') x = self.__floor(self.root, key) if x is None: raise ValueError('argument to floor() is too small') else: return x.key def __floor(self, x, key): if x is None: return None if key == x.key: return x if key < x.key: self.__floor(x.left, key) t = self.__floor(x.right, key) if t is not None: return t else: return x def ceiling(self, key): """ Returns the smallest key in the symbol table greater than or equal to key i.e. Successor """ if key is None: raise ValueError('argument to ceiling() is None') if self.is_empty(): raise ValueError('calls ceiling() with empty symbol table') x = self.__ceiling(self.root, key) if x is None: raise ValueError('argument to ceiling() is too small') else: return x.key def __ceiling(self, x, key): if x is None: return None if key == x.key: return x if key > x.key: self.__ceiling(x.right, key) t = self.__ceiling(x.left, key) if t is not None: return t else: return x def select(self, rank): if rank < 0 or rank >= self.size(): raise ValueError(f'argument to select() is invalid {rank}') return self.__select(self.root, rank) def __select(self, x, rank): if x is None: return None left_size = self.__size(x.left) if left_size > rank: return self.__select(x.left, rank) elif left_size < rank: return self.__select(x.right, rank - left_size - 1) else: return x.key def rank(self, key): if key is None: raise ValueError('argument to rank() is None') return self.__rank(key, self.root) def __rank(self, key, x): if x is None: return 0 if key < x.key: return self.__rank(key, x.left) elif key > x.key: return 1 + self.__size(x.left) + self.__rank(key, x.right) else: return self.__size(x.left) def check(self): if not self.is_bst(): print('Not in symmetric order') if not self.is23(): print('Not a 2-3 tree') if not self.is_balanced(): print('Not balanced') def is_bst(self): return self.__is_bst(self.root, None, None) def __is_bst(self, x, __min, __max): if x is None: return True if __min is not None and x.key <= __min: return False if __max is not None and x.key >= __max: return False return self.__is_bst(x.left, __min, x.key) and self.__is_bst(x.right, x.key, __max) def is_balanced(self): black = 0 x = self.root while x is not None: if not self.__is_red(x): black += 1 x = x.left return self.__is_balanced(self.root, black) def __is_balanced(self, x, black): if x is None: return black == 0 if not self.__is_red(x): black -= 1 return self.__is_balanced(x.left, black) and self.__is_balanced(x.right, black) def is23(self): return self.__is23(self.root) def __is23(self, x): """ Does the tree have no red right links, and at most one (left) red links in a row on any path? """ if x is None: return True if self.__is_red(x.right): return False if x != self.root and self.__is_red(x) and self.__is_red(x.left): return False return self.__is23(x.left) and self.__is23(x.right) def __repr__(self): return f'<RedBlackBST(root={self.root})>' def main(): inp = 'SEARCHEXAMPLE' st = RedBlackBST() for i in range(len(inp)): st.put(inp[i], i) print(st) if __name__ == '__main__': main()
""" dijkstra_all_pairs_sp.py Dijkstra's algorithm run from each vertex. * Takes time proportional to E V log V and space proportional to EV. The DijkstraAllPairsSP class represents a data type for solving the * all-pairs shortest paths problem in edge-weighted digraphs * where the edge weights are non-negative. * * This implementation runs Dijkstra's algorithm from each vertex. * The constructor takes Theta(V (E log V)) time * in the worst case, where V is the number of vertices and * E is the number of edges. * Each instance method takes Theta(1) time. * It uses Theta(V2) extra space (not including the * edge-weighted digraph). """ import math from graphs.directed_edge import DirectedEdge from graphs.edge_weighted_digraph import EdgeWeightedDigraph from graphs.dijkstra_sp import DijkstraSP class DijkstraAllPairsSP: _all = list() def __init__(self, g): self._all = [DijkstraSP(g, v) for v in range(g.get_V())] def path(self, s, t): self.__validate_vertex(s) self.__validate_vertex(t) return self._all[s].path_to(t) def has_path(self, s, t): self.__validate_vertex(s) self.__validate_vertex(t) return self.dist(s, t) < math.inf def dist(self, s, t): self.__validate_vertex(s) self.__validate_vertex(t) return self._all[s].dist_to(t) def __validate_vertex(self, v): n = len(self._all) if v < 0 or v >= n: raise AttributeError(f'vertex {v} is not between 0 and {n - 1}') def __repr__(self): return f'<{self.__class__.__name__}(\n' \ f'_all={self._all}\n)>' def main(): with open("../resources/tinyEWD.txt", ) as f: values = "".join(f.readlines()).splitlines() V, E = int(values[0]), int(values[1]) g = EdgeWeightedDigraph(V) for line in values[2:]: vertices = line.split(' ') v, w, weight = int(vertices[0]), int(vertices[1]), float(vertices[2]) e = DirectedEdge(v, w, weight) g.add_edge(e) dijkstra = DijkstraAllPairsSP(g) print(dijkstra) if __name__ == '__main__': main()
""" three_sum.py * A program with cubic running time. Reads n integers * and counts the number of triples that sum to exactly 0 * (ignoring integer overflow). * The ThreeSum class provides static methods for counting * and printing the number of triples in an array of integers that sum to 0 * (ignoring integer overflow). * This implementation uses a triply nested loop and takes proportional to n^3, * where n is the number of integers. """ from fundamentals.stopwatch import StopWatch class ThreeSum: @staticmethod def print_all(a): n = len(a) for i in range(n): for j in range(i + 1, n): for k in range(j + 1, n): if a[i] + a[j] + a[k] == 0: print(f'{a[i]} {a[j]} {a[k]}') @staticmethod def count(a): n = len(a) count = 0 for i in range(n): for j in range(i + 1, n): for k in range(j + 1, n): if a[i] + a[j] + a[k] == 0: count += 1 return count def main(): with open('../resources/1Kints.txt') as f: a = list(map(int, f.read().replace(' ', '').splitlines())) timer = StopWatch() count = ThreeSum.count(a) print(f'elapsed time = {timer.elapsed_time()}') print(count) if __name__ == '__main__': main()
""" average.py $ python fundamentals/average.py 10.0 5.0 6.0 """ import sys class Average: @staticmethod def main(*args): count, _sum = 0, 0.0 a = list(*args) while count < len(a): value = float(a[count]) _sum += value count += 1 average = _sum / count print(f'average is {average}') if __name__ == '__main__': Average.main(sys.argv[1:])
def solution(heights): answer = [] stack = [] for idx, val in enumerate(heights): if idx == 0: #print(0,end=' ') answer.append(0) stack.append((idx+1,val)) else: while 1: try: if stack[-1][1] > val: #print(stack[-1][0],end=' ') answer.append(stack[-1][0]) stack.append((idx+1,val)) break else: stack.pop() except: #print(0,end=' ') answer.append(0) stack.append((idx+1,val)) break return answer
def check(x) : if x in ['*', '/']: return 3 elif x in ['+', '-']: return 2 elif x in ["(", ")"]: return 1 return 0 s = input() answer = '' stack = [] for cha in s: pri = check(cha) if cha in ['+', '-', '*', '/']: #스택의 top보다 비교 대상 연산자의 연산자가 낮거나 같을 경우 = pop while stack and check(stack[-1]) >= pri: answer += stack.pop() stack.append(cha) elif cha == '(': stack.append(cha) elif cha == ')': while stack and stack[-1] != "(" : answer += stack.pop() stack.pop() else: answer += cha #마지막 스택에 남은 원소를 모두 결과에 삽입 while stack : answer += stack.pop() print(answer)
import random def create(matrix): i = 0 while i < 3 : print(3*(" ---")) print("|",end = '') if matrix[i][0] == 1 : print(" X ",end = '') elif matrix[i][0] == 2 : print(" O ",end = '') else : print(" ",end = '') print("|",end = '') if matrix[i][1] == 1 : print(" X ",end = '') elif matrix[i][1] == 2 : print(" O ",end = '') else : print(" ",end = '') print("|",end = '') if matrix[i][2] == 1 : print(" X ",end = '') elif matrix[i][2] == 2 : print(" O ",end = '') else : print(" ",end = '') print("|") i += 1 print(3*(" ---")) return def place(board,player,position): integer_position = position.strip().split(',') i = 0 j = 0 while i < 3 : if int(integer_position[0])-1 == i : while j < 3 : if int(integer_position[1])-1 == j : if board[i][j] == 0 : board[i][j] = player return True j += 1 i += 1 print("you can't put your piece here") return False def winner(matrix) : player1 = 1 player2 = 2 ''' checking the diagonals ''' if matrix[0][0] == matrix[1][1] == matrix[2][2] == player1 : return True elif matrix[0][0] == matrix[1][1] == matrix[2][2] == player2 : return True elif matrix[0][2] == matrix[1][1] == matrix[2][0] == player1 : return True elif matrix[0][2] == matrix[1][1] == matrix[2][0] == player2 : return True ''' checking the horizontal ''' i = 0 while i < 3 : if (matrix[i][0] == matrix[i][1] == matrix[i][2] == player1): return True elif (matrix[i][0] == matrix[i][1] == matrix[i][2] == player2) : return True i += 1 ''' checking the vertical ''' j = 0 while j < 3 : if (matrix[0][j] == matrix[1][j] == matrix[2][j] == player1) : return True elif (matrix[0][j] == matrix[1][j] == matrix[2][j] == player2) : return True j += 1 return False def isFull(board): for x in range(3) : for y in range(3) : if board[x][y] == 0 : return False return True def play(name1, name2): player1 = 1 player2 = 2 board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] while True : create(board) if isFull(board) == False : p1 = input(name1 + " :") while place(board,player1,p1) == False : p1 = input(name1 + " :") if winner(board) == False : create(board) if isFull(board) == False : p2 = input(name2 + " :") while place(board, player2, p2) == False : p2 = input(name2 + " :") if winner(board) == True : create(board) return 2 else : return 0 else : create(board) return 1 else : return 0 def machine(board): ''' winning diagonal''' if board[0][0] == board[1][1] == 2 : if board[2][2] == 0 : board[2][2] = 2 return if board[0][2] == board[1][1] == 2 : if board[2][0] == 0 : board[2][0] = 2 return if board[2][0] == board[1][1] == 2 : if board[0][2] == 0 : board[0][2] = 2 return if board[2][2] == board[1][1] == 2 : if board[0][0] == 0 : board[0][0] = 2 return ''' winning smart diagonal ''' if board[0][0] == board[2][2] == 2 or (board[0][2] == board[2][0] == 2) : if board[1][1] == 0 : board[1][1] = 2 return ''' winning horizontal''' for i in range(3) : for j in range(2) : if board[i][j] == board[i][j+1] == 2 : if j == 0 : if board[i][2] == 0 : board[i][2] = 2 return elif j == 1 : if board[i][0] == 0 : board[i][0] = 2 return ''' winning vertical ''' for c in range(3) : for r in range(2) : if board[r][c] == board[r+1][c] == 2 : if r == 0 : if board[2][c] == 0 : board[2][c] = 2 return elif r == 1 : if board[0][c] == 0 : board[0][c] = 2 return ''' winning smart horizontal ''' for m in range(3) : if board[m][0] == board[m][2] == 2 : if board[m][1] == 0 : board[m][1] = 2 return ''' winning smart vertical ''' for n in range(3) : if board[0][n] == board[2][n] == 2 : if board[1][n] == 0 : board[1][n] = 2 return ''' defensive ''' ''' dangerzone diagonal''' if board[0][0] == board[1][1] == 1 : if board[2][2] == 0 : board[2][2] = 2 return if board[0][2] == board[1][1] == 1 : if board[2][0] == 0 : board[2][0] = 2 return if board[2][0] == board[1][1] == 1 : if board[0][2] == 0 : board[0][2] = 2 return if board[2][2] == board[1][1] == 1 : if board[0][0] == 0 : board[0][0] = 2 return ''' smart diagonal ''' if board[0][0] == board[2][2] == 1 or (board[0][2] == board[2][0] == 1) : if board[1][1] == 0 : board[1][1] = 2 return ''' dangerzone horizontal''' for i in range(3) : for j in range(2) : if board[i][j] == board[i][j+1] == 1 : if j == 0 : if board[i][2] == 0 : board[i][2] = 2 return elif j == 1 : if board[i][0] == 0 : board[i][0] = 2 return ''' dangerzone vertical ''' for c in range(3) : for r in range(2) : if board[r][c] == board[r+1][c] == 1 : if r == 0 : if board[2][c] == 0 : board[2][c] = 2 return elif r == 1 : if board[0][c] == 0 : board[0][c] = 2 return ''' smart horizontal ''' for m in range(3) : if board[m][0] == board[m][2] == 1 : if board[m][1] == 0 : board[m][1] = 2 return ''' smart vertical ''' for n in range(3) : if board[0][n] == board[2][n] == 1 : if board[1][n] == 0 : board[1][n] = 2 return ''' out of the dangerzone and no wining capability''' while True : row = random.randint(0,2) col = random.randint(0,2) if board[row][col] == 0 : board[row][col] = 2 return def playAI(name): player1 = 1 board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] while True : create(board) if isFull(board) == False : p1 = input(name + " :") while place(board,player1,p1) == False : p1 = input(name + " :") if winner(board) == False : create(board) if isFull(board) == False : print("AI plays ...") machine(board) if winner(board) == True : create(board) return 2 else : return 0 else : create(board) return 1 else : return 0 if __name__ == "__main__" : print("This is an XO game for 2 player") print("each player should make his move by stating the position") print("of each piece he/she wants to play , example : 1,1") print("the first 1 means the first row and the second 1 means the first column") print("OK ?? ") print("let's Start") choice = int(input("choose 1 to play against the computer and 2 to play against a player : ")) if choice == 1 : name = input("what is your name ? ") c1 = 0 c2 = 0 while True : AIRound = playAI(name) if AIRound == 1 : print(name + " wins ") c1 += 1 elif AIRound == 2 : print("AI wins ") c2 += 1 else : print("Draw") print("\n\n\n" +name + " : " + str(c1) + " " + "AI" + " : " + str(c2) + "\n\n\n") answer = input("Game ended , wanna go again ? (yes/no)") if answer == "no" : print("Thank you for trying the game , Bye !!!") break else : print("Btw , player 1 is X and player 2 is O") name1 = input("Player 1 , pleasse enter your name :") name2 = input("Player 2 , pleasse enter your name :") counter1 = 0 counter2 = 0 while True : a_round = play(name1,name2) if a_round == 1 : print(name1 + " wins ") counter1 += 1 elif a_round == 2 : print(name2 + " wins ") counter2 += 1 else : print("Draw") print("\n\n\n" +name1 + " : " + str(counter1) + " " + name2 + " : " + str(counter2) + "\n\n\n") answer = input("Game ended , wanna go again ? (yes/no)") if answer == "no" : print("Thank you for trying the game , Bye !!!") break
import re def ignore_articles(string): """ Takes a string and returns it with initial articles excluded. Useful for alphabetical sorting. """ str_low = string.lower() if str_low.startswith("the "): return string[4:] elif str_low.startswith("an "): return string[3:] elif str_low.startswith("a "): return string[2:] else: return string def dumb_to_smart_quotes(string): """ Takes a string and returns it with dumb quotes, single and double, replaced with smart quotes. """ # Find dumb double quotes coming directly after letters or punctuation, # and replace them with right double quotes. string = re.sub(r'([a-zA-Z0-9.,?!;:\'\"])"', r'\1&#8221;', string) # Find any remaining dumb double quotes and replace them with # left double quotes. string = string.replace('"', '&#8220;') # Reverse: Find any SMART quotes that have been (mistakenly) placed around HTML # attributes (following =) and replace them with dumb quotes. string = re.sub(r'=&#8220;(.*?)&#8221;', r'="\1"', string) # Follow the same process with dumb/smart single quotes string = re.sub(r"([a-zA-Z0-9.,?!;:\"\'])'", r'\1&#8217;', string) string = string.replace("'", '&#8216;') string = re.sub(r'=&#8216;(.*?)&#8217;', r"='\1'", string) return string def roman_year(year): if year == 2012: return 'MMXII' elif year == 2013: return 'MMXIII'
import time start_time = time.time() f = open('names_1.txt', 'r') names_1 = f.read().split("\n") # List containing 10000 names f.close() f = open('names_2.txt', 'r') names_2 = f.read().split("\n") # List containing 10000 names f.close() duplicates = [] # for name_1 in names_1: # for name_2 in names_2: # if name_1 == name_2: # duplicates.append(name_1) # implementing solution with linked list class Node: def __init__(self, value, next=None): self.value = value self.next = next def get_next(self): return self.next def set_next(self, node): self.next = node class LinkedList: def __init__(self, head = None, tail = None): self.head = head self.tail = tail def add_to_tail(self, value): new_tail = Node(value) if self.head is None: self.head = new_tail if self.tail: self.tail.set_next(new_tail) self.tail = new_tail def remove_dupes(name_list): start_node = name_list.head # TEST CODE TO PRINT EVERY VALUE IN LINKED LIST # while start_node.next: # print(start_node.value) # start_node = start_node.next # TEST CODE ENDS HERE start_next = start_node.next name_store = set([start_node.value]) while start_next: value = start_next.value if value in name_store: start_node.next = start_next.next start_next = start_next.next else: name_store.add(value) start_node = start_next start_next = start_next.next def printDupes(name_list): start_node = name_list.head # TEST CODE TO PRINT EVERY VALUE IN LINKED LIST # while start_node.next: # print(start_node.value) # start_node = start_node.next # TEST CODE ENDS HERE start_next = start_node.next name_store = set([start_node.value]) while start_next: value = start_next.value if value in name_store: duplicates.append(value) start_next = start_next.next else: name_store.add(value) start_next = start_next.next name_list1 = LinkedList(None, None) name_list2 = LinkedList(None, None) for name_1 in names_1: name_list1.add_to_tail(name_1) for name_2 in names_2: name_list2.add_to_tail(name_2) remove_dupes(name_list1) remove_dupes(name_list2) names1_without_dupes = [] names2_without_dupes = [] starting_node1 = name_list1.head while starting_node1: names1_without_dupes.append(starting_node1.value) starting_node1 = starting_node1.next starting_node2 = name_list2.head while starting_node2: names2_without_dupes.append(starting_node2.value) starting_node2 = starting_node2.next combined_list = LinkedList(None, None) for name_1 in names1_without_dupes: combined_list.add_to_tail(name_1) for name_2 in names2_without_dupes: combined_list.add_to_tail(name_2) printDupes(combined_list) end_time = time.time() print (f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n") print (f"runtime: {end_time - start_time} seconds")
""" This codes purpose is to give me the latest story listing from a specific website. Website not mentioned for reasons. """ import requests from bs4 import BeautifulSoup # get input from user url = input("Enter the URL: ") finalUrl = "" # check if user input www if "www." in url: # replace www with http:// finalUrl = url.replace("www.", "http://") else: finalUrl = "https://" + url print("url : " + finalUrl) # get web page html content r = requests.get(finalUrl) # grab all the text and parse to html soup = BeautifulSoup(r.text, 'html.parser') formatted_link = [] for link in soup.find_all('h2', class_='post-block__title'): # get the name of the a attribute with whitespaces stripped name = [text for text in link.stripped_strings] print("TITLE : " + name[0]) print("URL : " + link.a['href']) """ data = { 'title': name[0], 'URL': link.a['href'] } print(data) #formatted_link.append(data) """ #print(formatted_link)
def transHeight(x): if x == '5 feet 10 inch' or x == '5′ 10″' or x == "5'10''" or x == '5\'10"': return 1.778 elif x == '5\'3"' or x == "5'3''" or x == '5.3': return 1.6002 elif x == "5'8''" or x == "5'8" or x == '5.8' or x == '5\'8"' or x == '5 feet 8 inch' or x == '172.72 cm': return 1.7272 elif x == '5.6' or x == '5.6 feet' or x == '5\'6"' or x == "5'6''": return 1.6764 elif x == '6 feet' or x == '6.0"': return 1.8288 elif x == '5.5' or x == "5''5'" or x == '5\'5"' or x == "5'5''" or x == '5 feet 5 inch': return 1.651 elif x == '5\' 9"' or x == "5''9'" or x == "5' 9''" or x == '5.9' or x == '5feet 9 inch': return 1.7526 elif x == '5.11' or x == '5 feet 11 inch': return 1.8034 elif x == '5 feet 10.5 inch': return 1.7907 elif x == '5.2' or x == "5'2''" or x == '5\'2"': return 1.5748 elif x == '5.75': return 1.7145 elif x == '5.7' or x == '5 feet 7 inch' or x == '170.18 cm': return 1.7018 elif x == '5\'4"' or x == '5.4' or x == '5 feet 4 inch' or x == "5'4''": return 1.6256 elif x == "5'1" or x == '5.1': return 1.5494 elif x == '161.544': return 1.61544 elif x == '4.1': return 1.2446 elif x == '6 feet 1 inch' or x == "6'1''": return 1.8542 elif x == "4'11''": return 1.4986 def transBMI(x): if x < 18.5: return 2 elif x >= 18.5 and x < 25: return 1 elif x >= 25 and x < 30: return 2 elif x >= 30: return 3 def transDiabetic(x): if x == 0: return 1 elif x == 1: return 2 elif x == 2 or x == 3: return 3 elif x == 4 or x == 5: return 4 def transNegetive(x): if x == 1: return 3 elif x == 2: return 2 elif x == 3: return 1 import numpy as np import matplotlib.pyplot as plt import pandas as pd data_xls = pd.read_excel('Extended_version_2.csv.xlsx',index_col=None) data_xls.to_csv('EXTENDED_2.csv',encoding='utf-8',index=False) data_xls = pd.read_excel('Extended_version_3.csv.xlsx',index_col=None) data_xls.to_csv('EXTENDED_3.csv',encoding='utf-8',index=False) dataframe1 = pd.read_csv("DATASET_1.csv") dataframe2 = pd.read_csv("DATASET_2.csv") dataframe3 = pd.read_csv("DATASET_3.csv") dataframe4 = pd.read_csv("DATASET_4.csv") dataframe5 = pd.read_csv("DATASET_5.csv") dataframe6 = pd.read_csv("DATASET_6.csv") dataframe1.columns = ['ID', 'Current Place', 'Latitude', 'Longitude', 'Place of interest', 'Latitude.1', 'Longitude.1', 'Food you like most', 'Leisure time activity','Future plan', 'Typically your days are started at'] dataframe2.columns = ['ID', 'Current Place', 'Latitude', 'Longitude', 'Place of interest', 'Latitude.1', 'Longitude.1', 'Food you like most', 'Leisure time activity','Future plan', 'Typically your days are started at'] dataframe3.columns = ['ID', 'Current Place', 'Latitude', 'Longitude', 'Place of interest', 'Latitude.1', 'Longitude.1', 'Food you like most', 'Leisure time activity','Future plan', 'Typically your days are started at'] dataframe4.columns = ['ID', 'Current Place', 'Latitude', 'Longitude', 'Place of interest', 'Latitude.1', 'Longitude.1', 'Food you like most', 'Leisure time activity','Future plan', 'Typically your days are started at'] dataframe5.columns = ['ID', 'Current Place', 'Latitude', 'Longitude', 'Place of interest', 'Latitude.1', 'Longitude.1', 'Food you like most', 'Leisure time activity','Future plan', 'Typically your days are started at'] dataframe6.columns = ['ID', 'Current Place', 'Latitude', 'Longitude', 'Place of interest', 'Latitude.1', 'Longitude.1', 'Food you like most', 'Leisure time activity','Future plan', 'Typically your days are started at'] dataframe1.drop(0, axis = 0, inplace = True) dataframe2.drop(0, axis = 0, inplace = True) dataframe3.drop(0, axis = 0, inplace = True) dataframe4.drop(0, axis = 0, inplace = True) dataframe5.drop(0, axis = 0, inplace = True) dataframe6.drop(0, axis = 0, inplace = True) dataframe = pd.concat([dataframe1, dataframe2, dataframe3, dataframe4, dataframe5, dataframe6], ignore_index = True, sort = True) dataframe['ID'] = dataframe['ID'].astype(np.int64) dataframeEx1 = pd.read_csv("EXTENDED_1.csv") dataframeEx2 = pd.read_csv("EXTENDED_2.csv") dataframeEx3 = pd.read_csv("EXTENDED_3.csv") dataframeEx1 = dataframeEx1.drop(['Timestamp','Score','Unnamed: 25'],axis=1) dataframeEx2 = dataframeEx2.drop(['Timestamp','Total score'],axis=1) dataframeEx2Temp = pd.DataFrame(dataframeEx2.iloc[:,0:54:3].values) dataframeEx2Temp.columns = ['ID','Trying better than expected','Return more change','Not worrying about public affairs', 'Book lover','Book store in your area','Blood Group','Introvert or Extrovert','Concerned about life', 'Work time per day','Game time per day','Budget for laptop','Guilty for relaxation','Need to win to derive enjoyment', 'Trying more than once','Wait in line(Frustration)','Morning person','Perfectionist'] dataframeEx2 = dataframeEx2Temp dataframeEx3 = dataframeEx3.drop(['Timestamp','Total score'],axis=1) dataframeEx3Temp = pd.DataFrame(dataframeEx3.iloc[:,0:72:3].values) dataframeEx3Temp.columns = ['ID','Breakfast','Tuition','Spent Childhood','Favourite Destination', 'Proper diet','Frequently eat fast food','Exercise','Spend on meal',"Diabetic", "BP","Waist","Depression","Insecurity", "Patiency","Confidence","Helpful","Song","Anger",'iPhone or smartphone', 'Look does not matter','Mobile games','favorite mobile game genre','Study time'] dataframeEx3 = dataframeEx3Temp dataframeEx2['ID'] = dataframeEx2['ID'].astype(np.int64) dataframeEx3['ID'] = dataframeEx3['ID'].astype(np.int64) dataframeMergeTemp = pd.merge(dataframeEx1, dataframeEx2, on = "ID", how = "outer") dataframeMerge = pd.merge(dataframeMergeTemp, dataframeEx3, on = "ID", how = "outer") dataframeMerge.sort_values(by=['ID']) dataset = pd.merge(dataframe, dataframeMerge, on = "ID", how = "outer") dataset = dataset.sort_values(by=['ID']) dataset.to_csv('D:/Codes/Python/Pattern Lab/Fahim Lab Final/Pattern Final/Dataset.csv') column_name_dataset = ['ID','Height','Weight',"Diabetic","BP","Depression", "Insecurity","Patiency","Confidence","Helpful","Song","Anger"] mydataset = dataset[column_name_dataset] mydataset['ID'] = mydataset['ID'].astype('object') mydataset['Weight'] = mydataset['Weight'].astype('object') str_cols = mydataset.select_dtypes(['object']).columns mydataset_test = mydataset[str_cols].replace({'Yes':'3','No':'1','Maybe':'2','Normal':'1','Low':'2','High':'3'}) mydataset_test = mydataset_test.dropna() mydataset_test=mydataset_test.replace(r'ft', 'feet', regex=True) mydataset_test=mydataset_test.replace(r'inches', 'inch', regex=True) mydataset_test=mydataset_test.replace(r'CM', 'cm', regex=True) mydataset_test['Height'].unique() mydataset_test['Height'] = mydataset_test['Height'].apply(transHeight) mydataset_test['BMI'] = mydataset_test['Weight']/(mydataset_test['Height']*mydataset_test['Height']) mydataset_test['BMI'] = mydataset_test['BMI'].apply(transBMI) mydataset_test['Diabetic'] = mydataset_test['Diabetic'].apply(transDiabetic) Diabetic_dataset = mydataset_test[['ID','BMI','Depression','Diabetic','BP']] Diabetic_dataset['ID'] = Diabetic_dataset['ID'].astype(np.int64) Diabetic_dataset['Depression'] = Diabetic_dataset['Depression'].astype(np.int64) Diabetic_dataset['BP'] = Diabetic_dataset['BP'].astype(np.int64) dia_str_cols = Diabetic_dataset.select_dtypes(['object']).columns Diabetic_dataset[dia_str_cols] = Diabetic_dataset[dia_str_cols].astype(np.int64) Diabetic_dataset['Diabetic_Prediction'] = (Diabetic_dataset['BMI']*35 + Diabetic_dataset['Depression']*25 + Diabetic_dataset['Diabetic']*30 + Diabetic_dataset['BP']*10)/325 High_Dia = 0 Low_Dia = 0 Medium_Dia = 0 for i, x in Diabetic_dataset.iterrows(): if Diabetic_dataset.loc[i,'Diabetic_Prediction'] < 0.5: Low_Dia += 1 elif Diabetic_dataset.loc[i,'Diabetic_Prediction'] >= 0.5 and Diabetic_dataset.loc[i,'Diabetic_Prediction'] < 0.62: Medium_Dia += 1 else: High_Dia += 1 labels = 'Low Possibilty', 'Medium Possibilty', 'High Possibility' sizes = [Low_Dia, Medium_Dia, High_Dia] explode = (0, 0, 0.1) fig1, ax1 = plt.subplots() ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',shadow=True, startangle=90) ax1.axis('equal') plt.show() Mental_status_dataset = mydataset_test[['ID',"Depression", "Insecurity","Patiency","Confidence","Helpful","Song","Anger"]] Mental_status_dataset.info() men_str_cols = Mental_status_dataset.select_dtypes(['object']).columns Mental_status_dataset[men_str_cols] = Mental_status_dataset[men_str_cols].astype(np.int64) Mental_status_dataset["Depression"] = Mental_status_dataset["Depression"].apply(transNegetive) Mental_status_dataset["Anger"] = Mental_status_dataset["Anger"].apply(transNegetive) Mental_status_dataset["Patiency"] = Mental_status_dataset["Patiency"].apply(transNegetive) Mental_status_dataset["Insecurity"] = Mental_status_dataset["Insecurity"].apply(transNegetive) Mental_status_dataset['Mental_Status_Prediction'] = ((Mental_status_dataset.iloc[:,1:8]*10).sum(axis = 1, skipna = True))/210 Pos = 0 Avg = 0 Neg = 0 for i, x in Mental_status_dataset.iterrows(): if Mental_status_dataset.loc[i,'Mental_Status_Prediction'] < 0.62: Neg += 1 elif Mental_status_dataset.loc[i,'Mental_Status_Prediction'] >= 0.62 and Mental_status_dataset.loc[i,'Mental_Status_Prediction'] < 0.8: Avg += 1 else: Pos += 1 labels = 'Negetive', 'Average', 'Positive' sizes = [Neg, Avg, Pos] explode = (0.1, 0, 0) fig1, ax1 = plt.subplots() ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',shadow=True, startangle=90) ax1.axis('equal') plt.show() Mental_status_dataset_temp = Mental_status_dataset[['ID','Mental_Status_Prediction']] Diabetic_dataset_temp = Diabetic_dataset[['ID','Diabetic_Prediction']] Final_Dataset = pd.merge(mydataset_test, Diabetic_dataset_temp, on = "ID", how = "outer") Final_Dataset = pd.merge(Final_Dataset, Mental_status_dataset_temp, on = "ID", how = "outer") X = Final_Dataset.iloc[:, [14,13]].values from sklearn.cluster import KMeans wcss = [] for i in range(1,11): kmeans = KMeans(n_clusters = i, init = 'k-means++',max_iter = 300,n_init = 10, random_state =0) kmeans.fit(X) wcss.append(kmeans.inertia_) plt.plot(range(1,11),wcss) plt.title('The Elbow Method') plt.xlabel('Number of clusters') plt.ylabel('WCSS') plt.show() kmeans = KMeans(n_clusters = 6, init = 'k-means++',max_iter = 300,n_init = 10, random_state =0) y_kmeans = kmeans.fit_predict(X) plt.scatter(X[y_kmeans == 0,0], X[y_kmeans == 0,1], s = 100, c = 'red', label = 'Average_Low') plt.scatter(X[y_kmeans == 1,0], X[y_kmeans == 1,1], s = 100, c = 'green', label = 'Positive_Low') plt.scatter(X[y_kmeans == 2,0], X[y_kmeans == 2,1], s = 100, c = 'blue', label = 'Average_High') plt.scatter(X[y_kmeans == 3,0], X[y_kmeans == 3,1], s = 100, c = 'magenta', label = 'Negetive_High') plt.scatter(X[y_kmeans == 4,0], X[y_kmeans == 4,1], s = 100, c = 'yellow', label = 'Average_Medium') plt.scatter(X[y_kmeans == 5,0], X[y_kmeans == 5,1], s = 100, c = 'cyan', label = 'Positive_Med_High') plt.title('Correlation between personality and diabetic risk') plt.ylabel('Diabetic Risk') plt.xlabel('Personality') plt.legend() plt.show() D= Final_Dataset["Depression"].value_counts() D = D['3'] I= Final_Dataset["Insecurity"].value_counts() I = I['3'] P= Final_Dataset["Patiency"].value_counts() P = P['3'] C= Final_Dataset["Confidence"].value_counts() C = C['3'] H= Final_Dataset["Helpful"].value_counts() H = H['3'] A= Final_Dataset["Anger"].value_counts() A = A['3'] objects = ("Depressed","Insecure","Impatient","Confident","Helpful","Infuriated") y_pos = np.arange(len(objects)) performance = [D,I,P,C,H,A] plt.bar(y_pos, performance, align='center', alpha=0.5) plt.xticks(y_pos, objects) plt.ylabel('Number of people') plt.title('Personality') plt.show()
toplam=0 for i in range(3,1000): if(i%3==0): toplam=toplam+i elif(i%5==0): toplam=toplam+i else: continue print(toplam)
import turtle t=turtle.Turtle() for i in range(0,12): t.left(5) t.forward(10) t.left(50) for i in range(0,12): t.left(5) t.forward(10) t.left(135) for i in range(0,14): t.right(5) t.forward(10) t.penup() for i in range(0,5): t.left(3.3) t.backward(10) t.pendown() t.right(71) t.forward(60) t.penup() t.right(90) t.forward(44) t.right(90) t.pendown() t.forward(60)
class Pelicula: def __init__(self,nombre,actor): self.nombre= nombre self.actor=actor class Pila: def __init__(self): self.items=[] def apilar(self,dato): self.items.append(dato) def desapilar(self): return self.items.pop() def pilaVacia(self): return self.items == [] def buscarPelicula(pila,nomPeli): auxPel=Pelicula("","") while not pila.pilaVacia(): auxPel=pila.desapilar() if (auxPel.nombre==nomPeli): print auxPel.nombre def buscarActor(pila,actorPeli): auxPel=Pelicula("","") auxPila=Pila() while not pila.pilaVacia(): auxPel=pila.desapilar() if (auxPel.actor==actorPeli): auxPila.apilar(auxPel) while not auxPila.pilaVacia(): print auxPila.desapilar().nombre pila1=Pila() peli=Pelicula("Troya","Brad Pitt") pila1.apilar(peli) peli=Pelicula("El club de la pelea","Brad Pitt") pila1.apilar(peli) peli=Pelicula("Iron Man","Robert Downey") pila1.apilar(peli)
import random def shuffle(string): temp_list = list(string) random.shuffle(temp_list) return ''.join(temp_list) uppercaseLetter1=chr(random.randint(65,90)) uppercaseLetter2=chr(random.randint(65,90)) lowercaseLetter1=chr(random.randint(65,90)) lowercaseLetter2=chr(random.randint(65,90)) random_digit = (random.randint(0,9)) rndom_digit = (random.randint(0,9)) punctuation = chr(random.randint(33,47)) punctuation2 = chr(random.randint(33,47)) password = str(uppercaseLetter1) + str(uppercaseLetter2) + str(lowercaseLetter1.lower()) + str(lowercaseLetter2.lower())+ str(random_digit) + str(rndom_digit) + str(punctuation) + str(punctuation2) password = shuffle(password) def main(): welcome = input('Would you like a random password? (yes or no)') if welcome == ('yes'): print (password) else: print ('Maybe some other time!') def second(): repeat = input('Would you like the characters from the password to be shuffled? (yes or no)') if repeat == 'yes': print (shuffle(password)) second() else: exit() second() main()
# вводятся какое определенное колво чисел n, и среди них необходимо найти # среднее ариф число # 3 # 4 # 5 # 6 # # 5 n = int(input()) i = 0 arr = [] while i < n: num = int(input()) arr.append(num) i += 1 i = 0 sumi = 0 while i < n: sumi = sumi + arr[i] i += 1 print(sumi/n)
# вам необходимо создать переменную a = 100, присвоить # второй переменной # значение первой, а третьей переменной значение первой # но увеличнной на 90 # и четвертая это сумма второй и третьей переменной a = 100 b = a c = a+90 d = a + a + 90 print(a, b, c, d)
numbers = [ ["футболка", 2], ["шорты", 4], ["кофта", 6], ] i = 0 n = len(numbers) while i < n: arr = numbers[i] j = 0 k = len(arr) print(arr) while j < k: print(arr[j]) j += 1 i += 1 # i j 0 1 # 0 ["футболка", 2], # 1 ["шорты", 4], # 2 ["кофта", 6], # i -> 0,1,2 # j -> 0,1
def printData(arr123213): for i in arr123213: marks = i["marks"] avg = 0 for j in marks: avg = avg + j print(i["name"], avg / len(marks)) user1 = { "name": "user1", "marks": [1, 2, 3, 4, 5] } user2 = { "name": "user2", "marks": [4, 2, 3, 3, 5] } user3 = { "name": "user3", "marks": [4, 2, 3, 3, 5] } students = [user1, user2] students2 = [user1, user3] printData(students) printData(students2)
i = 0 n = 5 while i < n: print("External loop") j = 0 k = 9 while j < k: print("Inner loop") j += 1 i += 1
# 10 30 # 10 + 13 + 16 + 19 + 21 + 24.... # 10 11 12 13 a = int(input()) b = int(input()) sumi = 0 while a <= b: sumi = sumi + a a += 3 # sumi=10+3 # sumo=13+11+3 print(sumi)
# !=,==,>,<,<=,>= # c = 10 % 3 # # 13 % 3 = 1 # # 13 - 12 = 1 a = int(input("введите первое число")) b = int(input("введите второе число")) #a/b без остатка if a%b == 0: print("YES") else: print("NO")
# 1) # ВВОД: # # первое число:3 # второе число:4 # третье число:5 # # ВЫВОД: # Максимальное число:5 # Минимальное число:3 a = int(input()) b = int(input()) c = int(input()) maxi = 0 mini = 0 #find maximum if a > b and a > c: maxi = a if b > a and b > c: maxi = b if c > a and c > b: maxi = c #find minimum if a < b and a < c: mini = a if b < a and b < c: mini = b if c < a and c < b: mini = c print(f"Максимальное число {maxi}") print(f"Минимальное число {mini}")
n = int(input()) arr = [] # range(n)->[0..n] # range(1,n) -> [1 # ..n] for i in range(n): num = int(input()) arr.append(num) print(arr) # 5 # 123 # 123 # 12 # 23 # 23