text
stringlengths
37
1.41M
#python 列表 var1=['peng','man','yi'] var2='peng' if var2 in var1: print 'in' else: print 'not in' print var1 var1[1]='man' print var1 var3=['19891006',29] print var1+var3 for x in var1: print x #python截取列表 print var1[1:] print len(var1) print max(var1) print min(var1) var4=[20,30,10,34,53] print max(var4) print min(var4) print var4.index(10) var4.sort() print var4
from scipy.stats import truncnorm import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns def simulate_data() -> list: """ Generate data for Monte Carlo Simulation :return: a list of data >>> np.random.seed(1) >>> data=simulate_data() >>> print(data[1]) [28.0, 7.0, 22.0, 20.0, 18.0] >>> print(data[0]) [27, 22, 36, 15, 31] """ # seed=1 # the number of people in the line people=list(range(9)) prob=[0.04,0.08,0.12,0.16,0.2,0.16,0.12,0.08,0.04] #np.random.seed(seed) num=int(np.random.choice(people,1,p=list(prob))) # the time each person needs to order a cup of coffee (in seconds) order_lower, order_upper=5, 60 order_mu, order_sigma=25, 5 order=truncnorm((order_lower-order_mu)/order_sigma, (order_upper-order_mu)/order_sigma, loc=order_mu, scale=order_sigma) order_time=order.rvs(num+1) # the size of a cup of coffee cup=["tall","grande","venti"] cup_prob=[0.25,0.5,0.25] cup_size=np.random.choice(cup,num+1,p=list(cup_prob)) # the time a barista needs to make a cup of coffee make_t=[] for i in range(num+1): lower,upper=5,80 if cup_size[i]=="tall": mu=25 sigma=5 elif cup_size[i]=="grande": mu=28 sigma=7 elif cup_size[i]=="venti": mu=30 sigma=8 dist=truncnorm((lower-mu)/sigma, (upper-mu)/sigma, loc=mu, scale=sigma) make_t.append(float(dist.rvs(1))) make_t=[round(x) for x in make_t] order_time=[round(x) for x in order_time] return [make_t,order_time,num] class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item): self.items.insert(0,item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) class Barista: def __init__(self): self.break_t=0 self.currentOrder = None self.timeRemaining = 0 def busy(self): if self.currentOrder != None: return True else: return False def tick(self): if self.currentOrder != None: self.timeRemaining -= 1 if self.timeRemaining <= 0: self.timeRemaining=0 self.currentOrder = None def nextOrder(self,make_t): self.timeRemaining=make_t self.currentOrder=1 def simulation(times=1) -> list: """ Do Monte Carlo Simulation :param times: times of doing Monte Carlo Simulation :return: a list of a wait time list and two break time lists >>> np.random.seed(1) >>> results=simulation() >>> print(results) [[126], [32], [89]] """ wait_time = [] break_time_a = [] break_time_b = [] for i in range(times): data = simulate_data() customers_q = Queue() after_order = Queue() barista_a = Barista() barista_b = Barista() n = data[2] + 1 # the number of people in the line (including Johanna) wait_t = 0 # construct customers queue for i in range(n): customers_q.enqueue((data[1][i], data[0][i])) # a customer is ordering for count in range(n): customer = customers_q.dequeue() order_t = customer[0] while order_t > 0: order_t -= 1 wait_t += 1 if (not barista_a.busy()) and (after_order.isEmpty()): barista_a.break_t += 1 elif (not barista_a.busy()): make_t = after_order.dequeue() barista_a.nextOrder(make_t) barista_a.tick() else: barista_a.tick() if (not barista_b.busy()) and (after_order.isEmpty()): barista_b.break_t += 1 elif (not barista_b.busy()): make_t = after_order.dequeue() barista_b.nextOrder(make_t) barista_b.tick() else: barista_b.tick() after_order.enqueue(customer[1]) # after all customers have finished ordered if not barista_a.busy(): make_t = after_order.dequeue() barista_a.nextOrder(make_t) elif not barista_b.busy(): make_t = after_order.dequeue() barista_b.nextOrder(make_t) while barista_a.busy() or barista_b.busy(): wait_t += 1 if (not barista_a.busy()) and (not after_order.isEmpty()): make_t = after_order.dequeue() barista_a.nextOrder(make_t) barista_a.tick() elif (not barista_a.busy()): barista_a.break_t += 1 else: barista_a.tick() if (not barista_b.busy()) and (not after_order.isEmpty()): make_t = after_order.dequeue() barista_b.nextOrder(make_t) barista_b.tick() elif (not barista_b.busy()): barista_b.break_t += 1 else: barista_b.tick() wait_time.append(wait_t) break_time_a.append(barista_a.break_t) break_time_b.append(barista_b.break_t) return [wait_time,break_time_a,break_time_b] if __name__ == '__main__': mysimulations=simulation(5000) # summary of Johanna's wait time, barista_a's break time and barista_b's break time wait_time = pd.DataFrame(mysimulations[0]) print(wait_time.describe()) break_time_a = pd.DataFrame(mysimulations[1]) print(break_time_a.describe()) break_time_b = pd.DataFrame(mysimulations[2]) print(break_time_b.describe()) # density plot plt.figure(1) plt.subplot(211) sns.distplot(list(wait_time.loc[:,0]), hist = False, kde = True) plt.title('Wait Time') plt.subplot(212) sns.distplot(break_time_a, hist=False, kde=True,label='Barista A') sns.distplot(break_time_b, hist=False, kde=True,label='Barista B') plt.title('Break Time') plt.legend(title='Barista') plt.show()
# # Write a (recursive) method to compute all the permutations of a string. # # From the recursion section in Cracking the Coding Interview. # https://stackoverflow.com/questions/13109274/python-recursion-permutations?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa # # from itertools import permutations # # def get_perms(s): # return permutations(s) def rec_get_permutations(s): if len(s)==1: return [s] perm_list = [] for a in s: remaining_elements = [x for x in s if x != a] z = rec_get_permutations(remaining_elements) for t in z: perm_list.append([a]+t) return perm_list
def max_pairwise_product(numbers): n = len(numbers) max_product = 0 max_index1=0 for first in range(n): if max_index1==0 or numbers[first]>numbers[max_index1]: max_index1=first max_index2=0 for second in range(n): if second!=max_index1 and (max_index2==0 or numbers[second]>numbers[max_index2]): max_index2=second return (numbers[max_index1] * numbers[max_index2]) if __name__ == '__main__': input_n = int(input()) input_numbers = [int(x) for x in input().split()] print(max_pairwise_product(input_numbers))
# -*- coding: utf-8 -*- """ Created on Thu Jun 27 07:06:48 2019 @author: souma """ class Employee: # Define class variables raise_amount = 1.04 num_employees = 0 def __init__(self, fname, lname, pay): self.fname = fname self.lname = lname self.pay = pay self.email = self.fname + '.' + self.lname + '@company.com' Employee.num_employees += 1 # Class Methods def fullname(self): '''Returns the fullname of an employee''' fullname = self.fname + ' ' + self.lname return fullname def apply_raise(self): '''Adds a raise amount to the employees salary''' self.pay = int(self.pay * Employee.raise_amount) # Define an employee emp_1 = Employee('Soumadiptya', 'Chakraborty', 50000) print(emp_1.pay) emp_1.apply_raise() print(emp_1.pay) # Print the namespace of class instances and the class itself print(emp_1.__dict__) print(Employee.__dict__) # Changing class variables Employee.raise_amount = 1.05 # This will glbally update the value of raise amount print(Employee.raise_amount, emp_1.raise_amount) emp_1.raise_amount = 1.06 # Only change sit for employee 1 and includes it in it's namespace print(Employee.raise_amount, emp_1.raise_amount, emp_1.__dict__) print(Employee.num_employees)
import random from collections import Counter from typing import List Scores={ "Straight":1500, "Three Pairs" : 1500, (1,1):100, (1,2):200, (1,3):1000, (1,4):2000, (1,5):3000, (1,6):4000, (2,3):200, (2,4):400, (2,5):600, (2,6):800, (3,3):300, (3,4):600, (3,5):900, (3,6):1200, (4,3):400, (4,4):800, (4,5):1200, (4,6):1600, (5,1):50, (5,2):100, (5,3):500, (5,4):1000, (5,5):1500, (5,6):2000, (6,3):600, (6,4):1200, (6,5):1800, (6,6):2400 } class GameLogic: """ Name: GameLogic Description: A class used to handle the logic of the Game of Greed Game Methods: calculate_score(static method): Input: tuple of integers that represent a dice roll Output: integer representing the roll’s score according to rules of the game roll_dice(static method): Input: Integer ( between 1 and 6) Output: tuple with random values between 1 and 6 """ def __init__(self): pass @staticmethod def roll_dice(dice_num=6): return tuple(random.randint(1,6) for _ in range(0,dice_num)) @staticmethod def calculate_score(dice): score = 0 dices=Counter(dice) print(dices) x = list(dices) x.sort() # print(x) if x == [1,2,3,4,5,6]: score +=Scores["Straight"] elif list(dices.values()) == [2, 2, 2]: score +=Scores["Three Pairs"] else: for i in dices.items(): print(i) try: score +=Scores[i] except: score +=0 return score print(GameLogic.calculate_score((4,3,2,2,5,6))) print(GameLogic.calculate_score((3,3,2,2,6,6))) print(GameLogic.calculate_score((4,3,2,1,5,6))) print(GameLogic.calculate_score((4,4,4,1,1,1))) print(GameLogic.calculate_score((1, 1, 1, 2, 2, 2)))
# imports import pandas as pd import matplotlib.pyplot as plt import numpy as np # Read & sort dataset db = pd.read_csv("data.csv") db = db.sort_values(by=["month"],ascending=True) db = db[db.number_people != 0] # temp variables indexW=0 countW=0 avgW = [0] * 5 indexF=0 countF=0 avgF = [0] * 5 # get avg of ppl per month for month,ppl,durSem,isHoliday in zip(db.month,db.number_people,db.is_during_semester,db.is_holiday): if (1 <= month <= 5 and durSem==1 and isHoliday !=1): # Winter Semester if month == indexW+1: avgW[indexW] += ppl countW+=1 else: avgW[indexW] = avgW[indexW]/countW indexW+=1 countW=0 elif(8 <= month <= 12 and durSem==1 and isHoliday !=1): # Fall Semester if month == indexF+8: avgF[indexF] += ppl countF+=1 elif(countF!=0): avgF[indexF] = avgF[indexF]/countF indexF+=1 countF=0 # Calculate last month of semester avgW[indexW] = avgW[indexW]/countW avgF[indexF] = avgF[indexF]/countF # Plot Graphs monthsW = ["Jan","Feb","Mar","Apr","May"] # Winter Semester plt.bar(monthsW,avgW,label = "Winter") monthsF = ["Aug","Sep","Oct","Nov","Dec"] # Fall Semester plt.bar(monthsF,avgF,label = "Fall") plt.xlabel("Month") plt.ylabel("Average Number of People") plt.title("Average for the Winter and Fall Semester") plt.tight_layout() plt.legend(loc ="upper right") plt.gcf().set_size_inches(11,8) plt.savefig('AvgSemester.png', bbox_inches='tight') plt.show()
class Actor(): def list_actor(): actor=[] while True: name=input("please type the actor name : ") actor.append(name) if int(input("Do you want to continue? 0-1"))==0: break return actor
#Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. #Example: #Input: [0,1,0,3,12] #Output: [1,3,12,0,0] from typing import List def moveZeroes(nums: List[int]) -> None: j = 0 for i in range(0, len(nums)): if nums[i] != 0: temp = nums[i] nums[i] = nums[j] nums[j] = temp j+=1 #Sample run mylist= [0,1,0,3,1,2] moveZeroes(mylist) print(mylist)
from BinaryTree import BinaryTree from Bacteria import Bacteria import random #Original values to pass in _LENGTH = 1 _POS_X = 0 _POS_Y = 0 _AGE = 0 _SPACE_PER_LEVEL = 10 _EMPTY_LINE = "" for i in range(0, _SPACE_PER_LEVEL): _EMPTY_LINE += ' ' _DEBUG = True _TIME = 3 #Units of time that simulation runs _REPRODUCE_PROBABILITY = 0.5 #Probablility that bacteria reproduces given that it is long enough _MIN_LEN = 8 #Minimum length to be able to reproduce depth = (2*_TIME)+1 _NAME_LIST = ["Jane", "Lucy", "Mark", "Marie", "Sarah", "Logan"] def divide(parent_node): """parent_node is a tree representing parent bacterium. divide updates tree and returns it""" parent = parent_node.root l_name = random.randint(0, len(_NAME_LIST)-1) r_name = random.randint(0, len(_NAME_LIST)-1) (l, r) = parent.divide(_NAME_LIST[l_name], _NAME_LIST[r_name]) if _DEBUG: print("\nparent: {}".format(parent)) print("left child: {}".format(l.name)) print("right child: {}\n".format(r.name)) parent_node.insert_lc(l) parent_node.insert_rc(r) parent.murder() def shouldDivide(bacteria): p = bacteria.getDivisionProbability() luck = random.uniform(0,1) if luck < p: return True return False def printTree(self, output_file = "output.txt"): """Print the tree into text file""" depth #Lines occupied by tree in file num_lines = (2**(depth+1)) - 1 print("Number of lines is {}.".format(num_lines)) line_data = dict() self._get_line_data(depth, (num_lines//2)+1, line_data) self.printDict(line_data) with open(output_file, 'w') as f: for line_no in range(1, num_lines+1): print("Working on line {}.".format(line_no)) #Build string for this line line = "" if line_no in line_data: print("Line {} has something".format(line_no)) line_dict = line_data[line_no] self.printDict(line_dict) for ht in range (0, depth+1): if ht in line_dict: bact = line_dict[ht] print("found bacteria {}".format(bact.name)) line_length = _SPACE_PER_LEVEL - len(bact.name) horizontal_line = "" if ht!= 0: #Build a line of approrpiate length for the diagram for j in range(0, line_length): horizontal_line+="-" horizontal_line+="|" line = bact.name + horizontal_line + line else: line = _EMPTY_LINE + line f.write(line) if __name__ == '__main__': timothy = Bacteria(_LENGTH, _POS_X, _POS_Y, _AGE, "timothy") tree = BinaryTree(timothy) # divide(tree) #Run for i units of time for i in range(_TIME): children = tree.getLiveBacteria() for child in children: if shouldDivide(child.root): divide(child) if (_DEBUG): print(child.root.name) print("Age: {}".format(str(child.root.age))) print("Length: {}".format(str(child.root.len))) tree.ageTree() print(tree.root)
goal = int(input("What is your savings goal: ")) deposit = int(input("What is your monthly deposit: ")) interest = int(input("What is the annual interest rate: ")) print("") total = 1000 month = 1 while total <= goal: monthly_interest = total / 120 format_total = "{:.2f}".format(total) print(f"Month {month}: You have saved: ${format_total}") total += deposit + monthly_interest month += 1 if total > goal: format_total = "{:.2f}".format(total) print(f"Month {month}: You have saved: ${format_total}") print(f"It will take {month} months to save ${goal}")
r = float(input("반지름 입력 : ")) def circle_square(r): x = r**2 * 3.14 print('원의 면적은 {}이다.'.format(x)) return r circle_square(r)
num = input("Enter Your Number :") numb = int(num) if(numb>=0): print(numb, " is Positive Number") else: print(numb," is negetive Number")
program_terminate = False while not program_terminate: n1=input("Enter num1 value :\n") n2=input("Enter num2 value :\n") n1=int(n1) n2=int(n2) con = input("Enter The method like 'quit,sub,add' only one from here :\n") while True: if con=="quit": program_terminate=True break if con not in ["add","sub"]: print("Unknown Method") break if con=="add": print("sum is = ",n1+n2) break if con =="sub": print("num2-num1 number\'s sub is = ",n2-n1) break
marks = input("Enter your marks :") marks = int(marks) if marks>=80: grade="A+" elif marks>=70: grade="A" elif marks>=60: grade="A-" elif marks>=50: grade="B+" elif marks>=40: grade="B" else: grade="F" print("Your Grade is :",grade)
#Shitty code to generate input string randomly import string import random inp=input("Enter your string without space: ") out='' con=0 total=0 while(inp != out ): total+=1 randomLetter = random.choice(string.ascii_letters) print(randomLetter) if (randomLetter==inp[con]): out+=randomLetter con+=1 print ("IT'S A MATCH! New String: "+out) print("String: "+out) print("Found in "+str(total)+" iterations")
import numpy as np import pandas as pd def suited_to_int(s): """returns 1 if suited and 0 if unsuited Args: s (string): yes or no, input by user Returns: int: 1 if suited (True), 0 if unsuited (False) """ s = s[0].upper() if s == 'Y': return 1 else: return 0 def fix_val(val): # puts val in correct form """using input val assigns to same form as cards were stored in OG data Args: val (string): string with user input card value Returns: string: first letter of input card value (10 = 1, 5=5, Ace = A, ect.) uppercased """ if len(val) > 1: val = val[0] if val.isnumeric() == False: val = val.upper() return val # def fix_suit(suit): # puts suit in correct form # return suit[0].upper() def construct_cards(val1, val2, suited=0): """takes in 2 user input cards, calls fix_val to put them in correct form, looks at suited to assign suitedness, and puts them in a list. then calls return_card_vals to get rank, lowcard, highcard Args: val1 (string): first card val2 (string): second card suited (int, optional): whether the card was suited or not. 1 for suited 0 for unsuited Defaults to 0. Returns: [type]: [description] """ val1 = fix_val(val1) val2 = fix_val(val2) if suited: # gives card identical value for suit, if suited ==False different values for suit card1 = f'X{val1}' card2 = f'X{val2}' else: card1 = f'X{val1}' card2 = f'Y{val2}' cards = [card1, card2] rank, lc, hc = return_card_vals(cards) return rank, lc, hc def return_card_vals(cards): """using cards created in 'construct_cards' get highcard, lowcard, card_rank Args: cards (list): list of 2 card values Returns: rank (float): card_rank, value between -1.5 & 20 lc (int): lowest card hc (int): highest card """ hc = highest_card(cards) lc = lowest_card(cards) rank = cards_numeric(cards) return rank, lc, hc def cards_numeric(x): """Takes in cards and spits out card_rank Args: x (list): list of my hole cards Returns: float: card_rank, as dicated by the Chen Formula (sans rounding) """ result = 0 if isinstance(x, list): if len(x[0]) == 2 and len(x[1]) == 2: c1 = x[0] c2 = x[1] c1_rank = c1[1] c2_rank = c2[1] c1_suit = c1[0] c2_suit = c2[0] c_rank = [c1_rank, c2_rank] numeric_card_lst = [] for card in c_rank: # assigning numeric value of card ranks if card in ['A', 'K', 'Q', 'J', '1']: numeric_dic = {'A': 14, 'K': 13, 'Q': 12, 'J': 11, '1': 10} numeric_card_lst.append(numeric_dic[card]) else: numeric_card_lst.append(int(card)) highest = max(numeric_card_lst) # assigning points for highest card if highest > 10: # points for over 10 high_vals = {14:10, 13:8, 12:7, 11:6} result += high_vals[highest] else: # points for 10 & under result += highest / 2 if c1_suit == c2_suit: # assigning points for whether cards are suited result += 2 val = highest - min(numeric_card_lst) # getting the distance betweeen the cards if val == 0: # doubling points of pocket pairs result *= 2 if result < 5: # worth minimum of 5 points result = 5 else: # now assigning points for connectedness between if val <= 3: # 2 gapper and less result -= val - 1 else: if val == 4: # 3 gapper result -= val else: # 4 gapper and more result -= 5 if val <= 2 and val != 0 and numeric_card_lst[0] < 12 and numeric_card_lst[1] < 12: result += 1 return result # I elected not to round up as the formula dictates, not sure what benefit it would have in this scenario def highest_card(x): """Finds value of highest card Args: x (list): list of my 2 cards Returns: int: value of card, 2 being lowest and 14 (Ace) being highest """ result = None if isinstance(x, list): if len(x[0]) == 2 and len(x[1]) == 2: c1 = x[0] c2 = x[1] c1_rank = c1[1] c2_rank = c2[1] numeric_card_lst = [] c_rank = [c1_rank, c2_rank] for card in c_rank: # assigning numeric value of card ranks if card in ['A', 'K', 'Q', 'J', '1']: numeric_dic = {'A': 14, 'K': 13, 'Q': 12, 'J': 11, '1': 10} numeric_card_lst.append(numeric_dic[card]) else: numeric_card_lst.append(int(card)) result = int(max(numeric_card_lst)) return result def lowest_card(x): """find lowest card Args: x (list): list of my 2 cards Returns: int: value of card, 2 being lowest and 14 (Ace) being highest """ result = None if isinstance(x, list): if len(x[0]) == 2 and len(x[1]) == 2: c1 = x[0] c2 = x[1] c1_rank = c1[1] c2_rank = c2[1] numeric_card_lst = [] c_rank = [c1_rank, c2_rank] for card in c_rank: # assigning numeric value of card ranks if card in ['A', 'K', 'Q', 'J', '1']: numeric_dic = {'A': 14, 'K': 13, 'Q': 12, 'J': 11, '1': 10} numeric_card_lst.append(numeric_dic[card]) else: numeric_card_lst.append(int(card)) result = int(min(numeric_card_lst)) return result
def findTheNumbers(a): mydict={} for i,ele in enumerate(a): if ele not in mydict: mydict[ele] = list() mydict[ele].append(i) if len(mydict[ele])==2: del mydict[ele] return sorted(list(mydict.keys())) if __name__ == '__main__': a = [1, 3, 5, 6, 1, 4, 3, 6] print findTheNumbers(a)
# Globals for the directions # Change the values as you see fit EAST = 'east' NORTH = 'north' WEST = 'west' SOUTH = 'south' class Robot: def __init__(self, direction=NORTH, x=0, y=0): self.direction = direction self.x = x self.y = y @property def coordinates(self): return self.x, self.y def move(self, command): if command == None: raise ValueError("Invalid movement") else: for moving in command: self.returns_moviments(moving) def returns_moviments(self, moviment): if moviment == 'R': self.move_robo_right() elif moviment == 'L': self.move_robo_left() elif moviment == 'A': self.move_robo_advance() def move_robo_right(self): if self.direction == NORTH: self.direction = EAST elif self.direction == EAST: self.direction = SOUTH elif self.direction == SOUTH: self.direction = WEST elif self.direction == WEST: self.direction = NORTH def move_robo_left(self): if self.direction == NORTH: self.direction = WEST elif self.direction == WEST: self.direction = SOUTH elif self.direction == SOUTH: self.direction = EAST elif self.direction == EAST: self.direction = NORTH def move_robo_advance(self): if self.direction == NORTH: self.y += 1 elif self.direction == SOUTH: self.y -= 1 elif self.direction == EAST: self.x += 1 elif self.direction == WEST: self.x -= 1
def calculateYearlyPayment(balance, annualInterestRate, monthlyPayment): """ balance - integer annualInterestRate - float montlhyPamentRate - float return balance after paying minimum monthly payment, for one year """ monthlyInterestRate = annualInterestRate / 12.0 unpaidBalance = 0 for month in range(12): # minimumMonthlyPayment = balance * monthlyPaymentRate unpaidBalance = balance - monthlyPayment balance = unpaidBalance + (unpaidBalance * monthlyInterestRate) return balance def calculateLowestBalance(balance, annualInterestRate): payment = 0 index = 0 amountToPay = 1 while amountToPay >= 0: index += 1 payment += 0.01 amountToPay = calculateYearlyPayment(balance, annualInterestRate, payment) # print(balance) print("Lowest Payment: " + str(payment)) balance = 500000 annualInterestRate = 0.2 calculateLowestBalance(balance, annualInterestRate)
# -*- coding: utf-8 -*- ent=raw_input().split() dados=[int(ent[0]),int(ent[1])] while(dados[0]!=dados[1]): if dados[0]>dados[1]: print 'Decrescente' else: print 'Crescente' ent=raw_input().split() dados=[int(ent[0]),int(ent[1])]
# -*- coding: utf-8 -*- lista=[] for i in range(20): lista.append(float(input())) lista.reverse() for i,item in enumerate(lista): print 'N[%i] = %i'%(i,item)
# -*- coding: utf-8 -*- n=int(input()) resposta="" for i in range(n): p=int(input()) resposta="" if p!=0: if p%2==0: resposta= resposta+"EVEN" else: resposta= resposta+"ODD" if p>0: resposta=resposta+" POSITIVE" else: resposta= resposta+" NEGATIVE" else: reposta="NULL" print resposta
# -*- coding: utf-8 -*- n=int(input()) for i in range(n): v=raw_input().split() print "%.1f" %((float(v[0])*2+float(v[1])*3+float(v[2])*5)/10)
# -*- coding: utf-8 -*- def ganhou(lista): lis=[int(lista[0]),int(lista[1])] if lis[0]<lis[1]: return 'grem' if lis[0]>lis[1]: return 'inter' return 'emp' total=0 gre=0 inter=0 emp=0 cont=1 while (cont!=2): n=raw_input().split() ganhador=ganhou(n) if ganhador=='grem': gre+=1 elif ganhador=='inter': inter+=1 else: emp+=1 total+=1 print 'Novo grenal (1-sim 2-nao)' cont=int(input()) print '%i grenais' %total print 'Inter:%i'%inter print 'Gremio:%i'%gre print 'Empates:%i'%emp if gre>inter: print 'Gremio venceu mais' else: print 'Inter venceu mais'
# -*- coding: utf-8 -*- r=1 while(r!=2): if(r==1): i=0 soma=0 err=0 while (err<2 or i<2): n=float(input()) if (10>=n>=0): soma+=n i+=1 else: err+=1 print 'nota invalida' if i==2: break print 'media = %.2f' %(soma/i) print 'novo calculo (1-sim 2-nao)' else: print 'novo calculo (1-sim 2-nao)' r=int(input())
# -*- coding: utf-8 -*- senha=int(input()) while(senha!=2002): print 'Senha Invalida' senha=int(input()) else: print 'Acesso Permitido'
# -*- coding: utf-8 -*- n1,n2,n3,n4=raw_input().split(" ") n1=float(n1) n2=float(n2) n3=float(n3) n4=float(n4) media=(2*n1+3*n2+4*n3+n4)/10 print "Media: %.1f" %media if media>=7.0: print "Aluno aprovado." else: if media<5: print "Aluno reprovado." else: print "Aluno em exame." ne=float(input()) print "Nota do exame: %.1f" %ne media =(media+ne)/2 if media>=5: print "Aluno aprovado." else: print "Aluno reprovado." print "Media final: %.1f" %media
# -*- coding: utf-8 -*- arvore={"vertebrado":{"ave":{"carnivoro":"aguia","onivoro":"pomba"}, "mamifero":{"onivoro":"homem","herbivoro":"vaca"}},"invertebrado":{ "inseto":{"hematofago":"pulga","herbivoro":"lagarta"},"anelideo":{"hematofago":"sanguessuga","onivoro":"minhoca"}}} n1=raw_input() n2=raw_input() n3=raw_input() print arvore[n1][n2][n3]
def merge_sort(x): """ Merge sort is a recursive algorithm that continually splits a list in half. If the list is empty or has one item, it is sorted by definition (the base case). If the list has more than one item, we split the list and recursively invoke a merge sort on both halves. Once the two halves are sorted, the fundamental operation, called a merge, is performed. Merging is the process of taking two smaller sorted lists and combining them together into a single, sorted, new list. """ #function should return what was input if the list is only one number long if len(x) == 1: return x #function should take the list and split it in half and begin sorting according to index else: mid = int(len(x) / 2) left = merge_sort(x[:mid]) right = merge_sort(x[mid:]) """ The result of the merge will give us a list that is sorted in the below result = 0 This is though a holding or staging area which is empty because we are sorting still """ result = [] """ The split is indexed using i&j and we will sort through this list where i is the first index on the left half where j is the first index on the right half and we start at 0 """ i = j = 0 #the sorting that runs in the background with a while loop based on the above split while i < len(left) and j < len(right): #if the left side index element(i) is smaller than the right (j) then we add the i index if left[i] < right[j]: result.append(left[i]) i += 1 #or else the right side index element(i) is smaller than the right (j) then we add the i index else: result.append(right[j]) j += 1 result += left[i:] result += right[j:] return result def bubble_sort(items): """ This is bubble sort algorithm. The bubble sort makes multiple passes through a list. It compares adjacent items and exchanges those that are out of order. Each pass through the list places the next largest value in its proper place. """ for i in range (0, len(items) - 1): for j in range(0, len(items) -1 -i): if items[j] > items[j+1]: items[j], items[j+1] = items[j+1], items[j] '''Return array of items, sorted in ascending order''' return items def quick_sort(items): """ This is a quick sort function which first selects a value, which is called the pivot value. This quicksort algorithm makes use of recurssion and has the Hoare partition scheme which helps in the way of selecting the pivot. This is beneficial for performance and can be researched further using this url: https://en.wikipedia.org/wiki/Quicksort """ #So we split this list by using a fuction within a function def _quicksort(items, low, high): # must run partition on sections with 2 elements or more if low < high: p = partition(items, low, high) _quicksort(items, low, p) _quicksort(items, p+1, high) def partition(items, low, high): pivot = items[low] while True: while items[low] < pivot: low += 1 while items[high] > pivot: high -= 1 if low >= high: return high items[low], items[high] = items[high], items[low] low += 1 high -= 1 _quicksort(items, 0, len(items)-1) return items
#-------------------------------------------------# # Title: Mailroom part 2 # Dev: Rlarge # Date: 2/13/2019 # ChangeL/og: (Who, When, What) # RLarge, 01/31/2019, Created Script # RLarge, 02/13/2019, Modified script with # Exceptions and Comprehensions #-------------------------------------------------# # Import Modules import tempfile # Variables # Create variables for dict keys and values Names = ["William Gates III", "Jeff Bezos", "Paul Allen", "Mark Zuckerberg"] Donations = ([65332543, 377.32], [200.34, 9337.393], [8394.23, 777.2, 1.32], [273, 337692.15, 737361.23]) # create a dictionary, and 'zip' the keys and associated values together DictDonor = dict(zip(Names, Donations)) prompt = "\n".join(("Welcome to the Mail Room Program.", "Please choose from below options:", "1 - Send a Thank you", "2 - Create a Report", "3 - Send out Email drafts", "4 - Exit", ">>> ")) # Functions def MainMenu(): print(prompt) def ViewDonorList(): # if user types 'list', show them a list of the donor names and reprompt. ShowList = input("View current donor list? (y/n)") if ShowList.lower() == 'y': print("Current Donor List:\n") [print(donor) for donor in DictDonor] def SendThankYou(): # if user types a name not in the list, add that name to the data structure and use it while True: DonorNameInput = input('\n'"Please enter a Donor Name to update (type 'exit' to quit): ") if DonorNameInput.lower() == 'exit': break elif DonorNameInput in DictDonor: print("Updating {}'s information".format(DonorNameInput)) UpdateDonation = input("What is the new value(s) for {}?".format(DonorNameInput)) DictDonor[DonorNameInput].append(float(UpdateDonation)) print(DictDonor) else: NewDonation = [float(input("New Name entered. please add donation amount: "))] InputKey = [DonorNameInput] NewDict = dict.fromkeys(InputKey) NewDict[DonorNameInput] = NewDonation DictDonor.update(NewDict) print(NewDict) print("New entry successful! Here is the AutoGen Email: \n") # key would be the DonorNameInput, Values would be the letter template EmailTemplatedict = {"DonorName": DonorNameInput, "Email": "\nWe here at the Donation Center want " "to thank you for your contribution.\n" "Sincerely, \nthe Donation center.\n"} print("Dear {DonorName}, {Email}".format(**EmailTemplatedict)) def CreateReport(): # Generate a report showing formatted items in the DictDonor Header = "{:<25}| {:<10} | {:<10} | {:<10}".format('DonorName', 'Total Given','Num Gifts', 'Average Gift') print(Header) print("-"*67) # DonorList = DictDonor[] for x in DictDonor: DonorSum = sum(DictDonor[x]) DonorLen = len(DictDonor[x]) DonorAvg = DonorSum/DonorLen print('{:<25} ${:<15.0f} {:<10} ${:<2.2f}'.format(x, DonorSum, DonorLen, DonorAvg)) print("-"*67) def EmailToFile(enterdict): tempdir = tempfile.gettempdir() print(tempdir) name = enterdict.keys() for item in name: EmailTemplatedict = {"DonorName": item, "Email": "\nWe here at the Donation Center want " "to thank you for your contribution.\n" "Sincerely, \nthe Donation center.\n"} with open("{}\{}.txt".format(tempdir, item), "w") as f: f.write("Dear {},".format(EmailTemplatedict["DonorName"])) f.write(EmailTemplatedict["Email"]) print("Email drafts generated and saved to text files using the Donor name." " Text Files are saved here: \n\n({}) ".format(tempdir)) # Presentation def main(): try: response = input(prompt) if response == "1": ViewDonorList() SendThankYou() elif response == "2": CreateReport() elif response == "3": EmailToFile(DictDonor) elif response == "4": print("Thank you for using the Mailroom program.") else: raise TypeError except TypeError: print("ERROR: Please enter a value from 1 to 4...."'\n') return main() if __name__ == "__main__": # This guard blocks against code running automatically if module is imported main()
''' When squirrels get together for a party, they like to have cigars. A squirrel party is successful when the number of cigars is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of cigars. Return True if the party with the given values is successful, or False otherwise. cigar_party(30, False) → False cigar_party(50, False) → True cigar_party(70, True) → True ''' def cigar_party(cigars, is_weekend): # cigars is True if cigars is >40 and <60 # return True if cigars >60 if cigars >= 40 and cigars <= 60: return True elif is_weekend == True and cigars > 60: return True else: return False print(cigar_party(61, False)) print(cigar_party(30, False)) print(cigar_party(50, False)) print(cigar_party(70, True))
import math #Las funciones tienen un nombre y se declaran con la palabra raservada def y devuelven un valor usando la palabra #return. Se puede pasar una lista de argumentos o parametros: bien por posiciones o por clave #Funcion es conjunto de linesa de codigo agrupadas (bloque de codigo) que funcionen como una unidad realizando una #tarea especifica. #Las funciones en Python pueden devolver valores. #Las funciones en Python pueden tener parametros/argumentos. #A las funciones tambien se las denomina "metodos" cuando se encuentra definidas dentro de una clase. #Utilidad: Reutilizacion de codigo(cuando sea necesario o si es necesario) #Python pasa siempre los valores(parametros/argumentos) por referencia #Las funciones, junto con las clases, son una de los mecanismos para reutioisar codigo. #Tienen una lista de argumentos: #posicionales #por clave #argumentos agrupados: #tupla de argumentos posicionales (*args) #diccionario de argumentos accedidos por clave (**kwargs) #Los argumentos por clave se usan para indicar valores por defecto siempre se situan despues de los argumentos posicionales. # Paso de parametros a una funcion: # Variables y paso por referencia # En una asignacion de un valor a una variable, se crea una referencia al objeto que se encuentra en el lado derecho # de la asignacion. Esto es muy importante entenderlo cuando se trabaja con grandes volumenes de datos. #----------------------------------------- Variables y paso por referencia --------------------------------------------- # Ambas variables a y b referencian al mismo objeto. Si se modifica cualquiera de ellas, se modifican los dos. a = [1, 2, 3] # print("a-->", a) b = a # print("b-->", b) a[0]= 100 # print("a-->", a) # print("b-->", b) b[2] =500 # print("a-->", a) # print("b-->", b) # Nota importante: si creamos objeto como subconjunto de otros, NO referencian al mismo objeto: c = a[:3] # print("a-->", a) # print("b-->", b) # print("c-->", c) c[1] = 4999 # print("a-->", a) # print("b-->", b) # print("c-->", c) # IMPORTANTE # En Python el paso de argumentos a una funcion se hace por referencia, mientras que en otros lenguajes se permite paso # por valor y paso por referencia. def cambiarLista(lista, num): lista.append(num) a = [1, 2, 3, 4, 5] # cambiarLista(a, 22222) # print(a) def cambiarValue(numOld, numNew): numOld = numNew c = 3 b = 0 # print("c = ", c, " and b = ", b) # cambiarValue(c, b) # print("c = ", c, " and b = ", b) #-------------------------------------- Funcinones como argumentos de otras funciones ---------------------------------- # Supongamos que tenemos una lista de ciudades que necesitamos limpiar o formatear. ciudades = [' Madrid', 'BARcelonA', 'SeVILLa '] # Para dar un formato uniforme a esta lista antes de realizar otras tareas de analisis, es necesario transformarla eliminando # espacios en blanco y transformando cada nombre a tipo titulo. # Primera opcion # def formatear(lista): # resultado = [] # for ciudad in lista: # ciudad = ciudad.strip() # Elimina espacios en blanco # ciudad = ciudad.title() # tipo titulo # resultado.append(ciudad) # return resultado # formatear(ciudades) # ciudades = formatear(ciudades) # print(ciudades) operaciones = [str.strip, str.title, str.lower,] listaNumeros = [1, 2, 3, 4, 5, 45] def formatear(listaCiudades, operaciones): resultado = [] for ciudad in listaCiudades: for op in operaciones: ciudad = op(ciudad) resultado.append(ciudad) return resultado def formatearSimple(listaCiudades, fun): resultado = [] for ciudad in listaCiudades: ciudad = fun(ciudad) resultado.append(ciudad) return resultado # print(formatear(ciudades, operaciones)) # print(formatearSimple(ciudades, str.upper)) # print(ciudades) # El uso de funciones como argumentos de otra funcion es una caracteristica de los lenguajes funcionales. La funcion map # de los lenguajes funcionales tambien esta accesible en Python. Esta funcion aplica una funcion a una colleccion de objetos. mi = map(str.strip, ciudades) # print(list(mi)) # print(type(mi)) lista_Productos = map(lambda x: x * 100, listaNumeros) # print(list(lista_Productos)) #--------------------------------------------- Funciones anonimas (lambda) --------------------------------------------- # Las funciones anonimas son aquellas que no tienen nombre y se referen a una unica instruccion. Se declaran con la palabra # reservada lambda. # Son funciones cortas # Funciones normales def producto(x): return x * 2 # funciones anonimas, equivalente al funcion de ariba resultado = lambda x: x * 2 # Las funciones lambda se utilizan mucho en analisis de datos ya que es muy usual transformar datos mediante funciones # que tienen a otras funciones en su argumento. # Se usan funciones lambda en lugar de escribir funciones normales para hacer el codigo mas claro y mas corto. # Mutiplicar por 2 todos los numeros de la lista: listaNumeros = [1, 2, 3, 4, 5, 45] def doublingTheValue(listaNumeros, funcion): """Devuelve una nueva lista definida por compresion""" return [funcion(x) for x in listaNumeros] # ????????????????? # print(doublingTheValue(listaNumeros, producto)) # El mismo efecto lo consegimos mediante una funcion anonima, evitando asi la definicion de la funcio producto: # print(doublingTheValue(listaNumeros, lambda x: x * 2)) #------------------------------------------------- *args y **kwargs ---------------------------------------------------- #*args ** kwargs: # Usamos *args para representar una tupla arbitraria de argumentos agrupados. No es necesario que el nombre sea args # (aunque es frecuente por convenio hacerlo) def suma_varios (x, y, *others): print("x:",x) print("y:", y) print("others:", others) # suma_varios(1,2,3,4,5,6,7,8,9,10) # Se pueden definer los argumentos agrupados despues de los argumentos posiciones y por clave. Usamos **kwargs para representar # una lista arbitraria de argumentos agrupados representada como un diccionario. Como en el caso anterior, no es necesario # que el nombre sea kwargs: def sumar_varios2(x, y, *others, **more): print("x:", x) print("y:", y) print("others:", others) print("more:", more) # sumar_varios2(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, cien = 100, mil = 1000) #--------------------------------------------- Documentacion de funciones ---------------------------------------------- # Cada funcion escrita por un programador deberia realizar una tarea especifica. # Cuando la cantidad de funciones disponibles para ser utilizadas es grande, puede se dificil saber exactamente que hace # una funcion. Es por eso que es extremedamente importante documentar en cada funcion: # cual es la tarea que realiza # cuales son parametros que recibe # que es lo que devuelve # La documentacion de una funcion se coloca despues del encabezado de la funcion, en un parrafo encerrado entre tres # comillas doubles """ o simples '''. def cambia(lista, num): """Permite anadir un elemento a una lista.\n Recibe como parametro una lista y el elemento a anadir\n No devuelve nada """ lista.append(num) # cambia() # Cuando una funcion definida estacorrectamente documentada, es posible accerder a su documentacion mediante la funcion help(). # Contar con funciones es de gran utilidad, ya que nos permite ir armando una biblioteca de instrucciones con problemas # que vamos resolvendo, y que se pueden reutilizar en la resolucion de nuevos problemas. def mean(a1, a2, a3, a4): """Calcula la media de cuatro valores @:type a1: real @:type a2: real @:type a3: real @:type a4: real @:rtype: real """ s = 0.0 s = s + a1 s = s + a2 s = s + a3 s = s + a4 return s / 4 #mean() #---------------------------------------------- Espacio de nombres (namespaces) ---------------------------------------- # Las funciones pueden acceder a variables que se encuentran en dos tipos de ambitos: global y local # El ambito local (local namespace) se crea cuando se llama a una funcion. # Cuando la funcion termina de ejecutarse, el ambito local se destruye. # def fun1(): # t = [] # s = (1,2,3,4) # for i in s: # t.append(i) # En el caso anterior, la lista vacia t se crea en el ambito local de la funcion fun(). Fuera de ella no exste. # fun1() # t # no esta definida, dara un error NameError: name 't' is not defined # Las variables y los parametros que se declaran dentro de una funcion (ambito local) no existen fuera de ella, no se lo # conoce. Fuera de la funcion se puede ver solo el valor que retorna y es por eso que es necesario introducir la # instruccion return # Si declaramos t fuera de la funcion, en el ambito global: # t = [] # def fun2(): # s = (1,2,3,4) # for i in s: # t.append(i) # Al llamar a: # print(t) # fun2() # print(t) # Seguramente tendremos problemas cuando una variable se declara en el ambito local y global de la funcion: t = 2 def fun1(): t = [] s = (1,2,3,4) for i in s: t.append(i) # print(t) # Si queremos que una variable se refiera a la variable global en vez de a local (Python supone que cualquier variable # cambiada o creada en una funcion es local), debemos anadir la palabra reservada global: def f(): global s # print(s) s = "Esto claro." # print(s) s = "Python es genial!" f() # print(s) #----------------------------------------------------------------------------------------------------------------------- # Ejemplo de funcion con 2 argumentos posicionales y 2 por claves: # Los argumentos por claves siempre tienen que ir despues de posicionales def suma_varios2(x, y, z1 = 0, z2 = 0): m = x + y + z1 + z2 return m resultado1 = suma_varios2(2, 3) resultado2 = suma_varios2(2, 3, z2=1) resultado3 = suma_varios2(2, 3, z1=1) resultado4 = suma_varios2(2, 3, 1) # el treser parametro se va asignar al z1 resultado5 = suma_varios2(2, 3, z1=1, z2=1) resultado6 = suma_varios2(2, 3, 1, 1) # print(resultado1, resultado2, resultado3, resultado4, resultado5, resultado6) # Defenicion de una function: # def sumaTes(x, y, z): # m1 = x + y # m2 = m1 + z # return m2 # print(sumaTes(2, 3, 4)) # resultado = 0 # Ne rabotaet kak v java # def sumaTodos(x, y, z, t): # resultado = x + y + z + t # print(resultado) # r = sumaTodos(1, 2, 3, 4) # print(r, type(r)) # def salydo(): # print('Hello!!!') # salydo() # print(abs(2 - 5)) # valor absoluto # print(max(3, 5, 1, -6)) # valor maximo de un conjunto de valores # print(min(3, 5, 1, -6, -6.0)) # valor minimo de un conjunto de valores # print(round(18.65)) # redondea un float al entero mas cercano # print(int(18.65)) # convierte al entero mas cercano por de bajo # print(float(18)) # convierte a decimal, aunque la expresion de entrada sea entera # print(complex(2)) # convierte a numero complejo # print(str(256568)) # convierte la expresion a un cadena de characteres # name = input("What is you name?\n") # print("Hello, ", name) # Hay que poner return de forma consistente: # Bien # def foo(x): # if x >= 0: # return math.sqrt(x) # else: # return None # # Mal # def foo(x): # if x >= 0: # return math.sqrt(x) #--------------------------------------------------- enumerate() ------------------------------------------------------- # Cuando trabajamos con secuencias de elementos puede resuotar utio conoser el index de cada elemento # La funccion enumerate() devuelve una secuencia de tuplas de la forma (indice, valor). Mediante un bucle es posible # recorrerse dicha secuencia # ciudades = ["Madrid", "Sevilla", "Segovia", "Valencia"] # for (i, valor) in enumerate(ciudades): # print('%d: %s' %(i, valor)) #---------------------------------------------------- reversed() ------------------------------------------------------- # reversed() devuelve un iterador inverso de una lista # for (i, valor) in enumerate(reversed(ciudades)): # print('%d: %s' %(i, valor)) # ------------------------------------------------ Effecto interesante ------------------------------------------------- # Si en return poner dos resultados methodo devuelve tupla de estos valores def sum(n1, n2): return n1 + n2, n1 - n2 # print(sum(3,4)) # print(sum(3,4)[0]) # ------------------------------------------------- Parametros por defecto --------------------------------------------- def func(a = "Value por defecto"): print(a) # func() # func("Hola")
# Tanto las Tumpla como las listas son conjuntos ordenados de elementos, no asi los diccionarios. # Que son las listas: # Estructura de datos que nos permite almacenar grand cantidad de valores(equivalente a los array en todos lenguajes # de programacion. # En Python las listas pueden guardar diferentes tipos de valores(en otros lenguajes no ocurre esto con los array) # Se pueden expandir dinamicamente anadiendo nuevos elementos (otra novedad respecto a los arrays en otros lenguajes) # En la lista se puede guardar diferentes tipos # Una lista es similar a una tupla con la diferencia fundamental de que permite modificar los datos una ves creados. # Las listas se encierren entre corchetes []. lista_A = [4, 'Hola', 6.0, 99] # print('lista_A = ', lista_A) # print('Tupe de lista_A = ', type(lista_A)) # print('1--------------------------------------------') tupla_A = (4, 'Hola', 6.0, 99) # print('tupla_A = ', tupla_A) # print('Tupe de tupla_A = ', type(tupla_A)) # print('2--------------------------------------------') # print('tupla_A == lista_A ->',tupla_A == lista_A) # print('tupla_A[0] == lista_A[0] ->',tupla_A[0] == lista_A[0]) # print('3--------------------------------------------') miLista = ['Maria', 'Pepe', 'Marta', 'Antonio'] # Para aceder a todos elementos de la lista # print(miLista[:]) # Da una ERROR, este indice no existe # print(miLista[7]) # IndexError: list index out of range # print(miLista[0:10]) # Asi no le da IndexError #---------------------------------------------------- Una matriz ------------------------------------------------------- listaMatriz = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # print(listaMatriz) #------------------------------------------------ Modificacion de lista ------------------------------------------------ # Mientras que una tupla no permite modificar sus elementos, una lista si # print('Antes ',lista_A) lista_A[0] = 0.0 # print('Despues ',lista_A) # print('Antes ', listaMatriz) # listaMatriz[1] = 2 # listaMatriz[1] = None listaMatriz[1] = ['A', 'B', 'C'] # print('Despuse ', listaMatriz) # print('Antes ', listaMatriz) listaMatriz[1][0] = 'A' listaMatriz[1][0] = ['A', 'Z'] # print('Despuse ', listaMatriz) #------------ Acceso a los elementos de la secuencias ---------- # Los elementos de las secuencias pueden ser accedidos(indexados) mediante el uso de corchetes: lista[<index>] # En Python, la indexacion se empieze por 0, es decir, el primer elemento tiene indice cero. # print(lista_ordenada[0]) # Podemos indexar las secuencias utilisando la sintaxis: lista[<inicio>:<final>:<salto>] lista_ordenada = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # print(lista_ordenada[1:4]) # print(lista_ordenada[1:5:2]) # print(lista_ordenada[1:6:2]) # v ciomy exemplo 2 oznacae.... wchob zrozymitu treba duvutus exemplos # VNIMANIE Nety vuxoda za razmer lista # print(len(lista_ordenada)) # print(lista_ordenada[1:8]) # print(lista_ordenada[1:9]) # print(lista_ordenada[1:10]) # print(lista_ordenada[1:100]) # Asi no le da IndexError # Desde el primero hasta el 3 # print(lista_ordenada[:3]) # Desde el primero hasta el ultimo, saltando de 2 en 2: # print(lista_ordenada[::2]) # Desde el primero hasta el 4, saltando de 2 en 2: # print(lista_ordenada[:4:2]) # Desde el 2 hasta el ultimo, saltando de 2 en 2: # print(lista_ordenada[2::2]) # Forma inversa de acceso a una secuencia (de atras hacia adelante): Se usa una indice negativo. # print(lista_ordenada[-1]) # print(lista_ordenada[-2]) # print(lista_ordenada[-3]) # print(lista_ordenada[-3:-1]) # Los elementos de una lista o tupla pueden ser de cualquier tipo, incluyendo otra lista o tupla datosL = [['1', '2', '3'], 'Hola', 4] # print(datosL) sL = datosL[0][1] # print(sL) # print(type(sL)) #----------------------------------------------- Operaciones sobre listas ---------------------------------------------- # Crear una lista a partir de una tupla tupla_q = (2,3,1) lista_T = list(tupla_q) # print(lista_T) # Anadir un elemento, al final de la lista, con append() lista_Sem = ['lunes', 'jueves'] # print(lista_Sem) lista_Sem.append('viernes') # print(lista_Sem) # Anadir un elemento, en una determinada position, con insert() lista_Sem.insert(1, 'martes') # print(lista_Sem) # Funcion extend muy parasida a concatenacion, agrega todos elementos indicados en parametros al final de la lista lista_Sem.extend([1, 2, 3, 4, 5]) # print(lista_Sem) # Eliminar el elemento de la lista de un determinado posicion con pop(): e = lista_Sem.pop(3) # print(lista_Sem) # print(e) # e vale 'viernes' y lista vale ['lunes', 'martes', 'jueves'] # Si usar funcion pop sin parametros, ella va eliminar ultimo elemento en la lista # print(lista_Sem) lista_Sem.pop() # print(lista_Sem) # Elimina un elemento a partir de su valor con remove(). Methodo remove() borra primera occurencia # print(lista_Sem) # lista_Sem.remove('lunes') # functio remove nose puede usar sin argumentos # lista_Sem.remove() #TypeError:F remove() takes exactly one argument (0 given) # print(lista_Sem) # Funcion index nos auyda saber en que indice se encuentra value que buscamos # print(lista_Sem.index("jueves")) # print(lista_Sem.index(5)) # print(lista_Sem.index("Cara")) # ValueError: 'Cara' is not in list # Si se repiten los values en la lista, la funcion index devuelve primer indice que encuentre lista_Sem.insert(7, 'martes') # print(lista_Sem) # print(lista_Sem.index('martes')) # Para comprobar si existe value en la lista se usa in # print(5 in lista_Sem) # print('martes' in lista_Sem) # print('R' in lista_Sem) # Metodo count permite buscar la cantidad de mizmos elementos, es decir cuantos elementos(que se pasan como parametro) # iguales existen en la lista myLista = ['q', 'e', 't', 'q', 'c', 'q'] # print(myLista.count('q')) # Method len() le dice la longitud de lista # print(len(myLista)) # Ordenar una lista con funccion sort(). No es necesario crear una lista nueva. listaS = [8, 34, 56, 1, 9, 78, 78.5, 3, 18, 23, 21, 12, 10, 2, 3] # print(max(listaS)) # print(listaS) listaS.sort() # print(listaS) # Generar listas con range. range() solo admite enteros # inicio,fin,paso # print(list(range(11))) # print(list(range(0,11))) # print(list(range(0,11,2))) #----------------------------------- Concatenacion de listas con + -------------------------------------------- # Estas operaciones no modifican las secuencias originales. lista_1 = [1,2,3,4,5] lista_2 = [11,22,33,44,55] lista_result = lista_1 + lista_2 # print(lista_result) lista_result2 = [1, 2, 3] + [4, 5, 6] # print(lista_result2) #--------------------------------------------- Replication (*) de secuencias ------------------------------------------- # Estas operaciones no modifican las secuencias originales. l = lista_1 * 4 # print(l) #--------------------------------------------------- Help -------------------------------------------------------------- # help(list.remove) # help(list)
def menu(): print('----- Gestión de aeropuertos ------') print('-----------------------------------') print() print('1. Cargar pilotos.') print('2. Cargar aeropuertos.') print() print('3. Listar pilotos') print('4. Listar aeropuertos.') print('5. Listar rutas.') print() print('6. Modificar salario de un piloto') print('7. Crear nueva ruta') print('8. Guardar todas las rutas') print() print('0. Salir') def run(): seguir = True rutas = {} datos = bd.BaseDeDatos() while seguir: menu() opcion = int (input('Elige una opción: ')) if opcion == 0: despedida() seguir = False elif opcion == 1: opcionCargaPilotos(datos) elif opcion == 2: opcionCargaAeropuertos(datos) elif opcion == 3: opcionListadoPilotos(datos) elif opcion == 4: opcionListadoAeropuertos(datos) elif opcion == 5: opcionListadoRutas(rutas) elif opcion == 6: dni = str (input('Introduce dni del empleado: ')) sala = int (input('Introduce el nuevo salario: ')) datos.modificarPiloto(dni, salario = sala) elif opcion == 7: opcionCrearNuevaRuta(datos, rutas) elif opcion == 8: opcionGuardarRutas(rutas) else: pass
# Los conjunto o sets son colecciones no ordenadas de elmentos no repetidos. Los conjuntos pueden crearse de dos formas diferentes # Mediante una lista de elementos entre llaves { } # Mediante la funcion set() s1 = set([3, 3, 3, 1, 1, 1, 2]) s2 = {3, 5, 6, 7, 7, 1, 1, 1, 2} # Los conjuntos en Python admiten las operaciones matematicas habituales sobre conjuntos, como son la union, interseccion # diferencia, etc. # Diferencia: s2 - s1 s3 = s2.difference(s1) print(s1) print(s2) print(s3) # La llamada help(set) o (s1. por ejemplo, en el editor) devuelve una lista de los methodos que se pueden aplicar a conjuntos. # Esta estructura de datos resulta muy util cuando necesitamos eliminar elementos repetidos de una lista. # lista inicial con elementos repetidos lista = [3, 5, 6, 7, 7, 1, 1, 1, 2] # Creamos un conjunto a partir de la lista sin_repes = set(lista) # Creamos una lista a partir del conjunto anterior lista = list(sin_repes) print(lista)
FillerList1 = ["all", "no", "some"] FillerList2 = ["are", "are not", "have", "have no", "is", "is not"] def FindType(In1, In2, S1, S2): # Both have to be split! if In1[S1] == "all": if In2[S2] == "some" or In2[S2] == "no": Word_List[0] = 2 else: Word_List[0] = 0 # CAN BE 2 as well elif In1[S1] == "no": Word_List[0] = 2 # Can be 1 as well elif In1[S1] == "some": Word_List[0] = 2 if In1[(S1 + 2)] == "are": if In2[(S2 + 2)] == "are not" or In[S1] == "no": Word_List[1] = 1 else: Word_List[1] = 0 elif In1[(S1 + 2)] == "have": if In2[(S2 + 2)] == "have": Word_List[1] = 1 elif In2[(S2 + 2)] == "are": Word_List[1] = 3 else: Word_List[1] = 2 elif In1[(S1 + 2)] == "is": Word_List[1] = 5 elif In1[(S1 + 2)] == "have no": Word_List[1] = 3
import functools import operator def flattenList(l,*m): ''' flatten a list l, along with optionally expanding other list of the same length as l in the same fashion, for instance if we want to flatten l and m is another list where each entry corresponds to an entry in l, then we would expand m by duplicating the nth entry for each entry we extract from the nth entry of l assumes each entry in l is either a list (must be flattend) or not a list, and all entries are of the same class (ie list or not list) ''' if len(m) == 0: if len(l) == 0: return l while type(l[0]) is list: l = functools.reduce(operator.add, l) return l if len(l) == 0: return l,[None for i in m] mMap = {i:1 for i in range(len(l))} while type(l[0]) is list: _l = [] for i in range(len(l)): temp = functools.reduce(operator.add, l[i]) if type(temp) is list: mMap[i] = len(temp) _l += temp else: _l.append(temp) l = _l _m = [] for i in m: temp = [] for j in range(len(i)): temp += mMap[j]*[i[j]] _m.append(temp) return l, _m
#coding=utf-8 ''' python 中 一个字符串相对应一个字符数组 ''' name='abcdefghij中文' print("name=%s"%name) print() print("name[0]=%s"%name[0]) print("name[1]=%s"%name[1]) print("name[len(name)-1]=%s"%name[len(name)-1]) print("name[-1]=%s"%name[-1]) print("name[-5]=%s"%name[-5]) ''' 字符串切片 ''' print("name[2:4]=%s"%name[2:4])#包头不包尾 print("name[0:-2]=%s"%name[0:-2])#包头不包尾 print("name[1:6]=%s"%name[1:6]) print("name[:6]=%s"%name[:6]) print("name[:3]=%s"%name[:3]) print("name[2:]=%s"%name[2:]) print("name[0:]=%s"%name[0:]) #跳跃取 print("name[1:-1:2]=%s"%name[1:-1:2])#跳跃单位为2 print("name[1:-1:3]=%s"%name[1:-1:3])#跳跃单位为3 print("name[::2]=%s"%name[::2])#取出基数个 print("name[1::2]=%s"%name[1::2])#取出偶数个 #print("name[::0]=%s"%name[::0]) print("name[-2:-5:-1]=%s"%name[-2:-5:-1]) #倒序name print("name[::-1]=%s"%name[::-1])
#coding=utf-8 #需求:创建一个列表,里面包含10~27 #方法一 a=[] i=10 while i<=27: a.append(i) i+=1 print(a) print("-"*40) ''' range 注意下面表达式在2和3中不同表现 在python2中range存在风险,比如range(1,9999999999) 在python3中避免了这个风险,在使用时才真正开辟内存 ''' print("range(10)=%s"%range(10)) print("range(10,15)=%s"%range(10,15)) print("range(10,15,2)=%s"%range(10,15,2)) print("range(-10,-15,-2)=%s"%range(-10,-15,-2)) print("range(15,10,-2)=%s"%range(15,10,-2)) a=range(1,9999999999) print(a[2]) #方法二 考研使用列表生存式 range print("-"*40) a=[] for i in range(10,28): #range 系列,种类 a.append(i) print(a) # 简单写法 a=[] a=[i for i in range(10,28)] #构建好列表生成式去遍历出每一个i,赋值给i print(a) #变换 print("-"*40) a=[] a=[i for i in range(10,28,2)] print(a) print("-----------------变换----------------") #变换 print("-"*40) a=[] a=[i for i in range(10,28) if True] #执行前要判断后面是非是true print(a) #变换 print("-"*40) a=[] a=[i for i in range(10,28) if i%2==0] print(a) #变换 print("-"*40) a=[] a=[i for i in range(10,28) if []] #只要满足后面的条件,就执行生成 print(a) #变换 print("-"*40) a=[] a=[i for i in range(10,28) for j in range(2)] #每生成前,就要先判断后面是非true print(a) #变换 print("-"*40) a=[] a=[(i,j) for i in range(10,28) for j in range(2)] print(a) #变换 print("-"*40) a=[] a=[(i,j,k) for i in range(5) for j in range(5) for k in range(5)] #其实是for循环♻️ 的嵌套 print(a)
#coding=utf-8 def func1(n): if n>1: return n*func1(n-1) # return 4*func1(3)=4*3*func1(2)=4*3*2*func1(1) else: return 1 n=int(input("请输入一个数字:")) print(func1(n))
#coding=utf-8 names = [11,22,33,44,55] print(names) i=int(input("请数据值:")) for name in names: if i==name: print("%d在列表names中"%i) break #当跳出后,就跳出for循环,else也不执行 else: #当for循环♻️执行完成后执行eles print("%d不在列表names中"%i) ''' for else 结合break使用是个不错的设计 java中没有,在判断一个集合中是非有某变量时,不需要定义一个booble,在找到后设置booble=true来帮助判断 而是直接找到后就执行找到后的业务,然后break 跳出,跳出后else就不执行,否则说明没有找到,就执行else没有找到的业务 '''
#coding=utf-8 import numpy as np a = np.array([[1,2],[3,4],[1,1]]) b = np.array([[2],[4]]) print(a) print('----------') print(b) print('----------') print(a.dot(b)) print('----------') print(np.dot(a,b)) ''' 矩阵乘法 前提 a的列数 = b的行数 结果矩阵的行数=a的行数 列数=b的列数 结果矩阵的m,n的值=a第m行 与 b第n列 分别相乘 然后相加 '''
# 6-5. Rivers: make a dictionary containing three major rivers and the country # each river runs through. one key-value pair might be 'nile' : 'egypt'. # use a loop to print the name of each country included in the dictionary. # rivers = {'nile': 'egypt', 'hudson': 'usa', 'volga': 'russia', 'mississippi': 'usa', 'thames': 'uk'} #=== use a loop to print a sentence about each river, such as the Nile runs #=== through Egypt. # ===: The Key runs through Value # for river, country in rivers.items(): # if country in ['usa', 'uk']: # print(f"The {river.title()} runs through {country.upper()}.") # else: # print(f"The {river.title()} runs through {country.title()}.") #=== use a loop to print the name of each river included in the dictionary. # print('Rivers are :') # for river in rivers.keys(): # print('\t', river.title(), end=" |") # # # #=== use a loop to print the name of each country included in the dictionary. # print('\nCountries are:') # # for country in sorted(rivers.values(), reverse=True): # if country in ['usa', 'uk']: # print('\t', country.upper(), end=" |") # else: # print('\t', country.title(), end=" |") # print("\n********************** 6-11. Cities: ******************************") # cities = {'new york': {'country': 'usa', 'population': '8.4', 'fact': 'Big Apple'}, # 'istanbul': {'country': 'turkey', 'population': '15.52', 'fact': 'constantinople'}, # 'tashkent': {'country': 'uzbekistan', 'population': '2.5', 'fact': 'stone city'}, # 'moscow': {'country': 'russia', 'population': 12.53, 'fact': 'kremlin'} # } # # === "City is very beautiful in country, it has population and city is also known as fact" # # for city, info in cities.items(): # # print(city) # # print(info) # print(f"{city.title()} is very beautiful city in {info['country'].title()}." # f"It has {info['population']} mln population and the city is also known as {info['fact']}.") # HW: #================= print multiplication table 1-10 ================================ for i in range(1,11): for cal in range(1,11): print(f"{i} * {cal} = {i*cal}", end='\t') print('') #=======================================================================================
from tkinter import * class MainGUI: def __init__(self): window = Tk() window.title('Eight Queens') self.main_frame = Frame(window) # frame to hold the board self.main_frame.pack() # Queen positions queens = 8 * [-1] # queens are placed at (i, queens[i]) # -1 indicates that no queen is currently placed in the ith row queens[0] = 0 # Initially, place a queen at (0, 0) in the 0th row # k - 1 indicates the number of queens placed so far # We are looking for a position in the kth row to place a queen k = 1 while k >= 0 and k <= 7: # Find a position to place a queen in the kth row j = self.findPosition(k, queens) if j < 0: queens[k] = -1 k -= 1 # back track to the previous row else: queens[k] = j k += 1 self.getPictures(queens) self.drawBoard() window.mainloop() def findPosition(self, k, queens): start = 0 if queens[k] == -1 else (queens[k] + 1) for j in range(start, 8): if self.isValid(k, j, queens): return j # (k, j) is the place to put the queen no return -1 # Return True if a queen can be placed at (k, j) def isValid(self, k, j, queens): # See if (k, j) is a possible position # Check the jth column for i in range(k): if queens[i] == j: return False # Check major diagonal row = k - 1 column = j - 1 while row >= 0 and column >= 0: if queens[row] == column: return False row -= 1 column -= 1 # Check minor diagonal row = k - 1 column = j + 1 while row >= 0 and column <= 7: if queens[row] == column: return False row -= 1 column -= 1 return True def getPictures(self, queens): self.pictureRows = [] # store list of rows for i in range (8): self.spots = [] # store list of images self.pictureRows.append(self.spots) for j in range(8): if j == queens[i]: self.pictureRows[i].append(PhotoImage(file = 'images/queen.gif', width = 75, height = 75)) else: self.pictureRows[i].append(PhotoImage(file = 'images/red.gif', width = 75, height = 75)) def drawBoard(self): self.labelList = [] # store list of labels for i in range(8): self.labels = [] # list of labels self.labelList.append(self.labels) for j in range(8): self.labelList[i].append(Label(self.main_frame, image = self.pictureRows[i][j])) self.labelList[i][j].grid(row = i, column = j) # draw the board MainGUI()
# -*- coding: utf-8 -*- """ Created on Fri Feb 15 13:21:43 2019 @author: Erin Canada Project # 2 is to implement linear regression for binary classification from scratch (as we've been discussing / working on for the past several lectures). Minimize the logistic regression objective function in two different ways: 1) using gradient descent; 2) using stochastic gradient descent. To evaluate the performance of your gradient descent implementation, make a semilogy plot of objective function value versus iteration. To evaluate the performance of your stochastic gradient descent implementation, make a semilogy plot of the objective function value versus epoch. You can use the plt.title() function to give the plots informative titles. Train your logistic regression model on the same synthetic data that was used for the Perceptron project (project 1), and visualize the evolution of the decision boundary (which is a straight line) in the same way as was done for the Perceptron algorithm. We should observe that the decision boundary converges to a line that does a good job of separating the positive and negative training examples. Submit just a .py file that contains your code -- set up the code so that when I run your Python program, the evolution of the decision boundary is visualized, and the two semilogy plots are created. """ import numpy as np import matplotlib.pyplot as plt #log likelihood of the Logisitic Regression of Beta def evalF(B,X,Y): N = X.shape[0] L = 0 for i in range(N): L = Y[i]*np.log(sigmoid(X[i],B)) + (1-Y[i])*np.log(1-sigmoid(X[i],B)) return -L #Gradient of the Logistic Regression log liklihood def evalGrad(B,X,Y): N = X.shape[0] grad = 0 for i in range(N): grad = grad + X[i]*(Y[i]- sigmoid(X[i],B)) return -grad #Stochastic Gradient of the Logistic Regression def evalStoGrad(B,X,Y,idx): stoGrad = X[idx]*(Y[idx]- sigmoid(X[idx],B)) return -stoGrad #Generate Random data def generateData(): numPos = 100 numNeg = 100 np.random.seed(14) muPos = [1.0,1.0] covPos = np.array([[1.0,0.0],[0.0,1.0]]) muNeg = [-1.0,-1.0] covNeg = np.array([[1.0,0.0],[0.0,1.0]]) Xpos = np.ones((numPos,3)) for i in range(numPos): Xpos[i,0:2] = \ np.random.multivariate_normal(muPos,covPos) Xneg = np.ones((numNeg,3)) for i in range(numNeg): Xneg[i,0:2] = \ np.random.multivariate_normal(muNeg,covNeg) X = np.concatenate((Xpos,Xneg),axis = 0) return X #Function for plotting a semilogy graph, pertaining to above functions def semigraph(title, iteration, beta,lim): plt.grid(True, which="both") plt.semilogy(iteration, beta) plt.xlim(0,lim) plt.title('Logistic Regression w/ {}'.format(title)) plt.xlabel('Iteration') plt.ylabel('Objective Function') plt.show() #Prediction Function. Determines if data point should be classified as a 1 or zero def sigmoid(X,B): r = np.dot(X.T,B) bottom = 1 + np.exp(-r) sig = 1/bottom return sig #Plot line to determine decision boundary def plotLine(B,xMin,xMax,yMin,yMax): xVals = np.linspace(xMin,xMax,100) yVals = (-B[0]*xVals - B[2])/B[1] idxs = \ np.where((yVals >= yMin) & (yVals <= yMax)) plt.plot(xVals[idxs],yVals[idxs]) #Compute Binary Logistic Regression with Gradient Descent #Plot semilogy plot of objective function value vs iteration #Training Data X = generateData() N = X.shape[0] #Weights B = np.random.rand(3) #Classification Vector Y = np.zeros((N,1)) #Setting Classification Vector for i in range(N): if sigmoid(X[i],B) > 0.5: Y[i] = 1 #Cost and iteration will be for the semigraph() function. bound will be for computing boundary line cost = [] iteration = [] bound = [] t = 0.01 approx = 2000 for i in range(approx): B = B - (t*evalGrad(B,X,Y)) b = evalF(B,X,Y) bound.append(B) cost.append(b) iteration.append(i) #Seeing the convergence to zero through numbers ## if i % 5 == 0: ## print("Iteration: " + str(i) + " Cost: " + str(b)) #Setting Graph Window and setting variables for graph xMin = -3.0 xMax = 3.0 yMin = -3.0 yMax = 3.0 numPos = 100 numNeg = 100 np.random.seed(14) muPos = [1.0,1.0] covPos = np.array([[1.0,0.0],[0.0,1.0]]) muNeg = [-1.0,-1.0] covNeg = np.array([[1.0,0.0],[0.0,1.0]]) Xpos = np.ones((numPos,3)) for i in range(numPos): Xpos[i,0:2] = \ np.random.multivariate_normal(muPos,covPos) Xneg = np.ones((numNeg,3)) for i in range(numNeg): Xneg[i,0:2] = \ np.random.multivariate_normal(muNeg,covNeg) #Compute Binary Logistic Regression with Stochastic Gradient Descent #Plot Semilogy plot of objective function vs epoch X = generateData() N = X.shape[0] #Weights B = np.random.rand(3) #Classification Vector Y = np.zeros((N,1)) #Setting Classification Vector for i in range(N): if sigmoid(X[i],B) > 0.5: Y[i] = 1 #C and p are similar to cost and iteration for stochastic gradient descent graphs c = [] p = [] t = 0.01 num_epoch = 100 #Setting B1 = to B to not confuse two graphs B1 = B for epoch in range(num_epoch): idx = np.random.permutation(N) for idx in range(N): B1 = B1 - (t*evalStoGrad(B1,X,Y,idx)) beta = evalF(B1,X,Y) p.append(beta) c.append(epoch) ## if epoch % 10 == 0: ## print("Iteration: " + str(epoch) + " Cost: " + str(p[epoch])) #Decision Boundary Graph plt.figure() plt.scatter(Xpos[:,0],Xpos[:,1]) plt.scatter(Xneg[:,0],Xneg[:,1]) for i in range(len(cost)): if i % 100 == 0: plotLine(bound[i],xMin,xMax,yMin,yMax) plt.axis("equal") plt.show() #Semilogy for Gradient Descent plt.figure() title1 = "Gradient Descent" semigraph(title1,iteration, cost,approx) #Semilogy for Stochastic Gradient Descent plt.figure() title2 = "Stochastic Gradient Descent" semigraph(title2,c,p,num_epoch)
# hand-grenade sort, a near-enough is good enough implementation of quicksort import random randlist = [] for x in range(10): randlist.append(random.randint(1, 20)) def hgSort(inlist): l = [] e = [] g = [] hg = [] scannedOnce = False if len(inlist) > 1: pivot = inlist[0] for x in inlist: if x < pivot and scannedOnce is False and random.randint(0, 101) < 95: l.append(x) elif scannedOnce is True: l.append(x) if x == pivot: e.append(x) if x > pivot and scannedOnce is False and random.randint(0, 101) < 95: g.append(x) elif scannedOnce is True: g.append(x) else: hg.append(x) scannedOnce = True out = hgSort(l) + e + hgSort(g) for y in hg: out.insert(random.randint(0, len(out)), y) return out else: return inlist print randlist print hgSort(randlist)
#-*- coding:utf-8 -*- #filename: quick_sort.py import random def swap(A, i, j): A[i], A[j] = A[j], A[i] #print(A) def Partition(A, left, right): pivot = A[right] tail = left - 1 for i in range(left, right): if A[i] <= pivot: tail += 1 swap(A, tail, i) swap(A, tail+1, right) return tail+1 def QuickSort(A, left, right): if (left >= right): return index_pivot = Partition(A, left, right) QuickSort(A, left, index_pivot-1) QuickSort(A, index_pivot+1, right) def main(): #A = [5, 6, 8, 3, 7, 2, 9] A = [] for i in range(10**4): A.append(random.randint(1,100)) #print(A) QuickSort(A, 0, len(A)-1) #print(A) if __name__ == '__main__': main()
import pandas as pd import numpy as np # read the excel file file_path = 'Master.xlsx' df = pd.read_excel( file_path, index_col=None, header=None) # initialize the variable for do this task tables = [] split_tables = [] update_dates = {} start_index = {} end_index = {} current_table = None # find start row, end row, and last update date of each table, and add result of each table in key and value for index, row in df.iterrows(): col_1, col_2, col_3, col_4 = row if str(col_1).startswith('Table Name: '): name_table = str(col_1).replace('Table Name:', '').strip() tables.append(name_table) current_table = name_table elif current_table is not None: if str(col_1).startswith('Last Update Date:'): last_update_date = str(col_1).replace( 'Last Update Date:', '').strip() modified_date = last_update_date[0:4] + '-' + last_update_date[4:6] + '-' + last_update_date[6:] update_dates[name_table] = modified_date start_index[name_table] = index + 1 else: if index == len(df) - 1: end_index[name_table] = index + 1 else: end_index[name_table] = index # this function do for split each table in dataframe and transform the table in appropriate format def split_table(name_table): split_table = df[start_index[name_table] : end_index[name_table]] split_table = split_table.dropna(how='all', axis=1) header_row = split_table.iloc[0] split_table.columns = header_row split_table = split_table.drop([start_index[name_table]]) split_table = split_table.reset_index(drop=True) split_table['last_updated_date'] = update_dates[name_table] return split_table # this function do for add zero in the customer ID to become 7 digits def add_customer_digit(split_df): digit_str = str(split_df['custId']) length_digit = len(digit_str) if length_digit < 7: return digit_str.zfill(7) return digit_str # split each table in dataframe by calling the split table function for table in tables: name_split_df = table.replace(' ', '_').lower() split_tables.append(name_split_df) exec('{} = split_table(table)'.format(name_split_df)) # check and add the zero digit to be 7 digit in customer ID by calling add customer digit function customer_master['custId'] = customer_master.apply(add_customer_digit, axis=1) # print name and preview of each split table for table in split_tables: print('Name of split table: {}'.format(table)) print('Preview of split table') exec('print({}.head(3))'.format(table))
from collections import deque # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next # Simple Version, using queue # class Solution: # def connect(self, root: 'Node') -> 'Node': # if root is None: # return root # queue = deque([(1, root)]) # pre_node = None # pre_level = 0 # while len(queue) > 0: # cur_level, cur_node = queue.popleft() # if pre_node: # if cur_level == pre_level: # pre_node.next = cur_node # else: # pre_node.next = None # pre_node = cur_node # pre_level = cur_level # if cur_node.left: # queue.append((cur_level+1, cur_node.left)) # if cur_node.right: # queue.append((cur_level+1, cur_node.right)) # cur_node.next = None # return root # Using Queue # class Solution: # def connect(self, root: 'Node') -> 'Node': # if root is None: # return root # queue = deque([root]) # while len(queue) > 0: # size = len(queue) # pre_node = None # for i in range(size): # cur_node = queue.popleft() # if cur_node.right: # queue.append(cur_node.right) # if cur_node.left: # queue.append(cur_node.left) # cur_node.next = pre_node # pre_node = cur_node # return root # Not using queue, for perfect tree # class Solution: # def connect(self, root: 'Node') -> 'Node': # if not root: # return root # root.next = None # left_most_node = root # while left_most_node.left: # cur_node = left_most_node # while cur_node: # cur_node.left.next = cur_node.right # cur_node.right.next = cur_node.next.left if cur_node.next else None # cur_node = cur_node.next # left_most_node = left_most_node.left # return root # Not using queue, for general tree, self implemented # class Solution: # def connect(self, root: 'Node') -> 'Node': # if not root: # return root # root.next = None # left_most_node = root # continue_flag = True # # while left_most_node.left or left_most_node.right: # while continue_flag: # continue_flag = False # cur_node = left_most_node # while cur_node: # # if cur_node.left is None and cur_node.right is None: # # cur_node = cur_node.next # # continue # if cur_node.left and cur_node.right: # cur_node.left.next = cur_node.right # node = cur_node.right # elif cur_node.left: # node = cur_node.left # elif cur_node.right: # node = cur_node.right # else: # cur_node = cur_node.next # continue # continue_flag = True # # node.next = self.get_next_left_most(cur_node.next) if cur_node.next else None # node.next = self.get_next_left_most(cur_node.next) # cur_node = cur_node.next # left_most_node = self.get_next_left_most(left_most_node) # return root # # def get_next_left_most(self, left_most_node): # if left_most_node is None: # return left_most_node # cur_node = left_most_node # while cur_node: # if cur_node.left: # return cur_node.left # if cur_node.right: # return cur_node.right # cur_node = cur_node.next # return None # Not using queue, for general tree, self implemented. optimization class Solution: def connect(self, root: 'Node') -> 'Node': if not root: return root root.next = None left_most_node = root continue_flag = True while continue_flag: continue_flag = False cur_node = left_most_node left_most_node = None pre_node = None while cur_node: if cur_node.left and cur_node.right: if pre_node: pre_node.next = cur_node.left cur_node.left.next = cur_node.right pre_node = cur_node.right if left_most_node is None: left_most_node = cur_node.left elif cur_node.left: if pre_node: pre_node.next = cur_node.left pre_node = cur_node.left if left_most_node is None: left_most_node = cur_node.left elif cur_node.right: if pre_node: pre_node.next = cur_node.right pre_node = cur_node.right if left_most_node is None: left_most_node = cur_node.right else: cur_node = cur_node.next continue continue_flag = True cur_node = cur_node.next return root
from typing import List from collections import deque # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: queue = deque([(0, root)]) output = [] while len(queue) > 0: cur_level, cur = queue.popleft() if cur: if len(output) <= cur_level: # or len(output) == cur_level: output.append([cur.val]) else: output[cur_level].append(cur.val) if cur.left: queue.append((cur_level+1, cur.left)) if cur.right: queue.append((cur_level+1, cur.right)) return output
''' Ivor Zalud CS 5001, Fall 2020 Main function for the checkes game ''' import turtle from gamestate import GameState NUM_SQUARES = 8 # The number of squares on each row. SQUARE = 50 # The size of each square in the checkerboard. SQUARE_COLORS = ("light gray", "white") PIECE_RADIUS = SQUARE / 2 BOARD_SIZE = NUM_SQUARES * SQUARE CORNER = -BOARD_SIZE / 2 def main(): # draws the initial board board = GameState(NUM_SQUARES, SQUARE) if __name__ == "__main__": main()
S = 'A man, a plan, a canal: Panama ' #S = "race a car" #S = '' def validate(S): res = '' for s in S: if s.isalpha(): res += s.lower() return res == res[::-1] print validate(S) # Submission Result: Accepted class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ t = '' for s1 in s.lower(): if s1.isalpha() or s1.isdigit(): t += s1 return t == t[::-1]
class Solution: # @param A, a list of integers # @return a boolean def canJump(self, A): n=len(A) i=0 while True: #print i if i>=n-1: return True if A[i] ==0 : return False i+=A[i] return False
# Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: # @param intervals, a list of Intervals # @param newInterval, a Interval # @return a list of Interval def insert(self, intervals, newInterval): ts=[] ts.append(('s',newInterval.start)) ts.append(('e',newInterval.end)) for a in intervals: #attach start and end times into a list ts.append(('s',a.start)) ts.append(('e',a.end)) tss=sorted(ts,key=lambda x:x[1]) #sort the list by time cnt=0 res=[] n=len(tss) for i in range(n): # if the start and end at the same time, make sure the start count first. if i+1<n: if tss[i][1] == tss[i+1][1] and tss[i][0] =='e'and tss[i+1][0]=='s': tss[i],tss[i+1]= tss[i+1], tss[i] startp,endp=None,None for t in tss: # if the cnt ==0, interval end if t[0]=='s' : if cnt==0: startp=t[1] cnt+=1 elif t[0] =='e' : if cnt==1: endp=t[1] cnt-=1 if startp!=None and endp!=None: a=Interval(startp,endp) res.append(a) startp=None; endp=None return res
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return nothing, do it in place def flatten(self, root): # keep all node in a list, then remove left and add to right in sequence order=self.walk(root) n=len(order) for i in range(1,n): order[i-1].left=None order[i-1].right=order[i] def walk(self,n,order=None): if order is None: order=[] if n: order.append(n) order=self.walk(n.left,order) order=self.walk(n.right,order) return order
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a boolean def isValidBST(self, root): A=self.trav(root) for i in range(1,len(A)): if A[i] <= A[i-1]: return False return True def trav(self, n,A=None): if A is None: A=[] if n: A=self.trav(n.left,A) A.append(n.val) A=self.trav(n.right,A) return A
A = [ [2], [3,4], [3,2,7], [4,2,6,3], [5,7,5,1,3] ] n = len(A) def min_path_sum(A, n, sum1=0, min_sum=None, i=0, j=0): ''' recursive, working like a complete binary tree ''' if i >= n: if min_sum == None or sum1 < min_sum: min_sum = sum1 else: sum1 += A[i][j] min_sum = min_path_sum(A, n, sum1, min_sum, i+1, j) min_sum = min_path_sum(A, n, sum1, min_sum, i+1, j+1) return min_sum print min_path_sum(A,n)
class Solution: # @param A, a list of integer # @return an integer def singleNumber(self, A): x,y,z=0,0,0 # x,y,z for number shows are 1,2,3 times for a in A: y=y|x & a # if a shows twice, y include a, x & a includ a, assign to y x^=a # for first time, x includ a z=x&y # if x and y both has a, it shows 3 times x &=~z # complement, 0->1; 1->0, if z has a, remove it from x and y y &=~z # z the numbers that show up 3 times return x
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of lists of integers def levelOrder(self, root): if not root: return [] que,res,lvl=[],[],0 n=root res.append([n.val]) while n: if n.left: que.append((n.left,lvl+1)) if n.right: que.append((n.right,lvl+1)) if len(que)>0: que.reverse() n,lvl=que.pop() que.reverse() if lvl >=len(res): res.append([n.val]) else: res[-1] += [n.val] else: n=None return res
A = [ ['A', 'B', 'C', 'E' ], ['S', 'F', 'C', 'S' ], ['A', 'D', 'E', 'E' ] ] s ='SFDECCESC' def find_path(A, s): n = len(A) m = len(A[0]) for i in range(n): for j in range(m): if walk(A, s, i, j, n, m, res=False, k=0, ss='', coor=[]): return True return False def walk(A, s, i, j, n, m, res, k, ss, coor): if A[i][j] == s[k] and (i,j) not in coor: ss += A[i][j] coor.append((i,j)) k +=1 if ss == s: return True if i < n-1: res = walk(A, s, i+1, j, n, m, res, k, ss, coor) if i > 0: res = walk(A, s, i-1, j, n, m, res, k, ss, coor) if j < m-1: res = walk(A, s, i, j+1, n, m, res, k, ss, coor) if j >0: res = walk(A, s, i, j-1, n, m, res, k, ss, coor) return res print find_path(A,s)
class Solution: # @return a boolean def isValid(self, s): stack=[] n=len(s) for i in range(n): if s[i]=='(': stack.append(s[i]) elif s[i]=='{': stack.append(s[i]) elif s[i]=='[': stack.append(s[i]) elif s[i]==')' and len(stack)>0: if stack[-1]=='(': stack.pop() else: return False elif s[i]=='}' and len(stack)>0: if stack[-1]=='{': stack.pop() else: return False elif s[i]==']' and len(stack)>0: if stack[-1]=='[': stack.pop() else: return False else: return False if len(stack) != 0: return False else: return True
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @param sum, an integer # @return a boolean #def hasPathSum(self, root, sum): def hasPathSum(self, n,summ,res=0, out=False,path=[]): if n: res+=n.val #path.append(n.val) #print res, n.val if n.left==None and n.right==None and res==summ : # leaf out=True #print path, res, out return out #return res, out out=self.hasPathSum(n.left,summ, res,out,path) out=self.hasPathSum(n.right,summ, res,out,path) #print path #path.pop() return out
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return a ListNode def deleteDuplicates(self, head): if not head or not head.next: return head n=head dummy=ListNode(0)# dummy node pre=dummy pre.next=n # the node before duplicate while n: if n.next: #print 'n', n.val, 'n.next', n.next.val if n.val==n.next.val: #duplicate start k=n.val while n.val==k: # find first node after duplicates n=n.next if n==None: break pre.next=n else: # not duplicate pre=n n=n.next else: n=n.next return dummy.next
A=[[1,3],[2,6],[10,19],[5,8]] def merge(A): B = sorted(A, key = lambda x:x[0]) n = len(A) res = [] current_interval = B[0] for i in range(1, n): if B[i][0] <= current_interval[1]: # overlapping if B[i][1] > current_interval[1]: current_interval[1] = B[i][1] else: res.append(current_interval) current_interval = B[i] res.append(current_interval) return res print merge(A)
from sys import stdin from Token import * class Lexer: def __init__(self): self.inp = stdin self.the_string = self.inp.read() #self.the_string = str(input()) #self.the_file = open('sample.txt') #self.the_string = self.the_file.read() self.the_size = len(self.the_string) self.the_pos = 0 self.the_arr = [] # Calls nextToken until all of the Tokens are in the array while(self.the_size >= self.the_pos): self.the_arr.append(self.nextToken(self.the_pos)) self.the_pos += 1 # To remove None entries in the array if(None in self.the_arr): self.the_arr.pop() # A function to get all the Tokens in one def getData(self): return self.the_arr def nextToken(self, the_pos): # To make sure we dont go out of the array if(self.the_pos >= self.the_size): return #---------------------------- # Loop to skip all spaces and newlines while(self.the_string[self.the_pos] == " " or self.the_string[self.the_pos] == "\n"): self.the_pos += 1 if(self.the_pos >= self.the_size): return if(self.the_string[self.the_pos] == "="): #print(the_string[self.the_pos], "->ASSIGN") return Token("=", "ASSIGN") if(self.the_string[self.the_pos] == ";"): #print(the_string[self.the_pos], "->SEMICOL") return Token(";", "SEMICOL") if(self.the_string[self.the_pos] == "+"): #print(the_string[self.the_pos], "->PLUS") return Token("+", "ADD") if(self.the_string[self.the_pos] == "-"): #print(the_string[self.the_pos], "->SUB") return Token("-", "SUB") if(self.the_string[self.the_pos] == "*"): #print(the_string[self.the_pos],"->MULT") return Token("*", "MULT") if(self.the_string[self.the_pos] == "("): #print(the_string[self.the_pos],"->LPAREN") return Token("(", "LPAREN") if(self.the_string[self.the_pos] == ")"): #print(the_string[self.the_pos],"->RPAREN") return Token(")", "RPAREN") # If its a variable if(self.the_string[self.the_pos].isalpha()): #---------------------------------------- the_next = self.the_pos + 1 the_var = self.the_string[self.the_pos] #---------------------------- if(the_next >= self.the_size): return #---------------------------- while((self.the_string[the_next].isalpha() or self.the_string[the_next].isdigit()) and (self.the_pos < self.the_size)): the_next += 1 self.the_pos += 1 the_var += self.the_string[self.the_pos] if(the_next >= self.the_size): break if(the_var == "print"): #print(the_var, "->PRINT") return Token("print", "PRINT") if(the_var == "end"): #print(the_var, "->END") return Token("end", "END") #print(the_var, "->ID") return Token(the_var, "ID") # If its an integer elif(self.the_string[self.the_pos].isdigit()): #---------------------------------------- the_next = self.the_pos + 1 the_int = self.the_string[self.the_pos] # Just another check to make shure we dont index outside the array if(the_next >= self.the_size): return # To keep reading if it is a potential integer number while((self.the_string[the_next].isalpha() or self.the_string[the_next].isdigit()) and (self.the_pos < self.the_size)): the_next += 1 if(the_next >= self.the_size): break self.the_pos += 1 the_int += self.the_string[self.the_pos] if(the_int.isdigit()): #print(the_int,"->INT") return Token(the_int, "INT") # If it started as an int but got messed up we return an error token else: #print(the_int, "->ERROR") return Token(the_int, "ERROR")
#!/usr/bin/env python # coding: utf-8 # # Assignment 1 # ## Python Basic Programs # ### 1. Print Hello world! : # In[ ]: print("Hello world!") # ### 2. Declare the following variables: Int, Float, Boolean, String & print its value. # # In[ ]: a = 10 print(a, "is of type", type(a)) b = 5.0 print(b, "is a type of", type(b)) c = [] print(c, "is", bool(c)) d = [0] print(d, "is", bool(d)) e = 0.0 print(e, "is", bool(e)) my_string = "Hello" print(my_string, type(my_string)) my_strings = """Hello, welcome to my world""" print(my_strings, type(my_string)) # ### 3. Program to calculate the Area Of Triangle: # In[ ]: a = float (input ('Enter first side: ')) b = float (input ('Enter second side: ')) c = float (input ('Enter third side: ')) # semi-perimeter s = (a + b + c) / 2 # area area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 print ('The area of the triangle is %0.2f' %area) # ### 4. Program to calculate area of a square. # In[ ]: s = int(input('Enter side: ')) area = s * s print("{} is area of sqaure".format(area)) # ### 5. Program to swap two variables: # In[ ]: x = input ('Enter value of x: ') y = input ('Enter value of y: ') temp = x x = y y = temp print ('the value of x after swapping: {}'.format(x)) print ('the value of y after swapping: {}'.format(y)) # ### 6. Program is to check if a number is positive, negative or zero. # In[ ]: num = float(input("Enter number")) if num < 0: print("Negative") elif num == 0: print("Zero") else: print("Positive") # ### 7. Program is to check if a number is Even or Odd. # In[ ]: n = int(input('Enter a number')) if n % 2 == 0: print('{} is an even number.'. format(n)) else: print('{} is an odd number.'.format(n)) # ### 8. Program to print Odd number within a given range. # In[ ]: lower= int (input ("Enter the lower limit for the range :")) upper= int (input ("Enter the upper limit for the range :")) for i in range (lower, upper+1): if (i%2 != 0): print (i) # ### 9. Python program to find the factorial of a number. # In[ ]: n = int(input ("Enter number :")) fact = 1 while (n>0): fact =fact*n n=n-1 print("Factorial of the number is: ") print(fact) # ### 10. Program to reverse a given number. # In[ ]: n=int (input ("Enter number: ")) rev =0 while (n>0): dig =n%10 rev =rev*10+dig n =n//10 print ("Reverse of the number:", rev) # ### 11. Program to find out the sum of N Natural numbers. # In[ ]: num = int (input ("Enter a number: ")) if num < 0: print ("Enter a positive number") else: sum = 0 # ## Strings # ### 1. Program to reverse a string. # In[ ]: a=str(input ("Enter a string: ")) print("Reverse of the string is: ") print(a[::-1]) # ### 2. Program to check if string is palindrome or not: # In[ ]: my_str = 'aIbohPhoBiA' my_str = my_str.casefold() rev_str = reversed(my_str) if list (my_str) == list(rev_str): print("It is palindrome") else: print("It is not palindrome") # ### 3. Python Program to Replace all Occurrences of ‘a’ with $ in a String from user: # In[ ]: string = input("Enter string :") string= string.replace('a','$') string= string.replace('A','$') print("Modified string:") print(string) # ### 4. Python Program to Count the Number of Vowels in a String Input Two Strings and Display the Larger String without Using Built-in Functions: # In[ ]: string = input("Enter string:") vowels = 0 for i in string: if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'): vowels = vowels + 1 print("Vowel number {}".format(vowels)) print(i) string1 = input("Enter first string :") string2 = input("Enter second string :") count1=0 count2=0 for i in string1: count1=count1+1 for j in string2: count2=count2+1 if (count1<count2): print ("Larger string is :") print (string2) elif(count1==count2): print("Both strings are equal.") else: print("Larger string is:") print(string1) # ### 5. Count the number of digits & letter in a string: # In[ ]: string = input("Enter string :") word = input("Enter word :") a= [] count= 0 a=string.split(" ") for i in range (0, len(a)): if (word == a[i]): count = count+1 print ("Count of the word is:") print(count) # ### 6. Count Number of Lowercase Characters in a String: # In[ ]: string = input ("Enter string:") count = 0 for i in string: if (i.islower()): count = count + 1 print("The number of lowercase characters is :") print(count) else: print("please use lower case") # ### 7. Program to check if a Substring is Present in a Given String: # In[ ]: string = input("Enter string: ") sub_str = input("Enter word : ") if (string.find(sub_str)==-1): print ("Substring not found in string!") else: print("Substring in string!") # ## Conditional statements # ### 1. W. A P. which takes one number from 0 to 9 from the user and prints it in the word. And if the word is not from 0 to 9 then it should print that number is outside of the range and program should exit. # In[ ]: n = int(input("Enter number: ")) if n == 0: print("Zero") elif n == 1: print("One") elif n == 2: print("Two") elif n == 3: print("Three") elif n == 4: print("Four") elif n == 5: print("Five") elif n == 6: print("Six") elif n == 7: print("Seven") elif n == 8: print("Eight") elif n == 9: print("Nine") else: print("Invalid output") # ### 2. W. A P. to implement calculator but the operation to be done and two numbers will be taken as input from user:- Operation console should show below:- # Please select any one operation from below:- # 1. To add enter 1 # 2. to subtract enter 2 # 3. To multiply enter 3 # 4. To divide enter 4 # 5. To divide and find quotient enter 5 # 6. To divide and find remainder enter 6 # 7. To find num1 to the power of num2 enter 7 # 8. To Come out of the program enter 8 # In[ ]: n1 = float(input("Enter a number ")) n2 = float(input("Enter a number ")) op = input("Enter the operator ") 1 == '+' 2 == '-' 3 == '*' 4 == '/' 5 == '//' 6 == '%' 7 == '**' 8 == exit() if op == '1': print(n1 + n2) elif op == '2': print(n1 - n2) elif op == '3': print(n1 * n2) elif op == '4': if n2 == 0: print("Invalid input") else: print(n1 / n2) elif op == '5': print(n1 // n2) elif op == '6': print(n1 % n2) elif op == '7': print(n1 ** n2) elif op == '8': quit() else: print('Invalid output') # ### 3. W A P to check whether a year entered by user is an leap year or not? #  Check with below input:- # 1. leap year:- 2012, 1968, 2004, 1200, 1600,2400 # 2. Non-leap year:- 1971, 2006, 1700,1800,1900 # In[ ]: year = int(input('Enter an year: ')) if year % 4 == 0: print('Divisible by 4') if year % 100 == 0: print('Divisible by 100') if year % 400 == 0: print('Divisible by 400') print('Year is a leap year') else: print('not Divisible by 400') print('Year is not a leap year') else: print('Not Divisible by 100') print('Year is a leap year') else: print('Not Divisible by 4') print('Year is not a leap year') # ### 4. W A P which takes one number from the user and checks whether it is an even or odd number? If it even then prints number is even number else prints that number is odd number. # # In[ ]: n = input('Enter a number: ') if n.isdigit(): n = int(n) if n%2 == 0: print('{} is an even number.'.format(n)) else: print('{} is an odd number.'.format(n)) else: print('Invalid input!!!') # ### 5. W A P which takes two numbers from the user and prints below output:- # -num1 is greater than num2 if num1 is greater than num2 # # -num1 is smaller than num2 if num1 is smaller than num2 # # -num1 is equal to num2 if num1 and num2 are equal # # Note: - # 1. Do this problem using if - else # In[ ]: num1 = float(input("Enter 1st Number: ")) num2 = float(input("Enter 2nd Number: ")) if num1 > num2: print("1st Number is greater then 2nd Number") elif num1 == num2: print("Both numbers are equal") elif num1 < num2: print("1st Number is smaller then 2nd Number") else: print("Invalid input") # 2. Do this using ternary operator # In[ ]: num1, num2 =float(input("Enter 1st Number: ")), float(input("Enter 2nd Number: ")) print ("Both 1st Number and 2nd Number are equal" if num1 == num2 else "1st Number is greater than 2nd Number" if num1 > num2 else "1st number is smaller then 2nd Number") # ### 6. W A P which takes three numbers from the user and prints below output:- # -num1 is greater than num2 and num3 if num1 is greater than num2 and num3 # # -num2 is greater than num1 and num3 if num2 is greater than num1 and num3 # # -num3 is greater than num1 and num2 if num3 is greater than num1 and num2 # # Note:- # 1. Do this problem using if - elif - else # In[ ]: num1 = float(input("Enter 1st Number: ")) num2 = float(input("Enter 2nd Number: ")) num3 = float(input("Enter 3rd Number: ")) if (num1 > num2 and num1 > num3): print("1st Number is greater then 2nd & 3rd Number") elif (num2 > num1 and num2 > num3): print("2nd Number is greater then 1st & 3rd Number") elif (num3 > num1 and num3 > num2): print("3rd Number is greater then 1st & 2nd Number") else: print("Invalid input") # 2. Do this using ternary operator # In[ ]: num1, num2, num3 =float(input("Enter 1st Number: ")), float(input("Enter 2nd Number: ")), float(input("Enter 3rd Number: ")) mx = (num1 if (num1 > num2 and num1 > num3) else (num2 if (num2 > num1 and num2 > num3) else num3)) print("Largest number among is " + str(mx)) # ## Loops - for loop, while loop # ### 7. Write a Python program to find the length of the my_str using loop # # Input:- 'Write a Python program to find the length of the my_str' # # Output:- 55 # In[4]: my_str = "Write a Python program to find the length of the my_str" counter = 0 while counter < len(my_str): counter += 1 print('Length of string - {} = {}'.format(my_str, counter)) # ### 8. Write a Python program to find the total number of times letter 'p' is appeared in the below string using loop:- # #  Input:- 'peter piper picked a peck of pickled peppers.\n' # #  Output:- 9 # In[8]: mystr = 'peter piper picked a peck of pickled peppers.' c = 0 for i in mystr: if i == 'p': c += 1 print(c) # ### 9. Q. Write a Python Program, to print all the indexes of all occurrences of letter 'p' appeared in the string using loop:- # #  Input: - 'peter piper picked a peck of pickled peppers.' # #  Output:- #  0 #  6 #  8 #  12 #  21 #  29 #  37 #  39 #  40 # In[10]: mystr = 'peter piper picked a peck of pickled peppers.' for i in range(len(mystr)): if mystr[i] == 'p': print(i) # ### 10. Write a python program to find below output using loop:- # #  Input: - 'peter piper picked a peck of pickled peppers.' # #  Output:- ['peter', 'piper', 'picked', 'a', 'peck', 'of', 'pickled', 'peppers'] # In[12]: mystr = 'peter piper picked a peck of pickled peppers.' i = 0 from_indx = 0 str_list = [] while i < len(mystr): if mystr[i] == ' ': curr_indx = i str_list.append(mystr[from_indx:curr_indx]) from_indx = i+1 elif i == len(mystr) - 1: str_list.append(mystr[from_indx:]) i += 1 print('Result:- {}'.format(str_list)) # ### 11. Write a python program to find below output using loop:- # #  Input: - 'peter piper picked a peck of pickled peppers.' # #  Output:- 'peppers pickled of peck a picked piper peter' # In[ ]: mystr = 'peter piper picked a peck of pickled peppers.' mystr = mystr[:len(mystr) - 1] i = len(mystr) - 1 last_indx = len(mystr) newstr = [] while i >= 0: if mystr[i] == ' ': newstr.append(mystr[i+1 : last_indx ]) last_indx = i elif i == 0: newstr.append(mystr[i : last_indx ]) i = i - 1 print('Method 1: Output:- {}'.format(" ".join(newstr))) # ### 12. Write a python program to find below output using loop:- # #  Input: - 'peter piper picked a peck of pickled peppers.' # #  Output:- '.sreppep delkcip fo kcep a dekcip repip retep' # # In[ ]: mystr = 'peter piper picked a peck of pickled peppers.' i = len(mystr) - 1 newstr = '' while i >= 0: newstr = newstr + mystr[i] i = i -1 print('Method 1: Output:- {}'.format(newstr)) # ### 13. Write a python program to find below output using loop:- # #  Input: - 'peter piper picked a peck of pickled peppers.' # #  Output:- 'retep repip dekcip a kcep fo delkcip sreppep' # In[ ]: mystr = 'peter piper picked a peck of pickled peppers.' i = 0 from_indx = 0 newstr = '' while i < len(mystr): if mystr[i] == ' ': curr_indx = i newstr = newstr + mystr[from_indx:curr_indx][::-1] + ' ' from_indx = i+1 elif i == len(mystr) - 1: newstr = newstr + mystr[from_indx:i+1][::-1] i += 1 print('Method 1: Output:- {}'.format(newstr)) # ### 14. Write a python program to find below output using loop:- # #  Input: - 'peter piper picked a peck of pickled peppers.' # #  Output:- 'Peter Piper Picked A Peck Of Pickled Peppers' # # In[ ]: mystr = 'peter piper picked a peck of pickled peppers.' i = 0 from_indx = 0 from_indx = 0 newstr = '' while i < len(mystr): if mystr[i] == ' ': curr_indx = i newstr = newstr + mystr[from_indx].upper() + mystr[from_indx + 1:curr_indx] + ' ' from_indx = i+1 elif i == len(mystr) - 1: newstr = newstr + mystr[from_indx].upper() +mystr[from_indx + 1:i+1] i += 1 print('Output:- {}'.format(newstr)) # ### 15. Write a python program to find below output using loop:- # #  Input: - 'Peter Piper Picked A Peck Of Pickled Peppers.' # #  Output:- 'Peter piper picked a peck of pickled peppers' # In[ ]: mystr = 'Peter Piper Picked A Peck Of Pickled Peppers.' i = 0 newstr = '' from_indx = 0 while i < len(mystr): if mystr[i] == ' ': newstr = newstr + mystr[from_indx].upper() + mystr[from_indx + 1: ] break i += 1 print('Method 1: Output:- {}'.format(newstr)) # ### 16. Write a python program to implement index method using loop. If sub_str is found in my_str then it will print the index of first occurrence of first character of matching string in my_str:- # #  Input: - my_str = 'Peter Piper Picked A Peck Of Pickled Peppers.', # #  sub_str = 'Pickl' # #  Output:- 29 # # In[ ]: mystr = 'Peter Piper Picked A Peck Of Pickled Peppers.' sub_str = 'Pickl' print('Input:- {}'.format(mystr)) i = 0 from_indx = 0 newstr = '' while i < len(mystr): if sub_str == mystr[i:i+len(sub_str)]: break i += 1 print('Output:- {}'.format(i)) # ### 17. Write a python program to implement replace method using loop. If sub_str is found in my_str then it will replace the first occurrence of sub_str with new_str else it will will print sub_str not found:- # #  Input: - my_str = 'Peter Piper Picked A Peck Of Pickled Peppers.', # #  sub_str = 'Peck', new_str = 'Pack' # #  Output: - 'Peter Piper Picked A Pack Of Pickled Peppers.' # # In[ ]: mystr = 'Peter Piper Picked A Peck Of Pickled Peppers.' sub_str = 'Peck' new_str = 'Pack' print('Input:- {}'.format(mystr)) curr_indx = 0 from_indx = 0 newstr = '' IS_FOUND = False while curr_indx < len(mystr): if mystr[curr_indx] == ' ': if sub_str == mystr[from_indx:curr_indx]: newstr = newstr + new_str + mystr[curr_indx:] IS_FOUND = True break else: newstr = newstr + mystr[from_indx:curr_indx+1] from_indx = curr_indx + 1 elif curr_indx == len(mystr) - 1: if sub_str == mystr[from_indx:curr_indx]: newstr = newstr + new_str + mystr[curr_indx:] IS_FOUND = True break curr_indx += 1 if IS_FOUND == False: print('Output:- {} not found.'.format(sub_str)) else: print('Output:- {}'.format(newstr)) # ### 18. Write a python program to find below output (implements rjust and ljust) using loop:- # #  Input: - 'Peter Piper Picked A Peck Of Pickled Peppers.' # #  sub_str ='Peck', # #  Output:- '*********************Peck********************' # In[ ]: mystr = 'Peter Piper Picked A Peck Of Pickled Peppers.' sub_str = 'Peck' i = 0 from_indx = 0 newstr = '' while i < len(mystr): if mystr[i] == ' ': curr_indx = i if sub_str == mystr[from_indx:curr_indx]: break else: from_indx = i+1 elif i == len(mystr) - 1: curr_indx = i from_indx = i+1 i += 1 newstr = '*'*len(mystr[0:from_indx]) + mystr[from_indx:curr_indx] + '*'*len(mystr[curr_indx]) print('Output:- {}'.format(newstr)) # ### 19. Write a python program to find below output using loop:- # #  Input:- 'This is Python class', sep = ' is', # #  Output:- ['This', 'Python class'] # # In[ ]: mystr = 'This is Python class' sep = 'is' outlist = [] for each in mystr.split(' '): if each != sep: outlist.append(each) print('Output:- {}'.format(outlist)) # ### 20. WAP to read input from user. Allow the user to enter more numbers as long as the user enters valid integers. Terminate the program with proper message when they entered value is anything except integer. # # In[ ]: while(True): n = input('Enter an integer: ') FLAG = False if(n.isdigit()): FLAG = True else: FLAG = False if(FLAG== True): pass else: print('Invalid input') # ### 21. WAP to read input from a user. Allow the user to enter more numbers as long as the user enters valid numbers. Terminate the program with proper message when the user enters a value anything except valid number. # In[ ]: while(True): n = input('Enter a number: ') flag = False if(n.isnumeric() | n.replace('.','',1).isnumeric()): flag = True else: flag = False if(flag): pass else: print('Invalid Input') break # ### 22. WAP to read input from a user. Allow the user to enter more numbers as long as the user enters valid numbers. Terminate the program with proper message when the user enters a value anything except valid number. Allow wrong entry 'N' times. # # In[ ]: counter = 1 N = 2 while(True): n = input('Enter a number: ') flag = False if(n.isnumeric() | n.replace('.','',1).isnumeric()): flag = True else: flag = False if(flag ): pass else: counter += 1 if(counter <= N): pass else: print('You have entered invalid input {} times. Hence, Exiting the loop.'.format(counter)) break
#Q1 Reverse the whole list using list methods. print("<--solution 1-->") list=[1,2,3,4,5] list.reverse() print(list) #Q2 Print all the uppercase letters from a string. print("<--solution 2-->") string= "PULKIT JOHAR" for ch in string : if ch.isupper(): print(ch) #question 3 Split the user input on comma's and store the values in a list as integers. print("<--solution 3-->") i=input("enter the input ") list=[] list1=i.split(',') for n in list1: list.append(int(n)) print(list) #Q4 Check whether a string is palindromic or not. print("<--solution 4-->") n=int(input("Enter number:")) temp=n rev=0 while(n>0): dig=n%10 rev=rev*10+dig n=n//10 if(temp==rev): print("The number is a palindrome!",rev) else: print("The number isn't a palindrome!",rev) #Q5 Make a deepcopy of a list and write the difference between shallow copy and deep copy. print("<--solution 5-->") import copy as c list1 = [1, 2, [3,5], 4] list2 = c.deepcopy(list1) print ("Before deep copying") print("list1 = ",list1) print("list2 = ",list2) list2[2][1] = 125 print ("After deep copying in list2") print(list2) print ("After deep copying in list1") print(list1) print('\r')
def computepay(h,r): if h <= 40: return h * r else: return ((h-40) * (r * 1.5)) + (40 * r) hrs = float(input("Enter Hours: ")) rs = float(input("Enter Rate: ")) p = computepay(hrs,rs) print("Pay",p)
def sieve(limit: int) -> list: if limit < 2: return [] primes = [] nums = list(range(2, limit+1)) for index in range(2, limit+1): if index in nums: primes.append(index) for num in nums: if num % index == 0: nums.remove(num) return primes print(sieve(99999))
def is_isogram(string) -> bool: char_set = set() for char in string.lower().replace("-","").replace(" ", ""): if char in char_set: return False char_set.add(char) return True
__author__ = 'nunoe' class Location(object): def __init__(self, x, y): """ :param x: float, horizontal coordinate :param y: float, vertical coordinate """ self.x = x self.y = y def move_to(self, delta_x, delta_y): """ :param delta_x: float, distance to move along the x-axis :param delta_y: float, distance to move along the y-axis :return: Location, the new location after moving """ return Location(self.x + delta_x, self.y + delta_y) def get_x(self): return self.x def get_y(self): return self.y def dist_from(self, other): """ :param other: Location, the other location against which to calculate the current point's distance :return: float, the distance from self to other """ x_dist = self.x - other.get_x() y_dist = self.y - other.get_y() return (x_dist ** 2 + y_dist ** 2) ** 0.5 def __str__(self): return '<' + str(self.x) + ', ' + str(self.y) + '>'
""" URL Shortener Description: You are asked to develop code for a URL shortening service similar to https://goo.gl/. Users of this service will provide you URLs such as https://en. wikipedia.org/wiki/History_of_the_Internet. As a result your service should return a shortened URL such as http://foo.bar/1xf2. In this task we would like you to implement a method shortenURL that is called for every input URL. The output of this method is a shortened URL for the input URL. When is the problem solved? A shortened URL is returned. Please print the output of the method to the console. """ def shorten_url(long_url): pass if __name__ == "__main__": shorten_url("https://hw.ac.uk")
#coding=utf-8 import re def word_tokenize(text): return re.findall(r'\w+', text.lower()) ##removes non non-alphanumeric characters based on re def re_nalpha(str): pattern = re.compile(r'[^\w\s]', re.U) return re.sub(r'\n','',re.sub(r'_', '', re.sub(pattern, '', str))) ##tokenization in uni- to n-grams,a function that tokenize a string into words and multi-word strings #please be aware of that the redundant words will be append to the the end as one gram string #this fucntion will return a list containing the tokenized strings def tokenizer(text,size=1): # tokenize to 1 gram strings result_size1 = word_tokenize(text) if size == 1: return result_size1 # tokenize into n gram strings else: temp_list = [] temp_size = 0 for i in range(0,len(result_size1)-size+1): temp_str='' for j in range(size): temp_str = temp_str+" "+ result_size1[temp_size+j] temp_list.append(temp_str[1:]) temp_size += 1 return temp_list #this is a test, please remove if not needed #s = 'this is f@*cking co1ol!!!' #print re_nalpha(s)
def test(a, b, c): if a == b or b == c or c == a: return True else: return False Answer = test(5,6,7) print (Answer) #Extra Credit def Test(a,b,c): if a == b or b == int(c) or int(c) == a: return True else: return False Result = Test(7,8,"8") print(Result)
import math def lcm(a,b): ''' Lowest common multiple ''' return a*b/gcd(a,b) def gcd(a,b): ''' Greatest common divisor ''' if a%b == 0: return b else: return gcd(b,a%b) def sieve(MAXN): ''' Sieve of Eratosthenes up to MAXN (inclusive) ''' is_prime = [True]*(MAXN+1) for n in xrange(2,MAXN+1): if is_prime[n]: for mult in xrange(2,MAXN/n+1): is_prime[mult*n] = False primes = [] for n in xrange(2,MAXN+1): if is_prime[n]: primes.append(n) return primes def is_prime(n): ''' Check whether n is prime ''' for i in xrange(2,int(n**0.5)+1): if n%i == 0: return False return True def get_digits(num): ''' Return a list of digits of num ''' digits = [] while num > 0: digits.append(num%10) num /= 10 digits.reverse() return digits def is_square(N): ''' Check whether N is a perfect square ''' root = int(math.sqrt(N)) return root*root == N or (root+1)*(root+1) == N def phi(n): ''' Compute Euler's totient function ''' if n <= 1: return 0 res = n p = 2 while p*p <= n: if n%p == 0: res -= res/p while n%p == 0: n /= p p += 1 if n > 1: res -= res/n return res def continued_fraction(N): ''' Compute the continued fraction of N where N is a positive integer and not a perfect square. Returns a list of the continued fraction terms [a0,a1,...] and an integer for the seuqnece period. ''' root = int(math.sqrt(N)) #N must not be a perfect square assert root*root != N and (root+1)*(root+1) != N class Num(object): def __init__(self, root, a=0, b=1): self.root = root self.a = a self.b = b def get_val(self): return (math.sqrt(self.root)+self.a) / self.b def get_int(self): return int(self.get_val()) def step(self): a0 = self.get_int() self.a -= self.b*a0 new_den = self.root - self.a*self.a assert new_den % self.b == 0 new_den /= self.b self.a = -self.a self.b = new_den return a0 def __str__(self): return "(sqrt%i + %i)/%i" %(self.root,self.a,self.b) def key(self): return (self.a,self.b) mem = {} num = Num(N) i = 0 seq = [] while True: #print num if mem.has_key(num.key()): return seq, i-mem[num.key()] mem[num.key()] = i a = num.step() seq.append(a) #print a i += 1 def generate_phi(MAXN): ''' Generate phi(n) for all phi from 2 to MAXN inclusive. ''' phi_by_n = [1]*(MAXN+1) is_prime = [True]*(MAXN+1) for i in xrange(2,MAXN+1): if is_prime[i]: for m in xrange(1,MAXN/i+1): phi_by_n[i*m] *= 1-1.0/i is_prime[i*m] = False phi = [0,1] for i in range(2,MAXN+1): phi.append(int(round(phi_by_n[i]*i))) return phi
def is_palindrome(s): return s[::-1] == s def check(n): return is_palindrome(str(n)) and is_palindrome(bin(n)[2:]) ans = 0 for n in xrange(1,1000000): if check(n): ans += n #print n print ans
def get_digit_string(digits): string = "" start = -1 for i in xrange(5,10): if start == -1 or digits[i] < digits[start]: start = i cur = start for i in xrange(5): string += str(digits[cur]) string += str(digits[cur-5]) string += str(digits[(cur-5+1)%5]) cur += 1 if cur == 10: cur = 5 return string def find_outer(used,digits,s): for i in xrange(5,10): cur_sum = digits[i-5]+digits[(i-5+1)%5] d = s-cur_sum if d <= 0 or d > 10 or used[d]: return False used[d] = True digits[i] = d digit_string = get_digit_string(digits) global max_digit_string if len(digit_string) == 16 and int(digit_string) > int(max_digit_string): max_digit_string = digit_string return True def place_ring(i): if i == 5: for s in xrange(30): find_outer(list(used),list(digits),s) else: for d in xrange(1,11): if not used[d]: digits[i] = d used[d] = True place_ring(i+1) used[d] = False max_digit_string = "0" used = [False]*11 digits = [0]*10 #print get_digit_string([1,2,3,4,5,6,7,8,9,10]) place_ring(0) print max_digit_string
import math def is_pent(x): det = 1 + 24*x det_root = int(math.sqrt(det)) if (det_root+1)**2 == det: det_root += 1 n = (1 + det_root)/6 return n*(3*n-1)/2 == x def is_hex(x): det = 1+8*x det_root = int(math.sqrt(det)) if (det_root+1)**2 == det: det_root += 1 n = (1+det_root)/4 return n*(2*n-1) == x i = 286 while True: tri = i*(i+1)/2 if is_pent(tri) and is_hex(tri): print tri break i += 1
import math def is_tri(t): root = int(math.sqrt(1+8*t)) if (root+1)*(root+1) == 1+8*t: root += 1 if root*root != 1+8*t: return False n = (-1+root)/2.0 return abs(n-int(n)) < 1e-6 def convert(word): t = 0 for char in word: t += ord(char)-ord('A')+1 return t ans = 0 words = open("42.txt").read().split(",") for word in words: word = word.strip('"') t = convert(word) if is_tri(t): ans += 1 print ans
# Python 3.7 # This Program tells the diameter from one Node of the tree to another # By Yusuf Ali # Finds the Height of the tree class TreeHeight: def __init(self): self.h = 0 # Creates the Node class Node: def __init__(self, data): self.data = data self.left = self.right = None # This Function find the diameter for the binary tree def diameter(root, height): lh = TreeHeight() rh = TreeHeight() if root is None: height.h = 0 return 0 ldiameter = diameter(root.left, lh) rdiameter = diameter(root.right, rh) height.h = max(lh.h, rh.h) + 1 return max(lh.h + rh.h + 1, max(ldiameter, rdiameter)) #Creates all of the nodes root = Node(0) root.left = Node(50) root.right = Node(100) root.left.left = Node(200) root.left.right = Node(500) # Checks the root def check(root): if root == None: return "Invalid Root" check(root) # Prints the diameter height = TreeHeight() print(diameter(root, height))
# https://leetcode.com/problems/most-common-word/ import re from collections import Counter def find_most_common_word(paragraph, banned): words = re.findall(r'\w+', paragraph.lower()) allowed_words = [w for w in words if w not in set(banned)] return Counter(allowed_words).most_common()[0][0] paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." banned = ["hit"] print(find_most_common_word(paragraph, banned))
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def isSubtree(self, s, t): """ :type s: TreeNode :type t: TreeNode :rtype: bool """ def match(s, t): if not (s and t): return False elif not s and not t: return True equality = s.val == t.val left = self.isSubtree(s.left, t.left) right = self.isSubtree(s.right, t.right) return equality and left and right if not s and not t: return True if not (s and t): return False stack = [s] while stack: curr = stack.pop() if curr.val == t.val: return match(curr, t) if curr.left: stack.append(curr.left) if curr.right: stack.append(curr.right)
class Solution(object): def accountsMerge(self, accounts): """ :type accounts: List[List[str]] :rtype: List[List[str]]] n = len(accounts) email2name = dict() TODO https://leetcode.com/problems/accounts-merge/submissions/ """ n = len(accounts) email2name = dict() email2index = collections.defaultdict() uf = UnionFind(n) for i, account in enumerate(accounts): name = account[0] for email in account[1:]: if email not in email2index: email2name[email] = name email2index[email] = i uf.union(email2index[account[1]],email2index[email]) emailgroup= collections.defaultdict(list) for email in email2index: emailgroup[uf.find(email2index[email])].append(email) res = list() for item, emails in emailgroup.items(): res.append([email2name[emails[0]]] + sorted(emails)) return res class UnionFind(object): def __init__(self, size): self.father = dict() for i in range(size): self.father[i] = i def find(self, x): if self.father[x] == x: return x self.father[x] = self.find(self.father[x]) return self.father[x] def union(self, a, b): root_a = self.find(a) root_b = self.find(b) if root_a != root_b: self.father[root_a] = root_b
""" https://leetcode.com/problems/reorder-data-in-log-files/ """ class Solution(object): def reorderLogFiles(self, logs): """ :type logs: List[str] :rtype: List[str] """ digits = [] letters = [] # divide logs into two parts, one is digit logs, the other is letter logs for log in logs: if log.split()[1].isdigit(): digits.append(log) else: letters.append(log) letters.sort(key=lambda x: (x.split()[1:], x.split()[0])) return letters + digits logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"] sol = Solution() print(sol.reorderLogFiles(logs))
"""CSC148 Lab 4: Abstract Data Types === CSC148 Winter 2021 === Department of Mathematical and Computational Sciences, University of Toronto Mississauga === Module Description === In this module, you will write two different functions that operate on a Stack. Pay attention to whether or not the stack should be modified. """ from typing import Any, List ############################################################################### # Task 1: Practice with stacks ############################################################################### class Stack: """A last-in-first-out (LIFO) stack of items. Stores data in a last-in, first-out order. When removing an item from the stack, the most recently-added item is the one that is removed. """ # === Private Attributes === # _items: # The items stored in this stack. The end of the list represents # the top of the stack. _items: List def __init__(self) -> None: """Initialize a new empty stack.""" self._items = [] def is_empty(self) -> bool: """Return whether this stack contains no items. >>> s = Stack() >>> s.is_empty() True >>> s.push('hello') >>> s.is_empty() False """ return len(self._items) == 0 def push(self, item: Any) -> None: """Add a new element to the top of this stack.""" self._items.append(item) def pop(self) -> Any: """Remove and return the element at the top of this stack. Raise an EmptyStackError if this stack is empty. >>> s = Stack() >>> s.push('hello') >>> s.push('goodbye') >>> s.pop() 'goodbye' """ if self.is_empty(): raise EmptyStackError else: return self._items.pop() class EmptyStackError(Exception): """Exception raised when an error occurs.""" pass def size(s: Stack) -> int: """Return the number of items in s. >>> s = Stack() >>> size(s) 0 >>> s.push('hi') >>> s.push('more') >>> s.push('stuff') >>> size(s) 3 """ side_stack = Stack() count = 0 # Pop everything off <s> and onto <side_stack>, counting as we go. while not s.is_empty(): side_stack.push(s.pop()) count += 1 # Now pop everything off <side_stack> and back onto <s>. while not side_stack.is_empty(): s.push(side_stack.pop()) # <s> is restored to its state at the start of the function call. # We consider that it was not mutated. return count def remove_big(s: Stack) -> None: """Remove the items in <stack> that are greater than 5. Do not change the relative order of the other items. >>> s = Stack() >>> s.push(1) >>> s.push(29) >>> s.push(8) >>> s.push(4) >>> remove_big(s) >>> s.pop() 4 >>> s.pop() 1 >>> s.is_empty() True """ # temp = Stack() while not s.is_empty(): val = s.pop() # Only keep values less than or equal to five. if val <= 5: temp.push(val) # Restore the original stack. while not temp.is_empty(): s.push(temp.pop()) def double_stack(s: Stack) -> Stack: """Return a new stack that contains two copies of every item in <stack>. We'll leave it up to you to decide what order to put the copies into in the new stack. >>> s = Stack() >>> s.push(1) >>> s.push(29) >>> new_stack = double_stack(s) >>> s.pop() # s should be unchanged. 29 >>> s.pop() 1 >>> s.is_empty() True >>> new_items = [] >>> new_items.append(new_stack.pop()) >>> new_items.append(new_stack.pop()) >>> new_items.append(new_stack.pop()) >>> new_items.append(new_stack.pop()) >>> sorted(new_items) [1, 1, 29, 29] """ temp = Stack() # Stack to restore original values duplicated = Stack() # The stack to return. while not s.is_empty(): val = s.pop() temp.push(val) # Add duplicates for each value. duplicated.push(val) duplicated.push(val) # Restore the original stack. while not temp.is_empty(): s.push(temp.pop()) return duplicated if __name__ == '__main__': import doctest doctest.testmod()
"""Lab 7: Trees and Recursion, Task 3 === CSC148 Winter 2021 === Diane Horton and David Liu Department of Computer Science, University of Toronto === Module Description === This module contains a basic automatic random tiling generator that you will complete for Task 3 of this lab. There's quite a bit to read here---go slow, and make sure you read carefully before writing any code yourself. Keep in mind that this program requires the Python library pygame to be installed (it already is for the Teaching Labs, but you'll need to install it yourself if you're using your own machine). """ import random from typing import List, Tuple import pygame # Constants defining the size of a square, and two colours. SQUARE_SIZE = 20 BLACK = (0, 0, 0) WHITE = (255, 255, 255) def draw_grid(n: int) -> None: """Draw a pygame grid of size 2^n by 2^n. Precondition: n >= 1 """ # Initialize a pygame screen filled in black. pygame.init() screen = pygame.display.set_mode((2**n * SQUARE_SIZE, 2**n * SQUARE_SIZE)) screen.fill(BLACK) # Draw white gridlines in the screen. for i in range(2 ** n): for j in range(2 ** n): rect = (i * SQUARE_SIZE, j * SQUARE_SIZE, # Last two coordinates are *width and height* # http://www.pygame.org/docs/ref/rect.html # (i + 1) * SQUARE_SIZE, (j + 1) * SQUARE_SIZE) SQUARE_SIZE, SQUARE_SIZE) pygame.draw.rect(screen, WHITE, rect, 1) # Uncomment the following part after you've implemented tile_with_dominoes # tiling = tile_with_dominoes(n) # for domino in tiling: # domino.draw(screen) # Display the screen to the user. pygame.display.flip() class Domino: """A domino on a grid. === Attributes === position: The location of the domino on the grid. colour: The colour of the domino, representing in RGB colour form. === Representation invariants === - len(position) == 2 - position's two tuples are adjacent squares on the grid For a 2^n by 2^n grid, each tuple's (x, y) coordinates should both be between 0 and 2^n - 1, inclusive. The position should *not* depend on SQUARE_SIZE - this constant is only used when drawing the domino using pygame. **IMPORTANT!!!** In pygame, the origin (0, 0) position is located at the *top-left* corner of the window. Increasing the y coordinate moves *down* the grid. - each number in colour is between 0 and 255, inclusive """ position: List[Tuple[int, int]] colour: Tuple[int, int, int] def __init__(self, square1: Tuple[int, int], square2: Tuple[int, int]) -> None: """Initialize a new domino with the given two squares. Pick a random colour for the domino. Precondition: square1 and square2 are adjacent """ self.position = [square1, square2] self.colour = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) def add_offset(self, x_offset: int, y_offset: int) -> None: """Add the given offset to each square in this domino. """ for i in range(len(self.position)): old_x, old_y = self.position[i] self.position[i] = (old_x + x_offset, old_y + y_offset) def draw(self, screen: pygame.Surface) -> None: """Draw this domino onto the given screen. """ x_coords = [self.position[0][0], self.position[1][0]] y_coords = [self.position[0][1], self.position[1][1]] pygame.draw.rect(screen, self.colour, (min(x_coords) * SQUARE_SIZE, min(y_coords) * SQUARE_SIZE, (max(x_coords) - min(x_coords) + 1) * SQUARE_SIZE, (max(y_coords) - min(y_coords) + 1) * SQUARE_SIZE)) # TODO: implement this function! def tile_with_dominoes(n: int) -> List['Domino']: """Return a random tiling of a 2^n by 2^n grid by dominoes. Remember that you should be returning a list of dominoes here. Think recursively! Mentally divide up the 2^n by 2^n grid into four quadrants, each of size 2^(n-1). Precondition: n >= 1. **IMPORTANT!!!** In pygame, the origin (0, 0) position is located at the *top-left* corner of the window. Increasing the y coordinate moves *down* the grid. """ if n == 1: return _tile_2_by_2() else: # TODO (1) # Compute four different tilings of a 2^(n-1) by 2^(n-1) grid, # for the four different quadrants. upper_left_tiling = [] upper_right_tiling = [] lower_left_tiling = [] lower_right_tiling = [] # TODO (2) # Each tiling will have square coordinates between 0 and 2^(n-1), # but these coordinates are only good for the *upper-left* quadrant. # Add an offset to the upper-right, lower-left, and lower-right tilings # so that the dominoes are placed in the correct quadrant. # # Remember that the positions here do *not* depend on SQUARE_SIZE. # TODO (3) # Return the combined tiling for all four quadrants. def _tile_2_by_2() -> List['Domino']: """Return a random tiling of a 2 by 2 grid. Randomly choose between tiling the grid vertically or horizontally. """ # Remember that the positions here do *not* depend on SQUARE_SIZE. pass if __name__ == '__main__': import python_ta python_ta.check_all(config={ 'allowed-import-modules': ['pygame', 'random', 'typing', 'python_ta'], 'generated-members': 'pygame.*' }) draw_grid(5) input('Press Enter to exit\n')
"""CSC148 Lab 4: Abstract Data Types === CSC148 Winter 2021 === Department of Mathematical and Computational Sciences, University of Toronto Mississauga === Module Description === In this module, you will develop an implementation of the Queue ADT. It will be helpful to review the stack implementation from lecture. After you've implemented the Queue, you'll write two different functions that operate on a queue, paying attention to whether or not the queue should be modified. """ from typing import Any, List, Optional class Queue: """A first-in-first-out (FIFO) queue of items. Stores data in a first-in, first-out order. When removing an item from the queue, the most recently-added item is the one that is removed. """ def __init__(self) -> None: """Initialize a new empty queue.""" self._items = [] def is_empty(self) -> bool: """Return whether this queue contains no items. >>> q = Queue() >>> q.is_empty() True >>> q.enqueue('hello') >>> q.is_empty() False """ return len(self._items) == 0 def enqueue(self, item: Any) -> None: """Add <item> to the back of this queue. """ # To add to the front of the queue # self._items.insert(0, item) # To add at the end of queue self._items.append(item) def dequeue(self) -> Optional[Any]: """Remove and return the item at the front of this queue. Return None if this Queue is empty. (We illustrate a different mechanism for handling an erroneous case.) >>> q = Queue() >>> q.enqueue('hello') >>> q.enqueue('goodbye') >>> q.dequeue() 'hello' """ # To pop from end of queue # return self._items.pop() # Pop from front of queue return self._items.pop(0) def product(integer_queue: Queue) -> int: """Return the product of integers in the queue. Remove all items from the queue. Precondition: integer_queue contains only integers. >>> q = Queue() >>> q.enqueue(2) >>> q.enqueue(4) >>> q.enqueue(6) >>> product(q) 48 >>> q.is_empty() True """ # Keep track of product prod = 1 while not integer_queue.is_empty(): # Keep changing the product. prod *= integer_queue.dequeue() return prod def product_star(integer_queue: Queue) -> int: """Return the product of integers in the queue. Precondition: integer_queue contains only integers. >>> primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] >>> prime_line = Queue() >>> for prime in primes: ... prime_line.enqueue(prime) ... >>> product_star(prime_line) 6469693230 >>> prime_line.is_empty() False """ temp = Queue() # temp queue to restore the queue prod = 1 while not integer_queue.is_empty(): val = integer_queue.dequeue() prod *= val temp.enqueue(val) # Restore the queue while not temp.is_empty(): integer_queue.enqueue(temp.dequeue()) return prod if __name__ == '__main__': import doctest doctest.testmod()
import random import os def read(filepath = "./archivos/data.txt"): words = [] with open(filepath, "r", encoding = "utf-8") as f: for line in f: words.append(line.strip().upper()) return words def run(): data = read(filepath = "./archivos/data.txt") #Uso de modulo random para seleccion de palabra chosen_word = random.choice(data) chosen_word_list = [letter for letter in chosen_word] underscores = ["_"] * len(chosen_word_list) letter_index_dict = {} # Uso de ENUMERATE para ingresar cada letra en un # diccionario con un id para ser ubicado for idx, letter in enumerate(chosen_word): if not letter_index_dict.get(letter): letter_index_dict[letter] = [] letter_index_dict[letter].append(idx) while True: os.system("cls") print("Adivina la palabra") for element in underscores: print(element+" ",end="") print("\n") letter = input("Escriba una letra: ").strip().upper() #try assert letter.isalpha(), "Solo se permiten letras" #Reemplaza la letra correcta que se encuentra en el diccionario # en la lista de underscore a traves del id if letter in chosen_word_list: for idx in letter_index_dict[letter]: underscores[idx] = letter if "_" not in underscores: os.system("cls") print("Ganaste!, la palabra era", chosen_word) break if __name__ == '__main__': run()
n = int(input()) for i in range (n,0,-1): if (n%i == 0): print(int(n/i),end=" ")
import sys sys.stdin = open("input.txt",'r') def binary_search(pages,key): start = 1 end = pages cnt = 0 while start <= end: middle = int((start + end) / 2) cnt+=1 if key == middle: return cnt elif key > middle: start = middle else: end = middle t = int(input()) for tc in range(1,t+1): p,a,b = map(int,input().split()) a_cnt = binary_search(p,a) b_cnt = binary_search(p, b) if a_cnt < b_cnt: print(f'#{tc} A') elif a_cnt == b_cnt: print(f'#{tc} 0') else: print(f'#{tc} B')
result = [] data = [1,2,3,4,5] def combination(n,r,now=0,cnt=0,temp=None): global result if temp == None: temp = [] if cnt == r: result.append(temp) elif n-now < r-cnt: return elif now < n: # 선택 new_temp = temp + [data[now]] combination(n, r, now + 1, cnt + 1, new_temp) # 선택x combination(n,r,now+1,cnt,temp) combination(5,3) print(result)
# -*- coding: utf-8 -*- # !/usr/bin/env python3 import pathlib def tree(root_path_obj): assert root_path_obj.is_dir() items = list() for item in root_path_obj.resolve().iterdir(): if item.is_dir(): items.extend(tree(item)) # recursion! else: items.append(item) return items if __name__ == '__main__': # folder to be walked rel_myfolder = pathlib.Path('.') / 'myfolder' abs_myfolder = rel_myfolder.resolve() # --- WALK THE FOLDER USING ABSOLUTE PATHS --- print('\nWalking folder: {}'.format(abs_myfolder)) items = tree(abs_myfolder) print('\n'.join([str(i) for i in items])) # --- FILTER ONLY TEXT FILES USING RELATIVE PATHS --- print('\nWalking text files in folder: {}'.format(rel_myfolder)) for f in rel_myfolder.rglob('*.txt'): print(f) # --- FILTER ONLY FILES WHOSE NAME STARTS WITH 00 --- print('\nWalking files whose name starts with 00 in folder: {}'.format(rel_myfolder)) for f in rel_myfolder.rglob('00*'): print(f)
# -*- coding: utf-8 -*- # !/usr/bin/env python3 import PyPDF2 import pathlib # --- ROTATE CONTENTS OF A PDF FILE AND SAVE TO ANOTHER --- def rotate_clockwise(src_pdf_path, target_pdf_path, rotation_angle): assert isinstance(src_pdf_path, str) assert isinstance(target_pdf_path, str) assert isinstance(rotation_angle, int) assert rotation_angle >= 0 with open(src_pdf_path, 'rb') as f: reader = PyPDF2.PdfFileReader(f) writer = PyPDF2.PdfFileWriter() # we need to rotate all pages for index in range(reader.numPages): page = reader.getPage(index) page.rotateClockwise(rotation_angle) writer.addPage(page) # saving to target file with open(target_pdf_path, 'wb') as g: writer.write(g) if __name__ == '__main__': src = pathlib.Path('composers.pdf').resolve() target = pathlib.Path('output_rotated.pdf') target.touch() rotate_clockwise(str(src), str(target.resolve()), 180)
''' 주어진 리스트 데이터를 이용하여 3의 배수의 개수와 배수의 합을 구하여 아래와 같이 출력하세요 data = [1, 3, 5, 8, 9, 11, 15, 19, 18, 20, 30, 33, 31 ] ''' data = [1, 3, 5, 8, 9, 11, 15, 19, 18, 20, 30, 33, 31] #갯수를 구할 변수 count = 0 #합계를 구할 변수 sum = 0 for multiple in data : # print(multiple) if multiple%3==0 : #print("3의 배수:" , multiple, end="\t") #3의 배수이면 count에 1을 더해줌 count += 1 #3의 배수이면 sum에 더함 sum += multiple print("주어진 리스트에서 3의 배수의 개수=> %d" %count) print("주어진 리스트에서 3의 배수의 합=> %d" %sum)
#Python sayı tahmin oyunu #Python number guess game #You can copy that file as you want. #Its ok for me :D #Dosyayı istediğiniz gibi kopyalayabilirsiniz. #Benim için sorun yok :D sayi=50 a=1 denemeler = 0 while a==1: if denemeler <= 5: denemeler+=1 tahmin=input("tuttuğum bir sayı var. bu sayıyı tahmin edermisin?") tahmin=int(tahmin) if tahmin==sayi: print("Tebrik ederim! Doğru sayıyı buldun.") a=0 else: print("yanlış cevapladın. tekrar dene...") #print("çıkıyoorum") else: print("cok fazla denediniz.") break
import sqlite3 as sql db = sql.connect('dtb.db') cur = db.cursor() print("Welcome to our store. You can buy credits there.") print(""" Prices: 1 credit = 1 ¢ """) cur.execute("SELECT credit FROM credits") beforeCredits = cur.fetchall()[0][0] request = int(input("How many credits you want to buy?")) cur.execute(f"UPDATE credits SET credit = {beforeCredits+request}") db.commit() db.close()
#! /usr/bin/python # class BinaryHeap: def __init__(self): self.heap_list = [0] # do not init empty self.current_size = 0 def insert(self, node): self.heap_list.append(node) def find_min(self): print 'foo' def delete_min(self): print 'foo' def size(self): return len(self.help_list) def is_empty(self): return len(self.heap_list) == 0 def build_heap_list(self, list): print 'foo' def foo(self): return self.__perc_up() def __perc_up(self): print 'foo' def __perc_down(self): print 'foo' def __min_child(self): print 'foo' print BinaryHeap().foo()
#! /usr/bin/python class BinaryTree: def __init__(self, root): self.root = root self.left_child = None self.right_child = None def insert_left(self, node): new_tree = BinaryTree(node) if self.left_child == None: self.left_child = new_tree else: new_tree.left_child = self.left_child self.left_child = new_tree return self def insert_right(self, node): new_tree = BinaryTree(node) if self.right_child == None: self.right_child = new_tree else: new_tree.right_child = self.right_child self.right_child = new_tree return self def get_left(self): return self.left_child def get_right(self): return self.right_child def set_root(self, root): self.root = root return self def get_root(self): return self.root tree = BinaryTree(5).insert_left(4).insert_left(3) print(tree.get_left().get_root())
for i in range(6): #5줄을 출력할 수 있는 반복문 for n in range(5,i-1,-1): #숫자앞의 공백을 출력하는 반복문 print(end=" ") for j in range(1,i+1): print(j,end="") print()