text
stringlengths
37
1.41M
""" # Definition for a Node. class Node(object): def __init__(self, val, next, random): self.val = val self.next = next self.random = random """ class Solution(object): def copyRandomList(self, head): """ :type head: Node :rtype: Node """ h=Node(0,None,None) h1=h h2=h p=head dic={} while p: n=Node(p.val,None,p.random) h.next=n h=h.next dic[p]=h p=p.next while h1.next: h1=h1.next if h1.random!=None: h1.random=dic[h1.random] return h2.next
class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ res = [] x = path.split('/') for i in x: if i == '' or i == '.': continue elif i == '..': if res: res.pop() else: res.append(i) return '/'+'/'.join(res)
class Solution(object): def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ slow=fast=0 while 1: slow = nums[slow] fast = nums[nums[fast]] if slow==fast: break fast=0 while 1: slow = nums[slow] fast = nums[fast] if slow==fast: break return slow
#coding=utf-8 class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object):#递归方法1 def __init__(self): self.list = [] def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if root: self.inorderTraversal(root.left) self.list.append(root.val) self.inorderTraversal(root.right) return self.list class Solution1(object):#递归方法2 def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if root: return self.inorderTraversal(root.left)+[root.val]+self.inorderTraversal(root.right) else: return [] class Solution2(object):#非递归方法 def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ stack = [] res = [] while root or stack: if root: stack.append(root) root=root.left else: root = stack.pop() res.append(root.val) root=root.right return res a=TreeNode(1) b=TreeNode(2) c=TreeNode(3) d=TreeNode(4) e=TreeNode(5) a.left=b a.right=c b.left=d c.right=e s = Solution() s1= Solution1() print s1.inorderTraversal(a)
#Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if root==None: return [] layer_list=[] layer = [root] res = [] while layer: layer_list.append(layer) tmp = [] for i in range(len(layer)): if layer[i].left: tmp.append(layer[i].left) if layer[i].right: tmp.append(layer[i].right) layer=tmp for i in range(len(layer_list)): tmp = [] if i%2==0: for j in range(len(layer_list[i])): tmp.append(layer_list[i][j].val) res.append(tmp) else: for j in range(len(layer_list[i])): tmp.append(layer_list[i][j].val) res.append(tmp[::-1]) return res
class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ i=0 res = [] while i<len(nums1) and nums2: if nums1[i] in nums2: res.append(nums1[i]) nums2.remove(nums1[i]) i+=1 return res
import heapq class Solution(object): def getSkyline(self, buildings): """ :type buildings: List[List[int]] :rtype: List[List[int]] """ outline_list=[] for left,right,height in buildings: outline_list.append([left,-height,right]) outline_list.append([right,0,0]) outline_list.sort() heap=[[0,float('inf')]] result = [[0,0]] for left,height,right in outline_list: while left>=heap[0][1]: heapq.heappop(heap) if height!=0: heapq.heappush(heap,[height,right]) if result[-1][1]+heap[0][0]: result.append([left,-heap[0][0]]) return result[1:]
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def __init__(self): self.max=float('-inf') def mx(self,root): if not root: return 0 left = self.mx(root.left) right = self.mx(root.right) tmp = max(root.val,root.val+left,root.val+right) self.max = max(tmp,self.max,root.val+left+right) return tmp def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ self.mx(root) return self.max
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def buildTree(self, inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode """ if not postorder: return None root = ListNode(postorder[-1]) idx = inorder.index(postorder[-1]) ll = len(inorder[:idx]) root.left=self.buildTree(inorder[:idx],postorder[:ll]) root.right=self.buildTree(inorder[idx+1:],postorder[ll:-1]) return root
class Caja: estado = 'off' precios = { 1:10.2, 2:25.6 , 3:38.3, 4:46.3, 5:56.7, 6:67.8 } tickets = [] def __init__(self): print("Iniciando caja...") self.estado = 'on' def getEstado(self): return self.estado def apagar(self): print("Apagando caja...") #Falta guardar registro en un archivo self.estado = 'off' print("Enter para continuar.") input() def imprimeMenu(self): print("Seleccionar opción:") print(" 1.-Generar compra") print(" 2.-Imprimir número de tickets") print(" 3.-Imprimir ticket por id") print(" 4.-Corte de caja") print(" 5.-Apagar caja") def comprar(self): continuar = True compra = Compra() print("****Iniciando Compra...****") while(continuar): print(" idProducto (-1 para finalizar): ") idProducto = int( input() ) if(idProducto==-1): continuar = False else: compra.agregarProducto( [idProducto,self.precios[idProducto]] ) self.tickets.append(compra) self.imprimeTicket(compra) print(" Fin de la compra....") print("Enter para continuar.") input() def imprimeTicket(self,compra): print(" Imprimiendo ticket:") print(" ***************************") print(" *IdProducto : Precio") for p in compra.listaProductos: print(" * ", p[0],":",p[1]) print(" *TOTAL = ",compra.total) print(" ***************************") def imprimeNumeroTickets(self): print(" ************************") print(" **Número de tickets: ", len(self.tickets) ) print(" ************************") print("Enter para continuar.") input() def imprimeTicketPorID(self): print("Hay", len(self.tickets), "tickets, seleccione uno:" ) id = int( input() ) if id > 0 and id <= len(self.tickets): self.imprimeTicket( self.tickets[id-1] ) else: print('Opción no valida') print("Enter para continuar.") input() def corteCaja(self): total = 0 for t in self.tickets: total += t.getTotal() print(" ********************") print(" CORTE DE CAJA ") print(" NoTickets =",len(self.tickets) ) print(" TOTAL =",total ) print(" ********************") print("Enter para continuar.") input() class Compra: listaProductos = None total = None def __init__(self): self.listaProductos = [] self.total = 0 def agregarProducto(self, producto ): self.listaProductos.append( producto ) self.total += producto[1] print(" producto",producto[0],"agregado.") print(" Total = ", self.total) def getTotal(self): return self.total
class stack: def __init__(self): self.arr=[] def insert(self,value): self.arr.append(value) def delete(self): self.arr.pop() def insertionSort(self,arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position j = i-1 while j >=0 and key < arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = key # Driver code to test above if __name__=='__main__': arr = [10,2,30,4,5,110,11,24,45,76,90,6,8] n=len(arr) stack=stack() for i in range(len(arr)): stack.insert(arr[i]); stack.insertionSort(stack.arr); print ("Sorted array is:",stack.arr)
class Car(): def __init__(self): self.engine = None self.price = None self.maxspeed = None def __str__(self): return '{} | {} | {}'.format(self.engine, self.price, self.maxspeed) class AbstractBuilder(): def __init__(self): self.car = None def createNewCar(self): self.car = Car() # Concrete Builder: inherits the Abstract Builder and implements the above interface createNewCar of the Abstract Builder class for a car object i.e. to say that # its object is capable of creating a car by calling createNewCar() of AbstractBuilder; provides methods to create components of the product. class ConcreteBuilder(AbstractBuilder): def addEngine(self): self.car.engine = "16 Cylynder" def addprice(self): self.car.price = "20000" def addmaxspeed(self): self.car.maxspeed = "300 Kms" # Director: in charge of building the product using an object of Concrete Builder class Director(): def __init__(self, builder): self._builder = builder def constructCar(self): self._builder.createNewCar() self._builder.addEngine() self._builder.addprice() self._builder.addmaxspeed() def getCar(self): return self._builder.car concreteBuilder = ConcreteBuilder() director = Director(concreteBuilder) director.constructCar() carOne = director.getCar() print("Car Details:", carOne) carTwo = director.getCar() print("Car Details:", carTwo)
class TAXI: def __init__(self, num): self.num = num def ride_along(self): print("You may want to get in" + self.num) class TAXIPool(TAXI): def ride_along(self): print("You want a pool ride? ") print(self.num + " will take care of that with our srvices") y = TAXIPool("Shah and Shah") y.ride_along()
# conventional way to import import numpy as np import pandas as pd #import seaborn as sns #import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score from sklearn.linear_model import LinearRegression from sklearn import linear_model from sklearn import metrics # read CSV (comma separated value) file and save the results data = pd.read_csv('Dataset.csv') # visualize th relationship between the features and the response using scatterplots # sns.pairplot(data, x_vars=['Tm','Pr','Th','Sv'], y_vars='Idx', size=7, aspect=0.7, kind='reg') # show the plot # plt.show() # use the list to collect a subset of the original DataFrame feature_cols = ['Tm','Pr','Th','Sv'] X = data[feature_cols] # select a Series from the DataFrame y = data.Idx # splitting X and y into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)#test_size=0.2 # instantiate model linreg = LinearRegression() # fit the model to the training data (learn the coefficients of the line of best fit) linreg.fit(X_train, y_train) # print the intercept and coefficients print('////////////////LINEAR REGRESSION w/ TEST SPLIT////////////////') print('Intercept:',linreg.intercept_) print('Coefficients:',linreg.coef_) # make predictions on the testing set y_pred = linreg.predict(X_test) # computing the root mean squared error for our Idx predictions (RMSE is in the units of our response variable) (smaller is better) print('RMSE:',np.sqrt(metrics.mean_squared_error(y_test,y_pred))) # remove features to compare model accuracy feature_cols = ['Pr','Th','Sv'] X = data[feature_cols] X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1) linreg.fit(X_train, y_train) y_pred = linreg.predict(X_test) print('Without Tm:',np.sqrt(metrics.mean_squared_error(y_test,y_pred))) feature_cols = ['Tm','Th','Sv'] X = data[feature_cols] X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1) linreg.fit(X_train, y_train) y_pred = linreg.predict(X_test) print('Without Pr:',np.sqrt(metrics.mean_squared_error(y_test,y_pred))) feature_cols = ['Tm','Pr','Sv'] X = data[feature_cols] X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1) linreg.fit(X_train, y_train) y_pred = linreg.predict(X_test) print('Without Th:',np.sqrt(metrics.mean_squared_error(y_test,y_pred))) feature_cols = ['Tm','Pr','Th'] X = data[feature_cols] X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1) linreg.fit(X_train, y_train) y_pred = linreg.predict(X_test) print('Without Sv:',np.sqrt(metrics.mean_squared_error(y_test,y_pred))) # 10-fold cross-validation print('/////////LINEAR REGRESSION w/ 10-FOLD CROSS VALIDATION/////////') X = data[['Tm','Pr','Th','Sv']] scores = cross_val_score(linreg, X, y, cv=10, scoring='neg_mean_squared_error') # fix the signs of mean squared errors and convert to ROOT mse scores = np.sqrt(scores * -1) print('Cross Validation Scores:',scores) # use average accuracy as an estimate of out-of-sample accuracy print('Average Score (RMSE):',scores.mean()) # remove features to compare model accuracy feature_cols = ['Pr','Th','Sv'] X = data[feature_cols] print('Without Tm:',np.sqrt(-cross_val_score(linreg, X, y, cv=10, scoring='neg_mean_squared_error')).mean()) feature_cols = ['Tm','Th','Sv'] X = data[feature_cols] print('Without Pr:',np.sqrt(-cross_val_score(linreg, X, y, cv=10, scoring='neg_mean_squared_error')).mean()) feature_cols = ['Tm','Pr','Sv'] X = data[feature_cols] print('Without Th:',np.sqrt(-cross_val_score(linreg, X, y, cv=10, scoring='neg_mean_squared_error')).mean()) feature_cols = ['Tm','Pr','Th'] X = data[feature_cols] print('Without Sv:',np.sqrt(-cross_val_score(linreg, X, y, cv=10, scoring='neg_mean_squared_error')).mean()) # Conclusion print('///////////////////////MODEL COMPARISON//////////////////////') print(' Linear Regression model without removing any of the features \n results in a more accurate model because it minimizes the root mean squared error \n (using cross validation reduces the variance associated with a single trial of train/test split)') feature_cols = ['Tm','Pr','Th','Sv'] X = data[feature_cols] y = data.Idx clf = linear_model.LassoLars(alpha=.1) clf.fit(X,y) print('////////////////LARS LASSO////////////////') print('Intercept:',clf.intercept_) print('Coefficients:',clf.coef_) clf = linear_model.RidgeCV(alphas=[0.1, 1.0, 10.0], cv=10) clf.fit(X,y) print('////////////////RIDGE REGRESSION////////////////') print('Intercept:',clf.intercept_) print('Coefficients:',clf.coef_)
import json import datetime import requests class Game(object): def __init__(self): self.date = datetime.datetime(2003,8,1,12,4,5) #do we need the hour? def turn(self): self.date += datetime.timedelta(days=1) print(self.date) #reveal the new date class Celebrity(object): # this is a celeb character (which exist in game) def __init__(self, name="Unknown", worth=100000, team=None): self.worth = worth self.name = name self.volt = 1.0 self.team = team def calcDamage(self, triag): #assign some number value pass def event(self, positive=False, seti=False, twtVal=0): '''det outcome result, we assume bad bc celebs''' if not positive: pass #calcDamage(1) if seti: #we will scale tweets by 1000 self.worth += (self.worth * twtVal)/1000 def speak(self): print "hello this is %s, my net worth is %d\n", self.name, self.worth def updateTeam(self, team=None): self.team = team #assign celeb to player team ''' triag 1. death 2. drugs (quanitified) -> crime classification? 3. sex 4. crime (quantified) assault > dwi? 5. family conflict 6. debt(crime) 7. child(good or bad?) 8. extension family(complicated) 9. health 10. vacation(s) 11. significant other(s) 12. controversial news ex1. the game punches officer -> 100000 100 celebs bet on events - a team is made of many celebs (5) - a game is made of 2+ teams ''' ##################### Demo shit kanye = Celebrity("Kanye", 1000000) # k1= json.dumps(kanye) # raises TypeError with "is not JSON serializable" k1 = json.dumps(kanye.__dict__) # s set to: {"x":1, "y":2} print k1 payload = {'json_playload': k1} r = requests.get('http://myserver/emoncms2/api/post', data=payload)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 25 18:04:31 2021 @author: bhavinpatel """ # #Problem 1 l = ['*'] count = 4 for i in l: for j in range(1,7): if j != 6: print(i*j) else: for k in sorted(range(4),reverse=True): print(i*k) #Problem 2 def reverse(user): txt = user[::-1] return (txt) print(reverse('ineuron'))
import argparse # Argument parsers parser = argparse.ArgumentParser(description='Compute c (Assignment 1)') parser.add_argument('segments', metavar='N', type=int, help='The total time of the voyage') parser.add_argument('--time', required=True, type=int, help='The total time of the voyage') parser.add_argument('--distances', required=True, type=int, nargs='+', help='The distance(s) of each segment of the voyage') parser.add_argument('--speed', required=True, type=int, nargs='+', help='The speed(s) of each segment of the voyage') # Read args args = parser.parse_args() total_time = args.time d = args.distances s = args.speed n = args.segments assert n == len(d) == len(s) def check(c, n, s, d, tot_time): ''' Checks for a given parameters if a value of c is too big or too small ''' t = 0 for i in range(n): if c+s[i] <= 0: # the true speed is always positive! return 1 #increase c else: # add time to traverse each segment t+=d[i]/(s[i]+c) # time = distance/speed if(t>tot_time): #if the sum of the time for each segment is greater whole journey time return 1 #increase c else: #if the sum of the time for each segment is less than whole journey time return 0 #decrease c # init variables # the root has to be inside the interval [low, high] low = -500 high = 500 max_step = 2200 error = 0.0001 # stop criteria for error # solve problem for i in range(max_step): # this is bisection method no newton mid = (high+low)/2 # print(mid) if check(mid, n, s, d, total_time): low=mid else: high=mid if high - low < error: break c = mid print("It took {} iterations to obtain a c value of {} with an error of {}".format(i, c, error))
print('Welcome!') import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } city = [] city_df = [] month = [] day = [] def start(): start = input('Press enter to begin') def city_filter(): """ get input for city variable Input: a city name (as a string) from three options Output: city """ city_name = input('Which city would you like to see data for? Chicago, New York City, or Washington? ').title() cities = ['Chicago', 'New York City', 'Washington'] city = [] while True: if city_name.title() in cities: print('You chose: ', city_name) break else: print('You may not have spelled that right, please try again') city_name = input('Chicago, New York City, or Washington? ') city = str(city_name.lower()) return city def month_filter(): """ get input for month filter Input: month name as a string Output: month as an integer """ confirm_filter = str(input('There are six months of data available. Which month would you like to see data for?\n January, February, March, April, May or June? ').title()) months = {'January': 1, 'February': 2, 'March': 3, 'April' : 4, 'May' : 5, 'June' : 6} month = [] while True: if confirm_filter in months: month = months[confirm_filter] break elif confirm_filter == 'Cancel': month = 0 break else: confirm_filter = str(input('Please try typing the month name again, or type "cancel" to cancel this filter: ').title()) continue return month def day_filter(): """ get input for day of the week filter Input: day name as a string Output: a weekday name as a string """ confirm_filter = str(input('You can select any single weekday. Which day would you like to see data for?\n ').title()) days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] day = [] while True: if confirm_filter in days : day = confirm_filter break elif confirm_filter == 'Cancel' : day = 0 break else: confirm_filter = str(input('Please try typing the full day of the week, e.g. "Sunday" or "Monday", or write "cancel" to cancel this filter ').title()) continue return day def next_5(city_df): """ take and print next five rows of DataFrame Input: none Output: next five rows of data from the filtered data set """ num_string = [0,1,2,3,4] print(city_df.take(num_string, axis=0)) x = 5 while True: response = input('Do you want to see the next 5 lines of individual trip data? y/n') if response == 'y': print_nums = [i+x for i in num_string] print(city_df.take(print_nums)) x += 5 else: break def get_data(city_df, city, month, day): """ get user input to display data output as raw data or summary statistics Input: from options, as a string Output: data from city_df DataFrame """ print('\nData time!\n', '-'*30, '\nYou can begin viewing your data below, but first you must make a choice:') while True: response = str(input('If you would like to see the raw trip data, type: "raw" \nOtherwise, if you would prefer to see the summary statistics, type: "stats" \nTo exit, or change this selection, type: "exit" ').lower()) if response == 'raw': print('\n') print('-'*60,'\nSingle trip data for: {}, month: {}, day of week: {} '.format(city, month, day)) print('-'*60) next_5(city_df) elif response == 'stats': print('\n') print('-'*60,'\nSummary stats for: {}, month: {}, day of week: {} '.format(city, month, day)) print('-'*60, '\n-- Popular travel times -- ') while True: if month == 0: pop_month = city_df['month'].mode()[0] month_key = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June'} print('Popular month: ', month_key[pop_month]) break else: break while True: if day == 0: print('Popular day: ', city_df['day_of_week'].mode()[0]) break else: break city_df['Start Hour'] = city_df['Start Time'].dt.hour print('Starting hour: ', city_df['Start Hour'].mode()[0],':00 hrs') print('-'*10, '\n-- Trip info -- ') print('Total number of trips: ', city_df['Trip Duration'].count()) print('Total length of all trips taken: ', (((city_df['Trip Duration'].sum())/60)/60).round(1), 'hours') print('Average trip length: ', ((city_df['Trip Duration'].mean())/60).round(1), 'minutes' ) print('Shortest trip length: ', ((city_df['Trip Duration'].min())/60).round(1), 'minutes') print('Longest trip length: ', ((city_df['Trip Duration'].max())/60).round(1), 'minutes') print('-'*10, '\n-- Popular station --') city_df['Whole Trip'] = city_df[['Start Station','End Station']].agg(' to '.join, axis=1) print('Start: ', str(city_df['Start Station'].mode()[0])) print('End: ', str(city_df['End Station'].mode()[0])) print('Whole trip: ', city_df['Whole Trip'].mode()[0]) while True: print('-'*10, '\n-- Customer details -- \n') print('User distribution :\n', city_df['User Type'].value_counts()) if city == 'chicago' or city == 'new york city': print('\nAverage customer age: ', 2017 - (city_df['Birth Year'].mean().round(1))) print('Oldest customer age: ', int(2017 - (city_df['Birth Year'].min()))) print('Youngest customer age: ', int(2017 - (city_df['Birth Year'].max()))) print('\nGender:\n', city_df['Gender'].value_counts()) break elif city == 'washington': print('\n- Note: Age and gender info not available for Washington data -') break else: break break elif response == 'exit': break else: continue return city_df def review_data(city_df, city, month, day): while True: print('-'*60) continue_results = str(input('\nIf you would like to choose another data viewing option for this same data, please type: "view" \nIf you would like to reset the data filters, please type: "reset" \nIf you would like to exit the program, just type: "exit". ').lower()) if continue_results == 'view': get_data(city_df, city, month, day) continue elif continue_results == 'reset': city = reset_city(city) city_df = pd.read_csv(CITY_DATA[city]) month = reset_month(month) day = reset_day(day) city_df['Start Time'] = pd.to_datetime(city_df['Start Time']) city_df['month'] = city_df['Start Time'].dt.month city_df['day_of_week'] = city_df['Start Time'].dt.weekday_name if month != 0: city_df = city_df[city_df['month'] == month] if day != 0: city_df = city_df[city_df['day_of_week'] == day] print('-'*10, '\nYour selection is now set to: {}, month: {}, day: {} '.format(city, month, day)) get_data(city_df, city, month, day) continue elif continue_results == 'exit': break else: print('\nYour input didn\'t quite work, please try again.') continue return city_df, city, month, day def reset_city(city): """ get user input to confirm or change filter settings, then run get_data() again Input: Y/N to change city, month and day Output: city, month, day - updated """ while True: city_response = input('Would you like to change the city? Y/N ').lower() if city_response == 'y': city = city_filter() break else: break city = str(city.lower()) return city def reset_month(month): """ Prompt user to reset month filter or leave unchanged Input: month Output: month unchanged, or month reset """ while True: month_response = input('Would you like to change the month? Y/N ').lower() if month_response == 'y' or month_response == 'yes': month = month_filter() break else: break return month def reset_day(day): """ Prompt user to reset day filter or leave unchanged Input: day Output: day unchanged, or day reset """ while True: day_response = input('Would you like to change the weekday? Y/N ').lower() if day_response == 'y': day = day_filter() break else: break return day def review_data(city_df, city, month, day): while True: print('-'*60) continue_results = str(input('\nIf you would like to choose another data viewing option for this same data, please type: "view" \nIf you would like to reset the data filters, please type: "reset" \nIf you would like to exit the program, just type: "exit". ').lower()) if continue_results == 'view': get_data(city_df, city, month, day) continue elif continue_results == 'reset': city = reset_city(city) city_df = pd.read_csv(CITY_DATA[city]) month = reset_month(month) day = reset_day(day) city_df['Start Time'] = pd.to_datetime(city_df['Start Time']) city_df['month'] = city_df['Start Time'].dt.month city_df['day_of_week'] = city_df['Start Time'].dt.weekday_name if month != 0: city_df = city_df[city_df['month'] == month] if day != 0: city_df = city_df[city_df['day_of_week'] == day] print('-'*10, '\nYour selection is now set to: {}, month: {}, day: {} '.format(city, month, day)) get_data(city_df, city, month, day) continue elif continue_results == 'exit': break else: print('\nYour input didn\'t quite work, please try again.') continue return city_df, city, month, day def main(): # Get filters and load the dataframe city = city_filter() city_df = pd.read_csv(CITY_DATA[city]) print('Here is a preview of the data: ') print(city_df.head()) print('-'*30,'\nYou can choose to filter this data by a particular month and/or weekday. \nIf you do not set a filter for either of these values they will automatically be set to 0. You can then move on to see the data below.') while True: confirm_month_filter = str(input('Firstly, would you like to see data for a particular month? Y/N ').lower()) if confirm_month_filter == 'y' or confirm_month_filter == 'yes': month = month_filter() break elif confirm_month_filter == 'n' or confirm_month_filter == 'no': print('-- No month filter has been set') month = 0 break else: print('Oops, that didn\'t work properly, please try again by typing "y" or "n"') continue while True: confirm_day_filter = str(input('Would you like to filter data by day of the week? Y/N ').lower()) if confirm_day_filter == 'y' or confirm_day_filter == 'yes': day = day_filter() break elif confirm_day_filter == 'n' or confirm_day_filter == 'no': print('-- No weekday filter has been set') day = 0 break else: print('Oops, that didn\'t work properly, please try again by typing "y" or "n"') continue print('\nYou have opted to see data for: {}, for month: {}, and day: {}. Now let\'s view this data! '.format(city, month, day)) start() city_df['Start Time'] = pd.to_datetime(city_df['Start Time']) city_df['month'] = city_df['Start Time'].dt.month city_df['day_of_week'] = city_df['Start Time'].dt.weekday_name if month != 0: city_df = city_df[city_df['month'] == month] if day != 0: city_df = city_df[city_df['day_of_week'] == day] # city_df moved from here get_data(city_df, city, month, day) review_data(city_df, city, month, day) # Intro text print('\n','-'*10, '\nThis program will help you explore the US BikeShare project data collected in 2017.') print(' Data is available for three cities across the USA: Chicago, New York City, and Washington.') print(' After picking a city, you will have the option to filter data based on months or days of the week.') print(' You will then have the option to view the raw trip data, or view some summary statistics for the data.') print(' This program also allows you to reset the filters after you have viewed the data.\n', '-'*10) start() if __name__ == "__main__": main() print('\nAll done! Thank you for exploring this data today!')
my_list = range(16) filter(lambda x: x % 3 == 0, my_list) languages = ["HTML", "JavaScript", "Python", "Ruby"] # Add arguments to the filter() print filter(lambda x: x == "Python", languages) squares = [x ** 2 for x in range(1, 11)] print filter(lambda x: x >= 30 and x <= 70, squares) movies = { "Monty Python and the Holy Grail": "Great", "Monty Python's Life of Brian": "Good", "Monty Python's Meaning of Life": "Okay" } print movies.items() threes_and_fives = [x for x in range(1, 16) if x % 3 == 0 or x % 5 == 0] print threes_and_fives garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI" message = garbled[::-2] print message garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX" message = filter(lambda x: x != "X", garbled) print message
class Fruit(object): """A class that makes various tasty fruits.""" def __init__(self, name, color, flavor, poisonous): self.name = name self.color = color self.flavor = flavor self.poisonous = poisonous def description(self): print "I'm a %s %s and I taste %s." % (self.color, self.name, self.flavor) def is_edible(self): if not self.poisonous: print "Yep! I'm edible." else: print "Don't eat me! I am super poisonous." lemon = Fruit("lemon", "yellow", "sour", False) lemon.description() lemon.is_edible() # Class definition class Animal(object): """Makes cute animals.""" # For initializing our instance objects def __init__(self, name, age, is_hungry): self.name = name self.age = age self.is_hungry = is_hungry # Note that self is only used in the __init__() # function definition; we don't need to pass it # to our instance objects. zebra = Animal("Jeffrey", 2, True) giraffe = Animal("Bruce", 1, False) panda = Animal("Chad", 7, True) print zebra.name, zebra.age, zebra.is_hungry print giraffe.name, giraffe.age, giraffe.is_hungry print panda.name, panda.age, panda.is_hungry class Animal(object): def __init__(self, name): self.name = name zebra = Animal("Jeffrey") print zebra.name """ Class Scope Another important aspect of Python classes is scope. The scope of a variable is the context in which it's visible to the program. It may surprise you to learn that not all variables are accessible to all parts of a Python program at all times. When dealing with classes, you can have variables that are available everywhere (global variables), variables that are only available to members of a certain class (member variables), and variables that are only available to particular instances of a class (instance variables). The same goes for functions: some are available everywhere, some are only available to members of a certain class, and still others are only available to particular instance objects. """ class Animal(object): """Makes cute animals.""" is_alive = True def __init__(self, name, age): self.name = name self.age = age zebra = Animal("Jeffrey", 2) giraffe = Animal("Bruce", 1) panda = Animal("Chad", 7) print zebra.name, zebra.age, zebra.is_alive print giraffe.name, giraffe.age, giraffe.is_alive print panda.name, panda.age, panda.is_alive class Animal(object): """Makes cute animals.""" is_alive = True def __init__(self, name, age): self.name = name self.age = age # Add your method here! def description(self): print self.name print self.age hippo = Animal("waesdfg", 26) class Animal(object): """Makes cute animals.""" is_alive = True health = "good" def __init__(self, name, age): self.name = name self.age = age # Add your method here! def description(self): print self.name print self.age hippo = Animal("rgssfh", 26) sloth = Animal("Bea", 23) ocelot = Animal("Mayan", 20) print hippo.health print sloth.health print ocelot.health class ShoppingCart(object): """Creates shopping cart objects for users of our fine website.""" items_in_cart = {} def __init__(self, customer_name): self.customer_name = customer_name def add_item(self, product, price): """Add product to the cart.""" if not product in self.items_in_cart: self.items_in_cart[product] = price print product + " added." else: print product + " is already in the cart." def remove_item(self, product): """Remove product from the cart.""" if product in self.items_in_cart: del self.items_in_cart[product] print product + " removed." else: print product + " is not in the cart." my_cart = ShoppingCart("Pbal") my_cart.add_item("milk", 2.95) ###### INHERITANCE ####### """ Inheritance is the process by which one class takes on the attributes and methods of another, and it's used to express an is-a relationship. For example, a Panda is a bear, so a Panda class could inherit from a Bear class. However, a Toyota is not a Tractor, so it shouldn't inherit from the Tractor class (even if they have a lot of attributes and methods in common). Instead, both Toyota and Tractor could ultimately inherit from the same Vehicle class. """ class DerivedClass(BaseClass): # code goes here class Shape(object): """Makes shapes!""" def __init__(self, number_of_sides): self.number_of_sides = number_of_sides # Add your Triangle class below! class Triangle(Shape): def __init__(self, side1, side2, side3): self.side1 = side1 self.side2 = side2 self.side3 = side3 class Employee(object): """Models real-life employees!""" def __init__(self, employee_name): self.employee_name = employee_name def calculate_wage(self, hours): self.hours = hours return hours * 20.00 # Add your code below! class PartTimeEmployee(Employee): def calculate_wage(self, hours): self.hours = hours return hours * 12.00 class Derived(Base): def m(self): return super(Derived, self).m() class Employee(object): """Models real-life employees!""" def __init__(self, employee_name): self.employee_name = employee_name def calculate_wage(self, hours): self.hours = hours return hours * 20.00 # Add your code below! class PartTimeEmployee(Employee): def calculate_wage(self, hours): self.hours = hours return hours * 12.00 def full_time_wage(self, hours): return super(PartTimeEmployee, self).calculate_wage(hours) milton = PartTimeEmployee("Mlton") print milton.full_time_wage(10) class Triangle(object): number_of_sides = 3 def __init__(self, angle1, angle2, angle3): self.angle1 = angle1 self.angle2 = angle2 self.angle3 = angle3 def check_angles(self): return bool( self.angle1 + self.angle2 + self.angle3 == 180 ) class Equilateral(Triangle): angle = 60 def __init__(self): self.angle1 = self.angle self.angle2 = self.angle self.angle3 = self.angle my_triangle = Triangle(30, 60, 90) print my_triangle.number_of_sides print my_triangle.check_angles() class Car(object): condition = "new" def __init__(self, model, color, mpg): self.model = model self.color = color self.mpg = mpg def display_car(self): print "This is a %s %s with %d MPG." % (self.color, self.model, self.mpg) def drive_car(self): self.condition = "used" class ElectricCar(Car): def __init__(self, battery_type, model, color, mpg): self.battery_type = battery_type self.model = model self.color = color self.mpg = mpg def drive_car(self): self.condition = "like new" my_car = ElectricCar("molten salt", "DeLorean", "silver", 88) print my_car.condition my_car.drive_car() print my_car.condition class Point3D(object): def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self): return "(%d, %d, %d)" % (self.x, self.y, self.z) my_point = Point3D(1, 2, 3) print my_point
# -*- coding: utf-8 -*- """Provide functions for the creation and manipulation of Planes. Planes are represented using a numpy.array of shape (4,). The values represent the plane equation using the values A,B,C,D. The first three values are the normal vector. The fourth value is the distance of the plane from the origin, down the normal. .. seealso: http://en.wikipedia.org/wiki/Plane_(geometry) .. seealso: http://mathworld.wolfram.com/Plane.html """ from __future__ import absolute_import, division, print_function, unicode_literals import numpy import numpy.linalg from pyrr import vector def create_identity(): """Creates a plane that runs along the X,Y plane. It crosses the origin with a normal of 0,0,1 (+Z). :rtype: numpy.array :return: A plane that runs along the X,Y plane. """ return numpy.array( [ 0.0, 0.0, 1.0, 0.0] ) def create_from_points( vector1, vector2, vector3 ): """Create a plane from 3 co-planar vectors. The vectors must all lie on the same plane or an exception will be thrown. The vectors must not all be in a single line or the plane is undefined. The order the vertices are passed in will determine the normal of the plane. :param numpy.array vector1: a vector that lies on the desired plane. :param numpy.array vector2: a vector that lies on the desired plane. :param numpy.array vector3: a vector that lies on the desired plane. :raise ValueError: raised if the vectors are co-incident (in a single line). :rtype: numpy.array :return: A plane that contains the 3 specified vectors. """ # make the vectors relative to vector2 relV1 = vector1 - vector2 relV2 = vector3 - vector2 # cross our relative vectors normal = numpy.cross( relV1, relV2 ) if numpy.count_nonzero( normal ) == 0: raise ValueError( "Vectors are co-incident" ) # create our plane return create_from_position( position = vector2, normal = normal ) def create_from_position( position, normal ): """Creates a plane at position with the normal being above the plane and up being the rotation of the plane. :param numpy.array position: The position of the plane. :param numpy.array normal: The normal of the plane. Will be normalised during construction. :rtype: numpy.array :return: A plane that crosses the specified position with the specified normal. """ # -d = a * px + b * py + c * pz n = vector.normalise( normal ) d = -numpy.sum( n * position ) return numpy.array( [ n[ 0 ], n[ 1 ], n[ 2 ], d ] ) def invert_normal( plane ): """Flips the normal of the plane. The plane is **not** changed in place. :rtype: numpy.array :return: The plane with the normal inverted. """ # flip the normal, and the distance return -plane def position( plane ): """Extracts the position vector from a plane. This will be a vector co-incident with the plane's normal. :param numpy.array plane: The plane. :rtype: numpy.array :return: A valid position that lies on the plane. """ return plane[ :3 ] * plane[ 3 ] def normal( plane ): """Extracts the normal vector from a plane. :param numpy.array plane: The plane. :rtype: numpy.array :return: The normal vector of the plane. """ return plane[ :3 ]
class Body: def __init__(self, name): self.name = name self.children = set() self.parent = None def add_child(self, child_name): self.children.add(child_name) def add_parent(self, parent): self.parent = parent def direct(self): return len(self.children) def indirect(self): if self.name == "COM": return 0 node = self.parent distance = 0 while node.name != "COM": distance += 1 node = node.parent return distance class OrbitMap: def __init__(self): self.bodies = dict() def load_body(self, parent, child): if parent not in self.bodies.keys(): self.bodies[parent] = Body(parent) if child not in self.bodies.keys(): self.bodies[child] = Body(child) self.bodies[parent].add_child(self.bodies[child]) self.bodies[child].add_parent(self.bodies[parent]) def direct(self): num = 0 for body_name, body_object in self.bodies.items(): num += body_object.direct() return num def indirect(self): num = 0 for body_name, body_object in self.bodies.items(): num += body_object.indirect() return num def you_to_santa(self): return self.bodies["YOU"].distance_to_santa() if __name__ == "__main__": with open("./input.txt", "r") as file: Orbits = OrbitMap() for line in file: line = line.rstrip() parent, child = line.split(")") Orbits.load_body(parent, child) direct = Orbits.direct() indirect = Orbits.indirect() print(f"Direct: {direct}") print(f"Indirect: {indirect}") print(f"Part One: {direct + indirect}") print(f"Part Two: {Orbits.you_to_santa()}")
""" Module: Opponent ... """ class Opponent(object): """ Opponent is an interface. This is intended to be implemented by Player and Team, which are capable of participating in Games. """ def __init__(self): """ This constructor should never be called. Raise an error. """ raise NotImplementedError("Interface Constructor: DO NOT CALL") def id(self): """ Return a node id. """ raise NotImplementedError( "Interface Method: IMPLEMENTOR MUST OVERRIDE") def type(self): """ Return a node type. """ raise NotImplementedError( "Interface Method: IMPLEMENTOR MUST OVERRIDE") def name(self): """ Return a SqObject node name. """ raise NotImplementedError( "Interface Method: IMPLEMENTOR MUST OVERRIDE") @property def loss_count(self): """ Return an int representing this opponent's loss count. """ raise NotImplementedError( "Interface Method: IMPLEMENTOR MUST OVERRIDE") @property def win_count(self): """ Return an int representing this opponent's win count. """ raise NotImplementedError( "Interface Method: IMPLEMENTOR MUST OVERRIDE") @property def loss_percentage(self): """ Return a float representing this opponent's loss percentage. """ raise NotImplementedError( "Interface Method: IMPLEMENTOR MUST OVERRIDE") @property def win_percentage(self): """ Return an float representing this opponent's win percentage. """ raise NotImplementedError( "Interface Method: IMPLEMENTOR MUST OVERRIDE") @property def current_loss_streak(self): """ Return an int representing this opponent's loss streak. """ raise NotImplementedError( "Interface Method: IMPLEMENTOR MUST OVERRIDE") @property def current_win_streak(self): """ Return an int representing this opponent's win streak. """ raise NotImplementedError( "Interface Method: IMPLEMENTOR MUST OVERRIDE") @property def current_result_streak(self): """ Return the larger of win streak or result streak. """ raise NotImplementedError( "Interface Method: IMPLEMENTOR MUST OVERRIDE")
""" Module: exceptions API Exceptions to throw. """ class InputError(Exception): """ Exception raise when the incoming request has bad input. Variables: str reason an explanation for the error """ def __init__(self, parameter_name, parameter_value): """ Construct an bad input error. Required: str parameter_name the parameter that threw the exception. str parameter_value the value of that parameter. """ self.reason = "InputError: {0} can't have value, {1}.".format( parameter_name, parameter_value)
x = int(input()) y = int(input()) soma = 0 if y > x: for i in range(x, y + 1): if i % 13 != 0: soma += i print(soma) else: for i in range(y, x + 1): if i % 13 != 0: soma += i print(soma)
vals = input().split() a = int(vals[0]) b = int(vals[1]) c = int(vals[2]) if a < b and a < c: print(a) if b < c: print(b) print(c) else: print(c) print(b) if b < a and b < c: print(b) if a < c: print(a) print(c) else: print(c) print(a) if c < a and c < b: print(c) if a < b: print(a) print(b) else: print(b) print(a) print() print(a) print(b) print(c)
pi = 3.14159 R = float(input()) A = pi*R**2 print('A=%1.4f' %A)
balance = 320000 annualInterestRate = 0.2 monthlyInterestRate = annualInterestRate / 12 unPaid = balance lowerBound = balance / 12 upperBound = (balance * (1 + monthlyInterestRate) ** 12) / 12. monthlyPayment = 0 presion = 0.10 while balance >= presion: monthlyPayment = (lowerBound + upperBound) / 2 for x in range(12): minMonthPayment = monthlyPayment balance = balance - minMonthPayment if(balance <= 0): break else: interest = (annualInterestRate / 12) * balance balance = balance + interest if balance < 0: upperBound = monthlyPayment balance = unPaid elif balance > presion: lowerBound = monthlyPayment balance = unPaid print "Lowest Payment: ", round(monthlyPayment,2)
import time import math import heapq import queue import numpy # Customer arrives event # When customer arrives, they'll check each teller choose the first one is idle. # If there are none available, the customer (arrival time, work units) is pushed on the waiting line. def customerArrives(time, windows, workUnits, eventQueue, waitingQueue): ct = 0 # teller index for teller in windows: # for each teller, see if they are idle or not if teller[0] == "IDLE": # if teller is idle, push onto event queue a becomeBusy event heapq.heappush(eventQueue, (time, 1, ct, workUnits)) return ct += 1 # go to next teller waitingQueue.put((time, workUnits)) # no tellers idle, wait in line # Teller becomes busy event # The teller becomes busy and the time it will take to perform the work is calculated. # The teller will become idle at the current time + how long it will take to complete the task. def becomeBusy(time, windows, teller, workUnits, eventQueue): windows[teller][0] = "BUSY" # become busy timeTaken = math.ceil(workUnits / windows[teller][1] * 60) # calculate time to perform work (WU / WU/h) * 60 = hours to complete work * 60 = minutes to complete work heapq.heappush(eventQueue, (time + timeTaken, 2, teller)) # push onto event queue for teller to become idle at current time + timeTaken # Teller becomes idle event # When teller finishes a job, they become idle. # Before doing so, check the waiting line and see if there are any customers. # If so, get them from the queue and calculate how long they were waiting based on current time - arrival time of customer # Push become busy event at current time (start work immediately). This could be changed to have a slightly more accurate representation where it takes time for teller to signal customer, customer to get to window, etc. # Else (no customers), just become idle and wait. def becomeIdle(time, windows, teller, eventQueue, waitingQueue): if not waitingQueue.empty(): # check waiting line customer = waitingQueue.get() waitingTime = time - customer[0] # calc waiting time heapq.heappush(eventQueue, (time, 1, teller, customer[1])) # become busy return 1, waitingTime # return waiting time and if a waiter is now being served else: windows[teller][0] = "IDLE" # become idle return 0, 0 # return no waiting time and no waiter being served # General Teller without a priority queue for small requests # Initializes the teller and customer amount, hours of work, etc. # Event queue (events) is a priority queue based on time # events filled with exogenous events (customers arriving and end of workday) # While events is not empty, get next event and act according to event number. # Simulation ends (breaks) once event 3 (endOfWorkDay) is reached. def generalTeller(windows, tellerEfficiency, customers, hours): N = windows M = customers hours = hours minutes = hours * 60 numpy.random.seed(int(time.time())) tellers = [] for i in range(N): tellers.append(["IDLE", tellerEfficiency]) #tellers = [["IDLE", 10]] * N # can't do this with mutables if you want to change values inside ("IDLE" -> "BUSY") waiting = queue.Queue() events = [] # 0 = arrive # 1 = becomeBusy # 2 = becomeIdle # 3 = endOfWorkDay randList = numpy.random.normal(10, 0.5, M) # generate a random list of work units for each customer according to normal distribution randIndex = 0 for i in range(0, minutes, math.ceil(minutes/M)): # customers arrive in uniform distribution minutes / num of customers randWork = randList[randIndex] # get random work-units while randWork < 5.0 or randWork > 15.0: # while the value isn't in the truncated range, make up a new value randWork = numpy.random.normal(10, 0.5, 1)[0] heapq.heappush(events, (i, 0, randWork)) # push the customer arrive event into the events queue randIndex += 1 # increment to get next work unit value for next iteration heapq.heappush(events, (480, 3)) # push the end of work day exogenous event jobsDone = 0 waitingTime = 0 waitersServed = 0 while not len(events) == 0: # while events not empty event = heapq.heappop(events) # pop an event eventTime = event[0] eventAction = event[1] if eventAction == 0: # customer arrival work = event[2] customerArrives(eventTime, tellers, work, events, waiting) elif eventAction == 1: # teller becomes busy tellerIndex = event[2] work = event[3] becomeBusy(eventTime, tellers, tellerIndex, work, events) elif eventAction == 2: # teller becomes idle jobsDone += 1 tellerIndex = event[2] x, y = becomeIdle(eventTime, tellers, tellerIndex, events, waiting) if x: waitingTime += y waitersServed += x else: # end of work day break stillWorking = 0 for i in tellers: # see how many tellers still working if i[0] == "BUSY": stillWorking += 1 if jobsDone == 0: # no jobs completed, need to define waiting time as something return jobsDone, waiting.qsize(), stillWorking, 9999999 if waitersServed: # return waiting time as total waiting time / waiters served return jobsDone, waiting.qsize(), stillWorking, int(waitingTime / waitersServed) else: # else, just return 0 if no one had to wait or no waiters were served return jobsDone, waiting.qsize(), stillWorking, 0 # Customer arrives (priority queue) def customerArrivesLight(time, windows, workUnits, eventQueue, waitingQueue, lightQueue): ct = 0 for teller in windows: if teller[0] == "IDLE": heapq.heappush(eventQueue, (time, 1, ct, workUnits)) return ct += 1 if workUnits <= 9.5: # if the work units is less than or equal to 9.5, the customer is a priority and gets put on the light queue lightQueue.put((time, workUnits)) else: waitingQueue.put((time, workUnits)) # Teller becomes busy (priority queue) # same as becomeBusy def becomeBusyLight(time, windows, teller, workUnits, eventQueue): windows[teller][0] = "BUSY" timeTaken = math.ceil(workUnits / windows[teller][1] * 60) heapq.heappush(eventQueue, (time + timeTaken, 2, teller)) # Teller becomes idle (priority queue) def becomeIdleLight(time, windows, teller, eventQueue, waitingQueue, lightQueue): if not lightQueue.empty(): # check the light queue first because these are priority customers customer = lightQueue.get() waitingTime = time - customer[0] heapq.heappush(eventQueue, (time, 1, teller, customer[1])) return 1, waitingTime elif not waitingQueue.empty(): customer = waitingQueue.get() waitingTime = time - customer[0] heapq.heappush(eventQueue, (time, 1, teller, customer[1])) return 1, waitingTime else: windows[teller][0] = "IDLE" return 0, 0 # Priority queue teller system for small requests # Same as the generalTeller but adds a lightWaiting queue for small requests. def priorityTeller(windows, tellerEfficiency, customers, numhours): N = windows M = customers hours = numhours minutes = hours * 60 numpy.random.seed(int(time.time())) tellers = [] for i in range(N): tellers.append(["IDLE", tellerEfficiency]) #tellers = [["IDLE", 10]] * N waiting = queue.Queue() lightWaiting = queue.Queue() # new light queue for small requests events = [] # 0 = arrive # 1 = becomeBusy # 2 = becomeIdle # 3 = endOfWorkDay randList = numpy.random.normal(10, 0.5, M) randIndex = 0 for i in range(0, minutes, math.ceil(minutes/M)): randWork = randList[randIndex] while randWork < 5.0 or randWork > 16.0: randWork = numpy.random.normal(10, 0.5, 1)[0] heapq.heappush(events, (i, 0, randWork)) randIndex += 1 heapq.heappush(events, (480, 3)) jobsDone = 0 waitingTime = 0 waitersServed = 0 while not len(events) == 0: # while events not empty event = heapq.heappop(events) eventTime = event[0] eventAction = event[1] if eventAction == 0: work = event[2] customerArrivesLight(eventTime, tellers, work, events, waiting, lightWaiting) elif eventAction == 1: tellerIndex = event[2] work = event[3] becomeBusyLight(eventTime, tellers, tellerIndex, work, events) elif eventAction == 2: jobsDone += 1 tellerIndex = event[2] x, y = becomeIdleLight(eventTime, tellers, tellerIndex, events, waiting, lightWaiting) if x: waitingTime += y waitersServed += x else: break stillWorking = 0 for i in tellers: if i[0] == "BUSY": stillWorking += 1 if jobsDone == 0: # jobs waiting is now from both queues return jobsDone, waiting.qsize() + lightWaiting.qsize(), stillWorking, 9999999 if waitersServed: return jobsDone, waiting.qsize() + lightWaiting.qsize(), stillWorking, int(waitingTime / waitersServed) else: return jobsDone, waiting.qsize() + lightWaiting.qsize(), stillWorking, 0
__author__ = 'shahryar_saljoughi' def compute_sum(A): """ :param A: is of type list , containing numbers. :return: sum of the numbers in A will be returned . """ result = 0 for i in A: result += i return result def compute_maximum_subarray(A): """ :param A: A is a list , containing some numbers :return: (i, j, max_sum) will be returned , i is the index of the start of Maximum-subarray, and j refers to the end of subarray, max_sum is the sum of the numbers of subarray """ max_subarray = (0, 0) # (i, j) max_sum = A[0] for i in range(len(A)): # i is the start index for j in range(i, len(A)): # j is the end index subarray_sum = compute_sum(A[i:j]) if subarray_sum > max_sum: max_sum = subarray_sum max_subarray = (i, j) return max_subarray, max_sum if __name__ == '__main__': a = eval(raw_input(">>input array. i.e: [1,-12, 10, 15, -2, 6]")) b = compute_maximum_subarray(a) print b
#encoding: UTF-8 # Autor: Mauricio Alejandro Medrano Castro, A01272273 # Descripcion: Calcular la propina, el IVA y total de una cuenta. # A partir de aqui escribe tu programa subtotal = int(input("subtotal")) propina = subtotal * 0.15 impuesto = subtotal * 0.16 totalAPagar = subtotal + propina + impuesto print ("Subtotal: $", "%.2f" % subtotal) print ("Propina: $", "%.2f" % propina) print ("Impuesto: $", "%.2f" % impuesto) print ("Total a Pagar: $" ,"%.2f" % totalAPagar) ''' Ejemplo de salida (por ahora no te preocupes por los acentos): Suponiendo que el usuario teclea 250. Costo de la comida: $250.00 Propina: $37.50 IVA: $40.00 Total a pagar: $327.50 '''
import RPi.GPIO as GPIO import time GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(11,GPIO.IN) GPIO.setup(3,GPIO.OUT) GPIO.setup(13,GPIO.IN) GPIO.setup(5,GPIO.OUT) c1=0 while True: i=GPIO.input(11) if i==0: GPIO.output(3,1) print("person entering") c1=c1+1 print("no of person entered",c1) time.sleep(1) elif i==1: GPIO.output(3,0) print("no person entered") time.sleep(1) i=GPIO.input(13) if i==0: GPIO.output(5,1) print("person leaving") c2=c1 c2=c2-1 print("no of person left",c2) time.sleep(1) elif i==1: GPIO.output(5,0) print("no person left") time.sleep(1)
def arithmetic_arranger(problems, B = None): let = "abcdefghijklmnopqrstuvwxyz" ans = "" soln = 0 str = "" opStr = "" numspace = " " dash = "" if len(problems) > 5: return "Error: Too many problems." else: for i in enumerate(problems): if "+" not in i[1] and "-" not in i[1]: return "Error: Operator must be '+' or '-'." for letters in let: if letters in i[1] or letters.upper() in i[1]: return "Error: Numbers must only contain digits." if len(i[1].split()[0]) > 4 or len(i[1].split()[2]) > 4: return "Error: Numbers cannot be more than four digits." else: if len(i[1].split()[0]) < len(i[1].split()[2]): str += " " + numspace*(len(i[1].split()[2]) - len(i[1].split()[0])) + i[1].split()[0] + " " opStr += i[1].split()[1] + " " + i[1].split()[2] + " " dash += "-"*(len(i[1].split()[2]) + 2) + " " else: str += " " + i[1].split()[0] + " " opStr += i[1].split()[1] + " " + numspace*(len(i[1].split()[0]) - len(i[1].split()[2])) + i[1].split()[2] + " " dash += "-"*(len(i[1].split()[0]) + 2) + " " if i[1].split()[1] == "+": soln = int(i[1].split()[0]) + int(i[1].split()[2]) elif i[1].split()[1] == "-": soln = int(i[1].split()[0]) - int(i[1].split()[2]) ans += numspace*(len('{}'.format(max(int(i[1].split()[0]), int(i[1].split()[2])))) + 2 - len('{}'.format(soln))) + '{}'.format(soln) + " " arranged_problems = str[:-4] + "\n" + opStr[:-4] + "\n" + dash[:-4] if B == True: arranged_problems = str[:-4] + "\n" + opStr[:-4] + "\n" + dash[:-4] + "\n" + ans[:-4] return arranged_problems
import random random.seed(3900) MAX_COORDINATES = 1000 BUS_STOPS = 60 DIFFERENT = 3 NAMES = ["Square", "Stadium", "Bridge", "Washington", "Pool", "Road", "Highway to bell", "KYPES", "Circus", "Church", "Town Hall", "Zoo", "Pasalimani", "Tsoukaleika", "Vraxneika", "Kallithea", "Summoners Rift", "Mordor", "Minas Tirith", "Gondor", "Durotar", "Duskwood", "Westfall", "Helms Deep", "Moria", "Icecrown", "Dalaran", "Isenstar", "Kineta"] ZONES = [1, 2, 3] insert_str = "INSERT INTO bus_stop(bus_stop_coordinates,name,zone) VALUES " bustopsDic = {} insertedDic = {} for i in range(BUS_STOPS): x = random.randint(0, MAX_COORDINATES) #create a random map position y = random.randint(0, MAX_COORDINATES) coor = str(x) + "," + str(y) n1 = random.randint(0,len(NAMES)-1) #create a random name (2-parts) n2 = random.randint(1,DIFFERENT) name = NAMES[n1] + " " + str(n2) while name in insertedDic: n1 = random.randint(0,len(NAMES)-1) #create a random name (2-parts) n2 = random.randint(1,DIFFERENT) name = NAMES[n1] + " " + str(n2) insertedDic[name] = 1 z = random.randint(0,len(ZONES)-1) #pick a random zone zone = ZONES[z] insert_str += "('" + coor + "','" + name + "'," + str(zone) + ")" bustopsDic[i] = [coor, name, zone] if (i < BUS_STOPS - 1): insert_str += "," insert_str += ";" with open("strings.txt", 'a') as f: f.write("\n\n" + insert_str)
# class A(object): # def __init__(self, name): # self.name = name # # def __eq__(self, obj): # return self.name == obj.name # def __hash__(self): # return # # if __name__ == '__main__': # a = A("Leon") # b = A("Leon") # print(a == b) # print(id(a),id(b)) class Foo: def __init__(self, item): self.item = item def __eq__(self, other): print('使用了equal函数的对象的id',id(self)) if isinstance(other, self.__class__): print(self.__class__.__name__,other.__class__) return self.__dict__ == other.__dict__ else: return False def __hash__(self): print('f'+str(self.item)+'使用了hash函数') return hash(self.item) f1 = Foo(1) f2 = Foo(2) f3 = Foo(3) fset = set([f1, f2, f3]) print(fset) print(type(fset)) f = Foo(3) fset.add(f) # print('f3的id:',id(f3)) # print('f的id:',id(f)) print(f2.__dict__) it = ['a','b','c'] initial = ['zhou','li'] dic = {} dic.fromkeys(it,['zhou']) print(dic.fromkeys(it,word for word in initial)
def area_triangle(base, height): area = (base*height)/2 return area def area_circle(pi, radius): area = round((pi*(radius*radius)), 2) return area def memory_in_bits(target): length = 0 while (target): target >>= 1 length += 1 return(length) def memory_in_bytes(target): length = 0 while (target): target >>= 1 length += 1 return(int(length/8)) # Problem 1 (5 points): # Compute the area of a triangle. # Formula: (base*height)/2 # Complete line 9 and 10 base = height = 5 output_string = "The area of the triangle is %s." % (area_triangle(5, 5)) print (output_string) # """ # Problem 2 (5 points): # Compute the area of a circle. # Formula: PI*radius*radius # Complete line 24 and 25 # """ import math PI = math.pi radius = 10 output_string = "The area of a circle with a radius of %s is %s." % (radius, area_circle(PI, radius)) print (output_string) """ Problem 3 (5 points): Check the memory usage for the target integer. Complete line 35 to 37 """ target = 12345678 print("Integer: %s" % (target)) print("Memory: %s bits or %s bytes." % (memory_in_bits(target), memory_in_bytes(target))) # Problem 4 (15 points): country1 = "the-united-states-of-america" country2 = "the People's Republic of China" country3 = "jAPAN" country4 = "Italian Republic" country5 = "Great Socialist People's Libyan Arab Jamahiriya" list1 = [] list1.append(country1.split('-')[1][0].upper()) list1.append('.') list1.append(country1.split('-')[2][0].upper()) list1.append('.') list1.append(country1.split('-')[4][0].upper()) list1.append('.') list1 = "".join(list1) print(list1) list1 = [] list1.append(country2.split(' ')[1][0].upper()) list1.append(country2.split(' ')[2][0].upper()) list1.append(country2.split(' ')[4]) list1 = ".".join(list1) print(list1) list1 = [] list1.append(country3.split()[0][0].upper()) list1.append(country3.split()[0][1].lower()) list1.append(country3.split()[0][2].lower()) list1.append(country3.split()[0][3].lower()) list1.append(country3.split()[0][4].lower()) list1 = "".join(list1) print(list1) list1 = [] list1.append(country4.split()[0][0]) list1.append(country4.split()[0][1]) list1.append(country4.split()[0][2]) list1.append(country4.split()[0][3]) list1.append('y') list1 = "".join(list1) print(list1) list1 = [] list1.append(country5.split(" ")[3][0]) list1.append(country5.split(" ")[3][1]) list1.append(country5.split(" ")[3][2]) list1.append(country5.split(" ")[3][3]) list1.append('a') list1 = "".join(list1) print(list1)
''' Created on Mar 5, 2013 @author: RDrapeau A Pythagorean triplet is a set of three natural numbers, a b c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. ''' # Returns 3 numbers multiplied together which represent a Pythagorean Triplet def get_triplet(max): product = -1 for a in range(1, max - 2): # Must add up to max for b in range(1, max - a): c = max - a - b if is_pyth_triple(a, b, c): product = a * b * c return product # Returns whether or not the numbers a,b,c are Pythagorean Triplets def is_pyth_triple(a, b, c): return a ** 2 + b ** 2 == c ** 2 print get_triplet(1000)
''' Created on Mar 4, 2013 @author: RDrapeau A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99. Find the largest palindrome made from the product of two 3-digit numbers. ''' # Returns the largest palindrome made from the product of two digit-digit numbers def largest_palindrome(digit): max = 0 for x in range(10 ** (digit - 1), 10 ** digit): for y in range(x, 10 ** digit): n = x * y if is_palindrome(n) and n > max: max = n return max # Returns whether the number n is a palindromic number or not def is_palindrome(n): return str(n) == str(n)[::-1] print largest_palindrome(3)
''' Created on Mar 4, 2013 @author: RDrapeau 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? ''' numbers_to_check = [11, 13, 14, 16, 17, 18, 19, 20] # Returns the smallest number that passes check(number) def solve(): largest = 2520 number = largest while (not is_divisible(number)): number += largest return number # Returns whether or not n is evenly divisible by all numbers_to_check def is_divisible(n): for number in numbers_to_check: if n % number != 0: return False return True print solve()
import sqlite3 import csv import json DBNAME = 'choc.db' BARSCSV = 'flavors_of_cacao_cleaned.csv' COUNTRIESJSON = 'countries.json' def init_db(db_name): try: conn = sqlite3.connect('choc.db') cur = conn.cursor() except: print('an error was encountered') statement = "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'Countries';" table_exists = cur.execute(statement).fetchall()[0][0] if table_exists == 1: user_input = 'yes' if user_input == 'yes': statement = ''' DROP TABLE IF EXISTS 'Countries'; ''' cur.execute(statement) conn.commit() statement = ''' CREATE TABLE 'Countries' ( 'Id' INTEGER PRIMARY KEY AUTOINCREMENT, 'Alpha2' TEXT NOT NULL, 'Alpha3' TEXT NOT NULL, 'EnglishName' TEXT NOT NULL, 'Region' TEXT NOT NULL, 'Subregion' TEXT NOT NULL, 'Population' INTEGER, 'Area' REAL ); ''' cur.execute(statement) conn.commit() else: return else: statement = ''' CREATE TABLE 'Countries' ( 'Id' INTEGER PRIMARY KEY AUTOINCREMENT, 'Alpha2' TEXT NOT NULL, 'Alpha3' TEXT NOT NULL, 'EnglishName' TEXT NOT NULL, 'Region' TEXT NOT NULL, 'Subregion' TEXT NOT NULL, 'Population' INTEGER, 'Area' REAL ); ''' cur.execute(statement) conn.commit() countries_json_file = open(COUNTRIESJSON, 'r') countries_contents = countries_json_file.read() countries_json_file.close() COUNTRIES_DICTION = json.loads(countries_contents) for x in COUNTRIES_DICTION: zero = None one = x['alpha2Code'] two = x['alpha3Code'] three = x['name'] four = x['region'] five = x['subregion'] six = x['population'] seven = x['area'] insertion = (zero, one, two, three, four, five, six, seven) statement = 'INSERT OR IGNORE INTO "Countries"' statement += 'VALUES (?, ?, ?, ?, ?, ?, ?, ?)' cur.execute(statement, insertion) conn.commit() statement = "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'ChocolateBars';" table_exists = cur.execute(statement).fetchall()[0][0] if table_exists == 1: user_input = 'yes' if user_input == 'yes': statement = ''' DROP TABLE IF EXISTS 'ChocolateBars'; ''' cur.execute(statement) conn.commit() statement = ''' CREATE TABLE 'ChocolateBars' ( 'Id' INTEGER PRIMARY KEY AUTOINCREMENT, 'Company' TEXT NOT NULL, 'SpecificBeanBarName' TEXT NOT NULL, 'REF' TEXT NOT NULL, 'ReviewDate' TEXT NOT NULL, 'CocoaPercent' REAL NOT NULL, 'CompanyLocation' TEXT NOT NULL, 'CompanyLocationId' INTEGER, 'Rating' REAL NOT NULL, 'BeanType' TEXT NOT NULL, 'BroadBeanOrigin' TEXT NOT NULL, 'BroadBeanOriginId' INTEGER ); ''' cur.execute(statement) conn.commit() else: return else: statement = ''' CREATE TABLE 'ChocolateBars' ( 'Id' INTEGER PRIMARY KEY AUTOINCREMENT, 'Company' TEXT NOT NULL, 'SpecificBeanBarName' TEXT NOT NULL, 'REF' TEXT NOT NULL, 'ReviewDate' TEXT NOT NULL, 'CocoaPercent' REAL NOT NULL, 'CompanyLocation' TEXT NOT NULL, 'CompanyLocationId' INTEGER, 'Rating' REAL NOT NULL, 'BeanType' TEXT NOT NULL, 'BroadBeanOrigin' TEXT NOT NULL, 'BroadBeanOriginId' INTEGER ); ''' cur.execute(statement) conn.commit() query = "SELECT * FROM Countries" cur.execute(query) country_mapping = {} for country in cur: id = country[0] name = country[3] country_mapping[name] = id country_mapping['Unknown'] = 0 with open(BARSCSV) as csvDataFile: csvReader = csv.reader(csvDataFile) next(csvReader, None) for row in csvReader: the_none_thing = None company = row[0] specific_bean = row[1] REF = row[2] review_date = row[3] cocoapercent = row[4][:-1] CompanyLocation = row[5] try: fkey1 = country_mapping[CompanyLocation] except: fkey1 = 0 rating = row[6] beantype = row[7] beanorig = row[8] try: fkey2 = country_mapping[beanorig] except: fkey2 = 0 insertion = (the_none_thing, company, specific_bean, REF, review_date, cocoapercent, CompanyLocation, fkey1, rating, beantype, beanorig, fkey2) statement = 'INSERT OR IGNORE INTO "ChocolateBars"' statement += 'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' cur.execute(statement, insertion) conn.commit() conn.close() #Part 2: Implement logic to process user commands def process_command(command): DB_NAME = 'choc.db' try: conn = sqlite3.connect(DB_NAME) cur = conn.cursor() except Error as e: print(e) query = "SELECT * FROM Countries" cur.execute(query) country_mapping = {} for country in cur: alpha2 = country[1] name = country[3] country_mapping[alpha2] = name if 'bars ' in command: barsplit = command.split() basicbars =''' SELECT SpecificBeanBarName , Company, CompanyLocation, Rating, CocoaPercent, BroadBeanOrigin FROM ChocolateBars JOIN Countries as c ''' strbars=str(basicbars) if 'sellcountry' in command: bars_sell_phrase = barsplit[1] if '=' in bars_sell_phrase: bars_sell_split = bars_sell_phrase.split('=') user_bars_sell_demand = bars_sell_split[1] strbars += " WHERE ChocolateBars.CompanyLocationID = c.Id AND ChocolateBars.CompanyLocation = '{}'".format(country_mapping[user_bars_sell_demand]) else: strbars += " WHERE ChocolateBars.CompanyLocationID = c.Id" if 'sourcecountry' in command: bars_source_phrase = barsplit[1] if '=' in bars_source_phrase: bars_source_split = bars_source_phrase.split('=') user_bars_source_demand = bars_source_split[1] strbars += " WHERE ChocolateBars.BroadBeanOriginID = c.Id AND ChocolateBars.BroadBeanOrigin = '{}'".format(user_bars_source_demand) else: strbars += " WHERE ChocolateBars.BroadBeanOriginID = c.Id" if 'sellregion' in command: bars_sellreg_phrase = barsplit[1] if '=' in bars_sellreg_phrase: bars_sellreg_split = bars_sellreg_phrase.split('=') user_bars_sellreg_demand = bars_sellreg_split[1] strbars += " WHERE ChocolateBars.CompanyLocationID = c.Id AND c.Region = '{}'".format(user_bars_sellreg_demand) else: strbars += " WHERE ChocolateBars.CompanyLocationID = c.Id" if 'sourceregion' in command: bars_sourcereg_phrase = barsplit[1] if '=' in bars_sourcereg_phrase: bars_sourcereg_split = bars_sourcereg_phrase.split('=') user_bars_sourcereg_demand = bars_sourcereg_split[1] strbars += " WHERE ChocolateBars.BroadBeanOriginID = c.Id AND c.Region = '{}'".format(user_bars_sourcereg_demand) else: strbars += " WHERE ChocolateBars.BroadBeanOriginID = c.Id" trybool1 = bool('sellcountry' in command) trybool2 = bool('sourcecountry' in command) trybool3 = bool('sellregion' in command) trybool4 = bool('sourceregion' in command) test_str = str(trybool1) + str(trybool2) + str(trybool3) +str(trybool4) if test_str == 'FalseFalseFalseFalse': strbars += " WHERE ChocolateBars.CompanyLocationID = c.Id" trybool5 = bool('ratings' or 'cocoa' in barsplit) if trybool5 == False: strbars += " ORDER BY ChocolateBars.Rating" if 'ratings' in command: strbars += " ORDER BY ChocolateBars.Rating" if 'cocoa' in command: strbars += " ORDER BY ChocolateBars.CocoaPercent" if 'top' in command: #default is top = 10! bars_top_phrase = barsplit[-1] if '=' in bars_top_phrase: bars_top_split = bars_top_phrase.split('=') user_bars_top_demand = bars_top_split[1] strbars += " DESC" #highest first strbars += " LIMIT {}".format(user_bars_top_demand) else: strbars += " DESC" if 'bottom' in command: bars_bottom_phrase = barsplit[-1] if '=' in bars_bottom_phrase: bars_bottom_split = bars_bottom_phrase.split('=') user_bars_bottom_demand = bars_bottom_split[1] strbars += " ASC" strbars += " LIMIT {}".format(user_bars_bottom_demand) else: strbars += " ASC" bars_last_phrase = barsplit[-1] bool1 = bool('top' in bars_last_phrase) bool2 = bool('bottom' in bars_last_phrase) if (bool1, bool2) == (False, False): strbars += " DESC" strbars += " LIMIT 10" cur.execute(strbars) bars_output_list = [] for row in cur: bars_output = (row[0],row[1],row[2],(round(float(row[3]), 1)),((str(row[4])[:2]) + '%'),row[5]) bars_output_list.append(bars_output) return bars_output_list if 'companies ' in command: compsplit = command.split() if 'country' or 'region' not in command: format2 = " " trybool = bool('ratings' or 'cocoa' in compsplit) if trybool == False: format1 = " ORDER BY ChocolateBars.Rating" format3 = " ORDER BY ChocolateBars.Rating" if 'country' in command: comp_country_phrase = compsplit[1] if '=' in comp_country_phrase: comp_country_split = comp_country_phrase.split('=') user_comp_country_demand = comp_country_split[1] format2 = " AND c.EnglishName = '{}'".format(country_mapping[user_comp_country_demand]) else: format2 = " " if 'region' in command: comp_region_phrase = compsplit[1] if '=' in comp_region_phrase: comp_region_split = comp_region_phrase.split('=') user_comp_region_demand = comp_region_split[1] format2 = " AND c.Region = '{}'".format(user_comp_region_demand) else: format2 = " " if 'ratings' in command: format1 = " AVG(ChocolateBars.Rating)" format3 = " AVG(ChocolateBars.Rating)" if 'cocoa' in command: format1 = " AVG(ChocolateBars.CocoaPercent)" format3 = " AVG(ChocolateBars.CocoaPercent)" if 'bars_sold' in command: format1 = " COUNT(*)" format3 = " COUNT(*)" basiccompanies =''' SELECT Company, CompanyLocation,{} FROM ChocolateBars JOIN Countries AS c ON ChocolateBars.CompanyLocationId = c.Id GROUP BY Company HAVING COUNT(*) > 4 {} ORDER BY {} '''.format(format1, format2, format3) strcomp=str(basiccompanies) if 'top' in command: comp_top_phrase = compsplit[-1] if '=' in comp_top_phrase: comp_top_split = comp_top_phrase.split('=') user_comp_top_demand = comp_top_split[1] strcomp += " DESC" strcomp += " LIMIT {}".format(user_comp_top_demand) else: strcomp += " DESC" if 'bottom' in command: comp_bottom_phrase = compsplit[-1] if '=' in comp_bottom_phrase: comp_bottom_split = comp_bottom_phrase.split('=') user_comp_bottom_demand = comp_bottom_split[1] strcomp += " ASC" strcomp += " LIMIT {}".format(user_comp_bottom_demand) else: strcomp += " ASC" comp_last_phrase = compsplit[-1] bool1 = bool('top' in comp_last_phrase) bool2 = bool('bottom' in comp_last_phrase) if (bool1, bool2) == (False, False): strcomp += " DESC" strcomp += " LIMIT 10" cur.execute(strcomp) companies_output_list = [] for row in cur: companies_output = (row[0],row[1], (int(row[2])) if int(row[2]) > 5 else round(float(row[2]), 1)) companies_output_list.append(companies_output) return companies_output_list if 'countries ' in command: countrsplit = command.split() if 'country' or 'region' not in command: format5 = " " if 'sellers' or 'sources' not in command: format1 = " ChocolateBars.CompanyLocation" format3 = " ChocolateBars.CompanyLocationId = c.Id" format4 = " ChocolateBars.CompanyLocation" trybool = bool('ratings' or 'cocoa' in countrsplit) if trybool == False: format2 = " AVG(ChocolateBars.Rating)" format6 = " AVG(ChocolateBars.Rating)" if 'region' in command: count_region_phrase = countrsplit[1] if '=' in count_region_phrase: count_region_split = count_region_phrase.split('=') user_count_region_demand = count_region_split[1] format5 = " AND c.Region = '{}'".format(user_count_region_demand) else: format5 = " " if 'sellers' in command: format1 = " ChocolateBars.CompanyLocation" format3 = " ChocolateBars.CompanyLocationId = c.Id" format4 = " ChocolateBars.CompanyLocation" if 'sources' in command: format1 = " ChocolateBars.BroadBeanOrigin" format3 = " ChocolateBars.BroadBeanOriginId = c.Id" format4 = " ChocolateBars.BroadBeanOrigin" if 'ratings' in command: format2 = " AVG(ChocolateBars.Rating)" format6 = " AVG(ChocolateBars.Rating)" if 'cocoa' in command: format2 = " AVG(ChocolateBars.CocoaPercent)" format6 = " AVG(ChocolateBars.CocoaPercent)" if 'bars_sold' in command: format2 = " COUNT(*)" format6 = " COUNT(*)" basiccountries =''' SELECT {}, c.Region, {} FROM ChocolateBars JOIN Countries AS c ON {} GROUP BY {} HAVING COUNT(*) > 4 {} ORDER BY {} '''.format(format1, format2, format3, format4, format5, format6) strcount=str(basiccountries) if 'top' in command: count_top_phrase = countrsplit[-1] if '=' in count_top_phrase: count_top_split = count_top_phrase.split('=') user_count_top_demand = count_top_split[1] strcount += " DESC" strcount += " LIMIT {}".format(user_count_top_demand) else: strcount += " DESC" if 'bottom' in command: count_bottom_phrase = countrsplit[-1] if '=' in count_bottom_phrase: count_bottom_split = count_bottom_phrase.split('=') user_count_bottom_demand = count_bottom_split[1] strcount += " ASC" strcount += " LIMIT {}".format(user_count_bottom_demand) else: strcount += " ASC" count_last_phrase = countrsplit[-1] bool1 = bool('top' in count_last_phrase) bool2 = bool('bottom' in count_last_phrase) if (bool1, bool2) == (False, False): strcount += " DESC" strcount += " LIMIT 10" cur.execute(strcount) countries_output_list = [] for row in cur: countries_output = (row[0],row[1], (int(row[2])) if int(row[2]) > 5 else round(float(row[2]), 1)) countries_output_list.append(countries_output) return countries_output_list if 'regions ' in command: regsplit = command.split() if 'seller' or 'sources' not in command: format2 = " ChocolateBars.CompanyLocationId = c.Id" trybool = bool('ratings' or 'cocoa' in regsplit) if trybool == False: format1 = "AVG(Rating)" format3 = "AVG(Rating)" if 'sellers' in command: format2 = " ChocolateBars.CompanyLocationId = c.Id" if 'sources' in command: format2 = " ChocolateBars.BroadBeanOriginId = c.Id" if 'ratings' in command: format1 = " AVG(ChocolateBars.Rating)" format3 = " AVG(ChocolateBars.Rating)" if 'cocoa' in command: format1 = " AVG(ChocolateBars.CocoaPercent)" format3 = " AVG(ChocolateBars.CocoaPercent)" if 'bars_sold' in command: format1 = " COUNT(*)" format3 = " COUNT(*)" basicreg = ''' SELECT Region, {} FROM ChocolateBars JOIN Countries AS c ON {} GROUP BY Region HAVING COUNT(*) > 4 ORDER BY {} '''.format(format1, format2, format3) streg=str(basicreg) if 'top' in command: reg_top_phrase = regsplit[-1] if '=' in reg_top_phrase: reg_top_split = reg_top_phrase.split('=') user_reg_top_demand = reg_top_split[1] streg += " DESC" streg += " LIMIT {}".format(user_reg_top_demand) else: streg += " DESC" if 'bottom' in command: reg_bottom_phrase = regsplit[-1] if '=' in reg_bottom_phrase: reg_bottom_split = reg_bottom_phrase.split('=') user_reg_bottom_demand = reg_bottom_split[1] streg += " ASC" streg += " LIMIT {}".format(user_reg_bottom_demand) else: streg += " ASC" reg_last_phrase = regsplit[-1] bool1 = bool('top' in reg_last_phrase) bool2 = bool('bottom' in reg_last_phrase) if (bool1, bool2) == (False, False): streg += " DESC" streg += " LIMIT 10" cur.execute(streg) region_output_list = [] for row in cur: region_output = (row[0], (int(row[1])) if int(row[1]) > 5 else round(float(row[1]), 1)) region_output_list.append(region_output) return region_output_list def load_help_text(): with open('help.txt') as f: return f.read() # Part 3: Implement interactive prompt. We've started for you! init_db(DBNAME) def interactive_prompt(): init_db(DBNAME) help_text = load_help_text() response = '' while response.lower() != 'exit': response = input('Enter a command: ') if response.lower() == 'help': print(help_text) continue if response.lower() == 'exit': print('bye') break if 'bars' or 'companies' or 'countries' or 'regions' in response: try: commresponse = process_command(response) if len(commresponse[0]) == 6: for x in commresponse: proper_print_list = [] for thing in x: working_string = str(thing) if len(working_string) > 12: working_string = working_string.replace(working_string[10:], '...') proper_print_list.append(working_string) bars_formatted = '{0:15} {1:15} {2:15} {3:5} {4:5} {5:5}'.format(*proper_print_list) print(bars_formatted) if len(commresponse[0]) == 3: for x in commresponse: count_proper_print_list = [] for thing in x: count_working_string = str(thing) if len(count_working_string) > 12: count_working_string = count_working_string.replace(count_working_string[10:], '...') count_proper_print_list.append(count_working_string) count_formatted = '{0:15} {1:15} {2:15}'.format(*count_proper_print_list) print(count_formatted) if len(commresponse[0]) == 2: for x in commresponse: region_proper_print_list = [] for thing in x: region_working_string = str(thing) if len(region_working_string) > 12: region_working_string = region_working_string.replace(region_working_string[10:], '...') region_proper_print_list.append(region_working_string) region_formatted = '{0:15} {1:15}'.format(*region_proper_print_list) print(region_formatted) except: print('Command not recognized: {}'.format(response)) else: print('Command not recognized: {}'.format(response)) if __name__=="__main__": interactive_prompt()
A, B, C = map(int, input().split()) sq_A=A*A sq_B=B*B sq_C=C*C if sq_A+sq_B < sq_C: print("Yes") else: print("No")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: tylersschwartz """ import random WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. """ in_file = open(WORDLIST_FILENAME, 'r') line = in_file.readline() wordlist = line.split() return wordlist def choose_word(wordlist): """ Returns a word from wordlist at random """ return random.choice(wordlist) # Load the list of words into the variable wordlist # so that it can be accessed from anywhere in the program wordlist = load_words() def get_valid_guess(letters_guessed): """ letters_guessed: set, what letters have been guessed so far Takes in user input, a lowercase alphabetical character. If is a valid input returns that character, else prints an error message and returns to input prompt until valid guess is given. """ while True: guess = input("Please enter your guess: ", ) guess = guess.lower() if len(guess) > 1: print("Please only enter a single character.") elif not guess.isalpha(): print("Please use an alphabetical character.") elif guess in letters_guessed: print("Oops! You've already guessed that letter.") else: return guess def is_word_guessed(secret_word, letters_guessed): """ secret_word: string, the word the user is guessing letters_guessed: set, what letters have been guessed so far returns: boolean, True if all the letters of secret_word are in letters_guessed; False otherwise """ count = 0 for l in secret_word: if l in letters_guessed: count += 1 return count == len(secret_word) def get_guessed_word(secret_word, letters_guessed): """ secret_word: string, the word the user is guessing letters_guessed: set, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secret_word have been guessed so far. """ guess_word = "" for l in secret_word: if l in letters_guessed: guess_word = guess_word + l + " " else: guess_word += '_ ' return guess_word def get_available_letters(letters_guessed): """ letters_guessed: set of what letters have been guessed so far returns: string, comprised of letters that represents what letters have not yet been guessed. """ import string letters_left = "" for l in string.ascii_lowercase: if l not in letters_guessed: letters_left += l return letters_left def hangman(secret_word): """ secret_word: string, the secret word to guess. Starts up a game of Hangman. At startup, lets the user know how many guesses the have left. User supplies one valid guess per round, or is prompted to after an invalid guess. User receives feedback whether or not the guess is in secret word. After each round, user is given the correctly guessed letters of the secret word, as well as the available letters and the number of guesses left. """ guesses_left = 8 letters_guessed = set() print("Welcome to Hangman!") print("I'm thinking of a word that is", len(secret_word), "letters long.") while guesses_left > 0: print("-----------") print("You have", guesses_left, "guesses left.") print("Available letters: ", get_available_letters(letters_guessed)) guess = get_valid_guess(letters_guessed) letters_guessed.add(guess) if guess in secret_word: print("Good guess:", get_guessed_word(secret_word, letters_guessed)) if is_word_guessed(secret_word, letters_guessed): break else: print("Nope! That letter is not in the word: ", get_guessed_word(secret_word, letters_guessed)) guesses_left -= 1 if is_word_guessed(secret_word, letters_guessed): print("-----------") print("Congratulations, you guessed correctly!") else: print("-----------") print("Sorry, you ran out of guesses. The word was", secret_word + ".") secret_word = choose_word(wordlist).lower() hangman(secret_word)
import os import sys def rename(self_name,prefix,begin_offset,suffix): #print self_name path= os.getcwd() num = int(begin_offset) filelist = os.listdir(path) for file in filelist: # prevent from modifing the name of program self if file in self_name: continue Olddir = os.path.join(path,file) # judge whether it is a folder if os.path.isdir(Olddir): continue filename = prefix + '_' + str(num)+ '.' + suffix Newdir = os.path.join(path,filename) os.renames(Olddir,Newdir) num = num + 1 if __name__ == '__main__': if len(sys.argv) == 3: print 'please input a the filename\'s prefix & begin_offset & suffix!' print 'For example:rename.py image 0 png,then get image_0.png,image_1.png......' exit() else: self_name = sys.argv[0] filename_prefix = sys.argv[1] begin_offset = sys.argv[2] suffix = sys.argv[3] rename(self_name,filename_prefix,begin_offset,suffix)
import unittest from app.models import Movie class MovieTest(unittest.TestCase): """ Test Class to test the behaviour of the movie class """ def setUp(self): """Set up method taht will run before every Test """ self.new_movie = Movie(1234, 'Python must be crazy', 'A thrilling new python series', 'https://developers.themoviedb.org/3/getting-started/images/khsjha27hbs', 8.5,129993) def test_instance(self): self.assertTrue(isinstance(self.new_movie,Movie)) # def test_init(self): # self.assertEqual(self.new_movie.id,1234) # self.assertEqual(self.new_movie.title,"Python must be crazy") # self.assertEqual(self.new_movie.overview,"A thrilling new python series") # self.assertEqual(self.new_movie.image,'https://developers.themoviedb.org/3/getting-started/imageshttps://developers.themoviedb.org/3/getting-started/images/khsjha27hbs') # self.assertEqual(self.new_movie.vote_average,8.5) # self.assertEqual(self.new_movie.vote_count,129993) if __name__ == '__main__': unittest.main()
end = 6 totalSum = 0 for individualNumber in range(1, end + 1): totalSum += individualNumber print(totalSum)
# s = "azcbobobegghakl" s = "abcbcd" longestSubstring = "" start = 0 tempSubstring = s[start] while (start < len(s)-1): for j in range(start+1, len(s)): if s[j] >= tempSubstring[len(tempSubstring)-1]: tempSubstring = tempSubstring + s[j] start = j else: if len(tempSubstring) > len(longestSubstring): longestSubstring = tempSubstring start = j tempSubstring = s[start] break print("Longest substring in alphabetical order is: " + longestSubstring)
from blinkstick.blinkstick import BlinkStick, blinkstick_remap_rgb_value_reverse import asyncio class AsyncBlinkStick(BlinkStick): """ Controls BlinkStick devices in exactly the same was as the BlinkStick class, but uses asyncio.sleep instead of time.sleep so that it plays nice with code written using asyncio """ @asyncio.coroutine def pulse(self, channel=0, index=0, red=0, green=0, blue=0, name=None, hexadecimal=None, repeats=1, duration=1000, steps=50): """ Morph to the specified color from black and back again. @type channel: int @param channel: led channel @type index: int @param index: led channel index @type red: int @param red: Red color intensity 0 is off, 255 is full red intensity @type green: int @param green: Green color intensity 0 is off, 255 is full green intensity @type blue: int @param blue: Blue color intensity 0 is off, 255 is full blue intensity @type name: str @param name: Use CSS color name as defined here: U{http://www.w3.org/TR/css3-color/} @type hexadecimal: str @param hexadecimal: Specify color using hexadecimal color value e.g. '#FF3366' @type repeats: int @param repeats: Number of times to pulse the LED @type duration: int @param duration: Duration for pulse in milliseconds @type steps: int @param steps: Number of gradient steps """ r, g, b = self._determine_rgb(red=red, green=green, blue=blue, name=name, hexadecimal=hexadecimal) self.turn_off() for x in range(repeats): yield from self.morph(channel=channel, index=index, red=r, green=g, blue=b, duration=duration, steps=steps) yield from self.morph(channel=channel, index=index, red=0, green=0, blue=0, duration=duration, steps=steps) @asyncio.coroutine def blink(self, channel=0, index=0, red=0, green=0, blue=0, name=None, hexadecimal=None, repeats=1, delay=500): """ Blink the specified color. Asyncio friendly version @type channel: int @param channel: led channel @type index: int @param index: led channel index @type red: int @param red: Red color intensity 0 is off, 255 is full red intensity @type green: int @param green: Green color intensity 0 is off, 255 is full green intensity @type blue: int @param blue: Blue color intensity 0 is off, 255 is full blue intensity @type name: str @param name: Use CSS color name as defined here: U{http://www.w3.org/TR/css3-color/} @type hexadecimal: str @param hexadecimal: Specify color using hexadecimal color value e.g. '#FF3366' @type repeats: int @param repeats: Number of times to pulse the LED @type delay: int @param delay: time in milliseconds to light LED for, and also between blinks """ r, g, b = self._determine_rgb(red=red, green=green, blue=blue, name=name, hexadecimal=hexadecimal) ms_delay = float(delay) / float(1000) for x in range(repeats): if x: yield from asyncio.sleep(ms_delay) self.set_color(channel=channel, index=index, red=r, green=g, blue=b) yield from asyncio.sleep(ms_delay) self.set_color(channel=channel, index=index) @asyncio.coroutine def morph(self, channel=0, index=0, red=0, green=0, blue=0, name=None, hexadecimal=None, duration=1000, steps=50): """ Morph to the specified color. @type channel: int @param channel: led channel @type index: int @param index: led channel index @type red: int @param red: Red color intensity 0 is off, 255 is full red intensity @type green: int @param green: Green color intensity 0 is off, 255 is full green intensity @type blue: int @param blue: Blue color intensity 0 is off, 255 is full blue intensity @type name: str @param name: Use CSS color name as defined here: U{http://www.w3.org/TR/css3-color/} @type hexadecimal: str @param hexadecimal: Specify color using hexadecimal color value e.g. '#FF3366' @type duration: int @param duration: Duration for morph in milliseconds @type steps: int @param steps: Number of gradient steps (default 50) """ r_end, g_end, b_end = self._determine_rgb(red=red, green=green, blue=blue, name=name, hexadecimal=hexadecimal) r_start, g_start, b_start = blinkstick_remap_rgb_value_reverse(self._get_color_rgb(index), self.max_rgb_value) gradient = self._get_grandient_values(r_start, g_start, b_start, r_end, g_end, b_end, steps) ms_delay = float(duration) / float(1000 * steps) self.set_color(channel=channel, index=index, red=r_start, green=g_start, blue=b_start) for grad in gradient: grad_r, grad_g, grad_b = grad self.set_color(channel=channel, index=index, red=grad_r, green=grad_g, blue=grad_b) yield from asyncio.sleep(ms_delay) self.set_color(channel=channel, index=index, red=r_end, green=g_end, blue=b_end)
import unittest from typing import List def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]: def diameter(edges: List[List[int]]) -> int: start = -1 for i, l in enumerate(edges): if l: start = i break if start == -1: return 0 def maxDistance(n: int) -> int: graph = [[]] * 16 for i in range(1, 16): if n & (1 << i) > 0: for j in edges[i]: if n | (1 << j) > 0: graph[i].append(j) return diameter(graph) ans = [0] * (n - 1) for i in range(1, 1 << n): distance = maxDistance(n) ans[distance] = ans[distance] + 1 return ans class MyTestCase(unittest.TestCase): def test_something(self): self.assertEqual(4, countSubgraphsForEachDiameter(self, 'cabbac')) if __name__ == '__main__': unittest.main()
import unittest from Tree import Tree from typing import List def solve(root: Tree) -> bool: queue: List[Tree] = [root] meet_empty = False while root: node = queue.pop() if node: if meet_empty: return False queue.append(node.left) queue.append(node.right) else: meet_empty = True return True class MyTestCase(unittest.TestCase): def test_something(self): self.assertEqual(True, solve(Tree(1, None, None))) if __name__ == '__main__': unittest.main()
''' Stack is LIFO - implementing first using python List Implement using Node later ''' class Stack: def __init__(self): self._items = [] def push(self,item): self._items.append(item) print "pushing : {}".format(item) # print "stack is now {}".format(self._items) def pop(self): item = self._items.pop() print "popping : {}".format(item) # print "stack is now {}".format(self._items) return item def isEmpty(self): return len(self._items) == 0 def __str__(self): return str(self._items) def checkstack(): from random import randint stack = Stack() # insert items into stack for i in range(1,10): val=randint(1,100) print "going to put {} into stack".format(val) print "currently stack is {}".format(str(stack)) stack.push(val) def evalPostfix(expr): import re tokenList = re.split("[^0-9+*]",expr) stack=Stack() print "tokenList is {}".format(tokenList) for token in tokenList: #print "Processing token {}".format(token) if token == '' or token == ' ': continue elif token == '+': sum = stack.pop() + stack.pop() print "doing sum" #print "Sum is {}. pushing it to stack".format(sum) stack.push(sum) #print "Sum {} is pushed !!".format(sum) elif token == '*': product = stack.pop() * stack.pop() print "doing product" #print "Product is {}. pushing it to stack".format(product) stack.push(product) #print "Product {} is pushed !!".format(product) else: stack.push(int(token)) #print " {} is pushed".format(token) print "Getting final result" return stack.pop() if __name__=="__main__": evalPostfix("1 2 + 3 *")
import math import torch import torch.nn as nn import torch.nn.functional as F class FunctionRepresentation(nn.Module): """Function to represent a single datapoint. For example this could be a function that takes pixel coordinates as input and returns RGB values, i.e. f(x, y) = (r, g, b). Args: coordinate_dim (int): Dimension of input (coordinates). feature_dim (int): Dimension of output (features). layer_sizes (tuple of ints): Specifies size of each hidden layer. encoding (torch.nn.Module): Encoding layer, usually one of Identity or FourierFeatures. final_non_linearity (torch.nn.Module): Final non linearity to use. Usually nn.Sigmoid() or nn.Tanh(). """ def __init__(self, coordinate_dim, feature_dim, layer_sizes, encoding, non_linearity=nn.ReLU(), final_non_linearity=nn.Sigmoid()): super(FunctionRepresentation, self).__init__() self.coordinate_dim = coordinate_dim self.feature_dim = feature_dim self.layer_sizes = layer_sizes self.encoding = encoding self.non_linearity = non_linearity self.final_non_linearity = final_non_linearity self._init_neural_net() def _init_neural_net(self): """ """ # First layer transforms coordinates into a positional encoding # Check output dimension of positional encoding if isinstance(self.encoding, nn.Identity): prev_num_units = self.coordinate_dim # No encoding, so same output dimension else: prev_num_units = self.encoding.feature_dim # Build MLP layers forward_layers = [] for num_units in self.layer_sizes: forward_layers.append(nn.Linear(prev_num_units, num_units)) forward_layers.append(self.non_linearity) prev_num_units = num_units forward_layers.append(nn.Linear(prev_num_units, self.feature_dim)) forward_layers.append(self.final_non_linearity) self.forward_layers = nn.Sequential(*forward_layers) def forward(self, coordinates): """Forward pass. Given a set of coordinates, returns feature at every coordinate. Args: coordinates (torch.Tensor): Shape (batch_size, coordinate_dim) """ encoded = self.encoding(coordinates) return self.forward_layers(encoded) def get_weight_shapes(self): """Returns lists of shapes of weights and biases in the network.""" weight_shapes = [] bias_shapes = [] for param in self.forward_layers.parameters(): if len(param.shape) == 1: bias_shapes.append(param.shape) if len(param.shape) == 2: weight_shapes.append(param.shape) return weight_shapes, bias_shapes def get_weights_and_biases(self): """Returns list of weights and biases in the network.""" weights = [] biases = [] for param in self.forward_layers.parameters(): if len(param.shape) == 1: biases.append(param) if len(param.shape) == 2: weights.append(param) return weights, biases def set_weights_and_biases(self, weights, biases): """Sets weights and biases in the network. Args: weights (list of torch.Tensor): biases (list of torch.Tensor): Notes: The inputs to this function should have the same form as the outputs of self.get_weights_and_biases. """ weight_idx = 0 bias_idx = 0 with torch.no_grad(): for param in self.forward_layers.parameters(): if len(param.shape) == 1: param.copy_(biases[bias_idx]) bias_idx += 1 if len(param.shape) == 2: param.copy_(weights[weight_idx]) weight_idx += 1 def duplicate(self): """Returns a FunctionRepresentation instance with random weights.""" # Extract device device = next(self.parameters()).device # Create new function representation and put it on same device return FunctionRepresentation(self.coordinate_dim, self.feature_dim, self.layer_sizes, self.encoding, self.non_linearity, self.final_non_linearity).to(device) def sample_grid(self, data_converter, resolution=None): """Returns function values evaluated on grid. Args: data_converter (data.conversion.DataConverter): resolution (tuple of ints): Resolution of grid on which to evaluate features. If None uses default resolution. """ # Predict features at every coordinate in a grid if resolution is None: coordinates = data_converter.coordinates else: coordinates = data_converter.superresolve_coordinates(resolution) features = self(coordinates) # Convert features into appropriate data format (e.g. images) return data_converter.to_data(coordinates, features, resolution) def stateless_forward(self, coordinates, weights, biases): """Computes forward pass of function representation given a set of weights and biases without using the state of the PyTorch module. Args: coordinates (torch.Tensor): Tensor of shape (num_points, coordinate_dim). weights (list of torch.Tensor): List of tensors containing weights of linear layers of neural network. biases (list of torch.Tensor): List of tensors containing biases of linear layers of neural network. Notes: This is useful for computing forward pass for a specific function representation (i.e. for a given set of weights and biases). However, it might be easiest to just change the weights of the network directly and then perform forward pass. Doing the current way is definitely more error prone because we have to mimic the forward pass, instead of just directly using it. Return: Returns a tensor of shape (num_points, feature_dim) """ # Positional encoding is first layer of function representation # model, so apply this transformation to coordinates hidden = self.encoding(coordinates) # Apply linear layers and non linearities for i in range(len(weights)): hidden = F.linear(hidden, weights[i], biases[i]) if i == len(weights) - 1: hidden = self.final_non_linearity(hidden) else: hidden = self.non_linearity(hidden) return hidden def batch_stateless_forward(self, coordinates, weights, biases): """Stateless forward pass for multiple function representations. Args: coordinates (torch.Tensor): Batch of coordinates of shape (batch_size, num_points, coordinate_dim). weights (dict of list of torch.Tensor): Batch of list of tensors containing weights of linear layers for each neural network. biases (dict of list of torch.Tensor): Batch of list of tensors containing biases of linear layers for each neural network. Return: Returns a tensor of shape (batch_size, num_points, feature_dim). """ features = [] for i in range(coordinates.shape[0]): features.append( self.stateless_forward(coordinates[i], weights[i], biases[i]).unsqueeze(0) ) return torch.cat(features, dim=0) def _get_config(self): return {"coordinate_dim": self.coordinate_dim, "feature_dim": self.feature_dim, "layer_sizes": self.layer_sizes, "encoding": self.encoding, "non_linearity": self.non_linearity, "final_non_linearity": self.final_non_linearity} class FourierFeatures(nn.Module): """Random Fourier features. Args: frequency_matrix (torch.Tensor): Matrix of frequencies to use for Fourier features. Shape (num_frequencies, num_coordinates). This is referred to as B in the paper. learnable_features (bool): If True, fourier features are learnable, otherwise they are fixed. """ def __init__(self, frequency_matrix, learnable_features=False): super(FourierFeatures, self).__init__() if learnable_features: self.frequency_matrix = nn.Parameter(frequency_matrix) else: # Register buffer adds a key to the state dict of the model. This will # track the attribute without registering it as a learnable parameter. # We require this so frequency matrix will also be moved to GPU when # we call .to(device) on the model self.register_buffer('frequency_matrix', frequency_matrix) self.learnable_features = learnable_features self.num_frequencies = frequency_matrix.shape[0] self.coordinate_dim = frequency_matrix.shape[1] # Factor of 2 since we consider both a sine and cosine encoding self.feature_dim = 2 * self.num_frequencies def forward(self, coordinates): """Creates Fourier features from coordinates. Args: coordinates (torch.Tensor): Shape (num_points, coordinate_dim) """ # The coordinates variable contains a batch of vectors of dimension # coordinate_dim. We want to perform a matrix multiply of each of these # vectors with the frequency matrix. I.e. given coordinates of # shape (num_points, coordinate_dim) we perform a matrix multiply by # the transposed frequency matrix of shape (coordinate_dim, num_frequencies) # to obtain an output of shape (num_points, num_frequencies). prefeatures = torch.matmul(coordinates, self.frequency_matrix.T) # Calculate cosine and sine features cos_features = torch.cos(2 * math.pi * prefeatures) sin_features = torch.sin(2 * math.pi * prefeatures) # Concatenate sine and cosine features return torch.cat((cos_features, sin_features), dim=1)
x=input() y=0 for i in range(len(x)): if ord(x[i])>=2437 and ord(x[i])<=2443: y=y+1 elif ord(x[i])==2447==2448==2482==2524==2525==2510==2527==2528: y=y+1 elif ord(x[i])>=2451 and ord(x[i])<=2472: y=y+1 elif ord(x[i])>=2474 and ord(x[i])<=2480: y=y+1 elif ord(x[i])>=2486 and ord(x[i])<=2489: y=y+1 elif ord(x[i])>=2492 and ord(x[i])<=2500: y=y+1 if y>0: print("It is a bangla line") else: print("It is not a bangla line")
# 7. 어떤 회사 자동차의 hwy(고속도로 연비)가 가장 높은지 알아보려 합니다. # hwy(고속도로 연비) 평균이 가장 높은 회사 세 곳을 출력하세요. class Car(object): def __init__(self, car_data): car_data = car_data.split(",") self.manufacturer = car_data[0] self.model = car_data[1] self.displ = float(car_data[2]) self.year = int(car_data[3]) self.cyl = int(car_data[4]) self.trans = car_data[5] self.drv = car_data[6] self.cty = int(car_data[7]) self.hwy = int(car_data[8]) self.fl = car_data[9] self.car_class = car_data[10] def __repr__(self): return self.manufacturer + ", " + self.model \ + "," + str(self.displ) + ", " + str(self.year) \ + self.trans + ", " + self.drv \ + str(self.cty) + ", " + str(self.hwy) file = open("mpg.txt", "r") car_list = list() line = file.readline() # 첫줄 메뉴표라서 빼준겨 while True: line = file.readline() if not line: break car_list.append(Car(line.strip())) file.close() def search_car_dict_hwy_avg(company_name): circle_class = [tmp.hwy for tmp in car_list if tmp.manufacturer == company_name] return (company_name, round(sum(circle_class)/len(circle_class), 2)) company_of_car = [tmp.manufacturer for tmp in car_list] company_of_car_set = set(company_of_car) my_dict_company = [] for i in company_of_car_set: my_dict_company.append(search_car_dict_hwy_avg(i)) print(my_dict_company) s_my_dict_company = reversed(sorted(my_dict_company, key=lambda t : t[1])) count = 1 for j in s_my_dict_company: if count > 5: break else: print("hwy 평균 {}위 기업 : {} , {}".format(count, j[0], j[1])) count += 1
'Author: Ionwyn Sean' def knapsack(items, weight): table = [[0 for w in xrange(weight + 1)] for i in xrange(len(items) + 1)] for i in xrange(1, len(items) + 1): item_name, item_weight, item_value = items[i-1] for w in xrange(1, weight + 1): if (item_weight > w): table[i][w] = table[i-1][w] else: table[i][w] = max(table[i-1][w], table[i-1][w-item_weight] + item_value) result = [] w = weight for i in xrange(len(items), 0, -1): if (table[i][w] != table[i-1][w]): item_name, item_weight, item_value = items[i-1] result.append(items[i-1]) w -= item_weight return result # Counts the total weight and total value of items to be added def totalvalue(comb): weight_total = value_total = 0 for item_name, item_weight, item_value in comb: weight_total += item_weight value_total += item_value return (value_total, weight_total) 'items = ("Item Name", weight, value)' items = ( ("Book 1", 20, 150), ("Book 2", 20, 100), ("Water bottle", 5, 20), ("Laptop", 80, 200), ("Laptop charger", 10, 70), ("Phone charger", 3, 45), ("House keys", 3, 200), ("Notebook", 15, 70), ("Pen and pencil case", 5, 50), ("Umbrella", 5, 20), ("iPad", 10, 30), ("Lecture notes", 10, 50), ("Extra Clothings", 10, 25), ("Gum", 1, 10), ("Hygiene products", 10, 20), ("Headphones", 3, 70), ("Healthy snacks", 4, 35), ("Beer", 2, 40), )
A= [0,2,1,0] B = sorted(A) highest = B[-1] print(highest) i = 0 for a in A: if a == highest: print(i) break i += 1
#!/usr/bin/env python ''' Numpy [Python] Ejercicios de práctica --------------------------- Autor: Inove Coding School Version: 1.1 Descripcion: Programa creado para que practiquen los conocimietos adquiridos durante la semana ''' __author__ = "Inove Coding School" __email__ = "alumnos@inove.com.ar" __version__ = "1.1" # import numpy as np import random import math def ej1(): print('Comenzamos a divertirnos!') ''' Empecemos a jugar con las listas y su métodos, el objetivo es realizar el código lo más simple, ordenado y limpio posible, no utilizar bucles donde no haga falta, no "re inventar" una función que ya dispongamos de Python. El objetivo es: 1) Generar una lista 3 numéros aleatorios con random (pueden repetirse), que estén comprendidos entre 1 y 10 inclusive (NOTA: utilizar comprension de listas a pesar de poder hacerlo con un método de la librería random) 2) Luego de generar la lista sumar los números y ver si el resultado de la suma es menor o igual a 21 a) Si el número es menor o igual a 21 se imprime en pantalla la suma y los números recoletados b) Si el número es mayor a 21 se debe tirar la lista y volver a generar una nueva, repetir este proceso hasta cumplir la condicion "a" Realizar este proceso iterativo hasta cumplir el objetivo ''' acum = 0 marca = True while marca == True: # 1: acum += 1 lista_numeros = [random.randint(1, 10) for x in range(3)] # 2: suma = sum(lista_numeros) # 3: if suma <= 21: print('Suma de numeros:', suma,'\nLista:', lista_numeros,'\nCantidad de tiradas:', acum) marca = False def ej2(): print('Comenzamos a ponernos serios!') ''' Dado una lista de nombres de personas "nombres" se desea obtener una nueva lista filtrada que llamaremos "nombres_filtrados" La lista se debe filtrar por comprensión de listas utilizando la lista "padron" como parámetro. La lista filtrada sodo deberá tener aquellos nombres que empiecen con alguna de las letras aceptadas en el "padron". ''' padron = ['A', 'E', 'J', 'T'] nombres = ['Tamara', 'Marcelo', 'Martin', 'Juan', 'Alberto', 'Exequiel', 'Alejandro', 'Leonel', 'Antonio', 'Omar', 'Antonia', 'Amalia', 'Daniela', 'Sofia', 'Celeste', 'Ramon', 'Jorgelina', 'Anabela'] nombres_filtrados = [nombre for nombre in nombres for letra in padron if letra in nombre] print(nombres_filtrados) def ej3(): print("Un poco de Numpy!") # Ejercicio de funciones # Se desea calcular los valores de salida de # una función senoidal, dado "X" como el conjunto # de valores que deben someter a la función "sin" # Conjunto de valores "X" en un array x = np.arange(0, 2*np.pi, 0.1) # Utilizar la función np.sin para someter cada valor de "X", # obtenga el array "y_nump" que tenga los resultados # NO utilizar comprensión de listas, solo utilice la # funcion de numpy "np.sin" y_nump = np.array(np.sin(x)) print(y_nump) # Conjunto de valores "X" en una lista # Utilizar comprensión de listas para obtener la lista # "y_list" que tenga todos los valores obtenidos como resultado # de someter cada valor de "X" a la función math.sin y_list = [round(math.sin(numero), 8) for numero in x] # redondeo a 8 decimales print(y_list) # Este es un ejemplo práctico de cuando es útil usar numpy, # basicamente siempre que deseen utilizar una función matemática # que esté definida en numpy NO necesitaran un bucle o comprensión # de listas para obtener el resultado de un monton de datos a la vez. def ej4(): print("Acercamiento al uso de datos relacionales") # Transformar variable numéricas en categóricas # Se dispone del siguiente diccionario que traduce el número ID # de un producto en su nombre, por ejemplo: # NOTA: Esta información bien podría ser una tabla SQL: id | producto producto = { 556070: 'Auto', 704060: 'Moto', 42135: 'Celular', 1264: 'Bicicleta', 905045: 'Computadora', } lista_compra_id = [556070, 905045, 42135, 5674, 704060, 1264, 42135, 3654] # Crear una nueva lista "lista_compra_productos" que transforme la lista # de realizada por "ID" de producto en lista por "nombre" producto # Iterar sobre la lista "lista_compra_id" para generar la nueva # En cada iteración acceder al diccionario para traducir el ID. # NOTA: Tener en cuenta que puede haber códigos (IDs) que # no esten registrados en el sistema, en esos casos se debe # almacenar en la lista la palabra 'NaN', para ello puede hacer uso # de condicionales PERO recomendamos leer atentamente el método "get" # de diccionarios que tiene un parametro configurable respecto # que sucede sino encuentra la "key" en el diccionario. lista_compra_producto = [{id : producto.get(id, 'NaM')} for id in lista_compra_id] print(lista_compra_producto) def ej5(): print("Ahora sí! buena suerte :)") ''' Black jack! [o algo parecido :)] El objetivo es realizar una aproximación al juego de black jack, el objetivo es generar una lista de 2 números aleatorios entre 1 al 10 inclusive, y mostrar los "números" al usuario. El usuario debe indicar al sistema si desea sacar más números para sumarlo a la lista o no sacar más A medida que el usuario vaya sacando números aleatorios que se suman a su lista se debe ir mostrando en pantalla la suma total de los números hasta el momento. Cuando el usuario no desee sacar más números o cuando el usuario haya superado los 21 (como la suma de todos) se termina la jugada y se presenta el resultado en pantalla BONUS Track: Realizar las modificaciones necesarias para que jueguen dos jugadores y compitan para ver quien sacá la suma de números más cercanos a 21 sin pasarse! ''' print('¡Comencemos a jugar!') cant_part = int(input('Ingrese la cantidad de participantes: ')) participantes = [input('Ingresa tu nombre: ') for x in range(cant_part)] list_sumatoria_part = [] for participante in participantes: opcion = 's' acum_a = 0 print('------------ Jugando', participante,'-------------------------') while opcion == 's': lista_a = [random.randint(1,10) for x in range(2)] print(lista_a) acum_a += sum(lista_a) print('has acumulado', acum_a) if acum_a <= 21: opcion = input('¿Deseas tirar otra vez s/n?: ') else: print(acum_a, 'te pasaste....') opcion = 'n' acum_a = 'fuera de juego' list_sumatoria_part.append(str(acum_a)) puntaje = {participantes[x] : list_sumatoria_part[x] for x in range(cant_part)} # Evaluar el valor mas cercano a 21 lista_solo_valores = [int(numero) for numero in list_sumatoria_part if numero.isdigit() == True] valor_maximo = max(lista_solo_valores) # Informar el/los ganadores ganador_es = [print('Ganador:', participante) for participante, puntaje in puntaje.items() if puntaje == str(valor_maximo)] if __name__ == '__main__': print("Ejercicios de práctica") # ej1() # ej2() # ej3() # ej4() ej5()
import pyscipopt as scip def knapsack(weights, profits, capacity, name="Knapsack"): """Generates a knapsack MIP formulation. Parameters: ---------- profits: list[float] List of profits of each item weights: list[float] List of weights of each item capacity: float Capacity of knapsack Returns ------- model: scip.Model A pyscipopt model of the generated instance """ assert len(weights) == len(profits) assert capacity >= 0 assert all(w >= 0 for w in weights) assert all(p >= 0 for p in profits) model = scip.Model(name) # add variables and their cost variables = [model.addVar(lb=0, ub=1, obj=profit, vtype="B") for profit in profits] # add constraints model.addCons( scip.quicksum(weight * variable for weight, variable in zip(weights, variables)) <= capacity ) model.setMaximize() return model
import argparse import egglib import sys def complement(seq_str): comp_dict = {'A': 'T', 'G': 'C', 'T': 'A', 'C': 'G', 'N': 'N', '?': '?', '-':'-'} complement_seq = '' for base in seq_str: complement_seq += comp_dict[base] return complement_seq parser = argparse.ArgumentParser(description="Extract region from a fasta alignment file") parser.add_argument('-infile', required=True, help="input fasta file") parser.add_argument('-start', required=True, type=int) parser.add_argument('-end', required=True, type=int) parser.add_argument('-out', required=True, help="Outfile") parser.add_argument('--complement', required=False, action='store_true', help="complement sequences") parser.add_argument('--reverse', required=False, action='store_true', help="reverse sequences") parser.add_argument('--revcomp', required=False, action='store_true', help="reverse complement sequences") args = parser.parse_args() aln = egglib.io.from_fasta(args.infile) start = args.start - 1 # convert 1-based to zero-based end = args.end if args.complement and args.reverse: sys.exit("Choose --reverse or complement and not both") if args.complement and args.revcomp: sys.exit("Choose --complement or --revcomp and not both") if args.reverse and args.revcomp: sys.exit("Choose --reverse or --revcomp and not both") if args.reverse and args.revcomp and args.complement: sys.exit("Choose one of --reverse, --complement or --revcomp") sub_align = aln.extract(start, end) if args.complement: for i in range(aln.ns): seq = sub_align.get_sequence(i).string() comp_seq = complement(seq) sub_align.set_sequence(i, comp_seq) elif args.revcomp: for i in range(aln.ns): rc_seq = egglib.tools.rc((sub_align.get_sequence(i).string())) sub_align.set_sequence(i, rc_seq) elif args.reverse: for i in range(aln.ns): seq = sub_align.get_sequence(i).string() rev_seq = sub_align.get_sequence(i).string()[::-1] sub_align.set_sequence(i, rev_seq) sub_align.fix_ends() sub_align.to_fasta(args.out)
def quick_sort(num): if len(num)<=1: return num pivot = num[-1] less, greater, equal = [], [], [] for i in num: if i < pivot: less.append(i) elif i>pivot: greater.append(i) else: equal.append(i) return quick_sort(less)+equal+quick_sort(greater) import sys sys.stdin.readline() list1 = quick_sort(list(map(int,sys.stdin.readline().split()))) summation, answer = 0,0 for i in list1: summation+=i answer+=summation print(answer)
import re i = "Hello from Python" #Find all lower case characters alphabetically between "a"and "m": x = re.findall("[a-z]", i) print(x)
############################################################################################################################# # This python file contains the main program, it will process the data, create the grammar and oov, get the parsed results. # ############################################################################################################################# import os from Grammer import * from OOV import OoV from split_data import split from parser import * import sys def preprocess(raw_file, processed_file): '''Preprocess the data, to remove functional labels -------------------------------- Input: raw_file: the path to the file containing the raw data processed_file: the file path to store the processed results -------------------------------- Do not return anything, but write the results to processed_file ''' out = open(processed_file, 'w') with open(raw_file, 'r') as f: for i, line in enumerate(f): line = re.sub(r'-[A-Z].{0,3}[A-Z]\s',' ', line) line = re.sub(r'-OBJ::OBJ##OBJ/OBJ', '', line) line = re.sub(r'-DE_OBJ', '', line) line = re.sub(r'-AFF.DEMSUJ', '', line) out.write(line) out.close() def flat_print(t): '''Print a tree in the correct string format ----------------------------------- Input: t: the nltk Tree object ----------------------------------- Return: the correct string ''' tag = t.label() if len(t) == 1: if type(t[0]) == str: return '(' + tag + ' ' + str(t[0]) + ')' else: return '(' + tag + ' ' + flat_print(t[0]) + ')' else: s = [] for i in range(len(t)): s.append(flat_print(t[i])) return '(' + tag + ' ' + ' '.join(s) + ')' def main(test_file_path, train_file_path='./data/train', train_sent_file='./data/train_sent', output_file='evaluation_data2.parser_output'): '''main function to do the parsing task ------------------------------------- Input: test_file_path: the path to the test file containing sentences train_file_path: the path to the training file. train_sent_file: the path to the training sentence file output_file: the path to the output file containing the parsing results on test file ------------------------------------- Do not return anything, but write the results to the output file ''' if not os.path.exists('./processed_data'): preprocess("./raw_data", './processed_data') if not os.path.exists(train_file_path): split('train', 'train_sent', 'dev', 'dev_res', 'test', 'test_res', 'processed_data') grammer = Grammer() grammer.create_pcfg(train_file_path) oov = OoV(grammer) oov.get_embeddings('./embedding/polyglot-fr.pkl') oov.get_bigram(train_sent_file) pred = open(output_file, 'w') dev = open(test_file_path, 'r').read().splitlines() for i, line in enumerate(dev): sent = line.strip() s, p = PCYK(sent, grammer, oov) s = '( ' + s + ')' t = Tree.fromstring(s) t.un_chomsky_normal_form(unaryChar='_') res = flat_print(t) pred.write(res + '\n') pred.close() if __name__ == "__main__": args = sys.argv if len(args) <= 1: print("Error: please give the test file path!") if len(args) != 2 and len(args) != 5: print("Error: do not have correct number of arguments (expected 1 or 4)!") if len(args) == 2: main(args[1]) if len(args) == 5: main(args[1], args[2], args[3], args[4])
def find_cubes(n): return [i**3 for i in range(n)] def is_permutation(first, second): if len(first) != len(second): return False for f in first: if f not in second: return False second = second.replace(f, "", 1) if len(second) == 0: return True def find_permutations(n, cubes): permutations = [] for cube in cubes: if is_permutation(str(n), str(cube)): permutations.append(cube) return permutations if __name__ == "__main__": cubes = find_cubes(10000) for cube in cubes: permutations = find_permutations(cube, cubes) if len(permutations) >= 4: print(f"{cube}: {permutations}, smallest: {min(permutations + [cube])}")
# Consider sorting n numbers stored in array A by first finding the smallest element # of A and exchanging it with the element in A[1]. Then find the second smallest # element of A, and exchange it with A[2]. Continue in this manner for the first n  1 # elements of A. # I think it means A[0] def exchange_values(array, index1, index2): storage = array[index1] array[index1] = array[index2] array[index2] = storage return array def my_selection_sort(array): for i in range(len(array)): for j in range(i, len(array)): if array[i] > array[j]: array = exchange_values(array, i, j) return array print(my_selection_sort([5, 2, 4, 6, 1, 3]))
def print_maximum(a, b): if a > b: return a elif a == b: print('both {} and {} are equal'.format(a, b)) return a,b else: return b guess1 = int(input('enter number 1:')) guess2 = int(input('enter number 2:')) print(print_maximum(guess1, guess2))
guess = int(input('enter a number:')) i = 1 for i in range(i, guess+1): print('print count {}'.format(i)) if i == 3: print('done') break else: print('not done') else: print('else for')
from state import * import random import math from csv import * class Node(): """Documentation for node """ def __init__(self, ident, father, children, state, reward, n_visit): self.ident = ident self.father = father self.children = children self.state = state self.n_visit = n_visit self.reward = reward def __str__(self): return "\nIdent : " + str(self.ident) + "\nFather : " + str(self.father) + "\nSons : " \ + str(self.children) + "\nState : " + str(self.state) + \ "\nN_visit : " + str(self.n_visit) + \ "\nReward : " + str(self.reward) class random_AI(): """Random AI """ def __init__(self): self.activ = True def return_action(self, current_state): actions = current_state.get_possible_action() action_chosen = actions[random.randint(0, len(actions) - 1)] rew = [current_state.get_next_state(a)[2] for a in actions] rew = [float(i) + 0.1 for i in rew] m = sum(rew) pick = random.uniform(0, m) current = 0 for i in range(len(rew)): value = rew[i] current += value if current > pick: return actions[i] class minimax_AI(): """Random AI """ def __init__(self): self.activ = True def return_action(self, current_state): actions = current_state.get_possible_action() next_states = [current_state.get_next_state(a)[1] for a in actions] next_reward = [10 * current_state.get_next_state( a)[2] + current_state.get_next_state(a)[3] for a in actions] rew = [] for s in next_states: next_actions = s.get_possible_action() next_rew = [s.get_next_state(a)[2] for a in next_actions] if len(next_actions) != 0: rew.append(next_reward[next_states.index(s)] - max(next_rew)) else: rew.append(-1000) rew = [(float(i) + 0.1 + min(rew) * math.copysign(1, min(rew))) for i in rew] m = sum(rew) pick = random.uniform(0, m) current = 0 for i in range(len(rew)): value = rew[i] current += value if current > pick: return actions[i] class mcts(): """MCTS AI """ def __init__(self, player=1): self.c_value = 1.4 self.path = [] self.player = player self.tot_sim = 0 self.monte_carlo = False self.file_name_nodes = 'mcts_nodes.csv' self.file_name_n_sim = 'mcts_n_sim.csv' self.minimax = minimax_AI() self.sizes = [[] for _ in range(49)] def load_ai(self): self.tree = [] f1 = open(self.file_name_nodes, 'rb') f2 = open(self.file_name_n_sim, 'rb') reader1 = csv.reader(f1) reader2 = csv.reader(f2) for r in reader2: self.tot_sim = int(r[0]) for r in reader1: row = [int(c) for c in r] state = state_awale(row[1:13], row[13]) n = Node(row[0], row[22:], row[16:22], state, row[14], row[15]) self.tree.append(n) self.path.append(self.tree[1]) f1.close() f2.close() for n in self.tree: self.sizes[sum(n.state.board)].append(n.ident) def write_ai(self): f1 = open(self.file_name_nodes, 'w') f2 = open(self.file_name_n_sim, 'w') writer1 = csv.writer(f1) writer2 = csv.writer(f2) writer2.writerow((str(self.tot_sim),)) for n in self.tree: line = n.ident, line += tuple(n.state.board) line += (n.state.player, n.reward, n.n_visit) line += tuple(n.children) line += tuple(n.father) writer1.writerow(line) f1.close() f2.close() def return_action(self, current_state): state_known = self.state_already_known(current_state) if state_known: node = state_known[1] if node.children == [-1] * 6: self.monte_carlo = True return self.expansion(node) else: return self.selection(node) elif not self.monte_carlo: n = Node(self.tree[-1].ident + 1, (self.path[-1].ident,), [-1] * 6, current_state, 0, 0) self.sizes[sum(n.state.board)].append(n.ident) self.tree.append(n) self.monte_carlo = True return self.expansion(n) else: return self.monte_carlo_end(current_state) def selection(self, n): children = [self.tree[i] for i in filter(lambda x: x != -1, n.children)] uct = [] for c in children: uct.append(float(c.reward) / (c.n_visit + 1) + self.c_value * math.sqrt(math.log(self.tot_sim) / (c.n_visit + 1))) index = uct.index(max(uct)) chosen_node = children[index] self.path.append(chosen_node) return self.get_action_for_state(n.state, chosen_node.state) def expansion(self, n): next_nodes = [] possible_actions = n.state.get_possible_action() for i in range(len(possible_actions)): a = possible_actions[i] next_state = n.state.get_next_state(a)[1] state_known = self.state_already_known(next_state) if state_known: next_nodes.append(state_known[1]) state_known[1].father = list(state_known[1].father) state_known[1].father.append(n.ident) n.children[i] = state_known[1].ident else: n.children[i] = self.tree[-1].ident + 1 new_node = Node(self.tree[-1].ident + 1, (n.ident,), [-1] * 6, next_state, 0, 0) next_nodes.append(new_node) self.sizes[sum(new_node.state.board)].append(new_node.ident) self.tree.append(new_node) r = random.randint(0, len(next_nodes) - 1) self.path.append(next_nodes[r]) return self.get_action_for_state(n.state, next_nodes[r].state) def monte_carlo_end(self, current_state): actions = current_state.get_possible_action() rewards = [current_state.get_next_state(a)[2] for a in actions] action_chosen = actions[self.weighted_random_action(rewards)] action_chosen = self.minimax.return_action(current_state) return action_chosen def weighted_random_action(self, rew): rew = [float(i) + 0.1 for i in rew] m = sum(rew) pick = random.uniform(0, m) current = 0 for i in range(len(rew)): value = rew[i] current += value if current > pick: return i def back_propagation(self, win): self.tot_sim += 1 for node in self.path: node.reward += win node.n_visit += 1 self.path = [] self.monte_carlo = False self.path.append(self.tree[1]) def get_action_for_state(self, prev_state, next_state): possible_actions = prev_state.get_possible_action() for a in possible_actions: if prev_state.get_next_state(a)[1] == next_state: return a def state_already_known(self, state): res = False for i in self.sizes[sum(state.board)]: if self.tree[i].state == state: return True, self.tree[i] if not res: return res # mc = mcts() # mc.load_ai() # current_state = state_awale() # current_state.board = [0, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4] # current_state.player = 1 # state_known = mc.state_already_known(current_state) # print current_state # for n in mc.tree: # print n # print '\n\n\n' # if state_known: # node = state_known[1] # mc.path.append(node) # if node.children == [-1] * 6: # mc.expansion(node) # else: # mc.selection(node) # for n in mc.tree: # print n
from microbit import * def minmax(number, min, max): if number < min: return min elif number > max: return max else: return number while True: if (accelerometer.is_gesture("up")): display.show(Image.ARROW_N) elif (accelerometer.is_gesture("down")): display.show(Image.ARROW_S) elif (accelerometer.is_gesture("right")): display.show(Image.ARROW_W) elif (accelerometer.is_gesture("left")): display.show(Image.ARROW_E) else: display.clear() # start at the centre x = 2 y = 2 accel_x = accelerometer.get_x() accel_y = accelerometer.get_y() if accel_x < -600: x = 0 elif accel_x < -300: x = 1 elif accel_x < 300: x = 2 elif accel_x < 600: x = 3 else: x = 4 if accel_y < -600: y = 0 elif accel_y < -300: y = 1 elif accel_y < 300: y = 2 elif accel_y < 600: y = 3 else: y = 4 x = minmax(accel_x // 450 + 2, 0, 4) y = minmax(accel_y // 450 + 2, 0, 4) # print(accel_x, accel_y) display.set_pixel(x, y, 9) sleep(100) ''' if (abs(accelerometer.get_x()) < 300): display.set_pixel(0, 0, 0) display.set_pixel(1, 0, 0) display.set_pixel(2, 0, 9) display.set_pixel(3, 0, 0) display.set_pixel(4, 0, 0) elif (abs(accelerometer.get_x()) >= 300 and abs(accelerometer.get_x()) < 600): display.set_pixel(0, 0, 0) display.set_pixel(1, 0, 9) display.set_pixel(2, 0, 0) display.set_pixel(3, 0, 9) display.set_pixel(4, 0, 0) elif (abs(accelerometer.get_x()) >= 600 and abs(accelerometer.get_x()) < 800): display.set_pixel(0, 0, 9) display.set_pixel(1, 0, 0) display.set_pixel(2, 0, 0) display.set_pixel(3, 0, 0) display.set_pixel(4, 0, 9) '''
from copy import deepcopy import pdb def is_palindrome(num: int) -> bool: return str(num) == str(num)[::-1] def separate_2_three_digits_number(num: int) -> bool: result = False for i in range(100, 1000): if num % i == 0 and len(str(int(num / i))) == 3: result = True break return result def check(num: int) -> int: result = 0 for n in range(num - 1, 101100, -1): if is_palindrome(n): if separate_2_three_digits_number(n): result = deepcopy(n) break return result t = int(input().strip()) results = [0]*t for a0 in range(t): n = int(input().strip()) results[a0] = check(n) for result in results: print(result)
from os import name import sqlite3 as sq from sqlite3.dbapi2 import Cursor #pasos para usar y manipular una base de datos: # 1) Conectarme # 2) Definir cursor y modificar # 3) Guardar o asigna esa modificación # 4) Cerrar la conexión #conectarme a una base de datos conexion = sq.connect('ejemplo.db') print('Conectado a ejemplo.db') # definir cursor cursor = conexion.cursor() print(cursor) # Modificacion: crear tabla # En MAYUSCULA lo que es fijo y se debe escribir siempre, en minúscula lo que es propio de nosotros cursor.execute('CREATE TABLE IF NOT EXISTS usuarios (id INTEGRER, nombre VARCHAR(100), correo VARCHAR(100), salario INTEGRER)') #para borrar la tabla, se usa DROP TABLE y lo que le sigue es el nombre de la tabla #cursor.execute('DROP TABLE usuarios') #Insertar datos a la tabla usuarios #cursor.execute("INSERT INTO usuarios VALUES (1000644865, 'David Alejandro Gómez', 'gomez.david@uces.edu.co', 200000)") #Leer datos de la tabla # para leer una entrada de la tabla, el asterisco es porque se están leyendo todos los atributos cursor.execute('SELECT * FROM usuarios') usuario = cursor.fetchone() print(usuario) #Leer atributos específicos cursor.execute('SELECT nombre, correo FROM usuarios') usuario = cursor.fetchone() print(usuario) #Para buscar usuarios en particular por diferentes campos #cursor.execute('SELECT * FROM usuarios WHERE nombre = David Alejandro Gómez') usuario = cursor.fetchall() print(usuario) #Guardar los cambios que hicimos conexion.commit() #cerrar conexión: conexion.close() print('Desconectado a ejemplo.db')
import numpy as np data = np.array([1, 2]) ones = np.ones(2, dtype=int) # suma print("suma",data + ones) # resta print("resta",data - ones) # mult print("multiplicación",data * ones) # div print("división",data / ones) # se puede multiplicar todos y cada uno de los elementos por un entero o flotante print("entero",data * 8) print("flotante",data * 4.8) # inicialmente el array era de enteros, con esta operación se hace un casting y genera un array de flotantes # operadores max, min y sum a = np.array([[0.45053314, 0.17296777, 0.34376245, 0.5510652], [0.54627315, 0.05093587, 0.40067661, 0.55645993], [0.12697628, 0.82485143, 0.26590556, 0.56917101]]) print("max",a.max()) # encuentra el máximo de los elementos print("min",a.min()) # encuentra el mínimo de los elementos print("sum",a.sum()) # encuentra la sumatoria de los elementos print("media",a.mean()) # encuentra la media de los elementos
import numpy as np # una manera de crear un array desde una lista a = np.array([1, 2, 3, 4, 5, 6]) # Acceder a posiciones print(a[3]) # o también es posible crear matrices b = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) print(b[2,1]) # crear un array de ceros print(np.zeros(2)) # crear un array de unos print(np.ones(2)) # crear un array vacio, la función empty crea un array con valores aleatorios, los cuales dependen del estado en memoria print(np.empty(7)) # tambien puedo crear arrays desde listas de python print(np.arange(4)) # también puedo indicar el número inicial, final y el paso del array print(np.arange(2, 9, 2))
# escriba un código que transforme una lista de entrada con palabras # en una variable tipo string con las palabras separadas por # espacios. # ejemplo: # entrada: ["Hola", "a", "todos"] # salida: "Hola a todos" # Sol 1 wordsList = ["Hola", "a", "todos"] words = "" for i in wordsList: words = words + i + " " print(words) #print(words[:-1]) # Sol 2 # wordsList = ["Hola", "a", "todos"] # words = "-" # words = words.join(wordsList) # print(words)
# Stacks como listas s = [] s.append("eat") s.append("sleep") s.append("code") print(s) input("Press Enter to continue...") # Extraer último elemento en ingresar le = s.pop() print(le) print(s) input("Press Enter to continue...") # extraer más... s.pop() s.pop() print(s) # Stacks como dequeue (más rápidas y robustas) from collections import deque s = deque() s.append("eat") s.append("sleep") s.append("code") print(s) input("Press Enter to continue...") # Extraer último elemento en ingresar le = s.pop() print(le) print(s) input("Press Enter to continue...") # extraer más... s.pop() s.pop() print(s)
# Creación de diccionario my_dict = {} #empty dictionary print(my_dict) my_dict = {1: 'Python', 2: 'Java'} #dictionary with elements print(my_dict) input("Press Enter to continue...") # Acceder a elementos my_dict = {'First': 'Python', 'Second': 'Java'} print(my_dict['First']) #access elements using keys print(my_dict.get('Second')) input("Press Enter to continue...") # Cambiar un valor my_dict = {'First': 'Python', 'Second': 'Java'} print(my_dict) my_dict['Second'] = 'C++' #changing element print(my_dict) input("Press Enter to continue...") # Adicionar un par key-value my_dict['Third'] = 'Ruby' #adding key-value pair print(my_dict) input("Press Enter to continue...") # Eliminar valores my_dict = {'First': 'Python', 'Second': 'Java', 'Third': 'Ruby'} a = my_dict.pop('Third') #pop element print('Value:', a) print('Dictionary:', my_dict) input("Press Enter to continue...") # Eliminar el último key-value par b = my_dict.popitem() #pop the key-value pair print('Key, value pair:', b) print('Dictionary', my_dict) input("Press Enter to continue...") # Eliminar todos los datos del diccionario my_dict.clear() #empty dictionary print('n', my_dict) input("Press Enter to continue...") # Otras funciones my_dict = {'First': 'Python', 'Second': 'Java', 'Third': 'Ruby'} print(my_dict.keys()) #get keys print(my_dict.values()) #get values print(my_dict.items()) #get key-value pairs print(my_dict.get('First'))
import random N = 3 grid = [['.']*N for _ in range(N)] elements = ['1','2','3','4','5','6','7','8',' '] def clear_grid(): for i in range(N): for j in range(N): grid[i][j] = '.' def set_elements(): z = 0 for i in range(N): for j in range(N): while grid[i][j] == '.': x = random.randint(0, 2) y = random.randint(0, 2) if grid[x][y] == '.': grid[x][y] = elements[z] z +=1 def print_grid(): print('--' + '---' * (N+2) + '--') for i in range(N): for j in range(N): print(end='| ') print(grid[i][j], end=' ') print(end='|') print() print('--' + '---' * (N+2) + '--') def valid_move(i,j,i2,j2): if((abs(i - i2) == 1 and j == j2) or (abs(j - j2) == 1 and i == i2) and (grid[i2][j2] == ' ')): return True return False def valid_index(i,j,i2,j2): if(i >= 0 and i < 3 and i2 >= 0 and i2 < 3 and j >= 0 and j < 3 and j2 >= 0 and j2 < 3): return True return False def move_elements(i,j,i2,j2): grid[i2][j2] = grid[i][j] grid[i][j] = ' ' def check_win(): x = 0 for i in range(N): for j in range(N): if(grid[i][j] != elements[x]): return False x+=1 return True def read_input(i,j,i2,j2): i, j, i2, j2 = map(int, input("Enter a move: ").split()) while(not valid_move(i,j,i2,j2) or not valid_index(i,j,i2,j2)): i, j, i2, j2 = map(int, input("Enter a valid move: ").split()) return i,j,i2,j2 def play(): print("8-puzzle Game") while(True): print() print_grid() i,j,i2,j2 = 0,0,0,0 i,j,i2,j2 = read_input(i,j,i2,j2) move_elements(i,j,i2,j2) if(check_win()): print_grid() print("YOU WIN..!") break while (True): clear_grid() set_elements() play() c = input("Play Again [Y/N]") if not c == 'y' and not c == 'Y': break
from tkinter import * from PIL import ImageTk, Image import string root = Tk() root.title("UEFA EURO 2020") root.iconbitmap("images/football.ico") title = Label(root, text="UEFA EURO 2020 GROUPS") title.grid(row=0, column=0) # store teams and their photos pictures = { "italy": "images/italy.jpeg", "austria": "images/austria.jpg", "belgium": "images/belgium.jpg", "croatia": "images/croatia.jpeg", "czech": "images/czech_republic.jpg", "denmark": "images/denmark.jpg", "england": "images/england.jpg", "finland": "images/finland.jpg", "france": "images/france.jpg", "germany": "images/germany.jpg", "hungary": "images/hungary.jpg", "netherlands": "images/netherlands.jpg", "macedonia": "images/north_macedonia.jpg", "poland": "images/poland.jpg", "portugal": "images/portugal.jpg", "russia": "images/russia.jpg", "scotland": "images/scotland.jpg", "slovakia": "images/slovakia.jpeg", "spain": "images/spain.jpeg", "sweden": "images/sweden.jpg", "switzerland": "images/switzerland.jpeg", "turkey": "images/turkey.jpg", "ukraine": "images/ukraine.jpg", "wales": "images/wales.jpg" } # function for showing teams members def show_picture(team): global my_img new_window = Toplevel(root) new_window.title(team) title = Label(new_window, text=team.upper()) title.grid(row=0, column=0) my_img = ImageTk.PhotoImage(Image.open(pictures[team])) team_photo = Label(new_window, image=my_img) team_photo.grid(row=1, column=0) # Groups group_a = LabelFrame(root, text="Group A") group_b = LabelFrame(root, text="Group B") group_c = LabelFrame(root, text="Group C") group_d = LabelFrame(root, text="Group D") group_e = LabelFrame(root, text="Group E") group_f = LabelFrame(root, text="Group F") group_a.grid(row=1, column=0, sticky=W) group_b.grid(row=2, column=0, sticky=W) group_c.grid(row=3, column=0, sticky=W) group_d.grid(row=4, column=0, sticky=W) group_e.grid(row=5, column=0, sticky=W) group_f.grid(row=6, column=0, sticky=W) # TEAMS # Group A italy = Button(group_a, text="Italy", command=lambda: show_picture("italy")) wales = Button(group_a, text="Wales", command=lambda: show_picture("wales")) switzerland = Button(group_a, text="Switzerland", command=lambda: show_picture("switzerland")) turkey = Button(group_a, text="Turkey", command=lambda: show_picture("turkey")) italy.grid(row=0, column=0) wales.grid(row=0, column=1) switzerland.grid(row=0, column=2) turkey.grid(row=0, column=3) # Group B belgium = Button(group_b, text="Belgium", command=lambda: show_picture("belgium")) denmark = Button(group_b, text="Denmark", command=lambda: show_picture("denmark")) finland = Button(group_b, text="Finland", command=lambda: show_picture("finland")) russia = Button(group_b, text="Russia", command=lambda: show_picture("russia")) belgium.grid(row=0, column=0) denmark.grid(row=0, column=1) finland.grid(row=0, column=2) russia.grid(row=0, column=3) # Group C netherlands = Button(group_c, text="Netherlands", command=lambda: show_picture("netherlands")) austria = Button(group_c, text="Austria", command=lambda: show_picture("austria")) ukraine = Button(group_c, text="Ukraine", command=lambda: show_picture("ukraine")) north_macedonia = Button(group_c, text="North Macedonia", command=lambda: show_picture("macedonia")) netherlands.grid(row=0, column=0) austria.grid(row=0, column=1) ukraine.grid(row=0, column=2) north_macedonia.grid(row=0, column=3) # Group D england = Button(group_d, text="England", command=lambda: show_picture("england")) croatia = Button(group_d, text="Croatia", command=lambda: show_picture("croatia")) czech_republic = Button(group_d, text="Czech Republic", command=lambda: show_picture("czech")) scotland = Button(group_d, text="Scotland", command=lambda: show_picture("scotland")) england.grid(row=0, column=0) croatia.grid(row=0, column=1) czech_republic.grid(row=0, column=2) scotland.grid(row=0, column=3) # Group E sweden = Button(group_e, text="Sweden", command=lambda: show_picture("sweden")) spain = Button(group_e, text="Spain", command=lambda: show_picture("spain")) slovakia = Button(group_e, text="Slovakia", command=lambda: show_picture("slovakia")) poland = Button(group_e, text="Poland", command=lambda: show_picture("poland")) sweden.grid(row=0, column=0) spain.grid(row=0, column=1) slovakia.grid(row=0, column=2) poland.grid(row=0, column=3) # Group F france = Button(group_f, text="France", command=lambda: show_picture("france")) germany = Button(group_f, text="Germany", command=lambda: show_picture("germany")) portugal = Button(group_f, text="Portugal", command=lambda: show_picture("portugal")) hungary = Button(group_f, text="Hungary", command=lambda: show_picture("hungary")) france.grid(row=0, column=0) germany.grid(row=0, column=1) portugal.grid(row=0, column=2) hungary.grid(row=0, column=3) root.mainloop()
import re text = input() phone_num_regex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') found = phone_num_regex.findall(text) print(found) text = input() bat = re.compile(r'Bat(man|mobile|copter|bat|women)') mo = bat.search(text) print(mo.group())
def starts(): print("Jay Ganesh") print("jay Ganesh") print("jay Ganesh") print("jay Ganesh") def startsI(): icnt=1; while icnt<=5: print("Jay Ganesh") icnt=icnt+1 def main(): print("sequence approach") starts() print("Iteration approach") startsI() if __name__=="__main__": main()
# object orientation in python class Arithematic: # class definition value = 111 # class variable or static variable in c cpp def __init__(self, i, j): # class constructor self.no1 = i # class instance variable self.no2 = j # class instance variable def add(self): # instance method return self.no1+self.no2 def sub(self): # instance method return self.no1-self.no2 def main(): print("value ", Arithematic.value) obj1 = Arithematic(11, 21) # __init__(obj1,11,21) obj2 = Arithematic(100, 50) # __init__(obj2,100,50) ret = obj1.add() # ret=add(obj1) print("addition is:", ret) ret = obj1.sub() # ret=sub(obj1) print("sub is", ret) ret = obj2.add() # ret=add(obj2) print("addition is:", ret) ret = obj2.sub() # ret=sub(obj2) print("sub is", ret) if __name__ == "__main__": main()
#import Arithmetic -----------first Way #import Arithmetic as AR -----------second way #from Arithmetic import Addition,Substraction -------third way from Arithmetic import * #----fourth way def main(): print("__name__ from main is",__name__) print("Enter the first number") value1=int(input()) print("enter second number") value2=int(input()) #ret1=Arithmetic.Addition(value1,value2) -----first way #ret2=Arithmetic.Substraction(value1,value2) #ret1 = AR.Addition(value1, value2) ------second way #ret2=AR.Substraction(value1,value2) #ret1 = Addition(value1, value2) -------third way #ret2=Substraction(value1,value2) ret1 = Addition(value1, value2) #------fourth way ret2=Substraction(value1,value2) print("Addition is",ret1) print("Subtraction is",ret2) #code starter if __name__=="__main__": main()
#add 2 Numbers a = int(input("Enter the First Number :")) b = int(input("Enter the Second Number :")) c = a + b print("The Sum of Two Numbers : ",c)
#Write a program to use split and join methods in the string a="hi, i am python programmer" b=a.split() print (b) c=" ".join(b) print (c)
#Max of two Numbers a = int(input("Enter the First Number :")) b = int(input("Enter the Second Number :")) c = int(input("Enter the third Number :")) if a>=b: if a>=c: print("Greatest Number :",a) else: print("Greatest Number :",c) else: if b>=c: print("Greatest Number :",b) else: print("Greatest Number :",c)
# Calc Grade Of Student for 5 Subjects Marks def calcgrade(m): if((m >= 85) and (m <= 100)): return "AA" elif ((m >= 75) and (m < 85)): return "AB" elif ((m >= 65) and (m <= 75)): return "BB" elif ((m >= 55) and (m < 65)): return "BC" elif ((m >= 45) and (m < 55)): return "CC" elif ((m >= 40) and (m < 45)): return "CD" elif ((m >= 36) and (m < 40)): return "DD" else: return "FF" m1 = int(input("Enter the Subject 1 Marks : ")) m2 = int(input("Enter the Subject 2 Marks : ")) m3 = int(input("Enter the Subject 3 Marks : ")) m4 = int(input("Enter the Subject 4 Marks : ")) m5 = int(input("Enter the Subject 5 Marks : ")) print("------------------------------------------------") print("Grade of Subject 1 : ", calcgrade(m1)) print("Grade of Subject 2 : ", calcgrade(m2)) print("Grade of Subject 3 : ", calcgrade(m3)) print("Grade of Subject 4 : ", calcgrade(m4)) print("Grade of Subject 5 : ", calcgrade(m5))
''' A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects. ''' #Import the datetime module and display the current date import datetime x = datetime.datetime.now() #date contains year, month, day, hour, minute, second, and microsecond print(x) print(x.year) #year ''' To create a date, we can use the datetime() class of the datetime module. The datetime() class requires three parameters to create a date: year, month, day. ''' y = datetime.datetime(2020, 5, 29) #timezone - default value 0 print(y)
# perform Linear Search a = flag=0 items = [5, 7, 10, 12, 15] print("list of items is", items) x = int(input("enter item to search:")) while a < len(items): if items[a] == x: flag = 1 break a = a + 1 if flag == 1: print("item found at position:", a + 1) else: print("item not found") # print('----how to take a list from user') # a=[] # for i in range(5): # a.append(input()) # print(a)
# function which takes result of 10 students and give top 3 l = [23,45,22,44,32,13,24,34,41,19] def top3(l): l.sort(reverse=True) #x = l return l print(top3(l)[:3]) ''' l = [23,45,22,44,32,13,24,34,41,19] for i in range(0,50,10): print(i) '''
# Print Factors of Given Number import math n = int(input("Enter a Number Whose Factors Needs to Be Found : ")) # Approach 1 : 1 to n and if remainder 0 print it # k = 1 # ans = [] # while(k <= n): # if((n % k) == 0): # ans.append(k) # k = k+1 # for i in ans: # print(i, end=" ") # Approach 2 : 1 to sqrt(n) if remainder 0 print both factors(check if not equal as well) k = 1 ans = [] while(k <= math.sqrt(n)): if((n % k) == 0): if(k != (n/k)): ans.append(k) ans.append(int(n/k)) else: ans.append(k) k = k+1 ans.sort() for i in ans: print(i, end=" ")
# Write a python program that combines two lists into a dictionary. test_keys_list = ["Ram", "Shyam", "Ghanshyam"] test_values_list = [3, 11, 29] # Printing original keys-value lists print("Original key list is : ", test_keys_list) print("Original value list is : ", test_values_list) dict1 = {} # Empty Dictionary for key in test_keys_list: for value in test_values_list: dict1[key] = value test_values_list.remove(value) break print("Resultant dictionary is : ", dict1) # Printing resultant dictionary # METHOD 2 # combines lists into a dictionary & zip function working # subjects=['ENG','M1','M3','CP','PHY','CHE'] # marks=[85,90,91,95,84,87] # z=zip(subjects, marks) # print(z) # d=dict(z) # print (d)
#find the maximum from a list of numbers l=[] n=int(input("enter the size of list: ")) for i in range(0,n): a=int(input("enter number: ")) l.append(a) maxno=l[0] for i in range(0,len(l)): if l[i]>maxno: maxno=l[i] print("The maximum number is: %d"%maxno)
nome = str(input('Qual é o seu nome? ')).strip() if nome.title() == 'Thiago': print('Que nome bonito!') elif nome.title() == 'Isabella': print('Você é uma delícia hein!') elif nome.title == 'Manuella': print('Que princesinha linda!') elif nome.title() == 'Miguel': print('Bonitão, malucole!') elif nome.title() in 'Ana Cláudia Jéssica Juliana': print('Mulheres...') print('Tenha um bom dia, {}'.format(nome.title()))
carro = int(input('Digite a que velocidade está o carro: ')) if carro > 80: multa = (carro - 80) * 7 print('VOCÊ FOI MULTADO! O valor da MULTA é de R$ {:.2f}'.format(multa)) else: print('Sua velocidade está boa, PARABÉNS!')
p = float(input('Digite o valor do produto: R$ ')) print('Escolha a forma de pagamento:') fp = int(input('''Digite: [1] - À vista dinheiro/cheque: 10% de desconto [2] - À vista no cartão: 5% de desconto [3] - Em até 2x no cartão: preço normal [4] - Em 3x ou mais no cartão: 20% de juros sua opção: ''')) if fp == 1: print('Opção [1] selecionada, o valor final é R$ {:.2f}'.format(p - (p * 10 / 100))) elif fp == 2: print('Opção [2] selecionada, o valor final é R$ {:.2f}'.format(p - (p * 5 /100))) elif fp == 3: print('Opção [3] selecionada, são 2 parcelas de R$ {:.2f}, o valor final é R$ {:.2f}'.format(p/2, p)) elif fp == 4: x = int(input('Quantas vezes?: ')) print('Opção [4] selecionada, serão {} parcelas de R$ {:.2f},o valor final é R$ {:.2f}'.format(x, (p + (p * 20 / 100)) / x, p + (p * 20 / 100))) else: print('Opção inválida, tente novamente!')
maior = 0 for c in range (1, 6): peso = float(input('Digite o peso da {} pessoa: '.format(c))) if peso > maior: maior = peso if c == 1 : menor = peso if peso < menor: menor = peso print('O maior peso foi {:.1f}kg e o menor foi {:.1f}kg'.format(maior, menor))
n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a segunda nota: ')) m = (n1 + n2)/2 if m < 5: print('Aluno \033[41mREPROVADO!\033[m') elif 7 > m >= 5: print('Aluno em \033[43;30mRECUPERAÇÃO!\033[m') else: print('Aluno \033[42;30mAPROVADO!\033[m')
dinheiro = float(input('Quanto de dinheiro tem em sua carteira?: ')) print('Você pode comprar {:.2f} doláres!'.format(dinheiro / 3.27))
tupla = (int(input('Digite um número: ')), int(input('Digite outro número: ')), int(input('Digite mais outro número: ')), int(input('Digite o último número: '))) print(tupla)
frase = 'Curso em vídeo Python' #.Fatiamento print('-'*13) print('{:^13}'.format('Fatiamento')) print('-'*13) print(frase[9:13]) print(frase[9:21]) print(frase[9:21:2]) print(frase[:5]) print(frase[15:]) print(frase[9::3]) print(frase[::2]) print() #.Análise print('-'*13) print('{:^13}'.format('Análise')) print('-'*13) print(len(frase)) print(frase.count('o')) print(frase.count('o',0,13)) print(frase.find('deo')) print(frase.find('Android')) print('Curso' in frase) print() #.Transformação print('-'*13) print('{}'.format('Transformação')) print('-'*13) print(frase.replace('Python','Android')) print(frase.upper()) print(frase.lower()) print(frase.capitalize()) print(frase.title()) frase = ' Aprenda Python ' print() print(frase) print(frase.strip()) print(frase.rstrip()) print(frase.lstrip()) print() frase = 'Curso em vídeo Python' print('-'*13) print('{:^13}'.format('Divisão')) print('-'*13) print(frase.split()) print('-'.join(frase)) print('''Olá, escrevendo 3 aspas eu posso digitar um texto longo e posso pular a linha viu? sem ter que colocar outro print''') print()
'''num = [2, 5, 9, 1] num[2] = 3 num.append(7) num.sort(reverse=True) num.insert(2, 2) if 5 in num: num.remove(5) # varre do ínicio da lista ao final e remove o primeiro valor do indice else: print('Não achei o número 5') print(num) print(f'Essa lista tem {len(num)} elementos.') ''' '''valores = []''' '''valores.append(5) valores.append(9) valores.append(4) ''' '''for cont in range(0, 5): valores.append(int(input(f'Digite o {cont + 1}º valor: '))) for p, v in enumerate(valores): print(f'Na posicação {p}, encontrei o valor {v}') print('Acabou a lista') ''' a = [2, 3, 4, 7] # b = a <- assim eu crio uma ligação b = a[:] # assim eu faço uma cópia da lista b[2] = 8 print(f'Lista a: {a}') print(f'Lista b: {b}')
print('THE 10 TERMS OF AN A.P.') print('<><><><><><><><><><><><>') i = int(input('Digite o primeiro termo da P.A. : ')) r = int(input('Digite a razão da P.A. : ')) c = 1 t = i d = 10 counter = d answer = False while answer is False: while c <= d: if c < d: print('{} → '.format(t), end='') elif c == d: print(t) c += 1 t += r d = int(input('How many more terms do you want to see?: ')) c = 1 counter += d if d == 0: answer = True print('Finished! It was showed {} terms of an A.P.'.format(counter)) print('Thanks, good bye!')