text
stringlengths
37
1.41M
""" Helpful tools for dealing with BRFSS data. BRFSS stands for "Behavioral Risk Factor Surveillance System". """ import itertools import sqlite3 def AllRecords(year=None, filename='brfss.db', tablename='brfss'): """Returns an iterator over the entire BRFSS database. Each item is a dict from field name -> value. This should return instantly. See also RecordsByYear() """ con = sqlite3.connect(filename) con.row_factory = sqlite3.Row if year: return con.execute("select * from %s where year = %s" % (tablename, year)) else: return con.execute("select * from %s" % tablename) def RecordsByYear(filename='brfss.db', tablename='brfss'): """Returns an iterator of (year, iterator of records for year) This takes ~1 minute to return. Use like: for year, rec_it in brfss.RecordsByYear(): for rec in rec_it: pass """ con = sqlite3.connect(filename) con.row_factory = sqlite3.Row return itertools.groupby( con.execute('select * from %s order by year' % tablename), lambda rec: rec['year']) pound_in_kg = 0.45359237 inch_in_meters = 0.0254 bmi_conversion_factor = pound_in_kg / inch_in_meters ** 2 def BMIForRecord(d): """Returns BMI given a BRFSS Record dict or None.""" global bmi_conversion_factor w = d['weight_lbs'] h = d['height_ins'] if not w or not h: return None return bmi_conversion_factor * w / h ** 2
#!/usr/bin/env python # encoding: utf-8 import sys import datetime import random import math class sort(): """A sort class with many different sorting algorithms""" def __init__(self): self.data_unsorted = [] self.data_sorted = [] self.data_size = 0 def read_data(self, name): """read unsorted data from file""" fread = open(name) self.data_unsorted = map(int, fread.read().split()) self.data_size = len(self.data_unsorted) fread.close() def write_data(self, name): """write sorted data to file""" fwrite = open(name, 'w') fwrite.write('\n'.join(map(str, self.data_sorted))) fwrite.close() #def insertion_sort(self, cmp_func): #self.data_sorted = self.data_unsorted[:] #i = 1 #while i < self.data_size: #tmp = self.data_sorted[i] #j = i #while j > 0 and cmp_func(self.data_sorted[j - 1], tmp) > 0: #self.data_sorted[j] = self.data_sorted[j - 1] #j -= 1 #self.data_sorted[j] = tmp #i += 1 def bubble_sort(self, cmp_func): self.data_sorted = self.data_unsorted[:] i = 1 while i < self.data_size: j = i while j > 0: if cmp_func(self.data_sorted[j - 1], self.data_sorted[j]) > 0: self.data_sorted[j - 1], self.data_sorted[j] = \ self.data_sorted[j], self.data_sorted[j - 1] j -= 1 i += 1 def selection_sort(self, cmp_func): self.data_sorted = self.data_unsorted[:] i = 0 while i < self.data_size: tmp_i = i j = i + 1 while j < self.data_size: if cmp_func(self.data_sorted[tmp_i], self.data_sorted[j]) > 0: tmp_i = j j += 1 if i != tmp_i: self.data_sorted[i], self.data_sorted[tmp_i] = \ self.data_sorted[tmp_i], self.data_sorted[i] i += 1 def merge_sort(self, cmp_func): def _merge(a, start, mid, end): tmp = [] i = start j = mid while i < mid and j < end: if cmp_func(a[i], a[j]) < 0: tmp.append(a[i]) i += 1 else: tmp.append(a[j]) j +=1 if i < mid: tmp.extend(a[i:mid]) else: tmp.extend(a[j:end]) a[start:end] = tmp def _merge_sort(a, start, end): if (end - start) <= 1: return mid = (start + end) / 2 _merge_sort(a, start, mid) _merge_sort(a, mid, end) _merge(a, start, mid, end) self.data_sorted = self.data_unsorted[:] _merge_sort(self.data_sorted, 0, self.data_size) def quick_sort(self, cmp_func): def _quick_sort(a, start, end): if (end - start) <= 1: return left = start + 1 right = end - 1 pos = random.randint(start, end - 1) a[start], a[pos] = a[pos], a[start] pos = start while left <= right: if cmp(a[left], a[pos]) <= 0: a[left], a[pos] = a[pos], a[left] pos = left left += 1 else: a[left], a[right] = a[right], a[left] right -= 1 _quick_sort(a, start, pos) _quick_sort(a, pos + 1, end) self.data_sorted = self.data_unsorted[:] _quick_sort(self.data_sorted, 0, self.data_size) def heap_sort(self, cmp_func): def left_child(parent): return 2 * parent + 1 def right_child(parent): return 2 * parent + 2 def heapfy(a, i, size): largest_i = i #left = left_child(i) left = 2 * i + 1 #a bit faster than function call. if left < size: if cmp(a[largest_i], a[left]) < 0: largest_i = left #right = right_child(i) right = 2 * i + 2 if right < size: if cmp(a[largest_i], a[right]) < 0: largest_i = right if largest_i != i: a[i], a[largest_i] = a[largest_i], a[i] heapfy(a, largest_i, size) #initialize self.data_sorted = self.data_unsorted[:] heap_size = self.data_size #build heap i = heap_size / 2 while i >= 0: heapfy(self.data_sorted, i, heap_size) i -= 1 #sort while heap_size > 1: self.data_sorted[0], self.data_sorted[heap_size - 1] = \ self.data_sorted[heap_size - 1], self.data_sorted[0] heap_size -= 1 heapfy(self.data_sorted, 0, heap_size) def _insertion_sort(self, cmp_func, step): i = step while i < self.data_size: tmp = self.data_sorted[i] j = i - step while j >= 0 and cmp_func(self.data_sorted[j], tmp) > 0: self.data_sorted[j + step] = self.data_sorted[j] j -= step self.data_sorted[j + step] = tmp i += 1 def insertion_sort(self, cmp_func): self.data_sorted = self.data_unsorted[:] self._insertion_sort(cmp_func, 1) def shell_sort(self, cmp_func): def orig_increments(size): incs = [] i = size / 2 while i >= 1: incs.append(i) i /= 2 return incs def hibbard_increments(size): incs = [] k = 1 inc = math.pow(2, k) - 1 while inc < size: incs.append(int(inc)) k += 1 inc = math.pow(2, k) - 1 incs.reverse() return incs def knuth_increments(size): incs = [] k = 1 inc = (math.pow(3, k) - 1) / 2 while inc < size: incs.append(int(inc)) k += 1 inc = (math.pow(3, k) - 1) / 2 incs.reverse() return incs def sedgewick_increments(size): incs = [] k = 0 while True: inc1 = 9 * (math.pow(4, k) - math.pow(2, k)) + 1 if inc1 >= size: break incs.append(int(inc1)) inc2 = math.pow(2, k + 2) * (math.pow(2, k + 2) - 3) + 1 if inc2 >= size: break incs.append(int(inc2)) k += 1 incs.reverse() return incs self.data_sorted = self.data_unsorted[:] #speed: sedgewick > knuth > hibbard > orignal incs = sedgewick_increments(self.data_size) #incs = knuth_increments(self.data_size) #incs = hibbard_increments(self.data_size) #incs = orig_increments(self.data_size) for step in incs: self._insertion_sort(cmp_func, step) def small2big(a, b): return a - b def main(): s = sort() s.read_data(sys.argv[1]) dash = sys.argv[2].rindex('.') sort_name = [] sort_time = [] start = datetime.datetime.now() s.insertion_sort(small2big) end = datetime.datetime.now() delta = end - start sort_name.append('insertion') sort_time.append(delta.total_seconds()) output = sys.argv[2][:dash] + '_insertion' +sys.argv[2][dash:] s.write_data(output) start = datetime.datetime.now() s.bubble_sort(small2big) end = datetime.datetime.now() delta = end - start sort_name.append('bubble') sort_time.append(delta.total_seconds()) output = sys.argv[2][:dash] + '_bubble' +sys.argv[2][dash:] s.write_data(output) start = datetime.datetime.now() s.selection_sort(small2big) end = datetime.datetime.now() delta = end - start sort_name.append('selection') sort_time.append(delta.total_seconds()) output = sys.argv[2][:dash] + '_selection' +sys.argv[2][dash:] s.write_data(output) start = datetime.datetime.now() s.merge_sort(small2big) end = datetime.datetime.now() delta = end - start sort_name.append('merge') sort_time.append(delta.total_seconds()) output = sys.argv[2][:dash] + '_merge' +sys.argv[2][dash:] s.write_data(output) start = datetime.datetime.now() s.quick_sort(small2big) end = datetime.datetime.now() delta = end - start sort_name.append('quick') sort_time.append(delta.total_seconds()) output = sys.argv[2][:dash] + '_quick' +sys.argv[2][dash:] s.write_data(output) start = datetime.datetime.now() s.heap_sort(small2big) end = datetime.datetime.now() delta = end - start sort_name.append('heap') sort_time.append(delta.total_seconds()) output = sys.argv[2][:dash] + '_heap' +sys.argv[2][dash:] s.write_data(output) start = datetime.datetime.now() s.shell_sort(small2big) end = datetime.datetime.now() delta = end - start sort_name.append('shell') sort_time.append(delta.total_seconds()) output = sys.argv[2][:dash] + '_shell' +sys.argv[2][dash:] s.write_data(output) print "%8s" % '', for i in sort_name: print "%9s" % i, print "\n%8s" % sys.argv[1][sys.argv[1].rindex('/') + 1:sys.argv[1].index('_')], for i in sort_time: print "%9.4f" % i, print '' if __name__ == '__main__': main()
""" Project Title: Choosing Foods for a Happy Baby Author: Daniel Alvarez Date: July 2018 Class: MIDS-W200-Summer2018 """ """ Description: For this project, I will build a baby food menu whereby each food item on the menu triggers a response from the baby. Some food is agreeable, some food is sometimes agreeable and some food is just disagreeable to the baby. You are the parent trying to feed the baby a varied menu of foods over the course of a day (breakfast, lunch and dinner). You will encounter that the baby will find some foods agreeable when mixed with certain other foods, yet may sometimes find the same foods disagreeable when mixed with other foods. Objects will be the food items on the menu and responses to those foods. The goal is to choose the right set of foods to have a happy baby at the end of the day. """ """ Import libraries and packages """ import sys import random ### Main program print('\nHello, Welcome parent!') print('\nYou are presented with a menu of food options to feed your baby') print('\nEach food item on its own solicits a different response from your baby (agreeable, maybe agreeable, disagreeable)') print('\nEach food item can be mixed with another food item that may solicit a different response from your baby after each meal.') print('\nYou cannot feed the baby the same food item within the same day. Want a varied food menu for your baby.') print('\nThe goal is to be creative with your food menu for your baby without soliciting disagreeable responses.') ### Prompt if __name__ == "__main__": #Initialization print("Welcome to 'Choosing Foods for a Happy Baby'\n") while True: cmd = input("Please enter [b] to enter your [b]aby's details, or [q] to [q]uit the application or [h] for [h]elp\n") if cmd == "h": print("[b]aby - enter your baby information details") print("[q]uit - close the application") elif cmd == "baby" or cmd=="b": #Enter identifying information for you and your baby name = input("Enter your baby's name:\n") weight = input("Enter your baby's weight (in lbs):\n") print("...\n") print("It is time to start feeding " + name) break elif cmd == "quit" or cmd =="q": sys.exit() # dictionary of all possible foods for baby with associated agreeability values for baby dict_of_foods = {"bananas":3, "plain yogurt":3, "cheese":3, "puffs":3, "bread":2, "puffs":3, "peas":3, "cheerios":3, "eggs":3, "peeled grapes":3, "hummus":3, "oatmeal with peanut butter":3, "pasta with cheese":3, "apples with broccoli":2, "sweet potatoes":2, "pears":2, "oatmeal":2, "carrots":2, "oranges":2, "avocado":2, "carrots":2, "flavored yogurt":2, "pasta without cheese": 2, "apples":1, "mangos":1, "fish":1, "green beans":1, "meat":1, "chicken":1, "cantaloupe":1, "blueberries":1, "beets":1, "broccoli":1} # Lists of different meal types breakfast = ["bananas","plain yogurt","cheerios","peeled grapes","oatmeal with peanut butter","pears","oatmeal","oranges","flavored yogurt","apples","strawberries","blueberries"] lunch = ["cheese","bread","puffs","peas","eggs","hummus","pasta with cheese","apples with broccoli","avocado","green beans","meat","chicken","sweet potatoes"] dinner = ["pasta without cheese","mangos","fish","cantaloupe","beets","broccoli","hummus","peas","plain yogurt","pears","peeled grapes","green beans"] allmeals = ["bananas","plain yogurt","cheerios","peeled grapes","oatmeal with peanut butter","pears","oatmeal","oranges","flavored yogurt","apples","strawberries","blueberries", "cheese","bread","puffs","peas","eggs","hummus","pasta with cheese","apples with broccoli","avocado","green beans","meat","chicken","sweet potatoes", "pasta without cheese","mangos","fish","cantaloupe","beets","broccoli","hummus","peas","plain yogurt","pears","peeled grapes","green beans"] # Dictionary of food qualities for each baby food item that inform the baby's reaction to the food # Assign values from 1 (lowest) to 5 (highest) for each foodquality bananas = {"food":"bananas", "sweet":5,"sour":1,"soft":4,"chewy":2,"foul":1,"breakfast":"Yes","lunch":"No","dinner":"Yes"} plainyogurt = {"food":"plain yogurt", "sweet":2,"sour":4,"soft":5,"chewy":1,"foul":1,"breakfast":"Yes","lunch":"No","dinner":"Yes"} cheese = {"food":"cheese", "sweet":3,"sour":2,"soft":3,"chewy":2,"foul":1,"breakfast":"No","lunch":"Yes","dinner":"No"} bread = {"food":"bread", "sweet":1,"sour":1,"soft":3,"chewy":4,"foul":1,"breakfast":"No","lunch":"Yes","dinner":"No"} puffs = {"food":"puffs", "sweet":2,"sour":1,"soft":1,"chewy":5,"foul":1,"breakfast":"No","lunch":"Yes","dinner":"No"} peas = {"food":"peas", "sweet":3,"sour":1,"soft":2,"chewy":4,"foul":1,"breakfast":"No","lunch":"Yes","dinner":"Yes"} cheerios = {"food":"cheerios", "sweet":2,"sour":1,"soft":1,"chewy":5,"foul":1,"breakfast":"Yes","lunch":"No","dinner":"No"} eggs = {"food":"eggs", "sweet":1,"sour":1,"soft":4,"chewy":3,"foul":1,"breakfast":"No","lunch":"Yes","dinner":"No"} peeledgrapes = {"food":"peeled grapes", "sweet":5,"sour":1,"soft":2,"chewy":2,"foul":1,"breakfast":"Yes","lunch":"No","dinner":"Yes"} hummus = {"food":"hummus", "sweet":1,"sour":1,"soft":5,"chewy":1,"foul":1,"breakfast":"No","lunch":"Yes","dinner":"Yes"} oatmealwithpeanutbutter = {"food":"oatmeal with peanut butter", "sweet":3,"sour":1,"soft":5,"chewy":2,"foul":1,"breakfast":"Yes","lunch":"No","dinner":"No"} pastawithcheese = {"food":"pasta with cheese", "sweet":1,"sour":1,"soft":1,"chewy":5,"foul":1,"breakfast":"No","lunch":"Yes","dinner":"No"} sweetpotatoes = {"food":"sweet potatoes", "sweet":3,"sour":1,"soft":4,"chewy":3,"foul":1,"breakfast":"No","lunch":"Yes","dinner":"No"} pears = {"food":"pears", "sweet":5,"sour":1,"soft":3,"chewy":3,"foul":1,"breakfast":"Yes","lunch":"No","dinner":"Yes"} oatmeal = {"food":"oatmeal", "sweet":1,"sour":1,"soft":5,"chewy":1,"foul":1,"breakfast":"Yes","lunch":"No","dinner":"No"} carrots = {"food":"carrots", "sweet":3,"sour":1,"soft":1,"chewy":5,"foul":1,"breakfast":"No","lunch":"Yes","dinner":"No"} oranges = {"food":"oranges", "sweet":5,"sour":1,"soft":2,"chewy":3,"foul":1,"breakfast":"Yes","lunch":"No","dinner":"No"} avocado = {"food":"avocado", "sweet":2,"sour":1,"soft":4,"chewy":2,"foul":1,"breakfast":"No","lunch":"Yes","dinner":"No"} flavoredyogurt = {"food":"flavored yogurt", "sweet":3,"sour":3,"soft":5,"chewy":1,"foul":1,"breakfast":"Yes","lunch":"No","dinner":"No"} pastawithoutcheese = {"food":"pasta without cheese", "sweet":1,"sour":1,"soft":1,"chewy":5,"foul":1,"breakfast":"No","lunch":"No","dinner":"Yes"} apples = {"food":"apples", "sweet":5,"sour":1,"soft":5,"chewy":1,"foul":1,"breakfast":"Yes","lunch":"No","dinner":"No"} mangos = {"food":"mangos", "sweet":3,"sour":3,"soft":3,"chewy":3,"foul":1,"breakfast":"No","lunch":"No","dinner":"Yes"} fish = {"food":"fish", "sweet":1,"sour":1,"soft":4,"chewy":2,"foul":4,"breakfast":"No","lunch":"No","dinner":"Yes"} greenbeans = {"food":"green beans", "sweet":1,"sour":3,"soft":2,"chewy":4,"foul":3,"breakfast":"No","lunch":"Yes","dinner":"Yes"} meat = {"food":"meat", "sweet":1,"sour":1,"soft":2,"chewy":3,"foul":1,"breakfast":"No","lunch":"Yes","dinner":"No"} chicken = {"food":"chicken", "sweet":1,"sour":1,"soft":2,"chewy":3,"foul":1,"breakfast":"No","lunch":"Yes","dinner":"No"} cantaloupe = {"food":"cantaloupe", "sweet":5,"sour":1,"soft":3,"chewy":3,"foul":1,"breakfast":"No","lunch":"No","dinner":"Yes"} strawberries = {"food":"strawberries", "sweet":5,"sour":1,"soft":3,"chewy":3,"foul":1,"breakfast":"Yes","lunch":"No","dinner":"No"} beets = {"food":"beets", "sweet":3,"sour":3,"soft":2,"chewy":4,"foul":1,"breakfast":"No","lunch":"No","dinner":"Yes"} broccoli = {"food":"broccoli", "sweet":1,"sour":2,"soft":3,"chewy":4,"foul":1,"breakfast":"No","lunch":"No","dinner":"Yes"} # Define the base class for baby meals class BabyMeals(): def __init__(self, meal, foodselected): """ Generates the food menu for the particular meal """ self.meal = meal self.allmeals = allmeals self.foodselected = foodselected def __food__(self): """ Renders the menu of foods available to the screen """ print(self.meal) return def __repr__(self): """ Print the menu of foods nicely """ return " ".join(str(x) for x in self.meal) def get_food(self): """ Returns the food item selected by the user """ return self.foodselected def remove_from_menu(self): """ Removes the food item selected from the foods available """ self.meal.remove(self.foodselected) self.allmeals.remove(self.foodselected) print(self.foodselected + " removed from the available foods on the baby food menu") return def set_food(self, foodselected): """ Raises exception if food chosen is not among the available foods on the menu or if two foods have not been chosen""" self.foodselected = foodselected if self.foodselected not in self.meal: raise Exception ("Sorry, food selected is not among the available foods on the menu. Choose another food item.") print("Sorry, food selected is not among the available foods on the menu. Choose another food item.") else: print("Good choice, "+ self.foodselected + " is among the available food items on the menu.") return # Define class for baby response upon serving meals class ServeMeal: """ This class displays the baby's emotional response to the meal selected""" def __init__(self, meal, fooditem1, fooditem2): self.meal = meal self.fooditem1 = fooditem1 self.fooditem2 = fooditem2 self.dict_of_foods = {"bananas":3, "plain yogurt":3, "cheese":3, "puffs":3, "bread":2, "puffs":3, "peas":3, "cheerios":3, "eggs":3, "peeled grapes":3, "hummus":3, "oatmeal with peanut butter":3, "pasta with cheese":3, "apples with broccoli":2, "sweet potatoes":2, "pears":2, "oatmeal":2, "carrots":2, "oranges":2, "avocado":2, "carrots":2, "flavored yogurt":2, "pasta without cheese": 2, "apples":1, "mangos":1, "fish":1, "green beans":1, "meat":1, "chicken":1, "cantaloupe":1, "blueberries":1, "beets":1, "broccoli":1} def emotion(self): """ Returns whether the two food items selected in combination are agreeable, maybe agreeable or disagreeable""" # initiate an empty dictionary to add selected food items to self.foodselected = {} # Add food items to empty dictionary if self.fooditem1 in self.dict_of_foods: self.foodselected.get(self.fooditem1) self.foodselected[self.fooditem1]=self.dict_of_foods[self.fooditem1] if self.fooditem2 in self.dict_of_foods: self.foodselected.get(self.fooditem2) self.foodselected[self.fooditem2]=self.dict_of_foods[self.fooditem2] self.foodresponse = sum(self.foodselected.values()) if sum(self.foodselected.values()) > 4: babyreaction = "Agreeable" elif sum(self.foodselected.values()) == 4: babyreaction = "Maybe Agreeable" else: babyreaction = "Disagreeable" return babyreaction def emotion_message_to_parent(self): """ Returns message to user 'Happy baby' or 'Unhappy baby' """ if sum(self.foodselected.values()) > 4: print("Happy baby!") elif sum(self.foodselected.values()) == 4: print("Perhaps happy baby or perhaps not!") else: print("Unhappy baby!") return # Produces a message for parent for whether food item chosen is or is not in the menu class Foodsavailable(): """ This class tells the parent is foods are available to create baby meals """ def __init__(self, meal, fooditem1, fooditem2): self.meal = meal self.fooditem1 = fooditem1 self.fooditem2 = fooditem2 def message_to_parent(self): """ Produces message for parent if food item chosen is not in the menu for the given meal """ if self.fooditem1 not in self.meal: print("Cannot choose " + self.fooditem1 + " It is not an available food for your baby!") return elif self.fooditem2 not in self.meal: print("Cannot choose " + self.fooditem2 + " It is not an available food for your baby!") return else: print("Congrats. Both " + self.fooditem1 + " and " + self.fooditem2 + " are available meal food items for your baby.") return def __repr__(self): return (str(self.fooditem1) + ' and '+ str(self.fooditem2)+ ' chosen') """ Define classes for food qualities """ class FoodQualities(): """ This class assigns food qualities to food items """ def __init__(self, fooditem): self._fooditem = fooditem.get("food") self._sweet = fooditem.get("sweet") self._sour = fooditem.get("sour") self._soft = fooditem.get("soft") self._chewy = fooditem.get("chewy") self._foul = fooditem.get("foul") self._breakfast = fooditem.get("breakfast") self._lunch = fooditem.get("lunch") self._dinner = fooditem.get("dinner") def get_fooditem(self): return self._fooditem def get_sweet(self): return self._sweet def get_sour(self): return self._sour def get_soft(self): return self._soft def get_chewy(self): return self._chewy def get_foul(self): return self._foul def get_breakfast(self): return self._breakfast def get_lunch(self): return self._lunch def get_dinner(self): return self._dinner def __str__(self): return "FOOD ITEM: {}\nsweet: {}\nsour: {}\nsoft: {}\nchewy: {}\nfoul: {} \nbreakfast: {} \nlunch: {} \ndinner: {}"\ .format(self._fooditem, self._sweet, self._sour, self._soft, self._chewy, self._foul, self._breakfast, self._lunch, self._dinner) ################################################################################ """ Secondary main prompt that gets initiated once the parent user has entered in the baby's details """ if __name__ == "__main__": while True: #Initialization if name != None and weight != None: # Prompt parent to enter first food print("Here are the available foods for breakfast for " + name + ":") print(breakfast) foodselected1 = input("Please enter a single food item from the available menu items for " + name + "'s breakfast:\n") parentchoice1 = BabyMeals(breakfast,str(foodselected1)) print("You have selected " + foodselected1 + " for " + name) print("\n") # Tell parent that item has been removed from the menu parentchoice1.remove_from_menu() # Tells parent of foods available on the menu print("Here are the menu of foods available for breakfast: ") parentchoice1.__food__() # Tells parent to enter second food foodselected2 = input("Please enter a second food item selection for " + name + "'s breakfast:\n") parentchoice1 = BabyMeals(breakfast,str(foodselected2)) print("You have selected " + foodselected2) print("\n") # Tells parent if food item is among the available foods on the menu parentchoice1.set_food(str(foodselected2)) # Tell parent that second food item has been removed from the menu parentchoice1.remove_from_menu() print("") # Tells parent of baby's reaction to food's chosen breakfastchoice = ServeMeal(breakfast,str(foodselected1),str(foodselected2)) print("Your breakfast food selection was " + breakfastchoice.emotion() + " with " + name + "\n") print("After breakfast you have a: ") breakfastchoice.emotion_message_to_parent() ###################################################################### # Now time to move onto lunch. Iterate same steps as above for breakfast print("\nIt is now time to feed " + name + " lunch.\n") # Prompt parent to enter first food for lunch print("Here are the available foods for lunch for " + name + ":") print(lunch) foodselected3 = input("Please enter a single food item from the available menu items for " + name + "'s lunch:\n") parentchoice3 = BabyMeals(lunch,str(foodselected3)) print("You have selected " + foodselected3 + " for " + name) print("\n") # Tell parent that item has been removed from the menu parentchoice3.remove_from_menu() # Tells parent of foods available on the menu print("Here are the menu of foods available for lunch: ") parentchoice3.__food__() # Tells parent to enter second food foodselected4 = input("Please enter a second food item selection for " + name + "'s lunch:\n") parentchoice4 = BabyMeals(lunch,str(foodselected4)) print("You have selected " + foodselected4) print("\n") # Tells parent if food item is among the available foods on the menu parentchoice4.set_food(str(foodselected4)) # Tell parent that second food item has been removed from the menu parentchoice4.remove_from_menu() print("") # Tells parent of baby's reaction to food's chosen lunchchoice = ServeMeal(lunch,str(foodselected3),str(foodselected4)) print("Your lunch food selection was " + lunchchoice.emotion() + " with " + name + "\n") print("After lunch you have a: ") lunchchoice.emotion_message_to_parent() ###################################################################### # Now time to move onto dinner. Iterate same steps as above for breakfast print("\nIt is now time to feed " + name + " dinner.\n") # Prompt parent to enter first food for lunch print("Here are the available foods for dinner for " + name + ":") print(dinner) foodselected5 = input("Please enter a single food item from the available menu items for " + name + "'s dinner:\n") parentchoice5 = BabyMeals(dinner,str(foodselected5)) print("You have selected " + foodselected5 + " for " + name) print("\n") # Tell parent that item has been removed from the menu parentchoice5.remove_from_menu() # Tells parent of foods available on the menu print("Here are the menu of foods available for dinner: ") parentchoice5.__food__() # Tells parent to enter second food foodselected6 = input("Please enter a second food item selection for " + name + "'s dinner:\n") parentchoice6 = BabyMeals(dinner,str(foodselected6)) print("You have selected " + foodselected6) print("\n") # Tells parent if food item is among the available foods on the menu parentchoice6.set_food(str(foodselected6)) # Tell parent that second food item has been removed from the menu parentchoice6.remove_from_menu() print("") # Tells parent of baby's reaction to food's chosen dinnerchoice = ServeMeal(dinner,str(foodselected5),str(foodselected6)) print("Your dinner food selection was " + dinnerchoice.emotion() + " with " + name + "\n") print("After dinner you have a: ") dinnerchoice.emotion_message_to_parent() ####################################################################### # Tell parent end of day message after all three meals have been served print("\nYour end of day message is: ") if breakfastchoice.emotion_message_to_parent() == "Happy baby!" and lunchchoice.emotion_message_to_parent() == "Happy baby!" and dinnerchoice.emotion_message_to_parent() == "Happy baby!": print("Congratulations you have a happy baby! Good luck feeding tomorrow!") else: print("Sorry, you have an unhappy baby! Better luck feeding tomorrow!") ###################################################################### break else: cmd = input("Please enter your [b]aby's details, [q]uit the application of 'h' for help\n")
# fruits=["apple","pear","kiwi"] # print(fruits[2]) # # length of the list # print(len(fruits)) # # how to add an element in list? # fruits.append("mango") # print(fruits) # # how to remove an element from the specific position in the list? # fruits.pop(0) # print(fruits) # # how to reverse the list? # fruits.reverse() # print(fruits) # how to insert an element at specific position in the list? # fruits.insert(1,"orange") # print(fruits) # If the list contains an apple notify the user with the message "apple is present" else "OOPS!!!! List is without an apple" # if "apple" in fruits: # print("Apple is present") # else: # print("OOPS!!!! List is without an apple")
import numpy as np import scipy.stats as stats def calc(): n = 36 alpha = 0.005 mean_1 = 4.51 mean_2 = 6.28 std_1 = 1.98 std_2 = 2.54 t = (mean_1 - mean_2)/np.sqrt(std_1**2/n + std_2**2/n) # хотим альтернативу mean_1 < mean_2 q_val = stats.t.ppf(q=alpha, df=n+n-1) print('t_value: {}'.format(t)) print('q_value: {}'.format(q_val)) if t < q_val: print('Отвергаем H0') else: print('Не можем опровергнуть H0')
# strings and for loops # CS 140 - Vishesh Thakur # September 29, 2015 # Print a pyramid of an input character def pyramid (character) : space = " " print 4 * space, character print 3 * space, 3 * character print 2 * space, 5 * character print space, 7 * character print 9 * character #answer to the questions on which character lines up better # The character * lines up best as it is the closest in width # to the space character. All the other characters look lopsided # because they are much wider, meaning they extend far # more to the right than they should to make the pyramid even. # This function prints an inverted pyramid of an input character def invertedPyramid (character) : space = " " print 9 * character print space, 7 * character print 2 * space, 5 * character print 3 * space, 3 * character print 4 * space, character # justVowels2(): print only the vowels in piece of text def justVowels2 (myString) : for letter in myString : if letter in "aeiouAEIOU" : print letter # justVowels3(): print only the vowels in piece of text def justVowels3 (myString) : for letter in myString : if letter.lower() in "aeiou" : print letter # notVowels() # this function should print only consonants but if # the string contains vowels in uppercase, they get printed too def notVowels (myString) : for letter in myString : if not (letter in "aeiou") : print letter # notVowels2(): fixed so it only prints consonats def notVowels2 (myString) : for letter in myString : if not (letter in "aeiouAEIOU") : print letter # notVowels3(): fixed so it only prints consonats # another possible solution using lower() def notVowels3 (myString) : for letter in myString : if not(letter.lower() in "aeiou") : print letter # splitLetters(): takes a string and separates the vowels from the # consonants. It prints the vowels and the consonants in the # input string # Note: This version explicitly checks for consonants, instead if a # character is not a vowel. A version in which that line is replaced # with: if not letter.lower() in "aeiou": would also be acceptable. def splitLetters(myString): vowels= "" consonants = "" for letter in myString : if letter.lower() in "aeiou": vowels = vowels + letter if letter.lower() in "qwrtypsdfghjklzxcvbnm": consonants = consonants + letter print "Vowels: " + vowels print "Consonsants: " + consonants #spaceItOut(): takes a string and an integer as its input #it adds spaces in between each letter, then prints out the #resulting string def spaceItOut(aString, number): pile = "" space = " " for index in range(0, len(aString)-1) : #we don't want to add spaces after the last character pile = pile + aString[index] + number * space pile = pile + aString[len(aString)-1] #don't forget to concatenate the last character in the string print pile
import tkinter import tkinter as tk from tkinter import * from gui.area import ScrollableFrame root = tk.Tk() class gui: maximumIterations = tk.IntVar() precision = tk.DoubleVar() precision.set(0.00001) maximumIterations.set(50) numberOfEquations = tk.StringVar(root) method = tk.StringVar(root) OptionList = [ "Guass Elimination", "Guass Elimination-pivoting", "Guass Jordan", "Guass Seidel", "LU decomposition", "All" ] equationsList = [] frame = ScrollableFrame(root) read_from_file = False initials=[] def begin(self): self.makeLabelPackVertical(root, tk, "Solving linear equations", 60) self.file_button() self.takeInputs() self.chooseMethod() root.geometry("900x650") root.mainloop() def file_button(self): button1 = Checkbutton(root, text="File", command=lambda: read_file(), height=1, width=10) button1.pack() def read_file(): self.read_from_file = True root.destroy() def makeTable(self): self.frame = ScrollableFrame(root) n = int(self.numberOfEquations.get()) self.equationsList = [] lis = [] for i in range(n): listBox = Listbox(self.frame.scrollable_frame, height=1, width=53) listBox.insert(END, "Equation %s :" % (i + 1)) textBox = Text(self.frame.scrollable_frame, width=40, height=2) listBox.pack(pady=10) textBox.pack(pady=10) lis.append(textBox) listBox = Listbox(self.frame.scrollable_frame, height=1, width=53) listBox.insert(END, "Seidel initials :") textBox = Text(self.frame.scrollable_frame, width=40, height=2) listBox.pack(pady=10) textBox.pack(pady=10) lis.append(textBox) self.frame.pack() button_commit = Button(root, height=1, width=10, text="Solve", command=lambda: retrieve_input()) button_commit.pack() def retrieve_input(): for i in range(n): self.equationsList.append(lis[i].get("1.0", "end-1c")) intials_string = lis[len(lis) - 1].get("1.0", "end-1c") if intials_string!='': self.initials = intials_string.split(" ") self.initials = [float(i) for i in self.initials] #print(self.initials) root.destroy() def chooseMethod(self): self.makeLabelPackVertical(root, tk, "Choose method :", 20) self.method.set("Guass Elimination") opt = tk.OptionMenu(root, self.method, *self.OptionList) opt.config(width=40, font=('Helvetica', 12)) opt.pack(side="top") def callback(*args): pass #print(self.method.get()) self.method.trace("w", callback) def takeInputs(self): self.makeLabelPackVertical(root, tk, "Maximum iterations :", 20) name_entry = tk.Entry(root, textvariable=self.maximumIterations, font=('calibre', 10, 'normal'), width=40).pack() self.makeLabelPackVertical(root, tk, "Precision :", 20) name_entry = tk.Entry(root, textvariable=self.precision, font=('calibre', 10, 'normal'), width=40).pack() self.makeLabelPackVertical(root, tk, "Number of equations :", 20) name_entry = tk.Entry(root, textvariable=self.numberOfEquations, font=('calibre', 10, 'normal'), width=40).pack() def call(*args): for l in list(root.children.values()): if type(l) == tkinter.Listbox or type(l) == tkinter.Text or \ type(l) == tk.Button: l.destroy() self.frame.destroy() if self.numberOfEquations.get() != "": self.makeTable() self.numberOfEquations.trace("w", call) def makeLabelPackVertical(self, rootObject, tk, text, font): tk.Label(rootObject, text=text, justify=tk.CENTER, padx=0, font=font, pady=10).pack() # TODO: check if there is a solution
def Calculate(matrix, i, j): return [row[: j] + row[j+1:] for row in (matrix[: i] + matrix[i+1:])] def check_singular(matrix): n = len(matrix) if (n == 2): val = matrix[0][0]*matrix[1][1] - matrix[1][0]*matrix[0][1] return val det = 0 for i in range(n): s = (-1)**i sub_det = check_singular(Calculate(matrix, 0, i)) det += (s*matrix[0][i]*sub_det) return det matrix = [[78, 45, 4], [0, 0, 0], [7, 4, -54]] n = len(matrix) print("The given matrix") for i in range(n): for j in range(n): print(matrix[i][j], end=' ') print() if(check_singular(matrix)): print("The given matrix is non-Singular") else: print("The given matrix is singular")
def isZeroMatrix(matrix): #calculate number of rows rows = len(matrix) #calculate number of columns cols = len(matrix[0]) for i in range(0, rows): for j in range(0, cols): if matrix[i][j] != 0: return False return True
#func to matrix is singular or non singular def Sing(mtrx): n = len(mtrx) if (n == 2): v = mtrx[0][0]*mtrx[1][1] - mtrx[1][0]*mtrx[0][1] #determinant return v #calculating the det of matrix using cofactor dt = 0 for a in range(n): s = (-1)**a sbdt = Sing(Cofactor(mtrx, 0, a)) dtm += (s*mtrx[0][a]*sbdt) return dt #func to calculate the cofactor of a matrix def Cofactor(mtrx, a, b): return [row[: b] + row[a+1:] for row in (mtrx[: a] + mtrx[a+1:])]
#Define a faster fibonacci procedure that will enable us to computer #fibonacci(36). def fibonacci(n): i = 0 fib = 0 prev1 = 0 prev2 = 0 while i < n + 2: if i == 0: prev1 = 0 elif i == 1: prev2 = 1 else: fib = prev1 + prev2 if i % 2 > 0: prev1 = fib else: prev2 = fib i += 1 return fib print fibonacci(10) print fibonacci(36) #>>> 14930352
class FileReader(): def __init__(self, filename): self.filename = filename def lines(self): datafile = open(self.filename, "r") r = [] for l in datafile: r.append(l) return r class CSVFileReader(FileReader): def __init__(self, filename, seperator): super().__init__(filename) self.seperator = seperator def lines(self): # langform #ls = super().lines() #r = [] #for l in ls: # r.append(l.strip().split(self.seperator)) #return r # kurzform als list comprehension return [line.strip().split(self.seperator) for line in super().lines()] f1 = CSVFileReader("data.csv", ";") f2 = FileReader("data.csv") #print(f.lines()) print(type(f1)) print(type(f2)) if (type(f1) == CSVFileReader): print("f1 is of type CSVFileReader") # keine Vererbung, nur exakter Typ if (isinstance(f1), CSVFileReader): print("f1 is instance of FileReader") # berücksichtigt Vererbung
import pandas as pd import math filename = "./astronauts.csv" # df = dataframe df = pd.read_csv(filename, delimiter=",") # delimiter="," is default print(df.head()) print(len(df)) print(df.iloc[0]) # horizontal slicing print("*** ACCESS COLUMN ***") col_names = df["Name"] # access col / vertical slicing i = 0 for name in col_names: print("{} {}".format(i,name)) i = i + 1 if i >= 4: break e1 = df.iloc[0] # get first data element print("Name='{}'".format(e1["Name"])) # access cols of data element print("Birth Date='{}'".format(e1["Birth Date"])) print("***") subs = df.iloc[4:8] # horizontal slicing names = subs["Name"] print(names) print("*** ITERATE ***") for row in df.iterrows(): # how to iterate over rows (pos, dataitem) = row print("{}\t'{}'\t{}".format(pos, dataitem["Name"], dataitem["Space Flights"])) if pos >= 5: break print("*** FILTER ***") df_before_1960 = df[df["Year"] < 1960] print(df_before_1960) df_mission_deaths = df[not math.isnan(df["Death Mission"])] print(df_mission_deaths)
import tkinter from math import * from random import randint SCREEN_SIZE = (600, 600) def xs(x): return SCREEN_SIZE[0] // 2 + x def ys(y): return SCREEN_SIZE[1] // 2 - y def oxs(x): return x - SCREEN_SIZE[0] // 2 def oys(y): return SCREEN_SIZE[1] // 2 - y class Screen: def __init__(self, w, h): self.width = w self.height = h def w(self): return self.width def h(self): return self.height scr = Screen(SCREEN_SIZE[0], SCREEN_SIZE[1]) main = tkinter.Tk() canvas = tkinter.Canvas(main, bg='white', height=scr.h(), width=scr.w()) canvas.create_line((xs(0), ys(scr.h() // 2)), xs(0), ys(-scr.h() // 2), fill='#336699') canvas.create_line((xs(-scr.w() // 2), ys(0)), xs(scr.w() // 2), ys(0), fill='black') coords = [] n = int(input()) for i in range(n): coords.append(randint(-scr.w() // 2, scr.w() // 2)) coords.append(randint(-scr.h() // 2, scr.h() // 2)) print(coords) my_beautiful_polygon = canvas.create_polygon(coords, fill='white', width=3,outline = 'red') def reddraw_polygon(): canvas.coords(my_beautiful_polygon,coords) def remove_point(event): coords.pop() coords.pop() print(coords) reddraw_polygon() def add_point(event): coords.append(event.x) coords.append(event.y) print(coords) reddraw_polygon() canvas.bind('<Button 1>', add_point) canvas.bind('<Button 3>', remove_point) canvas.pack() main.mainloop()
input1 = input("enter first number: ") input2 = input("enter second number: ") input3 = input("enter third number: ") def largest(n1, n2, n3): if (n1 >= n2 and n1 >= n3): return n1 elif (n2 >= n1 and n2 >= n3): return n2 elif (n3 >= n1 and n3 >= n2): return n3 try: n1 = int(input1) n2 = int(input2) n3 = int(input3) result = largest(n1, n2, n3) print("largst number is: ", result) except: print("input valid value")
log = float(input("LOGPROG grade: ")) it = float(input("INTR-IT grade: ")) fit = float(input("FITWELL grade: ")) log = log * 3 it = it * 3 fit = fit * 2 gpa = (log + it + fit) / 8 print("Your GPA is", gpa) if gpa >= 3.400: print("You're a first honor dean's lister!") elif gpa < 3.400 and gpa >= 3.000: print("You're a second honor dean's lister!")
year = int(input("Enter a year: ")) year = year % 4 year2 = year % 100 year3 = year % 400 if year == 0: if year2 == 0: if year3 == 0: print("It's a leap year!") else: print("It's not a leap year.") else: print("It's a leap year!") else: print("It's not a leap year.")
############### # This is to certify that this project is my own work, based on my personal # efforts in studying and applying the concepts learned. I have constructed # the functions and their respective algorithms and corresponding code by # myself. The program was run,tested, and debugged by my own efforts. I # further certify that I have not copied in part or whole or otherwise # plagiarized the work of other students and/or persons. # # ________________ # Aldrich Limheya, 11427167 ################ ####################### #Task: Input stocks #Description: This segment lets the cashier type the stock for the day #Variables Used: BurgerBun,BeefBurgerPatty,ChickenBurgerPatty,RegularFries,LargeFries, #BurgerWrap,RegularSodaCup,LargeSodaCup #Outputs: The stock available for the day ####################### BurgerBun=int(input("Enter Burger Buns in stock today")) BeefBurgerPatty=int(input("Enter Beef Burger Patties in stock today")) ChickenBurgerPatty=int(input("Enter Chicken Burger Patty in stock today")) RegularFries=int(input("Enter Regular Fries in stock today")) LargeFries=int(input("Enter Large Fries in stock today")) BurgerWrap=int(input("Enter Burger Wrap in stock today")) RegularSodaCup=int(input("Enter Regular Soda Cup in stock today")) LargeSodaCup=int(input("Enter Large Soda Cup in stock today")) print ("") ####################### #Task: Stores the price of each product #Description: The variables here have a value which is their price #Variables Used: BB,CB.RF,LF,LS,RS,BBRC,BBLC,CBLC,CBRC #Outputs: At the end of the day report, it outputs the price of each product ####################### BB=80 CB=70 RF=20 LF=30 RS=15 LS=20 BBRC=100 BBLC=110 CBRC=90 CBLC=100 ###################### #Task: The variables here are for storing the amount of products sold #Description: Every product in the menu starts at zero and as it is being sold, #the amount of products adds up and shows at the end of the day report #Variables Used: BEEFBURGER,CHICKENBURGER,REGULARFRIES,LARGEFRIES,REGULARSODA, #LARGESODA,BEEFBURGERREGCOMBO,BEEFBURGERLARGCOMBO,CHICKENBURGERREGCOMBO,CHICKENBURGERLARGCOMBO #Outputs: At the end of the day report, the amount of the products sold will be displayed. ###################### BEEFBURGER=0 CHICKENBURGER=0 REGULARFRIES=0 LARGEFRIES=0 REGULARSODA=0 LARGESODA=0 BEEFBURGERREGCOMBO=0 BEEFBURGERLARGCOMBO=0 CHICKENBURGERREGCOMBO=0 CHICKENBURGERLARGCOMBO=0 ###################### #Task: Storing the sum of the price of the ordered products and customer count. #Description: The variable for customer is for stating the amount of customers who bought something. #The variable for A is for the sum of the price of all the food ordered on the first order. another variable is assigned #if there are more orders. #Variables Used: customer,A #Outputs: shown at the receipt for the customer and A is for either the total bill of a customer for 1 order only or, #for adding it to the total price if it is with the second order or more orders. ####################### customer=0 A=0 ####################### #Task: Getting the total stock and inputing if there is a customer or not #Description: All of the stock is added and if the total stock is zero, the end of the day report will be displayed. #countercustomer is also for inputting if there is a customer, it will continue the program if not then it will display #the end of the day report. #Variables Used: TotalStock,countercustomer #Outputs:if there is no stock or if there is no customers for the day, end of the day report will be displayed or else, #it will continue the program ####################### TotalStock=BurgerBun+BeefBurgerPatty+ChickenBurgerPatty+RegularFries+LargeFries+BurgerWrap+RegularSodaCup+LargeSodaCup countercustomer=input("Enter y if there is a customer. if none, press any key and click enter=)") while countercustomer=="y" and TotalStock>0: QTY=0 NQTY=0 PQ1=0 A=0 PQ=0 ####################### #Task: Getting the order and how many orders #Description: This determines the order and how many orders will there be #Variables Used: Order,QTY #Outputs: How many orders a customer orders and the orders itself ####################### Order=input("Please enter the order of your customer") QTY=int(input("How many orders?")) ####################### #Task: Computes the total price for the quantity and the product product price and decrease the stock that makes up the product #whenever a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program #continues, it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again #because it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the #first order and add the number of the product sold in the first order. #Variables Used: Order,QTY,BurgerBun,BeefBurgerPatty,BurgerWrap,PQ1,BEEFBURGER #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### if Order=="BB": if BurgerBun>=QTY and BeefBurgerPatty>=QTY and BurgerWrap>=QTY: print(QTY,"Beef Burger-",(BB*QTY)) BurgerBun=BurgerBun-QTY BeefBurgerPatty=BeefBurgerPatty-QTY BurgerWrap=BurgerWrap-QTY if BurgerBun>=0 and BeefBurgerPatty>=0 and BurgerWrap>=0: PQ1=(BB*QTY) BEEFBURGER=BEEFBURGER+QTY else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Beef Burgers that is available with the stock given.") print ("Burger Bun:",BurgerBun+QTY) print ("Beef Burger Patty:",BeefBurgerPatty+QTY) print ("Burger Wrap:",BurgerWrap+QTY) else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Beef Burgers that is available with the stock given.") print ("Burger Bun:",BurgerBun) print ("Beef Burger Patty:",BeefBurgerPatty) print ("Burger Wrap:",BurgerWrap) ####################### #Task: Computes the total price for the quantity and the product product price and decrease the stock that makes up the product whenever #a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program continues #, it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again because #it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the first #order and add the number of the product sold in the first order. #Variables Used: Order,QTY,BurgerBun,ChickenBurgerPatty,BurgerWrap,PQ1,CHICKENBURGER #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### elif Order=="CB": if BurgerBun>=QTY and ChickenBurgerPatty>=QTY and BurgerWrap>=QTY: print(QTY,"Chicken Burger-",(CB*QTY)) BurgerBun=BurgerBun-QTY ChickenBurgerPatty=ChickenBurgerPatty-QTY BurgerWrap=BurgerWrap-QTY if BurgerBun>=0 and ChickenBurgerPatty>=0 and BurgerWrap>=0: PQ1=(CB*QTY) CHICKENBURGER=CHICKENBURGER+QTY else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Chicken Burgers that is available with the stock given.") print ("Burger Bun:",BurgerBun+QTY) print ("Chicken Burger Patty:",BeefBurgerPatty+QTY) print ("Burger Wrap:",BurgerWrap+QTY) else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Chicken Burgers that is available with the stock given.") print ("Burger Bun:",BurgerBun) print ("Chicken Burger Patty:",BeefBurgerPatty) print ("Burger Wrap:",BurgerWrap) ####################### #Task: Computes the total price for the quantity and the product product price and decrease the stock that makes up the product whenever a # product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program continues #, it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again because #it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the first #order and add the number of the product sold in the first order. #Variables Used: Order,QTY,RegularFries,PQ1,REGULARFRIES #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### elif Order=="RF": if RegularFries>=QTY: print(QTY,"Regular Fries-",(RF*QTY)) RegularFries=RegularFries-QTY if RegularFries>=0: PQ1=(RF*QTY) REGULARFRIES=REGULARFRIES+QTY else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Regular Fries that is available with the stock given.") print ("Regular Fries:",RegularFries+QTY) else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Regular Fries that is available with the stock given.") print ("Regular Fries:",RegularFries) ####################### #Task: Computes the total price for the quantity and the product product price and decrease the stock that makes up the product whenever #a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program continues, #it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again because #it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the first #order and add the number of the product sold in the first order. #Variables Used: Order,QTY,LARGEFRIES,PQ1,LargeFries #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### elif Order=="LF": if LargeFries>=QTY: print(QTY,"Large Fries-",(LF*QTY)) LargeFries=LargeFries-QTY if LargeFries>=0: PQ1=(LF*QTY) LARGEFRIES=LARGEFRIES+QTY else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Large Fries that is available with the stock given.") print ("Large Fries:",LargeFries+QTY) else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Large Fries that is available with the stock given.") print ("Large Fries:",LargeFries) ####################### #Task: Computes the total price for the quantity and the product product price and decrease the stock that makes up the product whenever #a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program continues, #it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again because #it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the first #order and add the number of the product sold in the first order. #Variables Used: Order,QTY,REGULARSODA,PQ1,RegularSoda #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### elif Order=="RS": if RegularSodaCup>=QTY: print(QTY,"Regular Soda-",(RS*QTY)) RegularSodaCup=RegularSodaCup-QTY if RegularSodaCup>=0: PQ1=(RS*QTY) REGULARSODA=REGULARSODA+QTY else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Regular Soda that is available with the stock given.") print ("Regular Soda Cup:",RegularSodaCup+QTY) else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Regular Soda that is available with the stock given.") print ("Regular Soda Cup:",RegularSodaCup) ####################### #Task: Computes the total price for the quantity and the product product price and decrease the stock that makes up the product whenever #a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program continues, #it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again because #it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the first #order and add the number of the product sold in the first order. #Variables Used: Order,QTY,LargeSoda,PQ1,LARGESODA #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### elif Order=="LS": if LargeSodaCup>=QTY: print(QTY,"Large Soda-",(LS*QTY)) LargeSodaCup=LargeSodaCup-QTY if LargeSodaCup>=0: PQ1=(LS*QTY) LARGESODA=LARGESODA+QTY else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Large Soda that is available with the stock given.") print ("Large Soda Cup:",LargeSodaCup+QTY) else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Large Soda that is available with the stock given.") print ("Large Soda Cup:",LargeSodaCup) ####################### #Task: Computes the total price for the quantity and the product product price and decrease the stock that makes up the product whenever #a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program #continues, it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again #because it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the #first order and add the number of the product sold in the first order. #Variables Used: Order,QTY,BurgerBun,BeefBurgerPatty,BurgerWrap,RegularSodaCup,RegularFries,PQ1,BEEFBURGERREGCOMBO #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### elif Order=="BBRC": if RegularSodaCup>=QTY and RegularFries>=QTY and BurgerBun>=QTY and BeefBurgerPatty>=QTY and BurgerWrap>=QTY: print(QTY,"Beef Burger Regular Combo-",(BBRC*QTY)) BurgerBun=BurgerBun-QTY BeefBurgerPatty=BeefBurgerPatty-QTY BurgerWrap=BurgerWrap-QTY RegularFries=RegularFries-QTY RegularSodaCup=RegularSodaCup-QTY if RegularSodaCup>=0 and RegularFries>=0 and BurgerBun>=0 and BeefBurgerPatty>=0 and BurgerWrap>=0: PQ1=(BBRC*QTY) BEEFBURGERREGCOMBO=BEEFBURGERREGCOMBO+QTY else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Beef Burger Regular Combo that is available with the stock given.") print ("Burger Bun:",BurgerBun+QTY) print ("Beef Burger Patty:",BeefBurgerPatty+QTY) print ("Burger Wrap:",BurgerWrap+QTY) print ("Regular Soda Cup:",RegularSodaCup+QTY) print ("Regular Fries:",RegularFries+QTY) else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Beef Burger Regular Combo that is available with the stock given.") print ("Burger Bun:",BurgerBun) print ("Beef Burger Patty:",BeefBurgerPatty) print ("Burger Wrap:",BurgerWrap) print ("Regular Soda Cup:",RegularSodaCup) print ("Regular Fries:",RegularFries) ####################### #Task: Computes the total price for the quantity and the product product price and decrease the stock that makes up the product #whenever a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program #continues, it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again #because it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the #first order and add the number of the product sold in the first order. #Variables Used: Order,QTY,BurgerBun,BeefBurgerPatty,LargeFries,LargeSodaCup,BEEFBURGERLARGCOMBO,BurgerWrap,PQ1 #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### elif Order=="BBLC": if LargeSodaCup>=QTY and LargeFries>=QTY and BurgerBun>=QTY and BeefBurgerPatty>=QTY and BurgerWrap>=QTY: print(QTY,"Beef Burger Large Combo-",(BBLC*QTY)) BurgerBun=BurgerBun-QTY BeefBurgerPatty=BeefBurgerPatty-QTY BurgerWrap=BurgerWrap-QTY LargeFries=LargeFries-QTY LargeSodaCup=LargeSodaCup-QTY if LargeSodaCup>=0 and LargeFries>=0 and BurgerBun>=0 and BeefBurgerPatty>=0 and BurgerWrap>=0: PQ1=(BBLC*QTY) BEEFBURGERLARGCOMBO=BEEFBURGERLARGCOMBO+QTY else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Beef Burger Large Combo that is available with the stock given.") print ("Burger Bun:",BurgerBun+QTY) print ("Beef Burger Patty:",BeefBurgerPatty+QTY) print ("Burger Wrap:",BurgerWrap+QTY) print ("Large Soda Cup:",LargeSodaCup+QTY) print ("Large Fries:",LargeFries+QTY) else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Beef Burger Large Combo that is available with the stock given.") print ("Burger Bun:",BurgerBun) print ("Beef Burger Patty:",BeefBurgerPatty) print ("Burger Wrap:",BurgerWrap) print ("Large Soda Cup:",LargeSodaCup) print ("Large Fries:",LargeFries) ####################### #Task: Computes the total price for the quantity and the product product price and decrease the stock that makes up the product #whenever a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program #continues, it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again #because it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the #first order and add the number of the product sold in the first order. #Variables Used: Order,QTY,BurgerBun,RegularFries,RegularSodaCup,ChickenBurgerPatty,CHICKENBURGERREGCOMBO,BurgerWrap,PQ1 #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### elif Order=="CBRC": if RegularSodaCup>=QTY and RegularFries>=QTY and BurgerBun>=QTY and ChickenBurgerPatty>=QTY and BurgerWrap>=QTY: print(QTY,"Chicken Burger Regular Combo-",(CBRC*QTY)) BurgerBun=BurgerBun-QTY ChickenBurgerPatty=ChickenBurgerPatty-QTY BurgerWrap=BurgerWrap-QTY RegularFries=RegularFries-QTY RegularSodaCup=RegularSodaCup-QTY if RegularSodaCup>=0 and RegularFries>=0 and BurgerBun>=0 and ChickenBurgerPatty>=0 and BurgerWrap>=0: PQ1=(CBRC*QTY) CHICKENBURGERREGCOMBO=CHICKENBURGERREGCOMBO+QTY else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Chioken Burger Regular Combo that is available with the stock given.") print ("Burger Bun:",BurgerBun+QTY) print ("Chicken Burger Patty:",ChickenBurgerPatty+QTY) print ("Burger Wrap:",BurgerWrap+QTY) print ("Regular Soda Cup:",RegularSodaCup+QTY) print ("Regular Fries:",RegularFries+QTY) else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Chioken Burger Regular Combo that is available with the stock given.") print ("Burger Bun:",BurgerBun) print ("Chicken Burger Patty:",ChickenBurgerPatty) print ("Burger Wrap:",BurgerWrap) print ("Regular Soda Cup:",RegularSodaCup) print ("Regular Fries:",RegularFries) ####################### #Task: Computes the total price for the quantity and the product product price and decrease the stock that makes up the product #whenever a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program #continues, it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again #because it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the #first order and add the number of the product sold in the first order. #Variables Used: Order,QTY,BurgerBun,CHICKENBURGERLARGCOMBO,LargeFries,LargeSodaCup,BeefBurgerPatty,BurgerWrap,PQ1,BEEFBURGER #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### elif Order=="CBLC": if LargeSodaCup>=QTY and LargeFries>=QTY and BurgerBun>=QTY and ChickenPatty>=QTY and BurgerWrap>=QTY: print(QTY,"Chicken Burger Large Combo-",(CBLC*QTY)) BurgerBun=BurgerBun-QTY ChickenBurgerPatty=ChickenBurgerPatty-QTY BurgerWrap=BurgerWrap-QTY LargeFries=LargeFries-QTY LargeSodaCup=LargeSodaCup-QTY if LargeSodaCup>=0 and LargeFries>=0 and BurgerBun>=0 and ChickenPatty>=0 and BurgerWrap>=0: PQ1=(CBLC*QTY) CHICKENBURGERLARGCOMBO=CHICKENBURGERLARGCOMBO+QTY else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Chicken Burger Large Burger that is available with the stock given.") print ("Burger Bun:",BurgerBun+QTY) print ("Chicken Burger Patty:",ChickenBurgerPatty+QTY) print ("Burger Wrap:",BurgerWrap+QTY) print ("Large Soda Cup:",LargeSodaCup+QTY) print ("Large Fries:",LargeFries+QTY) else: print("Here is the remaining amount of stocks. Please enter the appropriate amount of Chicken Burger Large Burger that is available with the stock given.") print ("Burger Bun:",BurgerBun) print ("Chicken Burger Patty:",ChickenBurgerPatty) print ("Burger Wrap:",BurgerWrap) print ("Large Soda Cup:",LargeSodaCup) print ("Large Fries:",LargeFries) ####################### #Task: Getting the next order or multiple orders for the same customer #Description: You will input if the same customer has another order or not #Variables Used: MoreOrder #Outputs: Another order or the end of the day report ####################### MoreOrder=input("Is there another order for the same customer? Type Y if yes or N if no") while MoreOrder=="Y" or MoreOrder=="y": ####################### #Task: Getting the order and how many orders the second time #Description: This determines the second or more orders and how many orders will there be #Variables Used: Order2,NQTY #Outputs: How many orders a customer orders and the orders itself ####################### Order2=input("Please enter the additional order of your customer") NQTY=int(input("How many orders?")) ####################### #Task: Computes the total price of multiple orders for the quantity and the product product price and decrease the stock that #makes up the product whenever a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program #continues, it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again #because it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the #first order and add the number of the product sold in the first order. #and in the end if there is another order, it will ask again #Variables Used: Order,NQTY,BurgerBun,BeefBurgerPatty,BurgerWrap,PQ1,BEEFBURGER #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### if Order2=="BB": if BurgerBun>=NQTY and BeefBurgerPatty>=NQTY and BurgerWrap>=NQTY: print(NQTY,"Beef Burger-",(BB*NQTY)) BurgerBun=BurgerBun-NQTY BeefBurgerPatty=BeefBurgerPatty-NQTY BurgerWrap=BurgerWrap-NQTY if BurgerBun>=0 and BeefBurgerPatty>=0 and BurgerWrap>=0: PQ=(BB*NQTY) BEEFBURGER=BEEFBURGER+NQTY else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of Beef Burgers that is available with the stock given.") print ("Burger Bun:",BurgerBun+NQTY) print ("Beef Burger Patty:",BeefBurgerPatty+NQTY) print ("Burger Wrap:",BurgerWrap+NQTY) else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of Beef Burgers that is available with the stock given.") print ("Burger Bun:",BurgerBun) print ("Beef Burger Patty:",BeefBurgerPatty) print ("Burger Wrap:",BurgerWrap) ####################### #Task: Computes the total price of multiple orders for the quantity and the product product price and decrease the stock that makes #up the product whenever a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program #continues, it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again #because it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the #first order and add the number of the product sold in the first order. #and in the end if there is another order, it will ask again #Variables Used: Order,NQTY,BurgerBun,ChickenBurgerPatty,BurgerWrap,PQ1,CHICKENBURGER #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### elif Order2=="CB": if BurgerBun>=NQTY and ChickenBurgerPatty>=NQTY and BurgerWrap>=NQTY: print(NQTY,"Chicken Burger-",(CB*NQTY)) BurgerBun=BurgerBun-NQTY ChickenBurgerPatty=ChickenBurgerPatty-NQTY BurgerWrap=BurgerWrap-NQTY if BurgerBun>=0 and ChickenBurgerPatty>=0 and BurgerWrap>=0: PQ=(CB*NQTY) CHICKENBURGER=CHICKENBURGER+NQTY else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of CHicken Burgers that is available with the stock given.") print ("Burger Bun:",BurgerBun+NQTY) print ("Chicken Burger Patty:",ChickenBurgerPatty+NQTY) print ("Burger Wrap:",BurgerWrap+NQTY) else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of CHicken Burgers that is available with the stock given.") print ("Burger Bun:",BurgerBun) print ("Chicken Burger Patty:",ChickenBurgerPatty) print ("Burger Wrap:",BurgerWrap) ####################### #Task: Computes the total price of multiple orders for the quantity and the product product price and decrease the stock that makes #up the product whenever a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program #continues, it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again #because it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the #first order and add the number of the product sold in the first order. #and in the end if there is another order, it will ask again #Variables Used: Order,NQTY,RegularFries,PQ1,REGULARFRIES #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### elif Order2=="RF": if RegularFries>=NQTY: print(NQTY,"Regular Fries-",(RF*NQTY)) RegularFries=RegularFries-NQTY if RegularFries>=0: PQ=(RF*NQTY) REGULARFRIES=REGULARFRIES+NQTY else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of Regular Fries that is available with the stock given.") print ("Regular Fries:",RegularFries+NQTY) else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of Regular Fries that is available with the stock given.") print ("Regular Fries:",RegularFries) ####################### #Task: Computes the total price of multiple orders for the quantity and the product product price and decrease the stock that makes up #the product whenever a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program #continues, it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again #because it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the #first order and add the number of the product sold in the first order. #and in the end if there is another order, it will ask again #Variables Used: Order,NQTY,LARGEFRIES,PQ1,LargeFries #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### elif Order2=="LF": if LargeFries>=NQTY: print(NQTY,"Large Fries-",(LF*NQTY)) LargeFries=LargeFries-NQTY if LargeFries>=0: PQ=(LF*NQTY) LARGEFRIES=LARGEFRIES+NQTY else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of Large Fries that is available with the stock given.") print ("Large Fries:",LargeFries+NQTY) else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of Large Fries that is available with the stock given.") print ("Large Fries:",LargeFries) ####################### #Task: Computes the total price of multiple orders for the quantity and the product product price and decrease the stock that makes #up the product whenever a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program #continues, it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again #because it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the #first order and add the number of the product sold in the first order. #and in the end if there is another order, it will ask again #Variables Used: Order,NQTY,REGULARSODA,PQ1,RegularSoda #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### elif Order2=="RS": if RegularSodaCup>=NQTY: print(NQTY,"Regular Soda-",(RS*NQTY)) RegularSodaCup=RegularSodaCup-NQTY if RegularSodaCup>=0: PQ=(RS*NQTY) REGULARSODA=REGULARSODA+NQTY else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of Regular Soda that is available with the stock given.") print ("Regular Soda Cup:",RegularSodaCup+NQTY) else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of Regular Soda that is available with the stock given.") print ("Regular Soda Cup:",RegularSodaCup) ####################### #Task: Computes the total price of multiple orders for the quantity and the product product price and decrease the stock that makes up #the product whenever a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program #continues, it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again #because it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the #first order and add the number of the product sold in the first order. #and in the end if there is another order, it will ask again #Variables Used: Order,NQTY,LargeSoda,PQ1,LARGESODA #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### elif Order2=="LS": if LargeSodaCup>=NQTY: print(NQTY,"Large Soda-",(LS*NQTY)) LargeSodaCup=LargeSodaCup-NQTY if LargeSodaCup>=0: PQ=(LS*NQTY) LARGESODA=LARGESODA+NQTY else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of Large Soda that is available with the stock given.") print ("Large Soda Cup:",LargeSodaCup+NQTY) else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of Large Soda that is available with the stock given.") print ("Large Soda Cup:",LargeSodaCup) ####################### #Task: Computes the total price of multiple orders for the quantity and the product product price and decrease the stock that makes up #the product whenever a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program #continues, it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again #because it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the #first order and add the number of the product sold in the first order. #and in the end if there is another order, it will ask again #Variables Used: Order,NQTY,BurgerBun,BeefBurgerPatty,BurgerWrap,RegularSodaCup,RegularFries,PQ1,BEEFBURGERREGCOMBO #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### elif Order2=="BBRC": if RegularSodaCup>=NQTY and RegularFries>=NQTY and BurgerBun>=NQTY and BeefBurgerPatty>=NQTY and BurgerWrap>=NQTY: print(NQTY,"Beef Burger Regular Combo-",(BBRC*NQTY)) BeefBurgerPatty=BeefBurgerPatty-NQTY BurgerWrap=BurgerWrap-NQTY BurgerBun=BurgerBun-NQTY RegularFries=RegularFries-NQTY RegularSodaCup=RegularSodaCup-NQTY if RegularSodaCup>=0 and RegularFries>=0 and BurgerBun>=0 and BeefBurgerPatty>=0 and BurgerWrap>=0: PQ=(BBRC*NQTY) BEEFBURGERREGCOMBO=BEEFBURGERREGCOMBO+NQTY else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of Beef Burgers Regular Combo that is available with the stock given.") print ("Burger Bun:",BurgerBun+NQTY) print ("Beef Burger Patty:",BeefBurgerPatty+NQTY) print ("Burger Wrap:",BurgerWrap+NQTY) print ("Regular Soda Cup:",RegularSodaCup+NQTY) print ("Regular Fries:",RegularFries+NQTY) else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of Beef Burgers Regular Combo that is available with the stock given.") print ("Burger Bun:",BurgerBun) print ("Beef Burger Patty:",BeefBurgerPatty) print ("Burger Wrap:",BurgerWrap) print ("Regular Soda Cup:",RegularSodaCup) print ("Regular Fries:",RegularFries) ####################### #Task: Computes the total price of multiple orders for the quantity and the product product price and decrease the stock that makes up #the product whenever a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program #continues, it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again #because it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the #first order and add the number of the product sold in the first order. #and in the end if there is another order, it will ask again #Variables Used: Order,NQTY,BurgerBun,BeefBurgerPatty,LargeFries,LargeSodaCup,BEEFBURGERLARGCOMBO,BurgerWrap,PQ1 #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### elif Order2=="BBLC": if LargeSodaCup>=NQTY and LargeFries>=NQTY and BurgerBun>=NQTY and BeefBurgerPatty>=NQTY and BurgerWrap>=NQTY: print(NQTY,"Beef Burger Large Combo-",(BBLC*NQTY)) BurgerBun=BurgerBun-NQTY BeefBurgerPatty=BeefBurgerPatty-NQTY BurgerWrap=BurgerWrap-NQTY LargeFries=LargeFries-NQTY LargeSodaCup=LargeSodaCup-NQTY if LargeSodaCup>=0 and LargeFries>=0 and BurgerBun>=0 and BeefBurgerPatty>=0 and BurgerWrap>=0: PQ=(BBLC*NQTY) BEEFBURGERLARGCOMBO=BEEFBURGERLARGCOMBO+NQTY else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of Beef Burgers Large Combo that is available with the stock given.") print ("Burger Bun:",BurgerBun+NQTY) print ("Beef Burger Patty:",BeefBurgerPatty+NQTY) print ("Burger Wrap:",BurgerWrap+NQTY) print ("Large Soda Cup:",LargeSodaCup+NQTY) print ("Large Fries:",LargeFries+NQTY) else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of Beef Burgers Large Combo that is available with the stock given.") print ("Burger Bun:",BurgerBun) print ("Beef Burger Patty:",BeefBurgerPatty) print ("Burger Wrap:",BurgerWrap) print ("Large Soda Cup:",LargeSodaCup) print ("Large Fries:",LargeFries) ####################### #Task: Computes the total price of multiple orders for the quantity and the product product price and decrease the stock that makes up #the product whenever a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program #continues, it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again #because it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the #first order and add the number of the product sold in the first order. #and in the end if there is another order, it will ask again #Variables Used: Order,NQTY,BurgerBun,RegularFries,RegularSodaCup,ChickenBurgerPatty,CHICKENBURGERREGCOMBO,BurgerWrap,PQ1 #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### elif Order2=="CBRC": if RegularSodaCup>=NQTY and RegularFries>=NQTY and BurgerBun>=NQTY and ChickenBurgerPatty>=NQTY and BurgerWrap>=NQTY: print(NQTY,"Chicken Burger Regular Combo-",(CBRC*NQTY)) BurgerBun=BurgerBun-NQTY ChickenBurgerPatty=ChickenBurgerPatty-NQTY BurgerWrap=BurgerWrap-NQTY RegularFries=RegularFries-NQTY RegularSodaCup=RegularSodaCup-NQTY if RegularSodaCup>=0 and RegularFries>=0 and BurgerBun>=0 and ChickenBurgerPatty>=0 and BurgerWrap>=0: PQ=(CBRC*NQTY) CHICKENBURGERREGCOMBO=CHICKENBURGERREGCOMBO+NQTY else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of Chicken Burger Regular Combo that is available with the stock given.") print ("Burger Bun:",BurgerBun+NQTY) print ("Chicken Burger Patty:",ChickenBurgerPatty+NQTY) print ("Burger Wrap:",BurgerWrap+NQTY) print ("Regular Soda Cup:",RegularSodaCup+NQTY) print ("Regular Fries:",RegularFries+NQTY) else: PQ=0 print ("Here is the remaining amount of stocks. Please enter the appropriate amount of Chicken Burger Regular Combo that is available with the stock given.") print ("Burger Bun:",BurgerBun) print ("Chicken Burger Patty:",ChickenBurgerPatty) print ("Burger Wrap:",BurgerWrap) print ("Regular Soda Cup:",RegularSodaCup) print ("Regular Fries:",RegularFries) ####################### #Task: Computes the total price of multiple orders for the quantity and the product product price and decrease the stock that makes up #the product whenever a product is sold and adds #the number of products will increase and display at the end of the day report for the number of a certain product is sold. #Description: If the order is a beef burger then it will continue the program or tell that there is no more stock. If the program #continues, it wll get the total price of the order #and subtract the quantity of the stock and if the stock is less than zero, it will display the remaining stock by adding it again #because it was first subtracted so when you add it again, #it will display the original stocks before subtracting it. If not, the total price will be stored and added to A as the sum of the #first order and add the number of the product sold in the first order. #and in the end if there is another order, it will ask again #Variables Used: Order,NQTY,BurgerBun,CHICKENBURGERLARGCOMBO,LargeFries,LargeSodaCup,BeefBurgerPatty,BurgerWrap,PQ1,BEEFBURGER #Outputs: Either the remaining stock or the order will be processed and be stored to another variable at the end ####################### elif Order2=="CBLC": if LargeSodaCup>=NQTY and LargeFries>=NQTY and BurgerBun>=NQTY and ChickenBurgerPatty>=NQTY and BurgerWrap>=NQTY: print(NQTY,"Chicken Burger Large Combo-",(CBLC*NQTY)) BurgerBun=BurgerBun-NQTY ChickenBurgerPatty=ChickenBurgerPatty-NQTY BurgerWrap=BurgerWrap-NQTY LargeFries=LargeFries-NQTY LargeSodaCup=LargeSodaCup-NQTY if LargeSodaCup>=0 and LargeFries>=0 and BurgerBun>=0 and ChickenBurgerPatty>=0 and BurgerWrap>=0: PQ=(CBLC*NQTY) CHICKENBURGERLARGCOMBO=CHICKENBURGERLARGCOMBO+NQTY else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of Chicken Burger Large Combo that is available with the stock given.") print ("Burger Bun:",BurgerBun+NQTY) print ("Chicken Burger Patty:",ChickenBurgerPatty+NQTY) print ("Burger Wrap:",BurgerWrap+NQTY) print ("Large Soda Cup:",LargeSodaCup+NQTY) print ("Large Fries:",LargeFries+NQTY) else: PQ=0 print("Here is the remaining amount of stocks. Please enter the appropriate amount of Chicken Burger Large Combo that is available with the stock given.") print ("Burger Bun:",BurgerBun) print ("Chicken Burger Patty:",ChickenBurgerPatty) print ("Burger Wrap:",BurgerWrap) print ("Large Soda Cup:",LargeSodaCup) print ("Large Fries:",LargeFries) ####################### #Task: Adds the first order Total price to A and determining if there is another customer #Description: The PQ is the first order and it adds to A to store how much A has and then adds to the total price when there is a problem. #Variables Used: A,PQ,MoreOrder #Outputs: At the end of the if program to get the receipt, it will add to the Total price. ####################### A=A+PQ MoreOrder=input("Is there another order for the same customer? Type Y if yes or N if no") print ("") ####################### #Task: Getting the Total Price and adding 1 to customer or be equal to itself if there is no actual order #Description: This adds PQ1 and the Total price and determines whether there is a customer or not #Variables Used: TotalPrice,A,PQ1,customer #Outputs: Displays the customer amount ####################### TotalPrice=A+PQ1 if TotalPrice==0: customer==customer else: customer=customer+1 print ("Customer",customer) print("Total amount:",TotalPrice) ####################### #Task: This will process the payment #Description: When the Total price is greater than zero, the program will process the payment and ask for the payment. #if you pay less than the total price, you will enter again the correct amount or it will continue the prohram and get the change #If there is another customer, the program will repeat taking the next customer #Variables Used: TotalPrice,AmountPay,Change,countercustomer #Outputs: How much you paid and the change ####################### if TotalPrice>0: AmountPay=int(input("Amount Received:")) while AmountPay<TotalPrice: AmountPay=int(input("Enter again Amount Received:")) Change=AmountPay-TotalPrice print ("Change:", Change) print("") countercustomer=input("Enter y if there is a customer. if none, press any key and click enter=)") ####################### #Task: The variables here are for storing the amount of the total price of the products sold #Description: Each variable is multiplied by its original price and will store each of the total price of the products #Variables Used: D,E,F,G,H,I,J,K,L,M,BB,CB,RF,LF,LS,RS,BBRC,BBLC,CBRC,CBLC,BEEFBURGER,CHICKENBURGER,REGULARFRIES,REGULARSODA, #LARGESODA,LARGEFRIES,BEEFBURGERREGCOMBO, #BEEFBURGERLARGCOMBO,CHICKENBURGERREGCOMBO,CHICKENBURGERLARGCOMBO #Outputs: It will output at the end of the day report and will display how much of a product was sold ####################### D=BB*BEEFBURGER E=CB*CHICKENBURGER F=RF*REGULARFRIES G=LF*LARGEFRIES H=RS*REGULARSODA I=LS*LARGESODA J=BBRC*BEEFBURGERREGCOMBO K=BBLC*BEEFBURGERLARGCOMBO L=CBRC*CHICKENBURGERREGCOMBO M=CBLC*CHICKENBURGERLARGCOMBO ####################### #Task: Displaying the end of the day report for each product sold, the price of the product and the total product price and #displays the number of customers that paid for the day. #Description: Displaying the number of products sold and it adds up as the loop program is taking place. it also displays the #computed total price of each products. #Variables Used: D,E,F,G,H,I,J,K,L,M,BB,CB,RF,LF,LS,RS,BBRC,BBLC,CBRC,CBLC,BEEFBURGER,CHICKENBURGER,REGULARFRIES,REGULARSODA, #LARGESODA,LARGEFRIES,BEEFBURGERREGCOMBO, #BEEFBURGERLARGCOMBO,CHICKENBURGERREGCOMBO,CHICKENBURGERLARGCOMBO,TPA #Outputs: Number of products sold, their price and their Total price for each product ####################### TPA=D+E+F+G+H+I+J+K+L+M print ("DAY END REPORT") print ("TOTAL CUSTOMERS:",customer) print ("Sales") print ("Beef Burger sold:",BEEFBURGER," ","P",BB," ",(D) ) print ("Chicken Burger sold:",CHICKENBURGER," ","P",CB," ",(E)) print ("Regular Fries sold:",REGULARFRIES," ","P",RF," ",(F)) print ("Large Fries sold:",LARGEFRIES," ","P",LF," ",(G)) print ("Regular Soda sold:",REGULARSODA," ","P",RS," ",(H)) print ("Large Soda sold:",LARGESODA," ","P",LS ," ",(I)) print ("Beef Burger Regular Combo sold:",BEEFBURGERREGCOMBO," ","P",BBRC," ",(J)) print ("Beef burger Large Combo sold:",BEEFBURGERLARGCOMBO," ","P",BBLC," ",(K)) print ("Chicken burger Regular Combo sold:",CHICKENBURGERREGCOMBO," ","P",CBRC," ",(L)) print ("Chicken burger Large Combo sold:",CHICKENBURGERLARGCOMBO," ","P",CBLC," ",(M)) ####################### #Task: Display the Total Sale and the Final Inventory #Description: The final inventory will be displayed because it was subtracted from the original inventory. every time a product is sold #Variables Used: BurgerBun,BeefBurgerPatty,ChickenBurgerPatty,RegularFries,LargeFries, #BurgerWrap,RegularSodaCup,LargeSodaCup #Outputs: Display the Total Sale and the Final Inventory ####################### print ("Total Sale:",TPA) print ("Final Inventory:") print ("Burger Bun:"," ",BurgerBun) print ("Beef Burger Patty:"," ",BeefBurgerPatty) print ("Chicken Burger Patty:"," ",ChickenBurgerPatty) print ("Regular Soda Cup:"," ",RegularSodaCup) print ("Large Soda Cup:"," ",LargeSodaCup) print ("Regular Fries"," ",RegularFries) print ("Large Fries"," ",LargeFries) print ("Burger Wrap:"," ",BurgerWrap)
'''Exercise 3: Peso to Dollar converter given exchange rate''' Peso=input('Please enter amount in Peso(s): ') Peso=float(Peso) ExRate=input('Please enter exchange rate in decimal(not in percent): ') ExRate=float(ExRate) Dollar=Peso*ExRate print(str(Peso),'Peso(s) to Dollar(s) is', Dollar,"Dollars")
#LCM gcd=1 num1=int(input('number1: ')) num2=int(input('number2: ')) factor=2 while num1 >= factor and num2 >= factor: while num1%factor==0 and num2%factor==0: gcd=gcd*factor num1//=factor num2//=factor factor+=1 lcm=gcd*num1*num2 print(lcm)
''' 2. Simple Calculator ''' strInput=input('Input the first number: ') first= float(strInput) strInput=input('Input the operation: ') operax=strInput strInput=input('Input the second number: ') second= float(strInput) if operax=="+": ans=first+second print('the answer is',ans) elif operax=="-": ans=first-second print('the answer is',ans) elif operax=="x": ans=first*second print('the answer is',ans) elif operax=="/": if second==0: print('The answer is undefined') else: ans=first/second print('The answer is',ans)
''' 14. How Old Are You? Write a program that asks for the current date (as an integer assuming the format mmddyyyy). You may use the numbers 1-12 to represent the month for convenience. After that, the program should also ask for the birthday of the user (as an integer assuming the format mmddyyyy). The program should display how old the user is. For example, if today is September 18, 2015 and the user's birthday is September 29, 1992, then the user is 22 years old. ''' strInput=input('enter current date (mmddyyyy): ') cdate=int(strInput) strInput=input('enter birth date (mmddyyyy): ') bdate=int(strInput) cmonth= cdate// 1000000 cday= cdate//10000%100 cyear= cdate% 10000 bmonth= bdate//1000000 bday= bdate//10000%100 byear= bdate%10000 age= cyear-byear if cmonth > bmonth: print(age,'years old') elif cmonth==bmonth: if cday < bday: age=age-1 print(age,'years old') else: print(age-1) #shorter code: strInput=input('enter current date (mmddyyyy): ') cdate=int(strInput) strInput=input('enter birth date (mmddyyyy): ') bdate=int(strInput) cmonth= cdate// 1000000 cday= cdate//10000%100 cyear= cdate% 10000 bmonth= bdate//1000000 bday= bdate//10000%100 byear= bdate%10000 age= cyear-byear if cmonth >= bmonth: if cday < bday: age=age-1 print(age,'years old') else: print(age-1)
''' Exercise 3 Write a program that converts a military time input to its equivalent 12-hour format. Note that: The input of the user is an integer assuming the format hhmm. The valid hour value in the military time format is [00; 23]. The valid minute value in the military time format is [00; 59]. Only valid military time inputs will be converted to the equivalent 12-hour format. Display an error message for invalid input. ''' strInput=input('enter military time (hhmm): ') milTime=int(strInput) hh= milTime//100 mm= milTime%100 if (hh >= 0 and hh <= 23) and (mm >= 0 and mm <= 59): if hh > 12: POD = "PM" #POD stands for period of the day else: POD = "AM" if hh%12 == 0 or mm % 60 == 0: hh= 12 print(str(hh)+':'+str(mm),POD) else: hh=hh%12 print(str(hh)+':'+str(mm),POD) else: print ('Invalid input') #without ":" output strInput=input('enter military time (hhmm): ') milTime=int(strInput) hh= milTime//100 mm= milTime%100 if (hh >= 0 and hh <= 23) and (mm >= 0 and mm <= 59): if hh > 12: POD = "PM" #POD stands for period of the day else: POD = "AM" if hh%12 == 0 or mm % 60 == 0: hh= 12 if mm < 10: print(str(hh)+':0'+str(mm),POD) else: print(str(hh)+':'+str(mm),POD) else: hh=hh%12 print(str(hh)+':'+str(mm),POD) else: print ('Invalid input')
n=int(input("n: ")) copy=n k=1 while k <= n: j=1 cnt=1 while j <= n: if j >= copy: print(cnt,"",end="") cnt+=1 else: print(" ",end="") j+=1 copy-=1 k+=1 print() print() copy=1 k=1 while k <= n: j=1 cnt=1 while j <= n: if j >= copy: print(cnt,"",end="") cnt+=1 else: print(" ",end="") j+=1 copy+=1 k+=1 print()
time = int(input("What's the time in military format? (HHMM) ")) if time >= 0000 and time < 100: print(time + 1200, "AM") elif time >= 100 and time < 1200: print(time, "AM") elif time >= 1200 and time <= 1259: print(time, "PM") else: print(time - 1200, "PM")
#Fahrenheit to Celsius Fahrenheit=input('Please enter temperature in degrees Fahrenheit: ') Fahrenheit=float(Fahrenheit) Celsius=(Fahrenheit-32)*5/9 print(Fahrenheit,'degrees Fahrenheit is equivalent to',Celsius,'degrees Celsius')
length = int(input("What's the length of the rectangle? ")) width = int(input("What's the width of the rectangle? ")) ask = input("Would you like to compute for (a) the area or (b) the perimeter? (a/b) ") if ask == "a": print("The rectangle's area is", length * width, "square meters.") else: print("The rectangle's perimeter is", 2 * length + 2 * width, "meters.")
''' 12. Write a program that will allow the user to enter a positive integer value. The program displays the digits of this value in reverse order. Enter a number: 1234 Display in reverse: 4321 Enter a number: 34530 Display in reverse: 03543 ''' place='' n= int(input('Enter a number: ')) while n > 0: digit= n%10 convert= str(digit) place= place+convert n= n//10 print('Display in reverse:',place)
############################################### def binary2deci(binaryN): powerOf2=1 deciConvert=0 while binaryN > 0: binary = binaryN%10 binaryN//=10 deciConvert+=binary*powerOf2 powerOf2*=2 return(deciConvert) # SAMPLE x=binary2deci(11100000) # SAMPLE print(x) ############################################### binaryN=int(input("binary number: ")) powerOf2=1 deciConvert=0 while binaryN > 0: binary = binaryN%10 binaryN//=10 deciConvert+=binary*powerOf2 powerOf2*=2 print(deciConvert)
# HOMEWORK ''' 2. Write a program that will allow the user to enter a positive integer value. The program displays in reverse the even- valued digits. Enter a number: 1234 Display even-digits in reverse: 42 Enter a number: 5397131 Display even-digits in reverse: ''' place='' n= int(input('Enter a number: ')) while n > 0: digit= n%10 if digit%2==0: convert= str(digit) place= place+convert n= n//10 print('Display even-digits in reverse:',place)
# -*- coding: utf-8 -*- """ Created on Sun Dec 10 21:31:49 2017 @author: SRIJANPABBI """ #%% import numpy as np #import matplotlib.pyplot as plt import pandas as pd #%% # Importing the dataset dataset_test = pd.read_csv('test.csv') dataset_train = pd.read_csv('train.csv') dataset_train.head() dataset_train.info() #%% dataset_train = dataset_train.drop(['PassengerId','Name','Ticket','Cabin','Fare'], axis = 1) dataset_test= dataset_test.drop(['PassengerId','Name','Ticket','Cabin','Fare'], axis = 1) #%% #X_test = dataset_test.iloc[:, [0,1,3,4,5,6,8,10]].values ##y_test = dataset_test.iloc[:, 1].values #X_train = dataset_train.iloc[:, [0,2,4,5,6,7,9,11]].values #y_train = dataset_train.iloc[:, 1].values # Taking care of missing data # only in titanic_df, fill the two missing values with the most occurred value, which is "S". dataset_train["Embarked"] = dataset_train["Embarked"].fillna("S") dataset_train["Age"] = dataset_train["Age"].fillna(30) dataset_test["Embarked"] = dataset_test["Embarked"].fillna("S") dataset_test["Age"] = dataset_test["Age"].fillna(30) dataset_test["Pclass"] = dataset_test["Pclass"].fillna(3) #%% X_train = dataset_train.iloc[:,1:].values y_train = dataset_train.iloc[:,0].values X_test = dataset_test.values #%% # Encoding categorical data # Encoding the Independent Variable from sklearn.preprocessing import LabelEncoder, OneHotEncoder le1 = LabelEncoder() le2 = LabelEncoder() X_train[:,0] = le1.fit_transform(X_train[:,0]) X_test[:,0] = le2.fit_transform(X_test[:,0]) le3 = LabelEncoder() le4 = LabelEncoder() X_train[:,1] = le3.fit_transform(X_train[:,1]) X_test[:,1] = le4.fit_transform(X_test[:,1]) le5 = LabelEncoder() le6 = LabelEncoder() X_train[:,-1] = le5.fit_transform(X_train[:,-1]) X_test[:,-1] = le6.fit_transform(X_test[:,-1]) #%% from sklearn.preprocessing import Imputer imputer = Imputer(missing_values = 'NaN', strategy = 'most_frequent', axis = 0) imputer = imputer.fit(X_test) X_test = imputer.transform(X_test) #%% ohe1 = OneHotEncoder(categorical_features = [0,5]) X_train = ohe1.fit_transform(X_train).toarray() ohe2 = OneHotEncoder(categorical_features = [0,5]) X_test = ohe2.fit_transform(X_test).toarray() #%% # dummy vab trap removal #X_train = X_train[:,[1,2,4,5,6,7,8,9,10]] #X_test = X_test[:,[1,2,4,5,6,7,8,9,10]] X_train = X_train[:,[1,2,4,5,6,7,8,9,]] X_test = X_test[:,[1,2,4,5,6,7,8,9]] #%% # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) #%% # Fitting Random Forest Classification to the Training set from sklearn.ensemble import RandomForestClassifier classifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0) classifier.fit(X_train, y_train) #%% # Predicting the Test set results y_pred1 = classifier.predict(X_test) y_pred = (y_pred1>0.5) final = y_pred.astype(int) final = np.array(final) final = final.ravel() dataset_test = pd.read_csv('test.csv') dataset_train = pd.read_csv('train.csv') d = {'PassengerId' : dataset_test.iloc[:,0].values, 'Survived':final} dataframe = pd.DataFrame(data = d) dataframe.to_csv("RF_predictions.csv") #%% df = pd.read_csv("gender_submission.csv") y_test = df.iloc[:,1].values #%% # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred)
""" Description: You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. 0 <= nums.length <= 100 0 <= nums[i] <= 400 source: https://leetcode.com/problems/house-robber/ """ class Solution: def rob(self, nums: List[int]) -> int: if not nums: return 0 firstVal = nums[0] if len(nums) > 0 else 0 firstResult = firstVal + self.rob(nums[2:]) secondVal = nums[1] if len(nums) > 1 else 0 secondResult = secondVal + self.rob(nums[3:]) if firstResult > secondResult: return firstResult else: return secondResult
from turtle import * from datetime import datetime def moving(distance, angle=0): penup() right(angle) forward(distance) left(angle) pendown() def layout(lenght, vast): fd(lenght*1.15) rt(90) fd(vast/2.0) lt(120) fd(vast) lt(120) fd(vast) lt(120) fd(vast/2.0) def timer_hands(name,lenght,vast): reset() moving(-lenght*0.15) begin_poly() layout(lenght, vast) end_poly() clock_labellings=get_poly() register_shape(name, clock_labellings) def clockface(radius): reset() pensize(7) for i in range(60): moving(radius) if i % 5 == 0: fd(25) moving(-radius-25) else: dot(3) moving(-radius) rt(6) def settings(): global second_hand,minute_hand,hour_hand timer_hands("second_hand", 125, 25) timer_hands("minute_hand", 130, 25) timer_hands("hour_hand", 90, 25) clockface(160) second_hand = Turtle() second_hand.shape("second_hand") second_hand.color("gray40", "black") minute_hand=Turtle() minute_hand.shape("minute_hand") minute_hand.color("red","orange") hour_hand = Turtle() hour_hand.shape("hour_hand") hour_hand.color("red", "orange") for hand in second_hand,minute_hand,hour_hand: hand.resizemode("user") hand.shapesize(1,1,3) hand.speed(0) ht() def tick(): t=datetime.today() secondTimer=t.second+t.microsecond*0.000001 minute=t.minute+secondTimer/60.0 onTheHour=t.hour+minute/60.0 try: tracer(False) second_hand.setheading(6*secondTimer) minute_hand.setheading(6*minute) hour_hand.setheading(30*onTheHour) tracer(True) ontimer(tick, 100) except Terminator: pass def main(): tracer(False) settings() tracer(True) tick() return "DONE" if __name__ == "__main__": mode("logo") msg=main() print(msg) mainloop()
# 111 #c = input() #print(c*2) # 112 #c = int(input("숫자를 입력하세요: ")) #print(c+10) # 113 #c = int(input()) #if c % 2==0: # print('짝수') #else: # print('홀수') # 114 #c = int(input()) #d = c+20 #if d >255: # print(255) #else: # print(d) # 115 #c = int(input()) #d = c-20 #if d<0: # print(0) #elif d>255: # print(255) #else: # print(d) # 116 #a,b = input().split(':') #if b!='00': # print('정각이 아닙니다.') #else: # print('정각입니다.') # 117 #fruit = ["사과", "포도", "홍시"] #c = input('좋아하는 과일은? ') #if c in fruit: # print('정답입니다.') #else: # print('오답입니다.') # 118 #warn_investment_list = ["Microsoft", "Google", "Naver", "Kakao", "SAMSUNG", "LG"] #c = input() #if c in warn_investment_list: # print('투자경고 종목입니다.') #else: # print('투자 경고 종목이 아닙니다.') # 119 fruit = {"봄" : "딸기", "여름" : "토마토", "가을" : "사과"} c = input() #if c in fruit.keys(): # print('정답입니다.') #else: # print('오답입니다.') # 120 if c in fruit.values(): print('정답니다.') else: print('오답입니다.') # 후기 # 분기문 파트는 쉬어가는 파트인게 확실하다...
#41 from typing import Tuple ticker = "btc_krw " print(ticker.upper()) print(ticker) #ticker 자체는 변하지 않음 #42 ticker="BTC_KRW" print(ticker.lower()) #43 print('hello'.capitalize()) #44 file_name="보고서.xlsx" print(file_name.endswith('xlsx')) #45 print(file_name.endswith('xlsx' or 'xls')) print(file_name.endswith(('xlsx','xls'))) #endswith() + ('xlsx', 'xls') #46 file_name ='2020_보고서.xlsx' print(file_name.startswith('2020')) #47 a="hello world" a = a.split() print(a) #split()은 원래 변수를 변화시키는 함수는 아님 #blank가 없이 괄호만 한 경우에 공백을 기준으로 나누는 것임 #48 ticker = "btc_krw" answer = ticker.split('_') print(answer) #49 date = "2020-05-01" date = date.split("-") print("{}년 {}월 {}일" .format(date[0], date[1], date[2])) #formatting 할 때 백틱기호일 필요 없음 #50 data = "039490-" print(data.rsplit()) print(data.rstrip("-")) print(data) #51 movie_rank = ['닥터 스트레인지' ,'스플릿', '럭키'] #52 movie_rank.append("배트맨") print(movie_rank) #53 movie_rank.insert(1, "슈퍼맨") print(movie_rank) #inser(index, elements) #54 movie_rank.remove('럭키') print(movie_rank) #del movie_rank[3] #55 del movie_rank[2:] print(movie_rank) #[start : end(x) : step] #56 lang1 = ["C","C++", "JAVA"] lang2 = ["Python", "Go" ,"C#"] langs = lang1 + lang2 print(langs) #배열에서 extend 함수는 뭐지 #57 nums = [1,2,3,4,5,6,7] print("min : " + str(min(nums))) print("max : " + str(max(nums))) # print("3"+3) : 자바랑 다르게 자동형변환이 안되는건가? print("max : ", max(nums)) print("min : ", min(nums)) #와우와우 : 자료형이 다른 건 +로 연결할 수 없지만 ,로 연결할 수 있음 #58 nums = [1,2,3,4,5] print(sum(nums)) #59 cook = ["피자", "김밥", '만두','양념치킨','족발','피자','김치만두','쫄면','쏘세지','라면','팥빙수','김치전'] print(len(cook)) #60 nums = [1,2,3,4,5] average = sum(nums)/len(nums) print(average) #61 price =['20180728','100','130','140','150','160','170'] print(price[1:]) #슬라이싱 [start : end : step] price.pop(0) print(price) #pop()이면 가장 마지막 index를 지우고, 괄호 안에 인덱스를 지정하면 그것을 지움 #62 nums = [1,2,3,4,5,6,7,8,9,10] print(nums[::2]) #63 print(nums[1::2]) #64 nums = [1,2,3,4,5] print(nums[::-1]) print(nums[-1::]) #이렇게 하면 5만 나옴 #65 interest = ['삼성전자' ,'lg전자','Naver'] print(interest[::2]) print(interest[0],interest[2]) #66 interest = ['삼성전자', '엘지전자','네이버','sk하이닉스','미래에셋대우'] print(" ".join(interest)) print("".join(interest)) #67 print("/".join(interest)) #68 print("\n".join(interest)) #69 string="삼성전자/lg전자/naver" interest=string.split("/") print(interest) #70 data=[2,4,3,1,5,10,9] print(data.sort()) print(data) #sort는 원래 리스트 자체를 바꿈 return은 none임 data=[2,4,3,1,5,10,9] print(sorted(data)) print(data) #sorted는 원래 리스트를 바꾸지 않음 #71 my_variable = () print(type(my_variable)) #72 movie_rank = ("닥터 스트레인지" ,"스플릿" ,"럭키") print(movie_rank, type(movie_rank)) #73 tuple_ex = (1) print(tuple_ex, type(tuple_ex)) tuple_ex =(1,) print(tuple_ex, type(tuple_ex)) #데이터를 하나만 저장하는 튜플의 경우 쉼표를 입력해야함 #74 #튜플은 요소 변경이 불가능하다 #75 t=1,2,3,4 print(type(t), t) #튜플은 괄호없이도 동작합니다 #76 t=('a','b','c') print(t[0]) #튜플은 요소를 변경할 수 없음. 다만 변수가 새로운 튜플을 가르키도록 할 수 있음 t=("A",'b','c') print(t) #77 interest=("삼성전자", "엘지전자" ,'sk hynix') print(interest) data=list(interest) print(data) #78 interest = ["삼성전자", 'lg전자','sk hynix'] data = tuple(interest) print(data) #79 temp = ('apple', 'banana', 'cake') a, b, c = temp print(a, b, c) print(a) print(b) print(c) #80 data = tuple(range(2,100,2)) data2 = list(range(2,100,2)) print(data) print(data2) data3 = tuple(range(5)) print(data3)
# 251 # 클래스 = # 객체 = # 인스턴스 = # 252 class Human: pass # 253 class Human: pass areum = Human() # 254 class Human: def __init__(self): print('응애응애') areum = Human() # 255 class Human: def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender areum = Human("아름", 25, "여자") 256 class Human: def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender areum = Human("아름", 25, "여자") print(areum.name, areum.age, areum.gender) # 257 class Human: def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender def who(self): print(self.name, self.age, self.gender) areum = Human("아름", 25, "여자") areum.who() # 258 class Human: def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender def setInfo(self, name, age, gender): self.name = name self.age = age self.gender = gender def who(self): print(f'이름 : {self.name} , 나이 : {self.age} , 성별 : {self.gender}') areum = Human("모름", 0, "모름") areum.who() areum.setInfo("아름", 25, "여자") areum.who() # 259 class Human: def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender def __del__(self): print('나의 죽음을 알리지 마라') areum = Human("아름", 25, "여자") # del areum del(areum) # 260 # class OMG : # def print() : # print("Oh my god") # OMG 객체 내의 메소드내에 self라는 매개 변수가 없어서 에러가 발생 class OMG : def print(self) : print("Oh my god") mystock = OMG() mystock.print() # 261 class Stock: pass # 262 class Stock: def __init__(self, name, code): self.name = name self.code = code 삼성 = Stock("삼성전자", "005930") print(삼성.name) print(삼성.code) # 263 class Stock: def __init__(self, name, code): self.name = name self.code = code def set_name(self, name): self.name = name a = Stock(None, None) print(a.name) a.set_name('samsung') print(a.name) # 264 class Stock: def __init__(self, name, code): self.name = name self.code = code def set_name(self, name): self.name = name def set_code(self, code): self.code = code a = Stock(None, None) print(a.code) a.set_code("005930") print(a.code) # 265 class Stock: def __init__(self, name, code): self.name = name self.code = code def get_name(self): return self.name def get_code(self): return self.code a = Stock('삼성', '005930') print('종목명 :', a.get_name()) print('종목코드 :', a.get_code()) # 266 # 종목명, 종목코드, PER, PBR, 배당수익률 class Stock : def __init__(self, name, code, PER, PBR, 배당수익률): self.name = name self.code = code self.PER = PER self.PBR = PBR self.배당수익률 = 배당수익률 # 267 # 삼성전자, 0059430, 15.79, 1.33, 2.83 class Stock: def __init__(self, name, code, PER, PBR, ratio) : self.name = name self.code = code self.PER = PER self.PBR = PBR self.ratio = ratio stock = Stock('삼성전자', '0059430', 15.79, 1.33, 2.83) print(stock.name, stock.code, stock.PER, stock.PBR, stock.ratio) # 268 class Stock: def __init__(self, name, code, PER, PBR, dividend): self.name = name self.code = code self.PER = PER self.PBR = PBR self.dividend = dividend def set_per(self, PER) : self.PER = PER def set_pbr(self, PBR): self.PBR = PBR def set_dividend(self, dividend): self.dividend = dividend # 269 class Stock: def __init__(self, name, code, PER, PBR, dividend): self.name = name self.code = code self.PER = PER self.PBR = PBR self.dividend = dividend def set_per(self, PER) : self.PER = PER def set_pbr(self, PBR): self.PBR = PBR def set_dividend(self, dividend): self.dividend = dividend stock = Stock('삼성전자', '0059430', 15.79, 1.33, 2.83) print(stock.PER) stock.set_per(12.75) print(stock.PER) # 270 class Stock: def __init__(self, name, code, PER, PBR, dividend): self.name = name self.code = code self.PER = PER self.PBR = PBR self.dividend = dividend def set_per(self, PER) : self.PER = PER def set_pbr(self, PBR): self.PBR = PBR def set_dividend(self, dividend): self.dividend = dividend def get_per(self): return self.PER def get_pbr(self): return self.PBR def get_dividend(self): return self.dividend # 삼성전자 005930 15.79 1.33 2.83 # 현대차 005380 8.70 0.35 4.27 # LG전자 066570 317.34 0.69 1.37 item = [] item.append(Stock('삼성전자', '005930', 15.79, 1.33, 2.83)) item.append(Stock('현대차', '00580', 8.70, 0.35, 4.27)) item.append(Stock('LG전자', '066570', 317.34, 0.69, 1.37)) for i in item: print(f'종목명 : {i.code} , PER : {i.PER}') # 271 # 은행이름, 예금주, 계좌번호, 잔액 import random class Account: def __init__(self, user, total): self.user = user self.total = total number = '' # _ _ _-_ _-_ _ _ _ _ _ for i in range(11): now = str(random.randint(0, 10)) number+=now if i==2: number+='-' elif i==4: number+='-' self.number = number self.bank = 'SC은행' account = Account('user1', 1000) print(account.user, account.total, account.number, account.bank) # 272 import random class Account: total_count = 0 def __init__(self, user, total): self.user = user self.total = total number = '' # _ _ _-_ _-_ _ _ _ _ _ for i in range(11): now = str(random.randint(0, 10)) number+=now if i==2: number+='-' elif i==4: number+='-' self.number = number self.bank = 'SC은행' Account.total_count +=1 kim = Account("김민수", 100) print(Account.total_count) lee = Account("이민수", 100) print(Account.total_count) # 273 import random class Account: total_count = 0 def __init__(self, user, total): self.user = user self.total = total number = '' # _ _ _-_ _-_ _ _ _ _ _ for i in range(11): now = str(random.randint(0, 10)) number+=now if i==2: number+='-' elif i==4: number+='-' self.number = number self.bank = 'SC은행' Account.total_count +=1 @classmethod def get_account_num(cls): print(cls.total_count) kim = Account("김민수", 100) lee = Account("이민수", 100) kim.get_account_num() # 274 import random class Account: total_count = 0 def __init__(self, user, total): self.user = user self.total = total number = '' # _ _ _-_ _-_ _ _ _ _ _ for i in range(11): now = str(random.randint(0, 10)) number+=now if i==2: number+='-' elif i==4: number+='-' self.number = number self.bank = 'SC은행' Account.total_count +=1 @classmethod def get_account_num(cls): print(cls.total_count) def deposit(self, amount): if amount>=1: self.total += amount kim = Account("김민수", 100) print(kim.total) kim.deposit(200) print(kim.total) # 275 import random class Account: total_count = 0 def __init__(self, user, total): self.user = user self.total = total number = '' # _ _ _-_ _-_ _ _ _ _ _ for i in range(11): now = str(random.randint(0, 10)) number+=now if i==2: number+='-' elif i==4: number+='-' self.number = number self.bank = 'SC은행' Account.total_count +=1 @classmethod def get_account_num(cls): print(cls.total_count) def deposit(self, amount): if amount>=1: self.total += amount def withdraw(self, ammount): if self.total>=ammount: self.total -=ammount kim = Account("김민수", 300) print(kim.total) kim.withdraw(200) print(kim.total) # 276 # 은행이름: SC은행 # 예금주: 파이썬 # 계좌번호: 111-11-111111 # 잔고: 10,000원 import random class Account: account_num = 0 def __init__(self, user, balance): self.user = user self.bank = 'SC은행' self.balance = balance first = random.randint(1, 999) mid = random.randint(1, 99) last = random.randint(1, 999999) first = str(first).zfill(3) mid = str(mid).zfill(2) last = str(last).zfill(6) self.bank_account = first+'-'+mid+'-'+last Account.account_num += 1 def display_info(self): print(f'은행이름: {self.bank}') print(f'예금주: {self.user}') print(f'계좌번호: {self.bank_account}') print(f'잔고: {self.balance}원') kim = Account("김민수", 300) kim.display_info() # 277 import random class Account: account_num = 0 def __init__(self, user, balance): self.bank = 'SC은행' self.user = user self.balance = balance first = random.randint(1, 999) mid = random.randint(1, 99) last = random.randint(1, 999999) first = str(first).zfill(3) mid = str(mid).zfill(2) last = str(last).zfill(6) self.bank_account = first+'-'+mid+'-'+last self.deposit_num = 0 def deposit(self, amount): self.deposit_num += 1 if amount>=1: self.balance += amount if self.deposit_num >= 5: self.balance += int(self.balance*0.1) p = Account("파이썬", 10000) p.deposit(10000) p.deposit(10000) p.deposit(10000) p.deposit(5000) p.deposit(5000) print(p.balance) # 278 import random class Account: def __init__(self, user, balance): self.user = user self.bank_name = 'SC은행' self.balance = balance first = random.randint(1, 999) mid = random.randint(1, 99) last = random.randint(1, 999999) first = str(first).zfill(3) mid = str(mid).zfill(2) last = str(last).zfill(6) self.bank_account = first+'-'+mid+'-'+last account = [] account.append(Account('Kim', 10000000)) account.append(Account('Lee', 10000)) account.append(Account('park', 10000)) for i in account: print(i.user) # 279 import random class Account: def __init__(self, user, balance): self.user = user self.bank_name = 'SC은행' self.balance = balance first = random.randint(1, 999) mid = random.randint(1, 99) last = random.randint(1, 999999) first = str(first).zfill(3) mid = str(mid).zfill(2) last = str(last).zfill(6) self.bank_account = first+'-'+mid+'-'+last def display_info(self): print(f'은행이름: {self.bank_name}') print(f'예금주: {self.user}') print(f'계좌번호: {self.bank_account}') print(f'잔고: {self.balance}원') account = [] account.append(Account('Kim', 10000000)) account.append(Account('Lee', 10000)) account.append(Account('park', 10000)) for i in account: if i.balance >= 1000000: i.display_info() # 280 import random class Account: def __init__(self, user, balance): self.user = user self.bank_name = 'SC은행' self.balance = balance first = random.randint(1, 999) mid = random.randint(1, 99) last = random.randint(1, 999999) first = str(first).zfill(3) mid = str(mid).zfill(2) last = str(last).zfill(6) self.bank_account = first+'-'+mid+'-'+last self.deposit_log = [] self.deposit_num = 0 self.withdraw_log = [] def display_info(self): print(f'은행이름: {self.bank_name}') print(f'예금주: {self.user}') print(f'계좌번호: {self.bank_account}') print(f'잔고: {self.balance}원') def deposit(self, amount): self.deposit_num += 1 if amount>=1: self.balance += amount self.deposit_log.append(amount) if self.deposit_num >= 5: self.balance += int(self.balance*0.1) def withdraw(self, amount): if self.balance >= amount: self.balance += amount self.withdraw_log.append(amount) def deposit_history(self): for amount in self.deposit_log: print(f'deposit : {amount}') def withdraw_history(self): for amount in self.withdraw_log: print(f'widthraw : {amount}') k = Account("Kim", 1000) k.deposit(100) k.deposit(200) k.deposit(300) k.deposit_history() k.withdraw(100) k.withdraw(200) k.withdraw_history() # 281 class 차: def __init__(self, 바퀴, 가격): self.바퀴 = 바퀴 self.가격 = 가격 car = 차(2, 1000) print(car.바퀴) # 2 print(car.가격) # 1000 # 282 class 차: def __init__(self, 바퀴, 가격): self.바퀴 = 바퀴 self.가격 = 가격 class 자전차(차): pass # 283 class 차: def __init__(self, 바퀴, 가격): self.바퀴 = 바퀴 self.가격 = 가격 class 자전차(차): def __init__(self, 바퀴, 가격): self.바퀴 = 바퀴 self.가격 = 가격 bicycle = 자전차(2, 100) print(bicycle.가격) # 100 # 284 class 차: def __init__(self, 바퀴, 가격): self.바퀴 = 바퀴 self.가격 = 가격 class 자전차(차): def __init__(self, 바퀴, 가격, 구동계): self.바퀴 = 바퀴 self.가격 = 가격 self.구동계 = 구동계 # # 답지 풀이 # class 자전차(차): # def __init__(self, 바퀴, 가격, 구동계): # super().__init__(바퀴, 가격) # self.구동계 = 구동계 bicycle = 자전차(2, 1000, "시마노") print(bicycle.구동계) print(bicycle.바퀴) # 285 class 차: def __init__(self, 바퀴, 가격): self.바퀴 = 바퀴 self.가격 = 가격 class 자동차(차): def __init__(self, 바퀴, 가격): super().__init__(바퀴, 가격) def 정보(self): print("바퀴 수 : %d" %self.바퀴) print("가격 : %d "%self.가격) car = 자동차(4, 1000) car.정보() # 286 class 차: def __init__(self, 바퀴, 가격): self.바퀴 = 바퀴 self.가격 = 가격 def 정보(self): print('바퀴 수 : %d' %self.바퀴) print('가격 : %d' %self.가격) class 자전차(차): def __init__(self, 바퀴, 가격, 구동계): super().__init__(바퀴, 가격) self.구동계 = 구동계 bicycle = 자전차(2, 100, "시마노") bicycle.정보() # 287 class 차: def __init__(self, 바퀴, 가격): self.바퀴 = 바퀴 self.가격 = 가격 def 정보(self): print('바퀴 수 : %d' %self.바퀴) print('가격 : %d' %self.가격) class 자전차(차): def __init__(self, 바퀴, 가격, 구동계): super().__init__(바퀴, 가격) self.구동계 = 구동계 def 정보(self): super().정보() print('구동계 ',self.구동계) bicycle = 자전차(2, 100, "시마노") bicycle.정보() # # 288 class 부모: def 호출(self): print("부모호출") class 자식(부모): def 호출(self): print("자식호출") 나 = 자식() 나.호출() # 자식호출 # 만이 출력된다. 289 class 부모: def __init__(self): print("부모생성") class 자식(부모): def __init__(self): print("자식생성") classes = 자식() # 자식생성 # 이 출력된다. # 290 class 부모: def __init__(self): print("부모생성") class 자식(부모): def __init__(self): print("자식생성") super().__init__() 나 = 자식() # 자식생성 # 부모생성 # 순으로 출력된다.
# 131 # 사과 # 귤 # 수박 # 132 # ##### # ##### # ##### # 133 print("A","B","C",sep="\n") # 134 print("출력:\"A\"") print("출력:\"B\"") print("출력:\"C\"") # 135 str_a = "A" str_b = "B" str_c = "C" print(f"변환: {str_a.lower()}") print(f"변환: {str_b.lower()}") print(f"변환: {str_c.lower()}") # 136 변수 = [10,20,30] for i in 변수: print(i) # 137 변수 = [10,20,30] for i in 변수: print(i) # 138 for i in 변수: print(i) print("-------") # 139 print('++++') for i in 변수: print(i) # 140 for i in range(4): print("--------") # 후기 # 문제 자체는 많지 않았으나 매일매일 학습할 분량을 # 정해서 하는게 좋을것 같다는 생각이 들어 하루 30문제를 풀생각해야겠다.
#!/usr/bin/python # -*- coding: utf-8 -*- # Trie Tree Python Implementation # # k childs are available from each parent # e.g. English: 26, Japanese: 場合による(カタカナ常用だけなら85) # offset is to calculate index for each character in utf-8 # e.g. English: 'a'=97が最小, Japanese ひらがな:12354, カタカナ:12449 import os import sys import codecs class Trie: k = 26 # number of alphabet offset = 97 # order for alphabet 'a' def __init__(self): self.child = [None]*self.k self.exist = False def insert(self, string): if(len(string)==0): self.exist = True return True index = ord(string[0])-self.offset if(index>=self.k or index<0): print "Invalid character found", index, string[0] return False if(self.child[index] == None): self.child[index] = Trie() self.child[index].insert(string[1:]) def search(self, string): if(len(string)==0): return self.exist index = ord(string[0])-self.offset if(index>=self.k or index<0): print "Invalid character found", index, string[0] return False if(self.child[index] == None): print "Not found" else: return self.child[index].search(string[1:]) if __name__ == "__main__": # use following dictinary extracted from ipadic lst = map(unicode.split, codecs.open("../../data/midashi_yomi.dic","r","utf_8").readlines()) Trie.k = 85 Trie.offset = 12449 jap_dict = Trie() for i, word in enumerate(lst): print i jap_dict.insert(word[1])
# -*- coding:utf-8 -*- #地址需要改成自己设定的地址 import re,os import urllib2 urls='http://www.imooc.com/course/list?page=' s=int(raw_input("how many pages:")) if s>32 or s<1 : print "your input is error" else : for i in range(s): os.mkdir('E:\\ceshi\\'+str(i+1)) req=urllib2.urlopen(urls+str(i+1)) buf=req.read() listurl1=re.findall(r'http:.+?\.jpg',buf) list_all=[listurl1[x] for x in range(len(listurl1)) if x%2==1] count=1 for url in list_all: imgpath='E:\\ceshi\\'+str(i+1)+'\\' with open(imgpath+str(count)+'.jpg','wb') as f: re_url= urllib2.urlopen(url) buf_url = re_url.read() f.write(buf_url) count+=1 print 'page %s is finash!' % (i+1)
from statistics import mean class Student: def __init__(self, name, surname, gender): self.name = name self.surname = surname self.gender = gender self.finished_courses = ['Введение в программирование'] self.courses_in_progress = ['Basic'] self.grades = {} def rate_lec(self, lector, course, grade): if isinstance(lector, Lecturer) and course in self.courses_in_progress and course in lector.courses_attached: if course in lector.grades: lector.grades[course] += [grade] else: lector.grades[course] = [grade] else: print ('Ошибка') return def __str__(self): od = 0 num = 0 for id in self.grades: num += 1 od += mean(self.grades[id]) od = od / num res = f'Имя: {self.name}\nФамилия: {self.surname}\nСредняя оценка: {od}\n' \ f'Курсы в процессе изучения: {str(self.courses_in_progress).strip("[]")}\n' \ f'Завершенные курсы: {str(self.finished_courses).strip("[]")}\n' return res def __lt__(self, other): if not isinstance(other,Student): print('ошибка сравнения') return else: comp_one = 0 num=0 for id in self.grades: num += 1 comp_one += mean(self.grades[id]) comp_one = comp_one / num comp_two = 0 num = 0 for id in other.grades: num += 1 comp_two += mean(other.grades[id]) comp_two = comp_two / num return comp_one<comp_two class Mentor: def __init__(self, name, surname): self.name = name self.surname = surname self.courses_attached = [] self.grades = {} class Lecturer(Mentor): def __str__(self): od = 0 num = 0 for id in self.grades: num += 1 od += mean(self.grades[id]) od = od / num res = f'Имя: {self.name}\nФамилия: {self.surname}\nСредняя оценка: {od}\n' return res def __lt__(self, other): if not isinstance(other,Lecturer): print('ошибка сравнения') return else: comp_one = 0 num=0 for id in self.grades: num += 1 comp_one += mean(self.grades[id]) comp_one = comp_one / num comp_two = 0 num = 0 for id in other.grades: num += 1 comp_two += mean(other.grades[id]) comp_two = comp_two / num return comp_one<comp_two class Reviewer(Mentor): def rate_hw(self, student, course, grade): if isinstance(student, Student) and course in self.courses_attached and course in student.courses_in_progress: if course in student.grades: student.grades[course] += [grade] else: student.grades[course] = [grade] else: return 'Ошибка' def __str__(self): res=f'Имя: {self.name}\nФамилия: {self.surname}\n' return res def StudentsAVG(stdlst,objectname): TempList=[] for id in stdlst: TempList += id.grades[objectname] TempListAVG = mean(TempList) return TempListAVG def LectorsAVG(stdlst,objectname): TempList=[] for id in stdlst: TempList += id.grades[objectname] TempListAVG = mean(TempList) return TempListAVG # заводим лучшего Студента best_student = Student('Ruoy', 'Eman', 'your_gender') best_student.courses_in_progress += ['Python'] # заводим второго студента student_two = Student('Vova', 'Oldboy', 'men') student_two.courses_in_progress += ['Python'] # заводим проверяющего преподователя cool_reviewer = Reviewer('Some', 'Buddy') cool_reviewer.courses_attached += ['Python'] cool_reviewer.courses_attached += ['Basic'] # заводим лучшего лектора cool_lector = Lecturer('Alex','Gendel') cool_lector.courses_attached += ['Python'] # заводим второго лектора lector_two = Lecturer('Second', 'Teacher') lector_two.courses_attached += ['Python'] # ставим оценки студентам cool_reviewer.rate_hw(best_student, 'Python', 10) cool_reviewer.rate_hw(best_student, 'Python', 10) cool_reviewer.rate_hw(best_student, 'Python', 10) cool_reviewer.rate_hw(best_student, 'Basic', 7) cool_reviewer.rate_hw(best_student, 'Basic', 9) cool_reviewer.rate_hw(student_two, 'Python', 5) cool_reviewer.rate_hw(student_two, 'Python', 6) cool_reviewer.rate_hw(student_two, 'Python', 7) # ставим оценки лекторам best_student.rate_lec(cool_lector,'Python', 8) best_student.rate_lec(cool_lector,'Python', 7) best_student.rate_lec(cool_lector,'Python', 9) best_student.rate_lec(lector_two,'Python', 8) best_student.rate_lec(lector_two,'Python', 9) best_student.rate_lec(lector_two,'Python', 10) # задание 3.1 печать по формату print(cool_reviewer) print(cool_lector) print(best_student) # 3.2 сравниваем средние оценки студентов по дисциплинам if student_two<best_student: print(f'Лучшие оценки у {best_student.name} {best_student.surname}') else: print(f'лучшие оценки у {student_two.name} {student_two.surname}') if lector_two<cool_lector: print(f'Лучшие оценки у {cool_lector.name} {cool_lector.surname}') else: print(f'лучшие оценки у {lector_two.name} {lector_two.surname}') #задание 4 StudentsList = [best_student,student_two] LectorsList = [cool_lector,lector_two] print("\nСредняя оценка студентов за курс Pyhon:",StudentsAVG(StudentsList,'Python')) print("\nСредняя оценка лекторов за курс Pyhon:",LectorsAVG(LectorsList,'Python'))
#coding:utf-8 #decorate 装饰器 #python 2.7.6 import functools def now(): print '2014-1-1' f = now f() #函数也是一个对象,函数对象可以赋值给变量,通过变量也能调用该函数。 #函数对象有一个__name__ 属性,可以拿到函数的名字:双下划线 print now.__name__ print f.__name__ #本质上,decorator 就是一个返回函数的高阶函数。 def log(func): @functools.wraps(func) #将原始函数属性复制到wrapper中 def wrapper(*args,**kw): print "call %s()"%func.__name__ return func(*args, **kw) return wrapper #使用Python 的@语法 在每个函数上使用 @log def test1(): print "Hello python..." test1() # equals test1 = log(test1) #wrapper() 函数的参数定义是(*args, **kw) ,因此, wrapper() 函数可以接受任意参数的调用。在wrapper() 函数内, #首先打印日志,再紧接着调用原始函数。 #如果decorator 本身需要传入参数,那就需要编写一个返回decorator的高阶函数 def log2(text): def decorator(func): @functools.wraps(func) def wrapper(*args,**kw): print '%s %s():'%(text, func.__name__) return func(*args,**kw) return wrapper return decorator @log2("text----") def now2(): print '2014-11-8' now2() print now2.__name__ #原理解析 now = log2('execute')(now) #我们来剖析上面的语句,首先执行log2('execute') ,返回的是decorator 函数,再调用返回的函数,参数是now 函 #数,返回值最终是wrapper 函数。 #但是返回的函数 已经变成了 wrapper #------------------------------------------------------
#coding:utf-8 #for while : #python 2.7.6 names =['Sean','Mirs','Index'] for name in names: print name sum=0 for x in range(101): # 0,100 sum = sum+x print sum # while sum=0 n=99 while n>0: sum=sum+n n=n-2 print sum #raw_input()读取的内容永远以字符串的形式返回,如果为int需要使用int('str')
""" LISTAS (arrays) Son colecciones o conjuntos de datos/valores, bajo un unico nombre Para acceder a esos valores podemos usar un indice numerico. """ pelicula = "Batman" # Definir lista peliculas = ["Batman", "Spiderman", "El señor de los anillos"] cantantes = list(("Shakira", "Adele", "Denisse")) years = list(range(2020, 2050)) variada = ["Laura", 27, 5.0, True, "Holi"] """ print(peliculas) print(cantantes) print(years) print(variada) """ # Indices print(peliculas[1]) print(peliculas[-2]) print(cantantes[0:1]) print(peliculas[2:]) # Añadir elementos a lista cantantes.append("Leon Larregui") cantantes.append("Cerati") print(cantantes) # Recorrer lista print("\n********* LISTADO PELICULAS *********\n") nueva_pelicula = "" """ while nueva_pelicula != "parar": nueva_pelicula = input("Introduce la nueva pelicula: ") if nueva_pelicula != "parar": peliculas.append(nueva_pelicula) """ for pelicula in peliculas: print(f"{peliculas.index(pelicula) + 1}. {pelicula}") # Listas multidimensionales print("\n***************** LISTADO DE CONTACTOS ******************") contactos = [ [ 'Antonio', 'antonio@email.com' ], [ 'Cristobal', 'cristobal@email.com' ], [ 'Laura', 'laura@email.com' ] ] for contacto in contactos: for elemento in contacto: if contacto.index(elemento) == 0: print("Nombre: " + elemento) else: print("Email: " + elemento) print("\n") #print(contactos[1][1])
""" Módulos: Son funcionalidades ya hechas para reutilizar En python hay muchos módulos, que los puedes consultar aqui: https://docs.python.org/3/py-modindex.html Podemos conseguir modulos que ya vienen en el lenguaje, modulos en internet y tambiién podemos crear nuestros modulos """ #Importar modulo propio #import mymodule #from mymodule import holaMundo from mymodule import * #print(mymodule.holaMundo("Laura Quinchia")) #print(mymodule.calculadora(3, 5, True)) print(holaMundo("Laura")) print(calculadora(3, 5, True))
""" Ejercicio 9 Hacer un programa que pida números al usuario indefinidamente hasta meter el número 111 """ cont = 1 while cont < 100: num = int(input("Introduce un número: ")) if num == 111: break else: print(f"Has introducido el {num}")
""" Plays the game, Nimm A pile of stones exists and each player takes turns removing one or two stones Whoever is last to take from the pile loses The number of stones, players, and acceptable removals can be modified if desired by the constants An 'AI' can be employed to always win In order to win, the player or AI must end a turn with 4 stones left in the pile """ import random #Keep this number in the form of 3n or 3n + 2 to always have the AI win #Change this number to a different form to have a chance at winning INITIAL_STONES = 20 PLAYER_COUNT = 2 ACCEPTABLE_REMOVAL = [1,2] def main(): nimm() def game_over(player: int)->str: print(f'Player {player}, you lose.') print('Game over') def remove_stones(pile: int, player: int)->int: """ function for removing stones will check if a removal of 2 stones is allowed and give a correct prompt """ if pile > 1: print(f'There are {pile} stones left') removal = 0 if player == 1: removal = ai_turn(pile) else: removal = int(input(f'Player {player} would you like to remove 1 or 2 stones? ')) while removal not in ACCEPTABLE_REMOVAL: removal = int(input('Please enter 1 or 2: ')) print(f'Player {player} removes {removal} stone(s)\n') return pile - removal else: print(f'There is {pile} stone left') print(f'Player {player}, you remove 1 stone') return 0 def ai_turn(pile: int): best_move = (pile - 1) % 3 if best_move == 0: return 0 return best_move def nimm()->None: """ Runs the game loop as long as the pile is not 0 I ended up having to use break There's probably a better way of doing this loop """ pile = INITIAL_STONES while pile > 0: for player in range(1, PLAYER_COUNT + 1): pile = remove_stones(pile, player) if pile == 0: game_over(player) break def ai_test(): for i in range(20, 1, -1): print(i, ai_turn(i)) if __name__ == '__main__': #ai_test() main()
PETURKSBOUIPO = 16 STANLAU = 25 MAYENGUA = 48 def main(): age = int(input('How old are you? ')) global_vote(age) def vote_peturksbouipo(age: int)->None: if age >= PETURKSBOUIPO: vote = 'can' else: vote = 'cannot' message = f'vote in Peturksbouipo where the voting age is {PETURKSBOUIPO}.' print(f'You {vote} {message}') def vote_stanlau(age: int)->None: if age >= STANLAU: vote = 'can' else: vote = 'cannot' message = f'vote in Stanlau where the voting age is {STANLAU}.' print(f'You {vote} {message}') def vote_mayengua(age: int)->None: if age >= MAYENGUA: vote = 'can' else: vote = 'cannot' message = f'vote in Mayengua where the voting age is {MAYENGUA}.' print(f'You {vote} {message}') def global_vote(age: int)->None: vote_peturksbouipo(age) vote_stanlau(age) vote_mayengua(age) if __name__ == "__main__": main()
""" This program generates the Warhol effect based on the original image. """ from simpleimage import SimpleImage N_ROWS = 2 N_COLS = 3 PATCH_SIZE = 222 WIDTH = N_COLS * PATCH_SIZE HEIGHT = N_ROWS * PATCH_SIZE PATCH_NAME = 'Week3/images/shiba.png' PINK_FILTER = (1.5, .5, 1.5) GREEN_FILTER = (.55, 1.5, 1.3) BLUE_FILTER = (.55, 1.1, 4.0) YELLOW_FILTER = (1.7, 1.8, .8) BRIGHT_FILTER = (1.6, 1.6, 1.6) def main(): final_image = SimpleImage.blank(WIDTH, HEIGHT) # TODO: your code here # This is an example which should generate a pinkish patch #patch = make_recolored_patch(1.5, 0, 1.5) pink_patch = make_recolored_patch(*PINK_FILTER) green_patch = make_recolored_patch(*GREEN_FILTER) bright_patch = make_recolored_patch(*BRIGHT_FILTER) yellow_patch = make_recolored_patch(*YELLOW_FILTER) normal_patch = SimpleImage(PATCH_NAME) blue_patch = make_recolored_patch(*BLUE_FILTER) patch_tuple = (pink_patch, green_patch, bright_patch, yellow_patch, normal_patch, blue_patch) final_image = make_final_image(patch_tuple, final_image) final_image.show() def make_final_image(patches: tuple, final_image: SimpleImage)->SimpleImage: current_patch = 0 for row in range(N_ROWS): for column in range(N_COLS): final_image = place_patch(patches[current_patch], final_image, column * PATCH_SIZE, row * PATCH_SIZE) current_patch += 1 return final_image def place_patch(patch: SimpleImage, working_image: SimpleImage, x_start: int, y_start: int)->SimpleImage: patch_y = 0 for y in range(y_start, y_start + PATCH_SIZE): patch_x = 0 for x in range(x_start, x_start + PATCH_SIZE): working_image.set_pixel(x, y, patch.get_pixel(patch_x, patch_y)) patch_x += 1 patch_y += 1 return working_image #def make_new_patch(red_scale, green_scale, blue_scale): # patch = SimpleImage(PATCH_NAME) # patch = make_gray(patch) # for pixel in patch: # pixel.red *= red_scale # pixel.green *= green_scale # pixel.blue *= blue_scale # patch.show() def make_colored(image, color): l_red = 0.299 l_green = 0.587 l_blue = 0.114 factor = 2.0 for pixel in image: lumonosity = (0.299 * pixel.red) + (0.587 * pixel.green) + (0.114 * pixel.blue) if color == 'red': pixel.red = lumonosity * 5 lumonosity = (0.299 * pixel.red) + (0.587 * pixel.green) + (0.114 * pixel.blue) pixel.green = lumonosity pixel.blue = lumonosity #pixel.red = lumonosity #pixel.green = lumonosity #pixel.blue = lumonosity return image def make_recolored_patch(red_scale, green_scale, blue_scale): ''' Implement this function to make a patch for the Warhol Filter. It loads the patch image and recolors it. :param red_scale: A number to multiply each pixel's red component by :param green_scale: A number to multiply each pixel's green component by :param blue_scale: A number to multiply each pixel's blue component by Returns the newly generated patch. ''' patch = SimpleImage(PATCH_NAME) for pixel in patch: pixel.red *= red_scale pixel.green *= green_scale pixel.blue *= blue_scale #patch.show() return patch if __name__ == '__main__': main()
""" >>> leap_check_1(2000) True """ def main(): year = int(input('Enter a year to check if it\'s a leap year: ')) print(leap_check(year)) def leap_check_1(year: int)->bool: return year % 4 == 0 # return True #return False def leap_check_2(year: int)->bool: if year % 100 == 0: if year % 400 == 0: return True return False return True def leap_check(year: int)->str: if leap_check_1(year) and leap_check_2(year): return 'That\'s a leap year!' return 'That\'s not a leap year!' if __name__ == "__main__": main()
""" Part A: This program will print 42, because divide_and_roun() has no return and n is not being reassigned by the function divide_and_round must do a return on n and in main() n = divide_and_round(n) must be used to reassign n """ """ Part B: Edit this code so that it works correctly """ def divide_and_round(n): """ Divides an integer n by 2 and rounds up to the nearest whole number """ if n % 2 == 0: #wrapped assignment in int() function so the number is an integer n = int(n / 2) else: #wrapped assignment in int() function so the number is an integer n = int((n + 1) / 2) #Adding a return for n so that the number calculated in here can be used elsewhere return n def main(): n = 42 #reassigning the value for n using n = divide_and_round n = divide_and_round(n) print(n) #Adding if name is main to call main if __name__ == '__main__': main()
#Write a script that parse sometext.txt file and outputs: # Total words in file: 4562 # Total characters: 20123 # Avg words per line: 10.4 # Avg len of word: 8.3 # Note that all stats should exclude punctutation! #Something wrong with the encoding of this file. #If you use errors = "ignore" it will remove unnedded characters.''' def open_file(x): '''create function to open the file''' with open("sometext.txt", encoding = "utf8")as text_file: if x == "byline": text_line = text_file.readlines() return text_line else: text_file = text_file.read() return text_file def words_counting(open_file): '''create function to count all the words(using open_file function as a var)''' total_words = 0 #to count the words we have to slip the text in to separated words words_list = open_file.split() for word in words_list: total_words += 1 return total_words def characters_counting(open_file): '''create function to count all the characters''' string_file = len(open_file) return (f"Total charachters in file: {string_file}") def avg_words_per_line(open_file, words_counting): '''create function to count Avg words per line''' total_words = words_counting number_of_lines = 0 read_byline = open_file for line in read_byline: number_of_lines += 1 words_per_line = total_words / number_of_lines return f"Average words per line: {round(words_per_line,1)}" def avg_len_of_word(open_file, words_counting): ''' create a function to count Avg len of word:''' total_words = words_counting total_letters = 0 for letter in open_file: if letter.isalpha(): total_letters += 1 return f"Total avg len of word: {round (total_letters / total_words,1)}" print(f"Total words in file: {words_counting(open_file(' '))}") print(characters_counting(open_file(' '))) print(avg_words_per_line(open_file('byline'), words_counting(open_file(' ')))) print(avg_len_of_word(open_file(' '), words_counting(open_file(' '))))
answear=(1) while answear=="1": print("ter ") answear=input("что?") if answear=="0": break
from random import randint n = int(input("Введите количество случ:")) for i in range(n): i = randint(1, 100) print(i, end=" ")
x = input(" Ведите предложение: ") if "вверх" in x.lower(): print(x.upper()) elif "вниз" in x.lower(): print(x.lower()) else: print(x)
#Все мы в магазин ходим со списком покупок. #Так вот представь себя на месте онлайн-магазина. #Пользователь вводит, что именно ему надо (наименование). #Если оно имеется в файле расценок магазина ‘prices.txt’, то пользователь получает сообщение, что товар в наличии и можно ввести необходимое количество. #После ввода количества, пользователь должен ввести свой email. #Пользователь получает чек на email. (Создать файл, где email пользователя будет названием файла) spisok_names = [] spisok_prices = [] shopper = True while shopper: shoper = input("Введите товар, который ищите (0 - если хотите закончить покупки)\t") price = open("D:\price.txt", "r", 1, "utf-8") if shoper == "0": shopper = False else: for i in price: ii = i.split() if ii[0] == shoper.lower(): print("Товар есть в наличии") spisok_names.append(ii[0]) col = int(input("Введите количество либо вес, который вам необходим\t")) spisok_prices.append(float(ii[1]) * col) price.close() for elem in range(len(spisok_names)): print(f"{spisok_names[elem]}---{spisok_prices[elem]}")
x = str(input("Введите слово: ")) if "музыка" in x.lower(): print("Тыц") print("тЫц") print("тыЦ") print("Тыц") print("тЫц") print("тыЦ") print("):") musik = input('введите слово музыка') tiz = "тыц" if "музыка" in musik.lower(): for num in range(len(tiz)): print(tiz.capitalize()) print(tiz[0]+tiz[1].swapcase()+tiz[2]) print(tiz[0]+tiz[1]+tiz[2].swapcase())
a=str(input("Язык программирования (вводим с большой буквы) : ")) if a=="C++": print("Появлся в 1980 году ; издатель Бьёрн Страуструп ") elif a=="Python": print(" Появился в 1991 году; Автор Гвидо ван Руссум") elif a=="R": print("Появился в 1993году; автор Росс Айхэка и Роберт Джентлмен") elif a=="Pascal": print("Появился в 1070 году; автор Никлаус Вирт") elif a=="Java": print("Появился в 1995 году; разработчики Джеймс Гослинг и Sun Microsystems ") elif a=="JavaScript": print("Год появления 1995; автор Брендан Эйх") elif a=="PHP": print("Появился 8 июня 1995; Разработчиком Лердроф, Расмус" "Гутман, Энди") elif a=="Ruby": print("Разработанный Юкихиро Мацумто в 1995 году") else: print("Нет такого языка программирования) или нет в базе ((")
a=str(input("Введите запрос: ")) if a=="лучший фильм" or a=="фильм": b=int(input("Введите дату: ")) if b<2017 or b>2020: print("Повторите попытку") if b==2017: c=str(input("введите жанр: ")) if c=="боевик": print("Gans") elif b==2018: c=str(input("введите жанр: ")) if c=="боевик": print("Шлейф подласти") elif b==2019: c=str(input("введите жанр: ")) if c=="боевик": print("Зло на месте") elif b==2020: c=str(input("введите жанр: ")) if c=="боевик": print("Закрег") if b==2017: if c=="комедия": print("Один в лифте") elif b==2018: if c=="комедия": print("Ни за одной") elif b==2019: if c=="комедия": print("За городом") elif b==2020: if c=="комедия": print("Скрепучий малый") if b==2017: if c=="мелодрама": print("Поцелуй в губы") elif b==2018: if c=="мелодрама": print("Не за чем так") elif b==2019: if c=="мелодрама": print("Не упусти свой шанс") elif b==2020: if c=="мелодрама": print("Поцелуй в низ")
kol_shkol = int(input("Коиличество школьников: ")) kol_iablok = int(input("Количество яблок: ")) korzina = kol_iablok % kol_shkol print("В корзине: ", korzina, "яблок") print("Каждому по ", kol_iablok // kol_shkol, "яблока")
""" -Problem: Some mathematical model answers to this equation: w = ax + by + cz The following represents this model behaviour: a + 2.3b + 3.1c = 23.4 (1) 2a + 4.5b + 5.2z = 41.5 (2) 3a + 5.3b + 6.7z = 52.4 (3) 4a + 6.1b + 7.1z = 57.8 (4) 5a + 6.8b + 7.7z = 63.9 (5) Find the value of constants a, b and c. -Solution approach: This may be a nonlinear behaviour and it's considered to be an overdetermined system of equations. Let's cluster some of them in linear combinations to examine consistent values in the behaviour exposed. I'll use Cramer's rule for this purpose. """ import numpy as np from cramer_rule import cramer_ruleNxN def analysis(results, equations): #Building matrixes results = np.array([results[0], results[1], results[2]]).reshape(3,1) equations = np.array([equations[0], equations[1], equations[2]]) #Trying to apply the Cramer's Rule try: return cramer_ruleNxN(equations, results, 3) except ZeroDivisionError: return None #Doing analysis of each linear combination constants = analysis([23.4, 41.5, 52.4], [[1, 2.3, 3.1], [2, 4.5, 5.2], [3, 5.3, 6.7]]) print(f"Solution for linear combination of (1), (2) and (3): {list(map(round, constants))}", end = "\n" * 2) constants = analysis([23.4, 41.5, 57.8], [[1, 2.3, 3.1], [2, 4.5, 5.2], [4, 6.1, 7.1]]) print(f"Solution for linear combination of (1), (2) and (4): {list(map(round, constants))}", end = "\n" * 2) constants = analysis([23.4, 41.5, 63.9], [[1, 2.3, 3.1], [2, 4.5, 5.2], [5, 6.8, 7.7]]) print(f"Solution for linear combination of (1), (2) and (5): {list(map(round, constants))}", end = "\n" * 2) constants = analysis([52.4, 57.8, 63.9], [[3, 5.3, 6.7], [4, 6.1, 7.1], [5, 6.8, 7.7]]) print(f"Solution for linear combination of (3), (4) and (5): {list(map(round, constants))}", end = "\n" * 2) constants = analysis([52.4, 57.8, 23.4], [[3, 5.3, 6.7], [4, 6.1, 7.1], [1, 2.3, 3.1]]) print(f"Solution for linear combination of (3), (4) and (1): {list(map(round, constants))}", end = "\n" * 2) constants = analysis([52.4, 57.8, 41.5], [[3, 5.3, 6.7], [4, 6.1, 7.1], [2, 4.5, 5.2]]) print(f"Solution for linear combination of (3), (4) and (2): {list(map(round, constants))}", end = "\n" * 2) #Printing out the conclusion print("General solution to the system: a = 1, b = 3, c = 5")
import copy class ConnectFour: def __init__(self): self.moves = 0 self.turn = 0 def PrintGameBoard(self, board): print(' 0 1 2 3 4 5 6') for i in range(5, -1, -1): print('|---|---|---|---|---|---|---|') print("| ",end="") for j in range(7): print(board[i][j],end="") if j != 6: print(" | ",end="") else: print(" |") print('`---------------------------´') def CanPlay(self, col, board): stacks = [[x[i] for x in board] for i in range(len(board[0]))] if (stacks[col].count(1) + stacks[col].count(2)) < 6: return (stacks[col].count(1) + stacks[col].count(2)) else: return -1 def MakeMove(self, board, col, player, row): board[row][col] = player self.moves += 1 return board def UnmakeMove(self, board, col, row): board[row][col] = " " self.moves -= 1 return board def IsWinning(self, currentplayer, board): for i in range(6): for j in range(4): #find colume 4 if board[i][j] == currentplayer and board[i][j+1] == currentplayer and board[i][j+2] == currentplayer and board[i][j+3] == currentplayer: return True for i in range(3): for j in range(7): #find row 4 if board[i][j] == currentplayer and board[i+1][j] == currentplayer and board[i+2][j] == currentplayer and board[i+3][j] == currentplayer: return True for i in range(3): for j in range(4): #find lower diagonal 4 if board[i][j] == currentplayer and board[i+1][j+1] == currentplayer and board[i+2][j+2] == currentplayer and board[i+3][j+3] == currentplayer: return True for i in range(3,6): for j in range(4): #find upper diagonal 4 if board[i][j] == currentplayer and board[i-1][j+1] == currentplayer and board[i-2][j+2] == currentplayer and board[i-3][j+3] == currentplayer: return True return False def PlayerMove(self, board, player): try: allowedmove = False while not allowedmove: print("Choose a column where you want to make your move (0-6): ",end="") col =input() row = self.CanPlay(int(col), board) if row != -1: board[row][int(col)] = player self.moves += 1 allowedmove = True else: print("This column is full") except (NameError, ValueError, IndexError, TypeError, SyntaxError) as e: print("Give a number as an integer between 0-6!") else: return board def SwitchPlayer(self, player): if player==1: nextplayer=2 else: nextplayer=1 return nextplayer def evaluation(self, board, player): list = [] opponent = self.SwitchPlayer(player) #if we are reaching the leaf what score is winning 512, lose -512 if self.IsWinning(player, board): score = 512 elif self.IsWinning(opponent, board): score = -512 #if running out of move, the score is 0 elif self.moves==42: score=0 else: score = 0 #find how many 4 together for player and opponent for i in range(6): for j in range(4): list.append([str(board[i][j]),str(board[i][j+1]),str(board[i][j+2]),str(board[i][j+3])]) for i in range(3): for j in range(7): list.append([str(board[i][j]),str(board[i+1][j]),str(board[i+2][j]),str(board[i+3][j])]) for i in range(3): for j in range(4): list.append([str(board[i][j]),str(board[i+1][j+2]),str(board[i+2][j+2]),str(board[i+3][j+3])]) for i in range(3, 6): for j in range(4): list.append([str(board[i][j]),str(board[i-1][j+2]),str(board[i-2][j+2]),str(board[i-3][j+3])]) for k in range(len(list)): if ((list[k].count(str(player))>0) and (list[k].count(str(opponent))>0)) or list[k].count(" ")==4: score += 0 if list[k].count(player)==1: score += 1 if list[k].count(player)==2: score += 10 if list[k].count(player)==3: score += 50 if list[k].count(opponent)==1: score -= 1 if list[k].count(opponent)==2: score -= 10 if list[k].count(opponent)==3: score -= 50 #also check who is next player if self.turn==player: score += 16 else: score -= 16 return score def alphabeta(self, board, depth, player, alpha, beta): if depth==0 or self.moves==42 or self.IsWinning(1, board) or self.IsWinning(2, board): return(self.evaluation(board, player),0) pos = 0 order = [3,2,4,1,5,0,6] if player==self.turn: for i in order: row = self.CanPlay(i, board) if row != -1: newboard = self.MakeMove(board, i, player, row) value, dummy = self.alphabeta(newboard, depth-1, self.SwitchPlayer(player), alpha, beta) newboard = self.UnmakeMove(board, i, row) if value>alpha: alpha=value pos=i if beta<=alpha: break return alpha, pos else: for i in order: row = self.CanPlay(i, board) if row != -1: newboard = self.MakeMove(board, i, player, row) value, dummy = self.alphabeta(newboard, depth-1, self.SwitchPlayer(player), alpha, beta) newboard = self.UnmakeMove(board, i, row) if value<beta: beta = value pos=i if beta<=alpha: break return beta, pos def alphabetapruning(self, board, depth, player): self.turn=player value, position=self.alphabeta(board, depth, player, -1000000000, 1000000000) board = self.MakeMove(board, position, player, self.CanPlay(position, board)) return board def PlayerMark(): print("Player 1 starts the game") mark = '' while not (mark == "1" or mark == "2"): print('Do you want to be 1 or 2: ',end="") mark = input() if mark == "1": return 1 else: return 2 def PlayAgain(): print('Do you want to play again? (yes or no) :',end="") return input().lower().startswith('y') def main(): print("Connect4") while True: mark = PlayerMark() connectfour = ConnectFour() if mark==1: player = 1 print("You are going to start the game\r\n\r\n") else: player = 2 print("Computer (negamax) starts the game") gameisgoing = True table = [[],[],[],[],[],[]] for i in range(7): for j in range(6): table[j].append(" ") while gameisgoing: connectfour.PrintGameBoard(table) if mark == 1: table = connectfour.PlayerMove(table, player) if connectfour.IsWinning(player, table): connectfour.PrintGameBoard(table) print('You won the game!') gameisgoing = False else: if connectfour.moves==42: connectfour.PrintGameBoard(table) print('Game is tie') break else: mark = 2 else: opponent = connectfour.SwitchPlayer(player) table = connectfour.alphabetapruning(table, 8, opponent) if connectfour.IsWinning(opponent, table): connectfour.PrintGameBoard(table) print('Computer won the game') gameisgoing = False else: if connectfour.moves==42: connectfour.PrintGameBoard(table) print('Game is tie') break else: mark = 1 if not PlayAgain(): print("Game ended") break if __name__ == '__main__': main()
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right root = TreeNode(1) k = 1 # 先LDR中序遍历,再二分查找数组位置或者直接输出第k-1个元素 class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: if not root: return 0 ldr_list = [] def search(root): if not root: return search(root.left) ldr_list.append(root.val) search(root.right) search(root) # return ldr_list[k-1] #print(ldr_list) left = 0 right = len(ldr_list) mid = (left + right) // 2 #print(mid) k = k-1 while k != mid: if k < mid: right = mid if k > mid: left = mid mid = (left + right) // 2 return ldr_list[mid] """官方题解,迭代""" class Solution: def kthSmallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ stack = [] while True: while root: stack.append(root) root = root.left root = stack.pop() k -= 1 if not k: return root.val root = root.right # 作者:LeetCode # 链接:https: // leetcode - cn.com / problems / kth - smallest - element - in -a - bst / solution / er - cha - sou - suo - shu - zhong - di - kxiao - de - yuan - su - by - le / # 来源:力扣(LeetCode) # 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 sl = Solution() print(sl.kthSmallest(root, 1))
"""159 / 167 个通过测试用例""" class Solution: def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int: if len(left) == 0: return n - min(right) if not right: return max(left) # 如果左数组都在右数组的左边 if max(left) < min(right): return max(max(left), n - min(right)) # 讨论相遇的情况 max_left = max(left) min_right = min(right) meet_time = (max_left - min_right) // 2 meet_idx = meet_time + min_right res_time = max(n - meet_idx, meet_idx) return res_time + meet_time """网上题解:理解为穿透""" class Solution: def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int: if len(left) == 0: return n - min(right) if not right: return max(left) return max(max(left), n - min(right))
import json # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.right.left = TreeNode(4) root.right.right = TreeNode(5) class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ pre_order = [] in_order = [] def pre_search(root): if not root: # ret.append(None) return pre_order.append(root.val) pre_search(root.left) pre_search(root.right) def in_search(root): if not root: # ret.append(None) return in_search(root.left) in_order.append(root.val) in_search(root.right) pre_search(root) in_search(root) pre_str = str(pre_order).replace(' ', '') in_str = str(in_order).replace(' ', '') return pre_str + '+' + in_str def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ plus_idx = data.index('+') pre_str, in_str = data[:plus_idx][1:-1], data[plus_idx + 1:][1:-1] pre_order = [int(pre) for pre in pre_str.split(',')] in_order = [int(pre) for pre in in_str.split(',')] def build_tree(pre_order, in_order): if len(pre_order) == 0 or len(in_order) == 0: return root = TreeNode(pre_order[0]) mid_idx = in_order.index(pre_order[0]) root.left = build_tree(pre_order[1:mid_idx + 1], in_order[:mid_idx]) root.right = build_tree(pre_order[mid_idx + 1:], in_order[mid_idx + 1:]) return root return build_tree(pre_order, in_order) """用层序遍历完成,序列化和反序列化时都使用queue来维护""" class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if not root: return '[]' queue = [root] res = [] while queue: root = queue.pop(0) if root: res.append(str(root.val)) queue.append(root.left) queue.append(root.right) else: res.append('#') return '[' + ','.join(res) + ']' def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ if data == '[]': return i = 1 vals = data[1:-1].split(',') print(vals) root = TreeNode(int(vals[0])) queue = [root] while queue: node = queue.pop(0) if vals[i] != '#': node.left = TreeNode(int(vals[i])) queue.append(node.left) i += 1 if vals[i] != '#': node.right = TreeNode(int(vals[i])) queue.append(node.right) i += 1 return root """深度优先,DLR先序遍历""" class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ res = [] def dfs(root): if not root: res.append('#') return res.append(str(root.val)) dfs(root.left) dfs(root.right) dfs(root) return ','.join(res) def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ vals = data.split(',') # print(vals) vals = iter(vals) # 把列表转换为迭代器 def dfs(): v = next(vals) if v == '#': return node = TreeNode(int(v)) node.left = dfs() node.right = dfs() return node root = dfs() return root codec = Codec() data = codec.serialize(root) print(data) print(codec.deserialize(data))
# 需要用Python3执行 from collections import OrderedDict class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self._capacity = capacity self.cache = OrderedDict() def get(self, key): """ :type key: int :rtype: int """ if key in self.cache: self.cache.move_to_end(key) return self.cache[key] else: return -1 def put(self, key, value): """ :type key: int :type value: int :rtype: None """ if key in self.cache: self.cache.move_to_end(key) self.cache.setdefault(key, value) if len(self.cache) > self._capacity: self.cache.popitem(last=False) """不使用高级API""" class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self._capacity = capacity self.cache = list() def get(self, key): """ :type key: int :rtype: int """ val = -1 for i, item in enumerate(self.cache): if key == item[0]: val = self.cache.pop(i)[1] break self.cache.append([key, val]) return val def traverse(self, key): """遍历cache,是否已有key""" for i, item in enumerate(self.cache): # 如果密钥已经存在 if key == item[0]: return True, i return False, -1 def put(self, key, value): """ :type key: int :type value: int :rtype: None """ flag, index = self.traverse(key) if flag: self.cache.pop(index) self.cache.append([key, value]) if len(self.cache) > self._capacity: self.cache.pop(0) # Your LRUCache object will be instantiated and called as such: obj = LRUCache(2) obj.put(2, 1) obj.put(2, 2) print(obj.get(2)) obj.put(1, 1) # print(obj.get(2)) obj.put(4, 1) print(obj.get(2)) # print(obj.get(3)) # print(obj.get(4))
class Solution: def cuttingRope(self, n: int) -> int: if n == 2: return 1 if n == 3: return 2 memo = {2: 2, 3: 3, 4: 4, 5: 6} def dp(n): if n in memo: return memo[n] res = 0 for i in range(2, n // 2 + 1): res = max(res, dp(i) * dp(n - i)) memo[n] = res return res return dp(n) """内存更优的解法""" import functools class Solution: def cuttingRope(self, n: int) -> int: if n == 2: return 1 if n == 3: return 2 memo = {2: 2, 3: 3, 4: 4, 5: 6} @functools.lru_cache(None) def dp(n): if n == 2: return 2 if n == 3: return 3 res = 0 for i in range(2, n // 2 + 1): res = max(res, dp(i) * dp(n - i)) return res return dp(n)
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right root = TreeNode(1) root.left = TreeNode(2) root.left.right = TreeNode(4) root.right = TreeNode(3) root.right.left = TreeNode(5) root.right.right = TreeNode(6) class Solution: def countPairs(self, root: TreeNode, distance: int) -> int: leaf_path = dict() self.path = [] def dfs(root): if not root: return self.path.append(root.val) if not root.left and not root.right: leaf_path[root.val] = self.path[::-1] self.path = [] return dfs(root.left) if root.val not in self.path: self.path.append(root.val) dfs(root.right) dfs(root) print(leaf_path) count = 0 for leaf1, path1 in leaf_path.items(): for leaf2, path2 in leaf_path.items(): if leaf1 == leaf2: continue for i in range(len(path1)): if path1[i] in path2: d = i + path2.index(path1[i]) if d <= distance: count += 1 return count // 2 class Solution: def countPairs(self, root: TreeNode, distance: int) -> int: if not root or not root.left and not root.right: return 0 def _dfs(root): """获取左右子树中叶子结点到当前节点的距离""" if not root: return {} # 叶子节点 if not root.left and not root.right: return {root: 0} left_leaf = _dfs(root.left) right_leaf = _dfs(root.right) # 距离加1 for k, v in left_leaf.items(): left_leaf[k] = v + 1 for k, v in right_leaf.items(): right_leaf[k] = v + 1 print(left_leaf, right_leaf) for lk, lv in left_leaf.items(): for rk, rv in right_leaf.items(): if lv + rv <= distance: self.ans += 1 # 合并左右子树的叶子节点,向上返回 left_leaf.update(right_leaf) return left_leaf self.ans = 0 _dfs(root) return self.ans # 作者:dz - lee # 链接:https: // leetcode - cn.com / problems / number - of - good - leaf - nodes - pairs / solution / dfsshen - du - yi - ci - bian - li - python3 - by - dz - lee / # 来源:力扣(LeetCode) # 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 sl = Solution() print(sl.countPairs(root, 4))
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def oddEvenList(self, head: ListNode) -> ListNode: if not head: return if not head.next: return head first_head = head second_head = head.next while head: if not head.next or head.next.next == None: break odd_node = head.next head.next = head.next.next head = head.next odd_node.next = odd_node.next.next head.next = second_head return first_head
"""原来暴力BFS就可以""" class Solution: def openLock(self, deadends, target: str) -> int: if '0000' in deadends: return -1 def generate_candidates(num_str): # 从一串数字生成下一个候选集 num_l = list(num_str) num_list = num_l.copy() candidates = [] for i in range(len(num_list)): if num_list[i] == '0': for c in ['1', '9']: new_item = ''.join(num_list[:i] + [c] + num_list[i+1:]) if new_item in visited or new_item in deadends: continue candidates.append(new_item) elif num_list[i] == '9': for c in ['0', '8']: new_item = ''.join(num_list[:i] + [c] + num_list[i+1:]) if new_item in visited or new_item in deadends: continue candidates.append(new_item) else: n_ascii = ord(num_list[i]) choices = [chr(n_ascii+1), chr(n_ascii-1)] for c in choices: new_item = ''.join(num_list[:i] + [c] + num_list[i + 1:]) if new_item in visited or new_item in deadends: continue candidates.append(new_item) return candidates queue = ['0000'] visited = set() visited.add('0000') step = 0 while queue: sz = len(queue) for i in range(sz): head = queue.pop(0) if head == target: return step for c in generate_candidates(head): queue.append(c) visited.add(c) step += 1 return -1 deadends = ["0201", "0101", "0102", "1212", "2002"] target = "0202" deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"] target = "0009" sl = Solution() print(sl.openLock(deadends, target))
"""双指针中心扩展法""" class Solution(object): def expandPalindrome(self, s, l, r): # 以l和r为中心扩展字符串寻找回文串 while(l>=0 and r<len(s) and s[l]==s[r]): l -= 1 r += 1 return s[l+1:r] def longestPalindrome(self, s): """ :type s: str :rtype: str """ if len(s)==0 or len(s)==1: return s res = str() for i in range(len(s)): s1 = self.expandPalindrome(s, i, i) s2 = self.expandPalindrome(s, i, i+1) print("The {}th iteration, s1: {}, s2: {}".format(i, s1, s2)) res = res if len(res)>len(s1) else s1 res = res if len(res)>len(s2) else s2 return res """动态规划法""" class Solution: def longestPalindrome(self, s: str) -> str: if not s: return '' dp = [[False] * len(s) for _ in range(len(s))] # 初始化base case,对角线即单个字符的时候为True for i in range(len(s)): dp[i][i] = True for i in range(len(s)-1, -1, -1): for j in range(i + 1, len(s)): if s[i] == s[j]: if j - i == 1: # 特殊情况 dp[i][j] = True else: dp[i][j] = dp[i + 1][j - 1] max_len = 0 pos =[0, 0] for i in range(len(dp)): for j in range(i, len(dp[0])): if dp[i][j]: if j-i > max_len: max_len = j-i pos[0], pos[1] = i, j return s[pos[0]:pos[1]+1] input_str = 'babad' input_str = 'ccc' sl = Solution() print(sl.longestPalindrome(input_str))
directs = [(0, 1), (0, -1), (1, 0), (-1, 0)] """DFS清晰简单:把与边缘O相连的O标记出来""" class Solution: def solve(self, board) -> None: """ Do not return anything, modify board in-place instead. """ if not board: return m = len(board) n = len(board[0]) def dfs(i, j): board[i][j] = 'M' for d in directs: next_i = i + d[0] next_j = j + d[1] if 0 <= next_i < m and 0 <= next_j < n and board[next_i][next_j] == 'O': dfs(next_i, next_j) for i in range(m): if board[i][0] == 'O': dfs(i, 0) if board[i][-1] == 'O': dfs(i, n - 1) for j in range(n): if board[0][j] == 'O': dfs(0, j) if board[m - 1][j] == 'O': dfs(m - 1, j) for i in range(m): for j in range(n): if board[i][j] == 'O': board[i][j] = 'X' if board[i][j] == 'M': board[i][j] = 'O' board = [["O","X","X","O","X"],["X","O","O","X","O"],["X","O","X","O","X"],["O","X","O","O","O"],["X","X","O","X","O"]] sl = Solution() sl.solve(board) for b in board: print(b)
"""超出时间限制""" class Solution: def largestRectangleArea(self, heights) -> int: if not heights: return 0 heights.append(0) dp = [0] * len(heights) dp[0] = heights[0] for i in range(1, len(heights) - 1): max_rec = dp[i - 1] for j in range(0, i + 1): if j > 0: # 如果当前高度比前一个还小,不用计算面积,跳过 if heights[j] <= heights[j - 1]: continue if (i - j + 1) * min(heights[j:i + 1]) > max_rec: max_rec = (i - j + 1) * min(heights[j:i + 1]) dp[i] = max_rec return dp[-2] """单调递增栈的解法,核心思想是找到左边第一个比i小的和右边第一个比i小的""" class Solution: def largestRectangleArea(self, heights) -> int: stack = [-1] area = 0 heights.append(0) for i in range(len(heights)): print(stack) while heights[i] < heights[stack[-1]]: h = heights[stack.pop()] area = max(area, h * (i - stack[-1] - 1)) print("h: ", h, " Area: ", area) stack.append(i) heights.pop() return area heights = [2, 1, 5, 6, 2, 3] sl = Solution() print(sl.largestRectangleArea(heights))
"""利用84的解法,求出每层的heights数组""" class Solution: def largestRectangleArea(self, heights) -> int: stack = [-1] area = 0 heights.append(0) for i in range(len(heights)): while heights[i] < heights[stack[-1]]: h = heights[stack.pop()] area = max(area, h * (i - stack[-1] - 1)) stack.append(i) heights.pop() return area def maximalRectangle(self, matrix) -> int: if not matrix: return 0 res = 0 dp = [0] * len(matrix[0]) # 从matrix中构建heights数组 for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == "1": dp[j] += 1 else: dp[j] = 0 res = max(res, self.largestRectangleArea(dp)) return res """"更普适的动态规划法""" class Solution: def maximalRectangle(self, matrix) -> int: if not matrix: return 0 res = 0 m = len(matrix) n = len(matrix[0]) dp = [[0] * n for _ in range(m)] # 同行前面(包括自身)有多少个1,前缀和 for i in range(m): for j in range(n): if matrix[i][j] == "0": continue else: dp[i][j] = dp[i][j - 1] + 1 if j > 0 else 1 w = float('inf') for k in range(i, -1, -1): # 回溯前面的行 h = i - k + 1 w = min(w, dp[k][j]) res = max(res, w * h) print("k: %d \t j:%d \t w: %d \t " % (k, j, w)) if w == 0: break return res matrix = [ ["1","0","1","0","0"], ["1","0","1","1","1"], ["1","1","1","1","1"], ["1","0","0","1","0"] ] sl = Solution() print(sl.maximalRectangle(matrix))
import random from DiceRoll import Dice print(random.random()) # Generates random values between 0 and 1 print(random.randint(10, 20)) # Generates random values between the specified limits members = ["Rajeev", "Anjali", "Kriti", "Sarthak"] leader = random.choice(members) # Picks a list element randomly print(f"The team leader is {leader}") diceRoll = Dice() print(diceRoll.roll())
is_hot = False is_cold = False if is_hot : print("It's a hot day") print("Drink plenty of water") elif is_cold : print("Its a cold day") print("Wear warm clothes") else: print("Its a lovely day" ) # EXERCISE price = 1000000 is_goodCredit = True if is_goodCredit : print(f" Please put forward ${price * 0.1}") else: print(f"Please put forward ${price * 0.2}")
from utils import find_max names = ['Rajeev', 'Anjali', 'Kriti', 'Sarthak'] names[2] = 'Kittu' # Updates list's elements print(names) # Exercise - Maximum number in list myList = [2, 4, 3, 6, 7] print(find_max(myList)) # 2D Lists lists = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(lists)
user_input = '' started = False stopped = False while True: user_input = input('> ').upper() if user_input == 'HELP': print('start -> to start the car') print('stop -> to stop the car') print('quit -> to quit the game') elif user_input == 'START' and not started : print('Car started, ready to go !') started = True stopped = False elif user_input == 'START' and started: print('Already started !') elif user_input == 'STOP' and not stopped: print('Car stopped !') stopped = True started = False elif user_input == 'STOP' and stopped : print('Already stopped !') elif user_input == 'QUIT': print('Quiting..') break else: print("I dont understand")
n=int(raw_input()) if (n>0): print(" Positive") elif (n<0): print(" Negative") else: print("Zero")
# Reversing a list using while loop def reverse_list(samplelist): i = len(samplelist) - 1 # Iterate till 1st element and keep on decrementing i while i >= 0: print(samplelist[i]) i -= 1 samplelist = [12, 35, 9, 56, 24] print(reverse_list(samplelist)) # Reversing a list using list comprehension # Syntax of List Comprehension [expression for item in list] def invert_list(input_list): input_list = [input_list[n] for n in range(len(input_list) - 1, -1, -1)] return input_list input_list = [11, 27, -1, -5, 4, 3] print(invert_list(input_list))
import re sample_str = 'an example word:cat!!' match = re.search(r'word:\w\w\w', sample_str) # If-statement after search() tests if it succeeded if match: # 'found word:cat' print('found', match.group()) else: print('did not find') # found, match.group() == "iii" match = re.search(r'iii', 'piiig') print(match.group()) # not found, match == None # match = re.search(r'igs', 'piiig') # print(match.group()) # . = any char but \n # found, match.group() == "iig" match = re.search(r'..g', 'piiig') print(match.group()) # \d = digit char, \w = word char # found, match.group() == "123" match = re.search(r'\d\d\d', 'p123g') print(match.group()) # found, match.group() == "abc" match = re.search(r'\w\w\w', '@@abcd!!') print(match.group()) # To find if it is a email sample_str1 = 'purple alice-b@google.com monkey dishwasher' match = re.search(r'\w+@\w+', sample_str1) if match: # 'b@google' print(match.group())
n = int(raw_input()) # the number of points used to draw the surface of Mars. land_x = [-1] * n land_y = [-1] * n for i in xrange(n): # land_x: X coordinate of a surface point. (0 to 6999) # land_y: Y coordinate of a surface point. By linking all the points together in a sequential fashion, you form the surface of Mars. land_x[i], land_y[i] = [int(j) for j in raw_input().split()] # game loop while True: # h_speed: the horizontal speed (in m/s), can be negative. # v_speed: the vertical speed (in m/s), can be negative. # fuel: the quantity of remaining fuel in liters. # rotate: the rotation angle in degrees (-90 to 90). # power: the thrust power (0 to 4). x, y, h_speed, v_speed, fuel, rotate, power = [int(i) for i in raw_input().split()] if abs(v_speed) > 40 : power = power + 1 if power < 4 else 4 print "0 %d" % power else: power = power - 1 if power > 2 else 2 print "0 %d" % power
import json from difflib import get_close_matches data = json.load(open("data.json")) z = input("This is a dictionary. Enter y to continue ") if z == "y": while z == "y": word = input("Enter the word you want to search ") word = word.lower() if word in data: output = data[word] elif word.title() in data: output = data[word.title()] elif word.upper() in data: output = data[word.upper()] elif len(get_close_matches(word, data.keys(), cutoff = 0.8)) > 0 : print("Did you mean %s ?" %get_close_matches(word, data.keys(), cutoff = 0.8) [0]) new = input("Enter y if yes and Enter n if no ") if new == "y": output = data[get_close_matches(word, data.keys(), cutoff = 0.8) [0]] elif new == "n": output = "You have entered a wrong word" else: output = "You have entered wrong input" else: output = "you have entered a wrong word" if type(output) == list: for item in output: print(item) else: print(output) z = input("Press y to continue or n to exit ")
class EnvironmentVariable(object): """A CAN environment variable. """ def __init__(self, name, env_type, minimum, maximum, unit, initial_value, env_id, access_type, access_node, comment): self._name = name self._env_type = env_type self._minimum = minimum self._maximum = maximum self._unit = unit self._initial_value = initial_value self._env_id = env_id self._access_type = access_type self._access_node = access_node self._comment = comment @property def name(self): """The environment variable name as a string. """ return self._name @property def env_type(self): """The environment variable type value. """ return self._env_type @env_type.setter def env_type(self, value): self._env_type = value @property def minimum(self): """The minimum value of the environment variable. """ return self._minimum @minimum.setter def minimum(self, value): self._minimum = value @property def maximum(self): """The maximum value of the environment variable. """ return self._maximum @maximum.setter def maximum(self, value): self._maximum = value @property def unit(self): """ The units in which the environment variable is expressed as a string. """ return self._unit @unit.setter def unit(self, value): self._unit = value @property def initial_value(self): """The initial value of the environment variable. """ return self._initial_value @initial_value.setter def initial_value(self, value): self._initial_value = value @property def env_id(self): """The id value of the environment variable. """ return self._env_id @env_id.setter def env_id(self, value): self._env_id = value @property def access_type(self): """The environment variable access type as a string. """ return self._access_type @access_type.setter def access_type(self, value): self._access_type = value @property def access_node(self): """The environment variable access node as a string. """ return self._access_node @access_node.setter def access_node(self, value): self._access_node = value @property def comment(self): """The environment variable comment, or ``None`` if unavailable. """ return self._comment @comment.setter def comment(self, value): self._comment = value def __repr__(self): return "environment_variable('{}', {}, {}, {}, '{}', {}, {}, '{}', '{}', {})".format( self._name, self._env_type, self._minimum, self._maximum, self._unit, self._initial_value, self._env_id, self._access_type, self._access_node, "'" + self._comment + "'" if self._comment is not None else None)
from typing import Union def num(number_as_string: str) -> Union[int, float]: """Convert given string to an integer or a float. """ try: return int(number_as_string) except ValueError: return float(number_as_string) except Exception: raise ValueError('Expected integer or floating point number.') from None
""" Digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer. """ x = 1634 while x > 10: for i in str(x): x = sum(int(i)) print(x) """ def digital_root(n): while n >= 10: n = sum(int(i) for i in str(n)) return n """
''' Stack. ''' __all__ = ['Stack'] ''' Almost identical to python's list. ''' class Stack(list): def push(self, value): ''' Add value to end of list. ''' self.append(value) def pop(self): ''' Return and delete the last value ''' ''' Raise EmptyStackError ''' if len(self) == 0: raise EmptyStackError('pop from empty stack.') value = self[-1] del self[-1] return value class EmptyStackError(IndexError): pass
# lists function friends = ['Jonas', 'Martha', 'Bartosz', 'Mikkel', 'Magnus', 'Franziska'] friends.remove('Mikkel') friends.count('Jonas') friends.sort() # friends.pop() # friends.clear() friends2 = friends.copy() friends2.reverse() print(friends) print(friends2)
#coding:utf-8 class Company: def __init__(self,employee_list): self.employee_list = employee_list #是实现切片操作的魔法函数(协议)item传递的是index 字典不可进行该迭代 #如何实现 将emlloyee_list传入的是字典也能直接进行对类做切片操作 def __getitem__(self, item): #print(item) #return self.employee_list[item] return self.employee_list[item] company = Company([1,2,3,4]) #company = Company({'a':1,'b':2,'c':3}) for item in company: print(item) class Vector: def __init__(self,x,y): self.x = x self.y = y def __add__(self, other): return (self.x+other.x ,self.y+other.y) def __str__(self): return (self.x,self.y) v1 = Vector(1,2) v2 = Vector(3,4) print(v1+v2)
#!/usr/bin/env python3 """ *map* module contains *class* **Cell** and **Map**. """ #Author: Zhiwei Luo class Cell: x = -1 y = -1 hasUpWall = False hasDownWall = False hasLeftWall = False hasRightWall = False def __init__(self, x, y): self.x = x self.y = y def setUpAsWall(self): self.hasUpWall = True def setLeftAsWall(self): self.hasLeftWall = True def setRightAsWall(self): self.hasRightWall = True def setDownAsWall(self): self.hasDownWall = True def setAllAsNoWall(self): self.hasUpWall = False self.hasDownWall = False self.hasLeftWall = False self.hasRightWall = False # For Testing def getWhichIsWall(self): whichIsWall = '[x=' + str(self.x) + ' y=' + str(self.y) + ']' if self.hasUpWall: whichIsWall += 'Up ' if self.hasDownWall: whichIsWall += 'Down ' if self.hasRightWall: whichIsWall += 'Right ' if self.hasLeftWall: whichIsWall += 'Left ' return whichIsWall class Map: """ The Map class represents a maze map. The single instance of the Map is stored in a micromouse. You can access the local map of a micromouse by ``mouse.mazeMap``. It maintains: * the size of the map: *height*, *width* * the cells of the map: The cells are represented by a 2-D list array. """ height = 0 width = 0 cells = None def __init__(self, height, width): self.height = height self.width = width self.cells = [[Cell(j, i) for i in range(width)] for j in range(height)] def getCell(self, x, y): """ Get the cell instance by given coordinates *x* and *y*. You may need to first call this function before you update or query a map. """ if x >= 0 and y >= 0 and x < self.width and y < self.height: return self.cells[x][y] else: return None def getCellUpWall(self, cell): """ Return True if there is a wall above the given cell, otherwise return False. You may use this function by ``getCellUpWall(getCell(x, y))`` where *x* and *y* is the coordinates. """ return cell.hasUpWall def getCellDownWall(self, cell): """ Return True if there is a wall below the given cell, otherwise return False. You may use this function by ``getCellDownWall(getCell(x, y))`` where *x* and *y* is the coordinates. """ return cell.hasDownWall def getCellLeftWall(self, cell): """ Return True if there is a wall on the left side of the given cell, otherwise return False. You may use this function by ``getCellLeftWall(getCell(x, y))`` where *x* and *y* is the coordinates. """ return cell.hasLeftWall def getCellRightWall(self, cell): """ Return True if there is a wall on the right side of given cell, otherwise return False. You may use this function by ``getCellRightWall(getCell(x, y))`` where *x* and *y* is the coordinates. """ return cell.hasRightWall def getRightCell(self, cell): return self.getCell(cell.x + 1, cell.y) def getLeftCell(self, cell): return self.getCell(cell.x - 1, cell.y) def getUpCell(self, cell): return self.getCell(cell.x, cell.y - 1) def getDownCell(self, cell): return self.getCell(cell.x, cell.y + 1) def setCellUpAsWall(self, cell): """ Update the map that put a wall above the given cell. You may use this function by ``setCellUpWall(getCell(x, y))`` where *x* and *y* is the coordinates. """ if cell != None: cell.setUpAsWall() cellUp = self.getUpCell(cell) if cellUp != None: cellUp.setDownAsWall() def setCellDownAsWall(self, cell): """ Update the map that put a wall below the given cell. You may use this function by ``setCellDownWall(getCell(x, y))`` where *x* and *y* is the coordinates. """ if cell != None: cell.setDownAsWall() cellDown = self.getDownCell(cell) if cellDown != None: cellDown.setUpAsWall() def setCellLeftAsWall(self, cell): """ Update the map that put a wall on the left side of the given cell. You may use this function by ``setCellLeftWall(getCell(x, y))`` where *x* and *y* is the coordinates. """ if cell != None: cell.setLeftAsWall() cellLeft = self.getLeftCell(cell) if cellLeft != None: cellLeft.setRightAsWall() def setCellRightAsWall(self, cell): """ Update the map that put a wall on the right side of the given cell. You may use this function by ``setCellRightWall(getCell(x, y))`` where *x* and *y* is the coordinates. """ if cell != None: cell.setRightAsWall() cellRight = self.getRightCell(cell) if cellRight != None: cellRight.setLeftAsWall() def readFromFile(self, mazeFile): """ Read and parse the maze file. The maze file example can be found `here <http://www.tcp4me.com/mmr/mazes/2018apec.maze>`_. The "|", "-" or "+" represents the vertical and horizontal walls. """ try: mazeFileReader = open(mazeFile, 'r') mazeLine = mazeFileReader.readlines() height = (int(len(mazeLine)/2)) width = (int(len(mazeLine[0])/2-1)) for i in range(height): for j in range(width): x = 2 * j + 1 y = 2 * i + 1 cell = self.getCell(j, i) cellLeftStr = mazeLine[y][x-1] cellUpStr = mazeLine[y-1][x] cellRightStr = mazeLine[y][x+1] cellDownStr = mazeLine[y+1][x] if cellLeftStr == '|': self.setCellLeftAsWall(cell) if cellUpStr == '-': self.setCellUpAsWall(cell) if cellRightStr == '|': self.setCellRightAsWall(cell) if cellDownStr == '-': self.setCellDownAsWall(cell) mazeFileReader.close() except: print('Open Maze File Error!')
#!/usr/bin/python3 from __future__ import print_function from random import seed, choice, randint from argparse import ArgumentParser class Random_Word (object) : """ Generate random words from the given charset in the given length range. """ def __init__ (self, charset, minlen = 2, maxlen = 7, randseed = None) : if randseed : seed (randseed) self.minlen = minlen self.maxlen = maxlen self.charset = charset # end def __init__ def __iter__ (self) : """ Iterator to return next random word """ while True : l = randint (self.minlen, self.maxlen) r = [] for k in range (l) : r.append (choice (self.charset)) yield ''.join (r) # end def __iter__ # end class Random_Word if __name__ == "__main__" : import sys cmd = ArgumentParser () cmd.add_argument \ ( "-c", "--charset" , dest = "charset" , help = "charset from which to chose the words" , default = ''.join (chr (x) for x in range (ord ('a'), ord ('z') + 1)) ) cmd.add_argument \ ( "-m", "--minlen" , dest = "minlen" , help = "Minimum length for a word" , type = int , default = 2 ) cmd.add_argument \ ( "-M", "--maxlen" , dest = "maxlen" , help = "Maximum length for a word" , type = int , default = 7 ) cmd.add_argument \ ( "-n", "--nwords" , dest = "nwords" , help = "Number of words to generate" , type = int , default = 5 ) cmd.add_argument \ ( "-r", "--randseed" , dest = "randseed" , help = "random seed" , type = int ) cmd.add_argument \ ( "-v", "--vvv" , dest = "vvv" , help = "send vvv before start" , default = False , action = "store_true" ) args = cmd.parse_args () if args.vvv : print ("vvv ") rw = Random_Word (args.charset, args.minlen, args.maxlen, args.randseed) print ('') for n, r in enumerate (rw) : print (r, end = ' ') if n + 1 == args.nwords : break print ()
def bubbleSort(arr): for num in range(len(arr)-1,0,-1): for i in range(num): if arr[i]>arr[i+1]: temp = arr[i] arr[i] = arr[i+1] arr[i+1] = temp arr = [9,8,6,7,1,4,5,32,45,3,4,555,3,2,3,2,1] bubbleSort(arr) print(arr) def bubbles(arr): x=len(arr)-1 for i in range(x): for j in range(x-i): if arr[j]>arr[j+1]: arr[j],arr[j+1]=arr[j+1],arr[j] return arr arr=[1,9,2,8,3,7,4,6,5,98] print(bubbles(arr)) print('Done')
import numpy as np import matplotlib.pyplot as plt def salt_overtime(mins): times = [] values_A = [] values_B = [] total_water_A = 100 total_water_B = 100 total_salt_A = 0 total_salt_B = 20 salt_concentration_in = .2 in_speed_A = 6 in_speed_B = 3 out_speed_A = 4 out_speed_B = 2 B_to_A = 1 for i in range(mins): #flow in total_water_A += in_speed_A total_salt_A += salt_concentration_in * in_speed_A salt_concentration_A = total_salt_A/total_water_A #flow out total_water_A -= out_speed_A total_salt_A -= salt_concentration_A * out_speed_A salt_concentration_A = total_salt_A/total_water_A times.append(i) values_A.append(salt_concentration_A) # flow in total_water_B += in_speed_B total_salt_B += salt_concentration_A * in_speed_B salt_concentration_B = total_salt_B / total_water_B # flow out total_water_B -= out_speed_B + B_to_A total_salt_B -= (salt_concentration_B * out_speed_B) + (salt_concentration_A * B_to_A) salt_concentration_B = total_salt_B / total_water_B values_B.append(salt_concentration_B) print(values_B[5]) return values_A, values_B, times def plot_me(): salt1, salt2, time = salt_overtime(1000) plt.plot(time, salt1, label='Tank A') plt.plot(time, salt2, label='Tank B') plt.legend() plt.show() plot_me()
class Node(object): # 构造函数 def __init__(self, elem): self.elem = elem self.next = None class SingleLinkList(object): """单链表""" def __init__(self, node=None): self.__head = node def is_empty(self): return self.__head == None def length(self): # 游标,用来移动遍历节点 cur = self.__head # count记录数量 count = 0 while cur != None: count += 1 cur = cur.next return count def travel(self): cur = self.__head while cur != None: print(cur.elem, end=' ') cur = cur.next print('\n') def add(self, item): # 头插法 node = Node(item) node.next = self.__head self.__head = node def append(self, item): # 尾插法 node = Node(item) if self.is_empty(): self.__head = node else: cur = self.__head while cur.next != None: cur = cur.next cur.next = node def insert(self, pos, item): if pos <= 0: self.add(item) elif pos > (self.length() - 1): self.append(item) else: pre = self.__head count = 0 while count < (pos - 1): pre = pre.next count += 1 node = Node(item) node.next = pre.next pre.next = node def remove(self, item): cur = self.__head pre = None while cur!=None: if cur.elem == item: # if cur ==self.__head: if self.__head.elem==item: self.__head=cur.next else: pre.next = cur.next break else: pre = cur cur = cur.next def search(self, item): cur = self.__head while cur != None: if cur.elem == item: return True else: cur = cur.next return False # node = Node() if __name__ == '__main__': s = SingleLinkList() print(s.is_empty()) print(s.length()) s.append(1) s.travel() print(s.is_empty()) print(s.length()) s.add('??') s.insert(0, 20) s.insert(1, 30) s.insert(20, 30) # s.append(1) # s.append(2) # s.append(3) s.travel() s.remove(20) s.travel()
#导入模块和要测试的函数 import unittest from name_function import get_fromatted_name #编写测试类,必须继承自unittest.TestCase class NamesTestCase(unittest.TestCase): """测试name_function.py""" #测试方法 def test_first_last_name(self): """能够正确的处理Python Java这样的名字吗?""" formatted_name=get_fromatted_name('python','java') #调用断言方法用来核实得到的结果是否与期望值结果一致 self.assertEqual(formatted_name,'Python Java') #运行测试 unittest.main()
#定义一个集合 mylist=['python','java','dotnet'] print(mylist) print('第一个元素:'+mylist[0]) print('第三个元素:'+mylist[2]) print('最后一个元素:'+mylist[-1]) print('倒数第二个元素:'+mylist[-2]) #修改元素 mylist[0]='php' print(mylist) #将元素添加到列表末尾 mylist.append('javascript') print(mylist) #在第二个元素之前插入 mylist.insert(1,'C++') print(mylist) #删除指定索引位置的元素 del mylist[1] mylist.append('go') mylist.pop(1) print(mylist) #删除列表中指定值的元素 mylist=['csharp','python','java','php','go'] mylist.remove('java') print(mylist) #列表排序 #永久性排序 mylist=['python','node.js','java','go','php','csharp'] mylist.sort() print(mylist) #临时性排序 arr=sorted(mylist) print(arr) print(mylist) #永久性的反转元素的排列顺序 mylist.reverse() print(mylist) #获取长度 len(mylist) #遍历列表 for s in mylist: print(s) #数值列表 for value in range(1,5): print(value) #设置步长 for value in range(2,11,4): print(value) #数值列表的统计计算 nums=[2,5,1,6] print(min(nums)) print(max(nums)) print(sum(nums)) #列表解析 mylist=[v+3 for v in range(2,4)] print(mylist) nlist=[str(n)+'w' for n in mylist] print(nlist) #列表切片 mylist=['csharp','python','java','php','go'] #用法一 print(mylist[1:3]) #用法二 print(mylist[:3]) #用法三 print(mylist[1:]) #输出最后三个元素 print(mylist[-3:]) #输出倒数第三个和倒数第二个元素 print(mylist[-3:-1]) #输出最后三个元素时,第二个参数不能指定为0(将会得不到任何结果) print(mylist[-3:0]) for p in mylist[:4]: print(p) #复制一个全新的列表 copy_list=mylist[:] print(copy_list) #元组的使用 mytuple=(10,20,30) for t in mytuple: print(t)
#读取整个文件 with open('pi_digits.txt') as file_object: contents=file_object.read() #去除多余空白 #print(contents.rstrip()) #逐行读取 #with open('pi_digits.txt') as file_object2: # for line in file_object2: # print(line) #创建包含文件各行内容的列表 with open('pi_digits.txt') as file_object3: #从文件中读取每一行,并将其存储在一个列表中 lines=file_object3.readlines() #在with代码块的外面读取该列表 for line in lines: print(line.rstrip())
filename='test.txt' #写入空文件 with open(filename,'w') as file_obj: file_obj.write('hello python!') #写入多行 with open(filename,'w') as file_obj2: file_obj2.write('java \n') file_obj2.write('python \n') #附加到文件 with open(filename,'a') as file_obj3: file_obj3.write('one \n') file_obj3.write('two \n') 异常处理 try: print(5/0) except ZeroDivisionError: print('被除数不能为0')
from collections import deque from typing import List import heapq ''' 1631. 最小体力消耗路径 你准备参加一场远足活动。给你一个二维 rows x columns 的地图 heights ,其中 heights[row][col] 表示格子 (row, col) 的高度。 一开始你在最左上角的格子 (0, 0) ,且你希望去最右下角的格子 (rows-1, columns-1) (注意下标从 0 开始编号)。 你每次可以往 上,下,左,右 四个方向之一移动,你想要找到耗费 体力 最小的一条路径。 一条路径耗费的 体力值 是路径上相邻格子之间 高度差绝对值 的 最大值 决定的。 请你返回从左上角走到右下角的最小 体力消耗值 。 ''' class Solution: # 代码很简洁,一看就明白了。 # 和一般的BFS不同的是, 使用优先队列代替普通队列,每次从队列中先出路径最小的节点。如果某次出队是终点,那么必是最小路径所达的终点 # 理解:假如说你比较皮,不是一条路走到底,而是每次给相连的最小消耗的区域涂色,就很好理解了。跟迪杰斯特拉算法很类似。 def minimumEffortPath1(self, heights: List[List[int]]) -> int: # m为行,n为列 m, n = len(heights), len(heights[0]) visit = set() nodes = [(0, 0, 0)] # dis, i, j while nodes: dis, i, j = heapq.heappop(nodes) if i == m - 1 and j == n - 1: return dis if (i, j) in visit: # 跳过已经遍历过的点 continue visit.add((i, j)) for x, y in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]: if 0 <= x < m and 0 <= y < n and (x, y) not in visit: heapq.heappush(nodes, (max(dis, abs(heights[x][y] - heights[i][j])), x, y)) # 二分法+bfs def minimumEffortPath2(self, heights: List[List[int]]) -> int: m, n = len(heights), len(heights[0]) mat = [[0]*n for _ in range(m)] l, r = 0, 999999 while l < r: mid = (l + r)//2 mat = [[0]*n for _ in range(m)] mat[0][0] = 1 queue = deque([(0, 0)]) while queue: i, j = queue.popleft() for x, y in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]: if 0<=x<m and 0<=y<n and mat[x][y]==0 and abs(heights[i][j] - heights[x][y]) <= mid: queue.append((x, y)) mat[x][y] = 1 if mat[-1][-1] == 1: r = mid else: l = mid + 1 return l if __name__ == '__main__': s=Solution() a=s.minimumEffortPath2([[1,2,2],[3,8,2],[5,3,5]]) print(a)
''' 24. 两两交换链表中的节点 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 示例 1: 输入:head = [1,2,3,4] 输出:[2,1,4,3] 示例 2: 输入:head = [] 输出:[] 示例 3: 输入:head = [1] 输出:[1] ''' import ListNode class Solution: def swapPairs(self, head: ListNode) -> ListNode: if not head or head.next: return head newHead = head.next head.next = self.swapPairs(newHead.next) newHead.next = head return newHead if __name__ == '__main__': s = Solution() a = s.swapPairs(head=[1, 2, 3, 4]) print(a)
''' 367. 有效的完全平方数 给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。 说明:不要使用任何内置的库函数,如 sqrt。 示例 1: 输入:16 输出:True 示例 2: 输入:14 输出:False ''' class Solution: # 暴力法 def isPerfectSquare1(self,num)->bool: i=1 while i*i<num: i+=1 return i*i==num # 二分法 def isPerfectSquare2(self,num)->bool: left=1 right=num while left<=right: mid=(left+right)//2 if mid*mid<num: left=mid+1 elif mid*mid>num: right=mid-1 else: return True #数学定理 def isPerfectSquare3(self, num) -> bool: i=1 while num>0: num-=i i+=2 return num==0 # 牛顿迭代法 def isPerfectSquare4(self,num)->bool: if 1==num: return True i=num//2 while i*i>num: i=(i+num//i)//2 return i*i==num s=Solution() t1=s.isPerfectSquare1(13) t2=s.isPerfectSquare2(16) t3=s.isPerfectSquare3(16) t4=s.isPerfectSquare4(16) print(t1) print(t2) print(t3) print(t4)