text
stringlengths
37
1.41M
"""Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you? You are given a system of equations:""" """You are given a system of equations: a**2 + b = n a + b**2 = m; You should count, how many there are pairs of integers (a, b) (0 ≤ a, b) which satisfy the system.""" """First method""" n, m = map(int, input().split()) if (m + n) < 10: x = (m + n) ** 2 else: x = max(n, m) a = -1 b = 0 count = 0 for i in list(range(x)): if a ** 2 + b == n and a + b ** 2 == m: a += 1 else: a += 1 for j in list(range(x)): if a ** 2 + b == n and a + b ** 2 == m: count += 1 b += 1 else: b += 1 b = 0 print(count) """Second method""" n, m = map(int, input().split()) if (m + n) < 10: x = (m + n) ** 2 else: x = max(n, m) a = 0 b = 0 count = 0 for i in list(range(x)): for j in list(range(x)): if a ** 2 + b == n and a + b ** 2 == m: count += 1 b += 1 else: b += 1 a += 1 b = 0 print(count)
import os from src.config import ( logging, DEFAULT_FILE_NAME ) class City: """ Can be destroyed, has a name and links """ def __init__(self, name): self.name = name self.links = {} def get_directions(self): """ Available links - remember these can be blown away! """ return self.links def remove_city_from_directions(self, citySearch): self.links = {k: v for k, v in self.links.items() if not citySearch == v} def destroy(self): self.links = {} def is_destroyed(self): return len(self.links) == 0 def load_map(): """ You should create a program that reads in the world map """ map_world_list = [] """ Assumptions: o Always use the = sign to split o Data is formatted as in world_map_small o No control/newline characters peppered through lines """ INPUT_FILE_NAME= os.getenv('FILE_NAME', DEFAULT_FILE_NAME) with open(INPUT_FILE_NAME) as mapFile: for entry in mapFile: tmpCity = City(entry.split(' ', 1)[0]) # Extract the location links and wire them up for our city locations = entry.split(' ', 1)[1] for direction in locations.split(" "): # What a line - this creates our hashmap of direction to city tmpCity.links[direction.split("=")[0].lower()] = \ direction.split("=")[1].strip() map_world_list.append(tmpCity) logging.debug(f"Created {len(map_world_list)} city entries") return map_world_list def display_map(map_list): for city in map_list: if city.is_destroyed(): continue result = city.name + " " # The order should match that of the input # Exceptions are cheaper than tests in Python so use that try: location = city.get_directions()["north"] result = result + "north=" + location + " " except KeyError: pass try: location = city.get_directions()["south"] result = result + "south=" + location + " " except KeyError: pass try: location = city.get_directions()["east"] result = result + "east=" + location + " " except KeyError: pass try: location = city.get_directions()["west"] result = result + "west=" + location + " " except KeyError: pass print(result)
import numpy as np def hist_match(after, before): """ Normalisation of images based on histogram matching to the before image. Input: ----------- after: np.ndarray Image to transform; the histogram is computed over the flattened array before: np.ndarray Template image; can have different dimensions to source Returns: ----------- matched: np.ndarray The transformed after image """ imgsize = after.shape #retrieve array size flata = after.ravel() #flatten input array flatb = before.ravel() #flatten reference array # get the set of unique pixel values and their corresponding indices and # counts a_values, bin_idx, a_counts = np.unique(flata, return_inverse=True, return_counts=True) b_values, b_counts = np.unique(flatb, return_counts=True) # take the cumulative sum of the counts and normalise by the number of pixels # to get the empirical CDF for the after and before images a_quantiles = np.cumsum(a_counts).astype(np.float64) a_quantiles /= a_quantiles[-1] b_quantiles = np.cumsum(b_counts).astype(np.float64) b_quantiles /= b_quantiles[-1] # linear interpolation of pixel values in the before image # to correspond most closely to the quantiles in the source image interp_b_values = np.interp(a_quantiles, b_quantiles, b_values) return interp_b_values[bin_idx].reshape(imgsize)
""" Toy game for explaining how to work with POMDPs Copied from: https://github.com/yandexdataschool/Practical_RL/blob/master/week7/rockpaperscissors.py """ import gym from gym import spaces from gym.utils import seeding import numpy as np class RockPaperScissors(gym.Env): """ Rock-paper-scissors game against an imperfect adversary. Your opponent operates in sequences of 3-7 actions. There are 5 such pre-defined sequences. Once enemy finishes his current sequence, he picks next one at random from 5 pre-defined sequences. Your observation is enemy's last turn: - [1,0,0] for rock - [0,1,0] for paper - [0,0,1] for scissors This game is a toy environment to play with recurrent networks in RL. """ # codes of rock, papes and scissors respectively codes = np.eye(3) # list of possible sequences sequences = ( (0, 1, 2, 0, 1, 2), (1, 0, 0, 1, 1), (2, 2, 2), (2, 2, 1, 1, 0, 0), (0, 0, 1, 2, 1, 0, 0) ) # reward for [i-th] action against [j-th] enemy reaction reward = ( # r p s (0, -1, 1), # r (1, 0, -1), # p (-1, 1, 0), # s ) def __init__(self): self.action_space = spaces.Discrete(3) self.observation_space = spaces.Box(0, 1, 3) self.reset() def get_observation(self): return self.codes[self.current_sequence[self.current_position]] def new_sequence(self): self.current_sequence = np.random.choice(self.sequences) self.current_position = 0 ###public methods def reset(self): self.new_sequence() return self.get_observation() def step(self, action): assert self.action_space.contains(action) self.current_position += 1 if self.current_position >= len(self.current_sequence): self.new_sequence() enemy_action = self.current_sequence[self.current_position] reward = self.reward[action][enemy_action] return self.get_observation(), reward, False, {} def render(*args, **kwargs): return 0
# coding=utf-8 """ 题目描述 有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子, 假如兔子都不死,问每个月的兔子总数为多少? /** * 统计出兔子总数。 * * @param monthCount 第几个月 * @return 兔子总数 */ public static int getTotalCount(int monthCount) { return 0; } 本题有多组数据,请使用while (cin>>)读取 输入描述: 输入int型表示month 输出描述: 输出兔子总数int型 示例1 输入 复制 9 输出 复制 34 """ # 相当于求 1 1 2 3 5 8 13 # 后一个月等于前两个月之和 while True: try: month = int(input()) a, b = 1, 0 for i in range(month): a, b = b, a + b print(b) except: break
# coding=utf-8 """ 题目描述 将一个字符中所有出现的数字前后加上符号“*”,其他字符保持不变 public static String MarkNum(String pInStr) { return null; } 注意:输入数据可能有多行 输入描述: 输入一个字符串 输出描述: 字符中所有出现的数字前后加上符号“*”,其他字符保持不变 示例1 输入 复制 Jkdi234klowe90a3 输出 复制 Jkdi*234*klowe*90*a*3* """ # 将数字周围都加上* 两个数字中间肯定有两个** 然后替换掉就行了 # 正则 sub + lambda 替换,非常简单 import re while 1: try: s = input() a = re.sub('\d+', lambda x: x.group(0).replace(x.group(0), f'*{x.group(0)}*'), s) print(a) except: break # 方法二 import re while 1: try: print(re.sub('(\d+)', '*\g<1>*', input())) except: break
""" 题目描述 计算字符串最后一个单词的长度,单词以空格隔开。 输入描述: 一行字符串,非空,长度小于5000。 输出描述: 整数N,最后一个单词的长度。 示例1 输入 复制 hello world 输出 复制 5 """ # split 分割 # -1 取最后一个 # len 求长度 while 1: try: print(len(input().split()[-1])) except: break
""" 题目描述 描述: 输入一个整数,将这个整数以字符串的形式逆序输出 程序不考虑负数的情况,若数字含有0,则逆序形式也含有0,如输入为100,则输出为001 输入描述: 输入一个int整数 输出描述: 将这个整数以字符串的形式逆序输出 示例1 输入 复制 1516000 输出 复制 0006151 """ # 把输入的数字当成字符串处理 # [::-1] 倒序 while 1: try: print(input()[::-1]) except: break
def quicksort(A, i, j, calculator): if i>=j: return calculator else: q, calculator=partition(A, i, j, calculator) calculator=quicksort(A, i, q-1, calculator) calculator=quicksort(A, q+1, j, calculator) return calculator def partition(A, left, right, calculator): pivot=A[right] i=left for j in range(left, right): calculator+=1 if A[j] <= pivot: A[i],A[j]=A[j],A[i] i+=1 else: continue A[right], A[i] = A[i], A[right] return i, calculator file=open('QuickSort.txt') words=file.readlines() numbers=[] for num in words: n=num.rstrip('\n') numbers.append(int(n)) count=quicksort(numbers, 0, len(numbers)-1, 0) print(numbers) print(count) a=[3,6,4,1,5,2] quicksort(a, 0, 5, 0) print(a)
""" Stock Pricing Problem: A competition model between two companies. """ from matplotlib import pyplot def company_a(x, y): a = 0.222 b = -0.0011 return a*x + b*x*y def company_b(x, y): c = -1.999 e = 0.010 return c*y + e*x*y def euler(step, start, end, initial_values, diffs): """ Euler method for two variable dependent differentials. """ outputs = [] #base base_x = initial_values[0] - step * diffs[0](initial_values[0], initial_values[1]) base_y = initial_values[1] - step * diffs[1](initial_values[0], initial_values[1]) outputs.append((base_x, base_y)) while start < end: tup = outputs[-1] x = tup[0] - step * diffs[0](tup[0], tup[1]) y = tup[1] - step * diffs[1](tup[0], tup[1]) outputs.append((x,y)) start += step return outputs #results outputs = euler(.0001, 0, 10, (199,21), (company_a,company_b)) x = [output[0] for output in outputs] y = [output[1] for output in outputs] #fist instance y>=x for output in outputs: if output[0]<output[1]: print 'y>=x:', output break #phase plot pyplot.title('Phase Diagram') pyplot.ylabel('y') pyplot.xlabel('x') pyplot.plot(x,y) pyplot.show()
import math import random from matplotlib import pyplot def f(x, mean=1, deviation=.25): exponent = - float((x-mean)**2)/(2*deviation**2) devisor = math.sqrt(2*math.pi*deviation**2) return 1/devisor * math.e**exponent initial_value = 1000000 days = [n for n in range(260)] values = [random.uniform(-initial_value,initial_value) for n in range(260)] results = [] for value in values: prob = random.uniform(0,1) if prob>f(value): initial_value = initial_value+value results.append(initial_value) pyplot.plot(days,results) results = [] for value in values: prob = random.uniform(0,1) if prob>f(value,mean=0,deviation=.5): initial_value = initial_value+value results.append(initial_value) pyplot.plot(days,results) pyplot.show() """ info: The stocks follow these trends because of the probability distribution that determines how likely the price of the stock will change within the future. run: python epi_stock.py """
import sys import exercise_2_1 def exercise(width:int = 8) -> None: """ Print a diamond Params: width -> The max width of the diamond (is even) Example > exercise(8) ## #### ###### ######## ######## ###### #### ## """ spaces:int = (width // 2) - 1 characters = 2 while characters <= width: print(f"{spaces * ' '}{characters * '#'}") spaces -= 1 characters += 2 exercise_2_1.exercise(width) if __name__ == "__main__": if len(sys.argv) <= 1: exercise() else: exercise(int(sys.argv[1]))
import sqlite3 import urllib.request from bs4 import BeautifulSoup import re #import ssl # Deal with SSL certificate anomalies Python > 2.7 #scontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1) scontext = None # 1. Elegir una página web. # 2. Extraer el texto de esa página. # 3. Dividirlo en palabras. # 4. Quitar las palabras no válidas (números, artículos, etc.). # 5. Guardar cada palabra y el número de veces que ha salido. conn = sqlite3.connect("webdata.sqlite") cur = conn.cursor() cur.execute(""" CREATE TABLE IF NOT EXISTS webs (ID INTEGER PRIMARY KEY, url TEXT UNIQUE, content TEXT) """) #url = input("Enter url to feed webdata (or just ENTER to exit): ") ##if len(url)<1: exit() #if len(url)<1: url = "https://www.deutschland.de/de/topic/politik/deutschland-europa/jahresvorschau-2017" url = "http://www.faz.net/aktuell/wirtschaft/unternehmen/deutsche-bahn-auf-chef-suche-alles-hoert-auf-kein-kommando-14844033.html" print ("web target is", url) pass # check url is correct and exists web = urllib.request.urlopen(url).read() #decode.('utf8') probar print ("01 - TEXTO BRUTO EN BINARIO -----------------------------------------------------------") print (web) soup = BeautifulSoup(web, "html.parser") # Quita el texto que haya dentro de las etiquetas <script> (código javascript) y <style> (Estilos CSS). # Ninguno de esos textos nos interesa. for script in soup(["script", "style"]): script.extract() dataText = soup.get_text() text = str(dataText) print ("02 - TEXTRO EXTRAIDO CON BEAUTIFULSOUP EN STRING ------------------------------------------") print (text) textClean = text.split() print ("03 - LISTA DE PALABRAS EXTRAIDAS CON METODO SPLIT--------------------------------------------") print (textClean) #words = re.findall(" ([^AB]+) ", dataText) #print (words) #dataText.split() #print (dataText) # Mejor solución: http://stackoverflow.com/questions/1936466/beautifulsoup-grab-visible-webpage-text #tags = soup.find_all("p") #for tag in tags: #print (soup.get_text()) # texts = soup.findAll(text=True) # print(texts)
def my_global_function(a,b): """Global Function. return a+b""" return a + b try: None.some_method_none_does_not_know_about() except Exception as ex: ex2 = ex print(ex2.args[0]) print(ex2.__class__) count_of_three = (1, 2, 5) try: count_of_three[2] = "three" except TypeError as ex: msg = ex.args[0] print(msg) locations = [ ("Illuminati HQ", (38, 52, 15.56, 'N'), (77, 3, 21.46, 'W')), ("Stargate B", (41, 10, 43.92, 'N'), (1, 49, 34.29, 'W')), ] print(locations[0][1][2]) try: my_global_function(1, 2, 3) except Exception as e: msg = e.args[0] print(msg) def whhile(): i = 1 result = 1 while i <= 10: result = result * i i += 1 return result def whhile2(): i = 0 result = [] while i < 10: i += 1 if (i % 2) == 0: continue result.append(i) return result print(whhile()) print(whhile2()) round_table = [ ("Lancelot", "Blue"), ("Galahad", "I don't know!"), ("Robin", "Blue! I mean Green!"), ("Arthur", "Is that an African Swallow or Amazonian Swallow?") ] result = [] for knight, answer in round_table: result.append("Contestant: '" + knight + "' Answer: '" + answer + "'") print(knight + ": " + answer + "\n") print(result)
#just like Models, forms are classes in Django from django import forms #validator to validate data from django.core import validators #most of the time we use a form to generate some HTML class SuggestionForm(forms.Form): #we have three fields currently name = forms.CharField() email = forms.EmailField() #so that we verify both emails are correct verify_email = forms.EmailField(label='verify email') #the widget is how the thing is represented to HTML suggestions = forms.CharField(widget=forms.Textarea) #this will help us prevent from submissions of the form by bots #there will be a hidden input, an invisibe field, normally called honey pot and if anything #is in that honeypot, then it is likely that it is a bot. so it will not submit the view #this field is not required, and is hidden (we want the field to be blankable - no one should #fill it up). The label attribute is for humans, that if they see it by any chance, #they know to leave it empty #we will see three step to do this: #1 #honeypot = forms.CharField(required=False, widget=forms.HiddenInput, label='Leave Empty') #now when django calls the is_valid(), it runs through every single field, and looks for functions #such as clean_nameOfTheField in the form (such that clean_name(), clean_email()). If it doesnt #find the function, it does the cleaning itself. #here, we overide the cleaning method for one individual field. This will be the method called #when is_vaild() is called by Django to clean the fields. """ def clean_honeypot(self): honeypot = self.cleaned_data['honeypot'] if len(honeypot): #if there is something in the honeypot, which shouldn't be - raise forms.ValidationError('honeypot should be left empty. Bad bot!') return honeypot #then we send back the field itself, no matter what """ #note that the above method to use honeypot is not the best way because we have to repeat the #function again if we want another field to be validated for any bot attacks #so we will use validator to validate data: #2 honeypot = forms.CharField(required=False, widget=forms.HiddenInput, label='Leave Empty', validators=[validators.MaxLengthValidator(0)]) #all of above methods lets us validate single field at a time #so for validating every single field in the form, we use form's clean method #this clean method is for entire form, not just a single field #also, other validation could go in the clean method too. def clean(self): #gets all the cleaned data cleaned_data = super().clean() email = cleaned_data['email'] # or cleaned_data.get('email') verify = cleaned_data['verify_email'] if email != verify: raise forms.ValidationError('Both email should match!') #we dont need to return anything from the 'clean()' method
#!/usr/bin/env python3 import sys encodingMap = { '0': ':SeriousSloth:', '1': ':panik:' } inputString = sys.stdin.read() decodedString = '' # empty string of decoded bits bits = '' while True: # try to find both symbols in the string # the closer one represents the next bit nearest = None minDistance = len(inputString) for key in encodingMap.keys(): # search for the substring distance = inputString.find(encodingMap[key]) if (distance != -1) and (distance < minDistance): minDistance = distance nearest = key if nearest is None: break bits += nearest newStart = minDistance + len(encodingMap[nearest]) inputString = inputString[newStart:] while len(bits) >= 8: # read the first 8 characters and convert them into integer byte = int(bits[:8], 2) # delete the first 8 characters from the string bits = bits[8:] decodedString += chr(byte) print(decodedString)
f=open('bank_analysis.txt',"a") import pandas as pd data_file = "budget_data.csv" data_file_df = pd.read_csv(data_file) data_file_df.head() count = data_file_df.shape[0] count total = data_file_df["Profit/Losses"].sum() total AccountChange = data_file_df["Profit/Losses"].diff() AccountChange data_file_df["diff"] = AccountChange data_file_df.head() average = AccountChange.mean() averagemean = round(average,2) averagemean maxvalue = AccountChange.max() maxvalue minvalue = AccountChange.min() minvalue GreatestIn = data_file_df[data_file_df['diff']==maxvalue] GreatestIn data_file_df.iloc[25,0] SmallestIn = data_file_df[data_file_df['diff']==minvalue] SmallestIn data_file_df.iloc[44,0] print("Financial Analysis", file=f) print("_ _ _ _ _ _ _ _ _ _ _ _ _", file=f) print("Total Months: ", count, file=f) print("Total: ", total, file=f) print("Average Change: ", averagemean, file=f) print("Greatest Increase in Profits: ", data_file_df.iloc[25,0], maxvalue,file=f) print("Greatest Decrease in Profits: ", data_file_df.iloc[44,0], minvalue, file=f) f.close()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 29 06:38:32 2018 @author: Jake """ import itertools items = [1, 2, 3, 4] powerset = [x for length in range(len(items)+1) for x in itertools.combinations(items, length)] from itertools import chain, combinations def Powerset(iterable): s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) test = [1,2,3,4,5] Powerset(test)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 22 09:01:02 2017 @author: Jake """ class Weird(object): def __init__(self, x, y): self.y = y self.x = x def getX(self): return x def getY(self): return y class Wild(object): def __init__(self, x, y): self.y = y self.x = x def getX(self): return self.x def getY(self): return self.y X = 7 Y = 8 print('\nstart') print('\n1.') w1 = Weird(X, Y) #print(w1.getX()) print('\n2.') #print(w1.getY()) print('\n3.') w2 = Wild(X, Y) print(w2.getX()) print('\n4.') print(w2.getY()) print('\n5.') w3 = Wild(17, 18) print(w3.getX()) print('\n6.') print(w3.getY()) print('\n7.') w4 = Wild(X, 18) print(w4.getX()) print('\n8.') print(w4.getY()) print('\n9.') X = w4.getX() + w3.getX() + w2.getX() print(X) print('\n10.') print(w4.getX()) print('\n11.') Y = w4.getY() + w3.getY() Y = Y + w2.getY() print(Y) print('\n12.') print(w2.getY())
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 13 06:23:07 2017 @author: Jake """ def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. ''' secretWordDict = {} guessed = {} #will eventually need to change this to lettersGuessed blankSecretWord = list('_' * len(secretWord)) for i in secretWord: secretWordDict[i] = i # print(secretWordDict) for letter in lettersGuessed: # print('letter =',letter) # print('guessed =',guessed) if letter in secretWord and letter not in guessed: secretWordDict.pop(letter) # print(secretWordDict) for j in range(len(secretWord)): if secretWord[j] == letter: blankSecretWord[j] = letter # print(' '.join(blankSecretWord)) elif letter in guessed: # print("Oops, you've already guessed",letter) pass guessed[letter] = letter # if secretWordDict == {}: # return True # else: # return False return ' '.join(blankSecretWord) secretWord = 'apple' lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's'] print(getGuessedWord(secretWord, lettersGuessed))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 2 06:58:26 2018 @author: Jake """ # import NumPy into Python import numpy as np # Create a 1000 x 20 ndarray with random integers in the half-open interval [0, 5001). X = np.random.randint(5001, size = (1000, 20)) # print the shape of X print('X:', X) # Average of the values in each column of X ave_cols = np.average(X, axis = 0) # Standard Deviation of the values in each column of X std_cols = np.std(X, axis = 0) # Print the shape of ave_cols print('ave_cols shape:', ave_cols.shape) # Print the shape of std_cols print('std_cols shape:', std_cols.shape) # Mean normalize X X_norm = (X - ave_cols) / std_cols # Print the average of all the values of X_norm print('Average of X_norm: ', round(np.average(X_norm), 4)) # Print the average of the minimum value in each column of X_norm print('Average of Min:', np.amin(X_norm, axis = 0) / X.shape[0]) # Print the average of the maximum value in each column of X_norm print('Average of Max:', np.amax(X_norm, axis = 0) / X.shape[0]) ######################### #### Data Separation #### ######################### # Create a rank 1 ndarray that contains a random permutation of the row indices of `X_norm` row_indices = np.random.permutation(X.shape[0]) # Create a Training Set X_train = X[row_indices[0 : int(X.shape[0] * 0.6)]] # Create a Cross Validation Set X_crossVal = X[row_indices[int(X.shape[0] * 0.6) : int(X.shape[0] * 0.8)]] # Create a Test Set X_test = X[row_indices[int(X.shape[0] * 0.8) : X.shape[0]]] # Print the shape of X_train print('X_train shape:', X_train.shape) # Print the shape of X_crossVal print('X_crossVal shape:', X_crossVal.shape) # Print the shape of X_test print('X_test shape:', X_test.shape)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 16 10:00:45 2018 @author: Jake """ import random def stochasticNumber(): ''' Stochastically generates and returns a uniformly distributed even number between 9 and 21 ''' num = random.randint(9,21) if num % 2 == 0: return num else: return stochasticNumber() print(stochasticNumber())
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 21 06:39:20 2017 @author: Jake """ def odd(x): ''' x: int returns: True if x is odd, False otherwise ''' # Your code here return(x%2 == 1)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jul 14 07:35:21 2018 @author: Jake """ # prerequisite package imports import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sb fuel_econ = pd.read_csv('fuel_econ.csv') #print(fuel_econ.head(5)) #TODO: Task 1: Plot the distribution of combined fuel mileage (column 'comb', in miles per gallon) by manufacturer (column 'make'), for all manufacturers with at least eighty cars in the dataset. Consider which manufacturer order will convey the most information when constructing your final plot. Hint: Completing this exercise will take multiple steps! Add additional code cells as needed in order to achieve the goal. #make_counts = fuel_econ.groupby('make')['comb'].value_counts() #make_counts = [x for x in fuel_econ['make'].value_counts() if x > 80] #print(make_counts) #sb.countplot(data = fuel_econ, x = 'VClass', hue = 'fuelType') #order = (fuel_econ['make'].value_counts() > 80) # #index_end = (order).sum() # #print(index_end) # #sb.countplot(data = fuel_econ[:index_end], x = 'VClass', hue = 'fuelType') # #test1 = fuel_econ.loc[fuel_econ['fuelType'].isin(['Premium Gasoline','Regular Gasoline'])] make_counts = fuel_econ['make'].value_counts() categories = make_counts[make_counts > 80].index fuel_econ_sub = fuel_econ.loc[fuel_econ['make'].isin(categories)] # #fType = fuel_econ.loc[fuel_econ['fuelType'].isin(['Premium Gasoline', 'Regular Gasoline'])] # #sb.countplot(data = fuel_econ_sub, x = 'VClass', hue = fType) grid = sb.FacetGrid(data = fuel_econ, col = 'make') grid.map(plt.hist, 'comb')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jul 19 06:04:35 2018 @author: Jake """ # Makes Python package NumPy available using import method import numpy as np # Creates matrix t (right side of the augmented matrix). t = np.array([4, 11]) # Creates matrix vw (left side of the augmented matrix). vw = np.array([[1, 2], [3, 5]]) # Prints vw and t print("\nMatrix vw:", vw, "\nVector t:", t, sep="\n") def check_vector_span(set_of_vectors, vector_to_check): # Creates an empty vector of correct size vector_of_scalars = np.asarray([None]*set_of_vectors.shape[0]) # Solves for the scalars that make the equation true if vector is within the span try: # DONE: Use np.linalg.solve() function here to solve for vector_of_scalars vector_of_scalars = np.linalg.solve(set_of_vectors, vector_to_check) if not (vector_of_scalars is None): print("\nVector is within span.\nScalars in s:", vector_of_scalars) # Handles the cases when the vector is NOT within the span except Exception as exception_type: if str(exception_type) == "Singular matrix": print("\nNo single solution\nVector is NOT within span") else: print("\nUnexpected Exception Error:", exception_type) return vector_of_scalars # Call to check_vector_span to check vectors in Equation 1 print("\nEquation 1:\n Matrix vw:", vw, "\nVector t:", t, sep="\n") s = check_vector_span(vw,t) # Call to check a new set of vectors vw2 and t2 vw2 = np.array([[1, 2], [2, 4]]) t2 = np.array([6, 12]) print("\nNew Vectors:\n Matrix vw2:", vw2, "\nVector t2:", t2, sep="\n") # Call to check_vector_span s2 = check_vector_span(vw2,t2) # Call to check a new set of vectors vw3 and t3 vw3 = np.array([[1, 2], [1, 2]]) t3 = np.array([6, 10]) print("\nNew Vectors:\n Matrix vw3:", vw3, "\nVector t3:", t3, sep="\n") # Call to check_vector_span s3 = check_vector_span(vw3,t3)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 12 06:35:16 2017 @author: Jake """ def isWordGuessed(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: boolean, True if all the letters of secretWord are in lettersGuessed; False otherwise ''' secretWordDict = {} guessed = {} for i in secretWord: secretWordDict[i] = i # print(secretWordDict) for letter in lettersGuessed: # print('letter =',letter) # print('guessed =',guessed) if letter in secretWord and letter not in guessed: secretWordDict.pop(letter) # print(secretWordDict) elif letter in guessed: # print("Oops, you've already guessed",letter) pass guessed[letter] = letter if secretWordDict == {}: return True else: return False secretWord = 'apple' lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's'] print(isWordGuessed('pineapple', ['z', 'x', 'q', 'p', 'i', 'n', 'e', 'a', 'p', 'p', 'l', 'e']))
def first_function(): ''' (NoneType) -> str Return the string 'I can write code!'. >>> first_function() 'I can write code!' Hint: this is not a trick question -- just a really easy one. If you are wondering what NoneType means, it indicates that there are no arguments - no types are being passed. ''' return 'I can write code!' def volume_triangular_prism(b, h, l): ''' (number, number, number) -> float Return the volume of a prism with a triangle base. The dimensions of the triangle are base b and height h. The prism has length l. >>> volume_triangular_prism(1, 2, 3) 3.0 >>> volume_triangular_prism(3, 4, 3.5) 21.0 ''' return 0.5*b*h*l def area_square(s): ''' (number) -> float Return the area of the square with side length s. >>> area_square(1) 1.0 >>> area_square(4.5) 20.25 ''' return s*s def area_cube(s): ''' (number) -> float Return the surface area (sum of the area of the faces) of a cube with side length s. Requirement: Use your function area_square(). > area_cube(1) 6.0 > area_cube(5) 150.0 ''' area_square = s*s # Defining area_square as area * area for the code to process it # and return s*s when used in a function return float(6*area_square)
# dynamic_programming.py # ---------- # User Instructions: # # Create a function compute_value which returns # a grid of values. The value of a cell is the minimum # number of moves required to get from the cell to the goal. # # If a cell is a wall or it is impossible to reach the goal from a cell, # assign that cell a value of 99. # # Write a function optimum_policy that returns # a grid which shows the optimum policy for robot # motion. This means there should be an optimum # direction associated with each navigable cell from # which the goal can be reached. # # Unnavigable cells as well as cells from which # the goal cannot be reached should have a string # containing a single space (' '), as shown in the # previous video. The goal cell should have '*'. # ---------- import numpy as np grid = [[0, 0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 1, 0]] # grid = [[0, 0, 0, 0, 0, 0], # [0, 0, 1, 0, 0, 0], # [0, 0, 1, 0, 0, 0], # [0, 0, 0, 0, 1, 0], # [0, 0, 1, 1, 1, 0], # [0, 0, 0, 0, 1, 0]] # grid = [[0, 0, 1, 0, 0, 0], # [0, 0, 1, 0, 0, 0], # [0, 0, 1, 0, 0, 0], # [0, 0, 1, 0, 0, 0], # [0, 0, 1, 0, 0, 0], # [0, 0, 1, 0, 0, 0]] # grid = [[0, 0, 1, 0, 0, 0], # [0, 0, 1, 0, 0, 0], # [0, 0, 1, 1, 0, 0], # [0, 0, 1, 0, 1, 0], # [0, 0, 1, 0, 1, 0], # [0, 0, 1, 0, 1, 0]] # keep track of how much it costs to get from each cell to the goal values = [[99, 99, 99, 99, 99, 99], [99, 99, 99, 99, 99, 99], [99, 99, 99, 99, 99, 99], [99, 99, 99, 99, 99, 99], [99, 99, 99, 99, 99, 99], [99, 99, 99, 99, 99, 99]] # keep track of which cells we've already searched searched_already = [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]] # keep track of all possible paths to the goal paths = [[' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ']] goal = [len(grid)-1, len(grid[0])-1] cost = 1 # the cost associated with moving from a cell to an adjacent one delta = [[-1, 0 ], # go up [ 0, -1], # go left [ 1, 0 ], # go down [ 0, 1 ]] # go right delta_name = ['^', '<', 'v', '>'] ####################################################################################### class Search_Element: # made a new class to hold the search information desired def __init__(self): self.cost = 0 # cost self.r = 0 # row self.c = 0 # col def __getitem__(self): return self.cost def set(self, cost, r, c): self.cost = cost self.r = r self.c = c def loc(self): return [self.r, self.c] def as_list(self): return [self.path_length, self.r, self.c] ####################################################################################### def valid_loc( loc, grid ): return loc[0] >= 0 \ and loc[1] >= 0 \ and loc[0] < len(grid) \ and loc[1] < len(grid[0]) \ and searched_already[loc[0]][loc[1]] == 0 \ and grid[loc[0]][loc[1]] == 0 \ def reverse_motion_index( motion_index ): motion = delta_name[motion_index] if motion == 'v': return '^' elif motion == '>': return '<' elif motion == '<': return '>' elif motion == '^': return 'v' else: return None def add_new_search_locs( search_list, cost ): cur_el = search_list[0] for index,motion in enumerate(delta): new_el = Search_Element() new_el.set( cur_el.cost+cost, cur_el.r+motion[0], cur_el.c+motion[1] ) if valid_loc( new_el.loc(), grid ): values[new_el.r][new_el.c] = new_el.cost search_list.append(new_el) searched_already[new_el.r][new_el.c] = 1 paths[new_el.r][new_el.c] = reverse_motion_index(index) def compute_value(grid,goal,cost): # initialization cur_el = Search_Element() cur_el.set( 0, goal[0], goal[1] ) search_list = [cur_el] values[cur_el.r][cur_el.c] = 0 searched_already[cur_el.r][cur_el.c] = 1 paths[cur_el.r][cur_el.c] = '*' # BFS starting from goal until all valid locations have been searched while len(search_list) > 0: add_new_search_locs( search_list, cost ) search_list.pop(0) compute_value( grid, goal, cost ) print np.array( values ) print np.array( paths )
''' The O(nlog(n)) time algorithm for calculating the search number of a tree given in [1]. [1]: The Complexity of Searching a Graph. N. Megiddo et. al. ''' import networkx as nx def isEdge(graph): ''' Given a graph, checks whether it is just an edge. INPUT graph: A NetworkX graph OUTPUT edge: Boolean on whether the graph is an edge ''' edge = False #An edge has two nodes with only one edge between them nodes = graph.nodes() edges = graph.edges() if len(nodes) == 2 and len(edges) == 1: if graph.has_edge(nodes[0], nodes[1]): edge = True return edge return edge def reRoot(tree, origRoot): ''' Given an input of a tree and a first root, changes the root to one of it's neighbours and continues info computation. INPUT tree: A networkx tree graph origRoot: The root that was selected first. Has degree = 1 OUTPUT treeInfo: info calculated with the new root and adjusted according to pg.8 of [1] ''' #Find the neighbour of origRoot neighbors = tree.neighbors(origRoot) if len(neighbors) == 0: #We have a graph with one node return ['E', 1, None] root = neighbors[0] #Calculate the new treeInfo with the root treeInfo = info(tree, root) #Adjust the the treeInfo if treeInfo[0] == 'H': treeInfo[0] = 'E' elif treeInfo[0] == 'I' and treeInfo[1] == 1: treeInfo[0] = 'E' elif treeInfo[0] == 'I' and treeInfo[1] != 1: treeInfo[0] = 'M' treeInfo[2] = ['E', 1, None] #TODO: We are not properly considering the M-info of the last case return treeInfo def split(tree, root): ''' Given a tree and a root, creates two trees. INPUT tree: A networkx tree graph root: A root node of degree at least two OUTPUT trees [tree1, tree2]: Two trees disjoint except for root whose union makes tree. ''' #Get the neighborhood of root neighbors = tree.neighbors(root) #Choose the first neighbor to remove removeNode = neighbors[0] #Make the tree with the vertex removed removedTree1 = tree.copy() removedTree1.remove_node(removeNode) tree1 = nx.ego_graph(removedTree1, root, radius = float('inf')) #Make the tree with everything but the selected vertex removed removedTree2 = tree.copy() for i in range(1, len(neighbors)): removedTree2.remove_node(neighbors[i]) tree2 = nx.ego_graph(removedTree2, root, radius = float('inf')) return [tree1, tree2] def merge(info1, info2): ''' Given info for two trees, merges their info records as per page 9 of [1]. INPUT info1: The info record for tree1 in a split info2: The info record for tree2 in a split OUTPUT mergedInfo: The merged info records ''' #Extract the search numbers, types and M-info type1 = info1[0] type2 = info2[0] s1 = info1[1] s2 = info2[1] Minfo1 = info1[2] Minfo2 = info2[2] #Check if the search numbers are equal and test cases 1-5 if s1 == s2: if type1 == 'H' and type2 == 'H': mergedInfo = ['H', s1, None] elif (type1 == 'H' and type2 == 'E') or \ (type1 == 'E' and type2 == 'H'): mergedInfo = ['E', s1, None] elif type1 == 'E' and type2 == 'E': mergedInfo = ['I', s1, None] elif (type1 == 'I' and type2 == 'H') or \ (type1 == 'H' and type2 == 'I'): mergedInfo = ['I', s1, None] elif type1 == 'M' or type2 == 'M': mergedInfo = ['H', s1 + 1, None] elif type1 == 'I' and type2 == 'I': mergedInfo = ['H', s1 + 1, None] elif (type1 == 'I' and type2 == 'E') or \ (type1 == 'E' and type2 == 'I'): mergedInfo = ['H', s1 + 1, None] elif s1 > s2: #Do cases 6-7 for s1>s2 if type1 == 'H' or type1 == 'E' or type1 == 'I': mergedInfo = [type1, s1, None] elif type1 == 'M': #Merge the two info records MinfoMerge = merge(Minfo1, info2) sPrime = MinfoMerge[1] if sPrime < s1: mergedInfo = ['M', s1, MinfoMerge] elif sPrime == s1: mergedInfo = ['H', s1 + 1, None] elif s2 > s1: #Do cases 6-7 for s2>s1 if type2 == 'H' or type2 == 'E' or type2 == 'I': mergedInfo = [type2, s2, None] elif type2 == 'M': #Merge the two info records MinfoMerge = merge(Minfo2, info1) sPrime = MinfoMerge[1] if sPrime < s2: mergedInfo = ['M', s2, MinfoMerge] elif sPrime == s2: mergedInfo = ['H', s2 + 1, None] return mergedInfo def info(tree, root): ''' Given an input of a tree graph, calculates the root's info as in [1]. This function is recursive. INPUT tree: A networkx tree graph root: A vertex from tree that is the current root of tree OUTPUT treeInfo: The info for the current tree. ''' #Calculate the degree of the root degree = nx.degree(tree, root) #Use reroot if the deg is 1 and merges otherwise if degree == 0: treeInfo = ['H', 1, None] elif degree == 1: #A single edge has search number = 1 if isEdge(tree): treeInfo = ['E', 1, None] else: #Since tree is not an edge, we re-root and keep going treeInfo = reRoot(tree, root) else: #Split the tree into two trees rooted at root trees = split(tree, root) #Calculate the info for each tree and merge info1 = info(trees[0], root) info2 = info(trees[1], root) treeInfo = merge(info1, info2) return treeInfo def computeInfo(tree): ''' Given an input of a tree computes [type, s(T), M-info(T)] INPUT tree: A networkx tree graph OUTPUT info [type, s(T), M-info(T)]: See page 8 of [1]. ''' #Make the root the first node root = tree.nodes()[0] #Get the info for tree information = info(tree, root) return information def edge_search(tree): ''' Returns the search number of an inputed tree. INPUT tree: A networkx tree graph OUTPUT searchNumber: The search number of tree ''' information = computeInfo(tree) searchNumber = information[1] return searchNumber
''' This file contains utility functions ''' from typing import List import pickle def save_pickle(filename: str, l: List): ''' Saves a list into a pickle file :param filename: output file :param l: input list :return: None ''' with open(filename, 'wb') as f: pickle.dump(l, f) def read_pickle(filename: str) -> List: ''' Reads from a pickle file and turn it into a list :param filename: input file :return: a list ''' with open(filename, 'rb') as f: l = pickle.load(f) return l def read_txt(filename: str) -> List: ''' Read a txt file into a list The txt file should contain one word per line without any seperaters :param filename: input file :return: a list ''' with open(filename, 'r') as f: l = f.read().splitlines() return l def write_txt(filename: str, input: str): ''' Write a string to a txt file ''' with open(filename, 'w') as f: f.write(input)
""" filedb.py """ import pickle import os class FileDB: """ Text file used to persist data Args: filename: The path to the file. """ def __init__(self, filename): if os.path.isfile(filename): self.filename = filename else: raise FileNotFoundError('Error! Crosswords file does not exist!') def create(self, crosswords): """ Saves the a list of crosswords to the file. Args: crosswords: the list of crosswords """ with open(self.filename, mode="wb") as file: pickle.dump(crosswords, file) def read_all(self): """ Reads all the crosswords from the file. """ crosswords = [] with open(self.filename, mode="rb") as file: try: crosswords = pickle.load(file) except EOFError: return crosswords return crosswords def save(self, crosswords): """ Saves the a list of crosswords to the file. Args: crosswords: the list of crosswords """ with open(self.filename, mode="wb") as file: pickle.dump(crosswords, file) if __name__ == '__main__': import unittest from .board import Board from .question import Question class TestFileDB(unittest.TestCase): def setUp(self): self.crosswords = [] self.filedb = FileDB('test.txt') self.questions = [ Question('1A', 'Capital City of Ireland.', 'Dublin'), Question('1D', "Copenhagen is it's capital city.", 'Denmark') ] self.coordinates = [[0,0], [0,0]] self.crosswordA = Board(15, 15) self.crosswordB = Board(14, 14) for question, coords in zip(self.questions, self.coordinates): self.crosswordA.add_question(question, x=coords[0], y=coords[1]) self.crosswordB.add_question(question, x=coords[0], y=coords[1]) self.crosswords= [self.crosswordA, self.crosswordB] def test_write(self): self.filedb.create(self.crosswords) def test_read_all(self): crosswords = self.filedb.read_all() print(len(crosswords)) print(crosswords[0].questions) unittest.main()
try: name = input() if len(name)>3: print("Account Created") else: raise valueError except: print("Invalid Name")
s1 = {1, 2, 3} print(s1) # make a copy of the set, not just a copy of the reference s2 = s1.copy() print("s1: {} | s2: {}".format(s1, s2)) s1.remove(2) print("After removing 2 from s1 | s1: {} | s2: {}".format(s1, s2)) # find the 'difference' between two sets, meaning 'contents of A minus contents of B' print("s1.difference(s2): {}".format(s1.difference(s2))) print("s2.difference(s1): {}".format(s2.difference(s1))) # remove() raises an exception if the value is not in the set, where discard() will simply do nothing in that case s3 = {'x', 'y', 'z'} s3.discard('w') try: s3.remove('w') except KeyError as ke: print("Caught a KeyError when calling set.remove() for value that is not in the set: {}".format(ke.args[0])) s4 = {1, 2, 3, 4} s5 = {2, 4, 6, 8} print("s4: {} | s5: {}".format(s4, s5)) # find the 'intersection' of two sets, meaning 'elements contained in both set A and set B' print("s4.intersection(s5): {}".format(s4.intersection(s5))) # get the 'union' of two sets, meaning 'elements contained in either OR both set A and set B' print("s4.union(s5): {}".format(s4.union(s5)))
# first-try.py # Needed to get myself off Jupyter Notebook and into a proper IDE :D # # I'm using this Python file to practice what I'm learning in this Udemy course: # https://www.udemy.com/course/complete-python-bootcamp/ # # This file isn't meant to have any purpose beyond learning/experimenting with Python features. # print('Hello, World!') # *args represents a variable number of args, and is available as a tuple within the method # NOTE: The name 'args' is a convention, but you could name it anything. The single * is the important part. def sum_args_and_return_five_percent(*args): return sum(args) * 0.05 # *kwargs represents a variable number of named (keyword) args, and is available as a dictionary within the method # NOTE: The name 'kwargs' is a convention, but you could name it anything. The double ** is the important part. def print_fruit_of_choice(**kwargs): print(kwargs) if 'fruit' in kwargs: print('Your fruit of choice is {}'.format(kwargs['fruit'])) else: print('You did not provide your fruit of choice') fivePercentOfSum = sum_args_and_return_five_percent(40, 60, 100) print("5 percent of sum is: {}".format(fivePercentOfSum)) print_fruit_of_choice(fruit='banana', vegetable='carrot') def coding_exercise_19(s): output_string = '' # proper way to iterate a range of values for i in range(0, len(s)): c = s[i] if i % 2 == 0: output_string += c.upper() else: output_string += c.lower() i += 1 return output_string print("Result for 'foobar': {}".format(coding_exercise_19('foobar'))) print("Result for 'Walter Jeffery': {}".format(coding_exercise_19('Walter Jeffery'))) def spy_game(int_list): """ :param int_list: list of 0 or more integers :return: boolean True if the list of integers contains the integers 0, 0, 7, contiguous or not, otherwise returns False """ secret_code = [0, 0, 7] for i in int_list: if secret_code[0] == i: # remove the matched value from head of 'secret_code' array (must specify pop(0) and not just pop()) secret_code.pop(0) # Did we match all values of secret_code yet? if len(secret_code) == 0: return True return False print(spy_game([6, 3, 1, 7, 4])) print(spy_game([0, 0, 7])) print(spy_game([])) print(spy_game([6, 3, 1, 0, 0, 7, 4, 8, 3, 1, 3, 2])) print(spy_game([6, 0, 108, 0, 999, 69, 7, 4, 8, 3, 1, 3, 2])) print(spy_game([6, 0, 108, 0, 999, 69, 171, 4, 8, 3, 1, 3, 2])) list_of_ints = [1, 2, 3, 4, 5, 6, 7, 8] # Example of built-in 'map()' function def square_an_int(i): return i ** 2 list_of_squared_ints = list(map(square_an_int, list_of_ints)) print(list_of_squared_ints) # Example of built-in 'filter()' function def is_even(i): return i % 2 == 0 list_of_even_ints = list(filter(is_even, list_of_ints)) print(list_of_even_ints) # Implement both of the above with lambda expressions list_of_squared_ints_b = list(map(lambda i:i**2, list_of_ints)) list_of_even_ints_b = list(filter(lambda i:i%2==0, list_of_ints)) print(list_of_squared_ints_b) print(list_of_even_ints_b) # ------------------------------------------------------------------------------------------------- # Playing around with variable scopes # ------------------------------------------------------------------------------------------------- xxx = 100 yyy = 200 def local_reassignment(): xxx = 111 yyy = 222 print('locally reassigned values | xxx: {} | yyy: {}'.format(xxx, yyy)) local_reassignment() print(xxx) print(yyy) def global_reassignment(): # explicitly declare that we are locally referencing global variable 'xxx' and not creating a new local 'xxx' global xxx xxx = 111 yyy = 222 print('reassigned value | xxx: {} '.format(xxx)) global_reassignment() print(xxx) print(yyy) # -------------------------------------------------------------------------------------------------
import timeit print("-".join(str(n) for n in range(100))) # Now I time how long it takes to do the code above 10000 times s = '' time_in_seconds = timeit.timeit('s = "-".join(str(n) for n in range(100))', number=10000) print("It took {} seconds to create that string 10000 times".format(time_in_seconds)) time_in_seconds = timeit.timeit('s = "-".join([str(n) for n in range(100)])', number=10000) print("It took {} seconds to create that string via list comprehension 10000 times".format(time_in_seconds)) time_in_seconds = timeit.timeit('s = "-".join(map(str,range(100)))', number=10000) print("It took {} seconds to create that string via map() 10000 times".format(time_in_seconds))
import sys #print('<ul>') #print('<li>') #for param in sys.argv[1:]: # print (param) #print('</li>') #print('<li>') #for param in sys.argv[1:]: # print (param.upper()) #print('</li>') #print('<li>') #for param in sys.argv[1:]: # print (param.lower()) #print('</li>') #print('</ul>') str_input = " ".join(sys.argv[1:]) my_html = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>List</title> </head> <body> <ul> <li>{orig}</li> <li>{lower}</li> <li>{upper}</li> </ul> </body> </html>""".format(orig = str_input, lower = str_input.lower(), upper = str_input.upper()) print(my_html)
""" https://www.pythonprogramming.in/how-to-use-new-and-init-in-python.html """ class Shape: def __new__(cls, sides, *args, **kwargs): if sides == 3: return Triangle(*args, **kwargs) else: return Square(*args, **kwargs) class Triangle: def __init__(self, base, height): self.base = base self.height = height def area(self): return (self.base * self.height) / 2 class Square: def __init__(self, length): self.length = length def area(self): return self.length * self.length a = Shape(sides=3, base=2, height=12) b = Shape(sides=4, length=2) print(str(a.__class__)) print(a.area()) print(str(b.__class__)) print(b.area())
def add_name(names, new_name): """ names is a list of strings, new_name is a string. add_name checks if the `new_name` is in the list. If it is not in the list: * the `new_name` is added to the list * the list is sorted * function returns True if it is in the list the function returns False and exits """ if new_name in names: return False else: names.append(new_name) names.sort() print(names) return True def test_add_name(): # don't change this function lst = ['bob', 'mike'] assert add_name(lst, 'bob') is False assert lst == ['bob', 'mike'] assert add_name(lst, 'ann') is True assert lst == ['ann', 'bob', 'mike'] assert add_name(lst, 'ann') is False assert lst == ['ann', 'bob', 'mike'] if __name__ == '__main__': test_add_name()
list1 = [11, 11, 33, 44, 55] list2=[13,33,31,47,44] my_list =list1+list2 my_set = set(my_list) my_new_list = list(my_set) print("List of unique numbers : ",my_new_list)
import math base_number = float(input("Enter the base number")) power = base_number*10 print("Power is =",power)
my_list = [*range(1,100)] this_year = 2019 birthday_year = int(input("Enter the birthday year: ")) your_age = this_year - birthday_year for age in my_list: if age == your_age: print(age, "This my age !!") break print(age, "not my age")
from random import randrange user_pets = [] class Pet: hunger_threshold = 3 hunger_decrement = 1 boredom_threshold = 3 boredom_decrement = 2 sounds = ["Hi", "Hello"] # INITIALIZE ATTRIBUTES def __init__(self, name, type): self.name = name self.type = type self.hunger = randrange(self.hunger_threshold) self.boredom = randrange(self.boredom_threshold) self.sounds = self.sounds[:] # INCREMENTS HUNGER AND BOREDOM def clock_tick(self): self.hunger += 1 self.boredom += 1 # CURRENT MOOD OF PET def current_mood(self): if self.boredom <= self.boredom_threshold and self.hunger <= self.hunger_threshold: return "happy" elif self.boredom >= self.boredom_threshold and self.hunger >= self.hunger_threshold: return "hungry & bored" elif self.boredom <= self.boredom_threshold and self.hunger >= self.hunger_threshold: return "hungry" else: return "bored" # STR TO DISPLAY CURRENT MOOD OF PET def __str__(self) -> str: mood = self.current_mood() return " I'm " + self.name + " current mood is " + mood + " Type is " + self.type + "." # REDUCE BOREDOM def reduce_boredom(self): self.boredom = max(0, self.boredom - self.boredom_decrement) # REDUCE HUNGER def reduce_hunger(self): self.hunger = max(0, self.hunger - self.hunger_decrement) # TEACH WORD METHOD TO REDUCE BOREDOM def teach(self, word): print(f"\n I learned the new word '{word}'") self.sounds.append(word) self.reduce_boredom() # SAY HI TO REDUCE BOREDOM def hi(self): print(self.sounds[randrange(len(self.sounds))]) self.reduce_boredom() # FEED THE PET def feed(self): print("\nThank you for feeding me!") self.hunger -= self.hunger_decrement self.reduce_hunger() class Dog1(Pet): def __init__(self): print("Dog 1 created") class Dog2(Pet): sounds = ["Woof", "ruff ruff"] def __init__(self): print("Dog 2 created") class Dog3(Dog1, Dog2): def __init__(self): Dog1.__init__(self) Dog2.__init__(self) print("Dog 3 created") class Cat(Pet): def __init__(self): print("Cat created") def display_user_pets(): print("Your Pets") for pet in user_pets: print(f"\n{pet}") # MAIN GAME p1 = Dog1() p2 = Dog2() p3 = Dog3() c1 = Cat() print("Welcome") game_on = True while game_on: if len(user_pets) == 0: print("\nNo Pets!") name = input("Enter the name of your pet: ") type = input("Enter the type of the pet: ") user_pets.append(Pet(name, type)) print("1.Display pets\n2.Adopt a Pet\n3.Greet\n4.Teach\n5.Feed\n6.Exit") user_choice = int(input("Enter your choice(1-6):")) print(user_choice) if user_choice == 1: display_user_pets() elif user_choice == 2: print("\nAdopting a new pet!") name = input("Enter the name of your pet: ") type = input("Enter the type of the pet: ") user_pets.append(Pet(name, type)) elif user_choice in range(2, 6): name = input("Enter the name of pet you want to interact with: ") pet_exists = False for pet in user_pets: if pet.name == name: if user_choice == 3: pet.hi() elif user_choice == 4: word = input("Enter the word you want to teach: ") pet.teach(word) elif user_choice == 5: pet.feed() pet_exists = True pet.clock_tick() if pet_exists == False: print(f"You don't have a pet with the name {name}") else: game_on = False
# -*- coding: utf-8 -*- """ Created on Mon Jan 27 17:40:51 2020 @author: Kapil """ print("Book Shop\n") orders=[["34587","Learning Python,Mark Lutz",4,40.95],["98762","Programing python, Mark Lutz",5,56.80],["77226","Head first Python,Paul Barry",3,32.95],["88112","Einfuhrung in Python3, Bernd klein",3,24.99]] print(orders) print("\nBefore applying Extra charges of rs 10 on less then 100 total amount ") print("Order No , Price of Total Quantity") list1=[(item[0],item[2]*item[3]) for item in orders] print(list1) def f2(x): if(x<100): return x+10 else: return x print("\nAfter applying Extra charges of rs 10 on less then 100 total amount ") print("Order No , Price of Total Quantity") list2=[(item[0],f2(item[2]*item[3])) for item in orders] print(list2)
a=int(input("Enter a no")) b=a rev=0 while (a>0): rem=a%10 rev=rev*10+rem a=a//10 print(rev) if (b==rev): print("Pallindrome") else: print("Not Pallindrome")
import numpy as np from paretoset.algorithms_numpy import paretoset_efficient, pareto_rank_naive from paretoset.utils import user_has_package, validate_inputs import pandas as pd if user_has_package("numba"): from paretoset.algorithms_numba import BNL def paretoset(costs, sense=None, distinct=True, use_numba=True): """Return boolean mask indicating the Pareto set of (non-NaN) numerical data. The input data in `costs` can be either a pandas DataFrame or a NumPy ndarray of shape (observations, objectives). The user is responsible for dealing with NaN values *before* sending data to this function. Only numerical data is allowed, with the exception of `diff` (different) columns. Parameters ---------- costs : np.ndarray or pd.DataFrame Array or DataFrame of shape (observations, objectives). sense : list List with strings for each column (objective). The value `min` (default) indicates minimization, `max` indicates maximization and `diff` indicates different values. Using `diff` is equivalent to a group-by operation over the columns marked with `diff`. If None, minimization is assumed. distinct : bool How to treat duplicate rows. If `True`, only the first duplicate is returned. If `False`, every identical observation is returned instead. use_numba : bool If True, numba will be used if it is installed by the user. Returns ------- mask : np.ndarray Boolean mask with `True` for observations in the Pareto set. Examples -------- >>> from paretoset import paretoset >>> import numpy as np >>> costs = np.array([[2, 0], [1, 1], [0, 2], [3, 3]]) >>> paretoset(costs) array([ True, True, True, False]) >>> paretoset(costs, sense=["min", "max"]) array([False, False, True, True]) The `distinct` parameter: >>> paretoset([0, 0], distinct=True) array([ True, False]) >>> paretoset([0, 0], distinct=False) array([ True, True]) """ if user_has_package("numba") and use_numba: paretoset_algorithm = BNL else: paretoset_algorithm = paretoset_efficient costs, sense = validate_inputs(costs=costs, sense=sense) assert isinstance(sense, list) n_costs, n_objectives = costs.shape diff_cols = [i for i in range(n_objectives) if sense[i] == "diff"] max_cols = [i for i in range(n_objectives) if sense[i] == "max"] min_cols = [i for i in range(n_objectives) if sense[i] == "min"] # Check data types (MIN and MAX must be numerical) message = "Data must be numerical. Please convert it. Data has type: {}" if isinstance(costs, pd.DataFrame): data_types = [costs.dtypes.values[i] for i in (max_cols + min_cols)] if any(d == np.dtype("O") for d in data_types): raise TypeError(message.format(data_types)) else: if costs.dtype == np.dtype("O"): raise TypeError(message.format(costs.dtype)) # No diff columns, use numpy array if not diff_cols: if isinstance(costs, pd.DataFrame): costs = costs.to_numpy(copy=True) for col in max_cols: costs[:, col] = -costs[:, col] return paretoset_algorithm(costs, distinct=distinct) n_costs, n_objectives = costs.shape # Diff columns are present, use pandas dataframe if isinstance(costs, pd.DataFrame): df = costs.copy() # Copy to avoid mutating inputs df.columns = np.arange(n_objectives) else: df = pd.DataFrame(costs) assert isinstance(df, pd.DataFrame) assert np.all(df.columns == np.arange(n_objectives)) # If `object` columns are present and they can be converted, do it. for col in max_cols: df[col] = -pd.to_numeric(df[col], errors="coerce") for col in min_cols: df[col] = pd.to_numeric(df[col], errors="coerce") is_efficient = np.zeros(n_costs, dtype=np.bool_) # Create the groupby object # We could've implemented our own groupby, but choose to use pandas since # it's likely better than what we can come up with on our own. groupby = df.groupby(diff_cols) # Iteration through the groups for key, data in groupby: # Get the relevant data for the group and compute the efficient points relevant_data = data[max_cols + min_cols].to_numpy(copy=True) efficient_mask = paretoset_algorithm(relevant_data.copy(), distinct=distinct) # The `pd.DataFrame.groupby.indices` dict holds the row indices of the group try: data_mask = groupby.indices[key] # When we groupby `diff_cols`, which is a list, we get out ('entry',) # but the groupby.indices object wants 'entry' except KeyError: data_mask = groupby.indices[key[0]] is_efficient[data_mask] = efficient_mask return is_efficient def paretorank(costs, sense=None, distinct=True, use_numba=True): """Return integer array with Pareto ranks of (non-NaN) numerical data. Observations in the Pareto set are assigned rank 1. After removing the Pareto set, the Pareto set of the remaining data is assigned rank 2, and so forth. The input data in `costs` can be either a pandas DataFrame or a NumPy ndarray of shape (observations, objectives). The user is responsible for dealing with NaN values *before* sending data to this function. Only numerical data is allowed, with the exception of `diff` (different) columns. Parameters ---------- costs : np.ndarray or pd.DataFrame Array or DataFrame of shape (observations, objectives). sense : list List with strings for each column (objective). The value `min` (default) indicates minimization, `max` indicates maximization and `diff` indicates different values. Using `diff` is equivalent to a group-by operation over the columns marked with `diff`. If None, minimization is assumed. distinct : bool How to treat duplicate rows. If `True`, only the first duplicate is returned. If `False`, every identical observation is returned instead. use_numba : bool If True, numba will be used if it is installed by the user. Returns ------- ranks : np.ndarray Integer array with Pareto ranks of the observations. Examples -------- >>> from paretoset import paretoset >>> import numpy as np >>> costs = np.array([[2, 0], [1, 1], [0, 2], [3, 3]]) >>> paretorank(costs) array([1, 1, 1, 2]) >>> paretorank(costs, sense=["min", "max"]) array([3, 2, 1, 1]) The `distinct` parameter: >>> paretorank([0, 0], distinct=True) array([1, 2]) >>> paretorank([0, 0], distinct=False) array([1, 1]) """ if user_has_package("numba") and use_numba: paretorank_algorithm = pareto_rank_naive else: paretorank_algorithm = pareto_rank_naive costs, sense = validate_inputs(costs=costs, sense=sense) assert isinstance(sense, list) n_costs, n_objectives = costs.shape diff_cols = [i for i in range(n_objectives) if sense[i] == "diff"] max_cols = [i for i in range(n_objectives) if sense[i] == "max"] min_cols = [i for i in range(n_objectives) if sense[i] == "min"] # Check data types (MIN and MAX must be numerical) message = "Data must be numerical. Please convert it. Data has type: {}" if isinstance(costs, pd.DataFrame): data_types = [costs.dtypes.values[i] for i in (max_cols + min_cols)] if any(d == np.dtype("O") for d in data_types): raise TypeError(message.format(data_types)) else: if costs.dtype == np.dtype("O"): raise TypeError(message.format(costs.dtype)) # CASE 1: THE ONLY SENSE IS MINIMIZATION # --------------------------------------- if all(s == "min" for s in sense): if isinstance(costs, pd.DataFrame): costs = costs.to_numpy(copy=True) return paretorank_algorithm(costs, distinct=distinct, use_numba=use_numba) n_costs, n_objectives = costs.shape if not diff_cols: # Its an array if not isinstance(costs, np.ndarray): costs = costs.to_numpy(copy=True) for col in max_cols: costs[:, col] = -costs[:, col] return paretorank_algorithm(costs, distinct=distinct, use_numba=use_numba) if isinstance(costs, pd.DataFrame): df = costs.copy() # Copy to avoid mutating inputs df.columns = np.arange(n_objectives) else: df = pd.DataFrame(costs) assert isinstance(df, pd.DataFrame) assert np.all(df.columns == np.arange(n_objectives)) # If `object` columns are present and they can be converted, do it. for col in max_cols + min_cols: df[col] = pd.to_numeric(df[col], errors="coerce") all_ranks = np.zeros(n_costs, dtype=np.int_) # Create the groupby object # We could've implemented our own groupby, but choose to use pandas since # it's likely better than what we can come up with on our own. groupby = df.groupby(diff_cols) # Iteration through the groups for key, data in groupby: # Get the relevant data for the group and compute the efficient points relevant_data = data[max_cols + min_cols].to_numpy(copy=True) ranks = paretorank_algorithm(relevant_data.copy(), distinct=distinct, use_numba=use_numba) # The `pd.DataFrame.groupby.indices` dict holds the row indices of the group data_mask = groupby.indices[key] all_ranks[data_mask] = ranks return all_ranks if __name__ == "__main__": import pytest pytest.main(args=[".", "--doctest-modules", "--maxfail=5", "--cache-clear", "--color", "yes", ""])
#-*-coding:utf-8-*- def trim(s): if s=='': return s while s[0]== ' ': s= s[1:] if s=='': #防止清空成'' return s # break while s[-1]== ' ': s= s[:-1] if s=='': #防止清空成'' return s # break return s #测试: if trim('hello ')!='hello': print('测试1失败!') elif trim(' hello')!='hello': print('测试2失败!') elif trim(' hello ')!='hello': print('测试3失败!') elif trim(' hellow orld ')!='hellow orld': print('测试4失败!') elif trim('')!='': print('测试5失败!') elif trim(' ')!='': print('测试6失败!') else: print('测试成功!') # SyntaxError: unindent does not match any outer indentation level ## 由于Tab和Space混用导致的错误
### 匿名函数 #Python中,对匿名函数提供了有限支持 >>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])) #[1, 4, 9, 16, 25, 36, 49, 64, 81] ## 关键字lambda表示匿名函数,冒号前面的x表示函数参数 ## 匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果 ## 匿名函数也是一个函数对象,也可以把匿名函数赋值给一个变量,再利用变量来调用该函数: >>> f = lambda x: x * x >>> f # <function <lambda> at 0x101c6ef28> >>> f(5) # 25 ## 练习 #用匿名函数改造下面代码 # -*- coding:utf-8 -*- def is_odd(n): return n % 2 == 1 L = list(filter(is_odd, range(1, 20))) print(L) print(list(filter(lambda n: n%2==1,range(1,20)))) ## 他人心得:lambda匿名函数的返回值与函数参数(输入)无关,只与:后面表达式的结果有关
### 函数的参数 ## Python的函数定义灵活度非常大。 ## 除了正常定义的必选参数外,还可以使用默认参数、可变参数和关键字参数 # 位置函数 def power(x): return x * x # 要计算x4、x5…,就要把power(x)修改为power(x, n),用来计算x^n def power(x, n): s = 1 while n > 0: n = n - 1 s = s * x return s ## x和n,这两个参数都是位置参数,调用函数时,传入的两个值按照位置顺序*依次*赋给参数x和n # 默认函数 # 新的power(x, n)函数定义没有问题,但旧的函数调用函数power()缺少了一个位置参数n def power(x, n=2): s = 1 while n > 0: n = n - 1 s = s * x return s # 当我们调用power(5)时,相当于调用power(5, 2) # 设置默认参数时,有几点要注意: ## 一是必选参数在前,默认参数在后,否则Python的解释器会报错; # 二是如何设置默认参数。 ## 当函数有多个参数时,把变化大的参数放前面,变化小的参数放后面。变化小的参数就可以作为默认参数。 # 默认函数的好处是能降低调用函数的难度,只有与默认参数信息不符的值才需要提供额外的信息 # 当不按顺序提供部分默认参数时,*需要把参数名写上。 #比如调用enroll('Adam', 'M', city='Tianjin') ## ***定义默认参数要牢记一点:默认参数必须指向不变对象! 否则自动叠加(!!List[]) def add_end(L=None): if L is None: L = [] L.append('END') return L # 不变对象一旦创建,对象内部的数据就不能修改,这样就减少了由于修改数据导致的错误。 # 此外,由于对象不变,多任务环境下同时读取对象不需要加锁,同时读一点问题都没有。 ## 可变参数 #可变参数就是传入的参数个数是可变的 def calc(numbers): sum = 0 for n in numbers: sum = sum + n * n return sum #但是调用的时候,需要先组装出一个list或tuple: >>> calc([1, 2, 3]) 14 >>> calc((1, 3, 5, 7)) 84 #如果利用可变参数,调用函数的方式可以简化成这样: >>> calc(1, 2, 3) 14 >>> calc(1, 3, 5, 7) 84 #所以,我们把函数的参数改为可变参数: def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum ## list或tuple前面加一个*号,把list或tuple的元素变成可变参数传进去: >>> nums = [1, 2, 3] >>> calc(*nums) 14 ## 关键字参数 ——不限制关键字,用于扩展 # 允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict # 它可以扩展函数,他将非必要的参数复制一个dict传给对应**kw参数,而不会影响本身的dict def person(name, age, **kw): print('name:', name, 'age:', age, 'other:', kw) >>> person('Bob', 35, city='Beijing') name: Bob age: 35 other: {'city': 'Beijing'} >>> person('Adam', 45, gender='M', job='Engineer') name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'} # >>> person('Adam', 45, **extra) ## 命名关键字参数 ——限制关键字,用于圈定 # 要限制关键字参数的名字,可以用命名关键字参数,要一个特殊分隔符*,*后面的参数被视为命名关键字参数 # 例如,只接收city和job作为关键字参数。 def person(name, age, *, city, job): print(name, age, city, job) # 如果函数定义中已经有了一个可变参数*args,后面的命名关键字参数就不再需要一个特殊分隔符*了 # 命名关键字参数必须传入参数名,这和位置参数不同。如果没有传入参数名,会报错(位置参数过多) def person(name, age, *, city='Beijing', job): print(name, age, city, job) >>> person('Jack', 24, job='Engineer') Jack 24 Beijing Engineer #命名关键字参数可以用缺省值来简化 ##如果没有可变参数,就必须加一个*作为特殊分隔符。否则将视作位置函数。 ## 函数组合 ## 参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。 def f1(a, b, c=0, *args, **kw): print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw) def f2(a, b, c=0, *, d, **kw): print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw) >>> f1(1, 2) a = 1 b = 2 c = 0 args = () kw = {} >>> f1(1, 2, c=3) a = 1 b = 2 c = 3 args = () kw = {} >>> f1(1, 2, 3, 'a', 'b') a = 1 b = 2 c = 3 args = ('a', 'b') kw = {} >>> f1(1, 2, 3, 'a', 'b', x=99) a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99} >>> f2(1, 2, d=99, ext=None) a = 1 b = 2 c = 0 d = 99 kw = {'ext': None} # 任意函数,都可以通过类似func(*args, **kw)的形式调用 >>> args = (1, 2, 3, 4) >>> kw = {'d': 99, 'x': '#'} >>> f1(*args, **kw) # 只有1个元素的tuple定义时必须加一个逗号,,来消除歧义 a = 1 b = 2 c = 3 args = (4,) kw = {'d': 99, 'x': '#'} >>> args = (1, 2, 3) >>> kw = {'d': 88, 'x': '#'} >>> f2(*args, **kw) a = 1 b = 2 c = 3 d = 88 kw = {'x': '#'} ## 使用太多组合会使函数接口的可理解性很差 # Practice # 以下函数允许计算两个数的乘积,请稍加改造,变成可接收一个或多个数并计算乘积: # -*- coding: utf-8 -*- # def product(x, y): # return x * y //原函数 def product(*args): if len(args) == 0: return x # //x未定义,为None. // raise TypeError("Empty tuple!") if len(args)>0: y=1 for i in args: y= y * i return y # 测试 print('product(5) =', product(5)) print('product(5, 6) =', product(5, 6)) print('product(5, 6, 7) =', product(5, 6, 7)) print('product(5, 6, 7, 9) =', product(5, 6, 7, 9)) if product(5) != 5: print('测试失败!') elif product(5, 6) != 30: print('测试失败!') elif product(5, 6, 7) != 210: print('测试失败!') elif product(5, 6, 7, 9) != 1890: print('测试失败!') else: try: product() print('测试失败!') except TypeError: print('测试成功!') ## 默认参数一定要用不可变对象,如果是可变对象,程序运行时会有逻辑错误! #要注意定义可变参数和关键字参数的语法: ## *args是可变参数,args接收的是一个tuple; **kw是关键字参数,kw接收的是一个dict。 ## 可变参数既可以直接传入:func(1, 2, 3),又可以先组装list或tuple, #再通过*args传入:func(*(1, 2, 3)); ## 关键字参数既可以直接传入:func(a=1, b=2),又可以先组装dict, # 再通过**kw传入:func(**{'a': 1, 'b': 2})。 ## 使用*args和**kw是Python的习惯写法,当然也可以用其他参数名,但最好使用习惯用法。 ## 命名的关键字参数是为了限制调用者可以传入的参数名,同时可以提供默认值。 ## 定义命名的关键字参数在没有可变参数的情况下不要忘了写分隔符*,否则定义的将是位置参数。
### 高级特性 # 构造一个1, 3, 5, 7, ..., 99的列表 L = [] n = 1 while n <= 99: L.append(n) n = n + 2 ## 代码越少,开发效率越高。越简单越好。 ## 切片 # 取一个list或tuple的部分元素是非常常见的操作 # 取前N个元素,也就是索引为0-(N-1)的元素,可以用循环: >>> r = [] >>> n = 3 >>> for i in range(n): ... r.append(L[i]) ... >>> r ['Michael', 'Sarah', 'Tracy'] # 应上面的问题,取前3个元素,用一行代码就可以完成切片: >>> L[0:3] #相当于字符串中取前三个字符 ['Michael', 'Sarah', 'Tracy'] # 如果第一个索引是0,还可以省略: >>> L[:3] ## Python支持L[-1]取倒数第一个元素,那么它同样支持倒数切片,试试: >>> L[-2:] ['Bob', 'Jack'] >>> L[-2:-1] ['Bob'] # 切片操作十分有用。我们先创建一个0-99的数列: >>> L = list(range(100)) >>> L [0, 1, 2, 3, ..., 99] # 前10个数,每两个取一个: >>> L[:10:2] [0, 2, 4, 6, 8] # 所有数,每5个取一个: >>> L[::5] [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] L[::-1] ## 每次都只取最后一个,相当于反转字符串 # 甚至什么都不写,只写[:]就可以原样复制一个list ## tuple也是一种list,唯一区别是tuple不可变。因此,tuple也可以切片,只是结果仍是tuple: >>> (0, 1, 2, 3, 4, 5)[:3] (0, 1, 2) # 字符串'xxx'也可以看成是一种list,每个元素就是一个字符,切片结果也是字符串 ## 去边取值时,负数放后面;反向取值时,负数放前边 >>> L=['a','b','c','d'] >>> L[-2:0] [] >>> L[-2:-1] ['c'] >>> L[-1:0] [] >>> L[-2:] ['c', 'd'] ## 练习 # 利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法: # -*- coding: utf-8 -*- def trim(s): if s=='': return s while s[0]== ' ': s= s[1:] if s=='': #防止清空成'' return s # break while s[-1]== ' ': s= s[:-1] if s=='': #防止清空成'' 用递归的话,先生成奇怪的值,才进判断会报错 return s # break return s # 测试: if trim('hello ') != 'hello': print('测试失败!') elif trim(' hello') != 'hello': print('测试失败!') elif trim(' hello ') != 'hello': print('测试失败!') elif trim(' hello world ') != 'hello world': print('测试失败!') elif trim('') != '': print('测试失败!') elif trim(' ') != '': print('测试失败!') else: print('测试成功!') # 问题主要集中在第5个测试和第6个测试。第5个测试输入了s='', # 如果这里直接调用s[0],而s一个字符都没有,就会报out of range错。 # 所以,必须要第一个if来解决这个问题。而我解决了这个问题后发现还是测试失败, # 这是因为第一个循环是while s[0],在第六个测试中,s=' ',循环的最后一步,s='', # 再调用s[0]就又会发生out of range错误,所以必须再加一个if来确保不发生索引越界。
#incremement n by 1; #only check it against previous primes. prime_numbers = [2,3] not_factors = [] def prime(): #print "prime numbers up top are: " #print prime_numbers n = prime_numbers[-1] n = n + 1 #print "n up top is: " #print n while n > 1 and n < 1000000: for p in prime_numbers: if n % p != 0: #print "p in the list iternation is: " #print p #print "n in the list iternation is:" #print n not_factors.append(p) #print "not factors of n are: " #print not_factors #elif n % p == 0: #print "p in the list iternation is: " #print p #print "n in the list iternation is: " #print n if len(not_factors) == len(prime_numbers): prime_numbers.append(n) #print "prime numbers are: " #print prime_numbers n = n + 1 del not_factors[:] #print "n at the bottom is: " #print n #print "prime numbers are: " print prime_numbers #print prime_numbers print prime() #def check_factorization(x,pn): #for p in pn: #while x > 1 and x % p == 0: #prime_factors.append(p) #x = x / p #print x #print prime_factors
# This is intuitive but VERY slow def lib(n): """ Functional definition of Fibonacci numbers """ if n <= 1: return 0 else: return lib(n - 1) + lib(n - 2) def fib2(x): if x < 5: return lib(x) else: return 0
import math # Calculates f(x) def f_function(x): return math.sin(x) # Calculates f"(x) def f_function_2_der(x): return -math.sin(x) # Calculates the error for the given trapezoidal sums approximation def calculate_error(integration_range, points): partitions_amount = len(points) - 1 der_2_abs_res = [abs(f_function_2_der(integration_range[0])), f_function_2_der(abs(integration_range[1]))] return ((math.pow(integration_range[1] - integration_range[0], 3)) / (12 * math.pow( partitions_amount, 2))) * max(der_2_abs_res) # Performs a trapezoidal sums approximation on the given integration range and with # the given amount of partitions and returns the result def trapezoidal_sums(integration_range, partitions_amount): partition_size = (integration_range[1] - integration_range[0]) / partitions_amount # N = amount of partitions = amount of points - 1 points_amount = partitions_amount + 1 points = [integration_range[0]] for i in range(1, points_amount): points.append(points[i - 1] + partition_size) f_sum = 0 for k in range(1, partitions_amount): f_sum += f_function(points[k]) return partition_size / 2 * (f_function(points[0]) + f_function(points[-1]) + 2 * f_sum), calculate_error( integration_range, points) # Since we want to perform the trapezoidal sums estimation for 11 points, # we give 10 as the amount of partitions, because partition number = points amount - 1 target_range = (0, math.pi / 2) partitions_number = 10 result = trapezoidal_sums(target_range, partitions_number) print("Trapezoidal Sums estimation: " + str(result[0])) print("|Error| <= " + "{0:.16f}".format(result[1]))
class PayrollSystem: def __init__(self): self._employee_policies = { 1: SalaryPolicy(3000), 2: SalaryPolicy(1500), 3: CommissionPolicy(1000, 100), 4: HourlyPolicy(15), 5: HourlyPolicy(9) } def get_policy(self, employee_id): policy = self._employee_policies.get(employee_id) if not policy: return ValueError(employee_id) return policy def calculate_payroll(self, employees): print('Calculating Payroll') print('===================') for employee in employees: print(f'Payroll for: {employee.id} - {employee.name}') print(f'- Check amount: {employee.calculate_payroll()}') if employee.address: print('- Sent to:') print(employee.address) print('') class PayrollPolicy: def __init__(self): self.hours_worked = 0 def track_work(self, hours): self.hours_worked += hours class SalaryPolicy(PayrollPolicy): def __init__(self, weekly_salary): super().__init__() self.weekly_salary = weekly_salary def calculate_payroll(self): return self.weekly_salary class HourlyPolicy(PayrollPolicy): def __init__(self, hour_rate): super().__init__() self.hour_rate = hour_rate def calculate_payroll(self): return self.hours_worked * self.hour_rate class CommissionPolicy(SalaryPolicy): def __init__(self, weekly_salary, commission_per_sale): super().__init__(weekly_salary) self.commission_per_sale = commission_per_sale @property def commission(self): sales = self.hours_worked / 5 return sales * self.commission_per_sale def calculate_payroll(self): fixed = super().calculate_payroll() return fixed + self.commission
""" Basic knapsack solvers: dynamic programming and various greedy solvers """ from copy import copy def dynamic_prog(items_count, capacity, density_sorted_items, verbose_tracking): """ Run the dynamic programming algorithm. It is right here! :param items_count: :param capacity: :param density_sorted_items: :param verbose_tracking :return: """ # Keep only the current and most recent prev column. # Each column stores a tuple at each position: (val, list_of_taken_elements) col = [(0, [])]*(capacity+1) cur = col for i in range(items_count): pred = cur cur = copy(col) (index, value, weight, density) = density_sorted_items[i] for w in range(capacity+1): (p_val, p_elmts) = pred[w - weight] if weight <= w else (0, []) cur[w] = max(pred[w], (int(weight <= w) * (value + p_val), p_elmts + [i]), key=lambda valElmts: valElmts[0]) if verbose_tracking and items_count >= 1000: if i > 0 and i % 100 == 0: print(f'{i}/{items_count}', end=' ') if i % 1000 == 0: print() if verbose_tracking and items_count >= 1000: print() return cur[capacity] def greedy_by_density(_items_count, capacity, items, _verbose_tracking): """ Run the greedy-by-density algorithm. :param _items_count: :param capacity: :param items: :param _verbose_tracking: :return: """ return greedy_by_order(capacity, sorted(items, key=lambda item: item.density, reverse=True)) def greedy_by_order(capacity, items): """ :param capacity: :param items: :return: """ # a trivial greedy algorithm for filling the knapsack # it takes items in-order until the knapsack is full value = 0 weight = 0 taken_greedy = [] for (index, item) in enumerate(items): if weight + item.weight <= capacity: taken_greedy.append(index) value += item.value weight += item.weight return (value, sorted(taken_greedy)) def greedy_by_value(_items_count, capacity, items): """ Run the greedy-by-value algorithm. :param _items_count: :param capacity: :param items: :return: """ return greedy_by_order(capacity, sorted(items, key=lambda item: item.value, reverse=True)) def greedy_by_weight(_items_count, capacity, items): """ Run the greedy-by-weight algorithm. :param _items_count: :param capacity: :param items: :return: """ return greedy_by_order(capacity, sorted(items, key=lambda item: item.weight))
"""object has no dict like method.""" class Vhost(object): def __init__(self, name, permission): self.name = name self.permission = permission if __name__ == '__main__': vhost1 = { "name": "test2", "permissions": "partily" } print "name:", vhost1["name"] print "permissions:", vhost1["permissions"] vhost = Vhost("test1", "all") print "name:", vhost["name"] print "permssion", vhost["permssion"]
# Julio Ureta, CSC102 #Define a class called Car with the following attributes: # Total Odometer Miles # Speed in miles per hour # Driver Name # Sponsor import random class Car(): def __init__(self): print("A Car is instantiated.") self.total_odometer_miles = 0.0 self.speed_in_miles_per_hour = random.randint(1, 120) self.driver_name = "" self.sponsor = "" # Utility functions def get_total_odometer_miles(a_car): a_car.total_odometer_miles = (a_car.total_odometer_miles + a_car.speed_in_miles_per_hour * 1/60) def get_speed_in_miles_per_hour(a_car): a_car.speed_in_miles_per_hour = random.randint(1,120) def get_driver_distance(a_car): print(a_car.driver_name, "at mile", a_car.total_odometer_miles) # Winning factor functions def no_winner(cars): for car in cars: if car.total_odometer_miles >= 500: return False return True def check_for_winner(cars): while no_winner(cars): for car in cars: get_speed_in_miles_per_hour(car) get_total_odometer_miles(car) get_driver_distance(car) def get_winner(cars): winner = None for car in cars: if car.total_odometer_miles >= 500: winner = car return winner # Main function def main(): #Initialize all the drivers. driver_one = Car() driver_one.driver_name = "Phil" driver_one.sponsor = "IBM" driver_two = Car() driver_two.driver_name = "Cookie Monster" driver_two.sponsor = "Sesame Street" driver_three = Car() driver_three.driver_name = "Tyler" driver_three.sponsor = "NASA" driver_four = Car() driver_four.driver_name = "Frankie" driver_four.sponsor = "Obisidan" driver_five = Car() driver_five.driver_name = "Victor" driver_five.sponsor = "Tonka" driver_six = Car() driver_six.driver_name = "Jose" driver_six.sponsor = "Bethesda" driver_seven = Car() driver_seven.driver_name = "Alex" driver_seven.sponsor = "Matell" driver_eight = Car() driver_eight.driver_name = "Brock" driver_eight.sponsor = "Heineken" driver_nine = Car() driver_nine.driver_name = "Jase" driver_nine.sponsor = "Crayola" driver_ten = Car() driver_ten.driver_name = "Cade" driver_ten.sponsor = "Roseart" driver_eleven = Car() driver_eleven.driver_name = "Melissa" driver_eleven.sponsor = "Telltale Games" driver_twelve = Car() driver_twelve.driver_name = "Cecil" driver_twelve.sponsor = "Toys R Us" driver_thirteen = Car() driver_thirteen.driver_name = "Jy" driver_thirteen.sponsor = "Australia" driver_fourteen = Car() driver_fourteen.driver_name = "Adam" driver_fourteen.sponsor = "Google" driver_fifteen = Car() driver_fifteen.driver_name = "Ian" driver_fifteen.sponsor = "Ubisoft" driver_sixteen = Car() driver_sixteen.driver_name = "Matt" driver_sixteen.sponsor = "Rockstar" driver_seventeen = Car() driver_seventeen.driver_name = "Aaron" driver_seventeen.sponsor = "Company X" driver_eighteen = Car() driver_eighteen.driver_name = "Jack" driver_eighteen.sponsor = "Black" driver_nineteen = Car() driver_nineteen.driver_name = "Fred" driver_nineteen.sponsor = "Dread" driver_twenty = Car() driver_twenty.driver_name = "Why" driver_twenty.sponsor = "Because" # Store all of the drivers in a list. cars = [] cars.append(driver_one) cars.append(driver_two) cars.append(driver_three) cars.append(driver_four) cars.append(driver_five) cars.append(driver_six) cars.append(driver_seven) cars.append(driver_eight) cars.append(driver_nine) cars.append(driver_ten) cars.append(driver_eleven) cars.append(driver_twelve) cars.append(driver_thirteen) cars.append(driver_fourteen) cars.append(driver_fifteen) cars.append(driver_sixteen) cars.append(driver_seventeen) cars.append(driver_eighteen) cars.append(driver_nineteen) cars.append(driver_twenty) check_for_winner(cars) winner = get_winner(cars) #Display the winner. print("The winner is", winner.driver_name, "who was sponsored by", winner.sponsor) main()
class Stack: def __init__(self): self._data = [] def is_empty(self): return not self._data def push(self, data): self._data.append(data) def pop(self): try: return self._data.pop() except IndexError: raise Exception('Invalid Operation: the stack is empty!') def peek(self): try: return self._data[-1] except IndexError: raise Exception('Invalid Operation: the stack is empty!') def size(self): return len(self._data) def __repr__(self): return repr(self._data) if __name__ == '__main__': stack = Stack() stack.push(2) stack.push(3) print(stack.size()) print("Popped: ", stack.pop()) print("Popped: ", stack.pop()) print(stack.size()) print("Peek:", stack.peek()) print(stack.size())
def oddTuples(tup): '''Take a tuple as input and return a new tuple as output, where every OTHER element of the input tuple is copied, starting with the first one.''' newTup = () for n in range(len(tup)): if n % 2 == 0: newTup += (tup[n],) return newTup
# method to determine odds of pulling three balls of the same color # from a cauldron containing three green and three red balls def redGreenTrial(numTrials): import random """ Returns the odds of pulling three consecutive balls of the same color from a set containing three balls of each color. Balls are assumed to be removed from the set upon selection. """ yes = 0 for n in range(numTrials): bucket = ['r','r','r','g','g','g'] choices = [] for i in range(3): # index = random.choice(0, len(bucket - 1)) # choices.append(bucket.pop(index)) # better implemetation here: ball = random.choice(bucket) bucket.remove(ball) choices.append(ball) first = choices[0] if all(first == next for next in choices): yes += 1 odds = yes/float(numTrials) print 'Odds: ', odds # hashSet fcn - building on earlier intSet class class hashSet(object): ''' hacked together class implementing much of the fcnality of Python native hash fcn i.e. dictionaries - but in much less efficient fashion ''' def __init__(self, numBuckets): ''' numBuckets: int. The number of buckets this hash set will have. Raises ValueError if this value is not an integer, or if it is not greater than zero. Sets up an empty hash set with numBuckets number of buckets. ''' if type(numBuckets) != int or numBuckets <= 0: raise ValueError else: self.storage = [] for i in range(0, numBuckets): self.storage.append([]) def hashValue(self, e): ''' e: an integer returns: a hash value for e, which is e mod the number 'o buckets in this hash set. Raise ValueError if e is not an int. ''' if type(e) != int: raise ValueError else: return e % len(self.storage) def getNumBuckets(self): ''' returns number of buckets in your sorry little hash ''' return len(self.storage) def member(self, e): ''' e: an integer returns: True if e is in self, False otherwise Raise ValueError if e not an integer ''' if type(e) != int: raise ValueError else: for bucket in self.storage: if e in bucket: return True else: continue return False def insert(self, e): ''' e: an integer inserts e into appropriate hash bucket. Raises ValueError if e is not an integer. ''' if self.member(e): return else: self.storage[self.hashValue(e)].append(e) def remove(self, e): ''' e: an integer removes e from self. Raises ValueError if e is not in self or if e is not an int. ''' if not self.member(e) or type(e) != int: raise ValueError else: self.storage[self.hashValue(e)].remove(e) def __str__(self): ''' returns the hash itself rather than some vague and useless < function at 90993j3ijoc > gibberish ''' return str(self.storage) # primeGen generator fcn def primeGen(): ''' generator function that yields an prime sequence of arbitrary length ''' primes = [] x = 1 while True: x += 1 # nifty trick here - since primes is empty on the first run # through this yields true for 2 if all(x % m != 0 for m in primes): primes.append(x) yield x # a gloriously hideous regex I came up with - part of 'Dive into Python' - but # I love regexes so much I assembled it on my own. Refactored to *not* match beginning # of string - so any superfluous verbiage before the number will be ignored hideousRegex = """ # don't match beginning of string, number can start anywhere \(? # match a possible opening bracket for area code (\d{3}) # area code at beginning of string \)? # match a possible closing bracket \D* # one or more 'non-word' character - e.g. a hyphen, a space (\d{3}) # trunk of number - 3 digits \D* # one or more 'non-word' chars (\d{4}) # last 4 digits \D* # more non-words (\d*)? # maybe an extension of one or more digits $ """ # first (admittedly underwhelming) class written from scratch! class Queue(object): ''' a standard queue that stores elements in a list and returns them in FIFO fashion. ''' def __init__(self): ''' store the junk in a regular list, inherited from object ''' self.storage = [] def insert(self, e): ''' get thee to the end of the line, e ''' self.storage.append(e) def remove(self): ''' hack to emulate Perl's shift method. Why not just have a shift method in Python? ''' try: # res = self.storage[0] # del self.storage[0] # return res ''' ok - learned you can give an index argument to pop... ''' return self.storage.pop(0) except: raise ValueError() # custom intersect and len methods class intSet(object): def __init__(self): self.vals = [] def intersect(self, other): ''' Returns a set consisting of the intersecting elements of two distinct sets. Returns an empty set if there is no intersection ''' res = [] for e in self.vals: if e in other.vals: res.append(e) if len(res) == 0: return '{}' else: return '{' + ','.join([str(e) for e in res]) + '}' def __len__(self): return len(self.vals) # my __eq__ and __repr__ methods class Coordinate(object): def __init__(self,x,y): self.x = x self.y = y def getX(self): # Getter method for a Coordinate object's x coordinate. # Getter methods are better practice than just accessing an attribute directly return self.x def getY(self): # Getter method for a Coordinate object's y coordinate return self.y def __str__(self): return '<' + str(self.getX()) + ',' + str(self.getY()) + '>' def __eq__(self, other): return self.x == other.x and self.y == other.y def __repr__(self): return 'Coordinate(%i, %i)' % (self.x, self.y) # my custom recursive range fcn def recurRange(x,y,step,storage=[]): storage.append(x) if y - x == 1: return storage else: return recurRange(x+step,y,step,storage) # to build up a frequency hash from a string freq = {} for c in string: freq[c] = freq.get(c, 0) + 1 # my isPrime fcn def isPrime(n): """ returns True if n is prime, False otherwise """ # if n is not type int, raise TypeError if type(n) != int: raise TypeError # if n is less or eql to 0, raise ValueError if n <= 0: raise ValueError # otherwise check for primality; testing up to square root of n improves efficiency if n == 2: return True elif n < 2: return False # iterate over vals from 2 through sqrt(n) to see if there are any divisors for div in range(2, int(n**0.5 + 1)): if n % div == 0: return False # exited loop with no clean divisors - so the thing is prime return True
#------------------------------------------------------------------------------------------------------------------------------------------------------ # Creator: Sarah Gillespie # Date: August 13th, 2019 # Filename: randomWord.py # Description: random vocab generator for GRE Questions # Github: https://github.com/SarahGillespie/GRE-vocab-multiple-choice #------------------------------------------------------------------------------------------------------------------------------------------------------ import pandas as pd import numpy as np import random from graphics import * WIDTH = 800 HEIGHT = 800 def setUp(WIDTH, HEIGHT): '''creates and repeats a simple multiple choice quiz ad infinitum''' vocabData = pd.read_csv('vocabData.csv') #opens and loads the list of vocabulary words. with open('vocabData.csv') as csvfile: row_count = sum(1 for row in csvfile) totalWords = int(row_count) #counts the total number of definitions. print(",___,") print('[O.o]"') print("/)__)") print('-"--"-') print(" ") print("words = ", totalWords) score = 0 total = 0 #creates a main window win = GraphWin("Game", 800, 800) #black backdrop BACKGROUND = Rectangle(Point(0,0), Point(WIDTH, HEIGHT)) BACKGROUND.setFill("black") BACKGROUND.draw(win) #sets up the scorebox scorebox = Rectangle(Point(HEIGHT - 80,(WIDTH/2 + 20)), Point(HEIGHT,(WIDTH/2 - 20))) scorebox.setFill('blue') scorebox.draw(win) #setting up the placement of each colored box placementHEIGHTA = (1/6)*HEIGHT#multiphy by what box it is placementWIDTHA = (1/6)*WIDTH Box_one = Rectangle(Point(placementHEIGHTA, placementWIDTHA), Point(placementHEIGHTA + 20, placementWIDTHA + 30)) # points are ordered ll, ur Box_one.draw(win) Box_two = Rectangle(Point(placementHEIGHTA, 2*placementWIDTHA), Point(placementHEIGHTA + 20, 2*placementWIDTHA + 30)) Box_two.draw(win) Box_three = Rectangle(Point(placementHEIGHTA, 3*placementWIDTHA), Point(placementHEIGHTA + 20, 3*placementWIDTHA + 30)) Box_three.draw(win) Box_four = Rectangle(Point(placementHEIGHTA, 4*placementWIDTHA), Point(placementHEIGHTA + 20, 4*placementWIDTHA + 30)) Box_four.draw(win) Box_five = Rectangle(Point(placementHEIGHTA, 5*placementWIDTHA), Point(placementHEIGHTA + 20, 5*placementWIDTHA + 30)) Box_five.draw(win) #definesthe colors for each box Box_one.setFill("purple") Box_two.setFill("purple") Box_three.setFill("purple") Box_four.setFill("purple") Box_five.setFill("purple") #prints the / sign in the scorebox divideText = Text(Point(HEIGHT - 60,(WIDTH/2 + 20)),"/") divideText.setTextColor("red") divideText.setSize(30) divideText.draw(win) #placeholder for printing the correct word/guestion when you get a question incorrect endText = Text(Point((5*6)*HEIGHT,((1/2)*WIDTH))," ") endText.setTextColor("red") endText.setSize(30) endText.draw(win) #placeholder for printing the correct definition when you get a question incorrect endText2 = Text(Point((5*6)*HEIGHT,((1/2)*WIDTH))," ") endText2.setTextColor("red") endText2.setSize(30) endText2.draw(win) #placeholder for printing the correct sentence when you get a question incorrect endText3 = Text(Point((5*6)*HEIGHT,((1/2)*WIDTH))," ") endText3.setTextColor("red") endText3.setSize(30) endText3.draw(win) #this will loop the game after each question repeat = True while repeat == True: #draws the first score of 0 scoreText = Text(Point(HEIGHT - 80,(WIDTH/2 + 20)),(score)) scoreText.setTextColor("red") scoreText.setSize(30) scoreText.draw(win) #draws the first total of 0 totalText = Text(Point(HEIGHT - 40,(WIDTH/2 + 20)),(total)) totalText.setTextColor("red") totalText.setSize(30) totalText.draw(win) #picks a random integer from the total number of words. remember that counting starts at 0 thisRow = random.randint(0, totalWords) #selects and displays the word from the random row as a question. question = [vocabData['def'][thisRow]] print(question,"?") #prints the question questionGRAPHIC = Text(Point(HEIGHT/2, WIDTH/9), str(question)) questionGRAPHIC.setSize(18) questionGRAPHIC.setTextColor("red") questionGRAPHIC.draw(win) #selects the correct definition theDef = vocabData['word'][thisRow] #selects the correct sentance sent = vocabData['sent'][thisRow] #chooses 4 random definitions to make the other muliple choice answers and make this more challenging. randomDef1 = vocabData['word'][int(random.randint(0, totalWords))] randomDef2 = vocabData['word'][int(random.randint(0, totalWords))] randomDef3 = vocabData['word'][int(random.randint(0, totalWords))] randomDef4 = vocabData['word'][int(random.randint(0, totalWords))] #creates a list of incorrect definitions, correct definitions, and a list with all definitions. wrong = [randomDef1, randomDef2, randomDef3, randomDef4] #list of all the wrong definitions correct = [theDef] #list of 1, just the correct definiton allChoices = wrong + correct #list of all definitions #shuffles/randomizes all definitions choices = random.sample(allChoices, len(allChoices)) #prints each definition to the screen choices1GRAPHIC = Text(Point(placementHEIGHTA + 20, placementWIDTHA + 30), str(choices[0])) choices1GRAPHIC.setSize(18) choices1GRAPHIC.setTextColor("red") choices1GRAPHIC.draw(win) choices2GRAPHIC = Text(Point(placementHEIGHTA + 20, 2*placementWIDTHA + 30), str(choices[1])) choices2GRAPHIC.setSize(18) choices2GRAPHIC.setTextColor("red") choices2GRAPHIC.draw(win) choices3GRAPHIC = Text(Point(placementHEIGHTA + 20, 3*placementWIDTHA + 30), str(choices[2])) choices3GRAPHIC.setSize(18) choices3GRAPHIC.setTextColor("red") choices3GRAPHIC.draw(win) choices4GRAPHIC = Text(Point(placementHEIGHTA + 20, 4*placementWIDTHA + 30), str(choices[3])) choices4GRAPHIC.setSize(18) choices4GRAPHIC.setTextColor("red") choices4GRAPHIC.draw(win) choices5GRAPHIC = Text(Point(placementHEIGHTA + 20, 5*placementWIDTHA + 30), str(choices[4])) choices5GRAPHIC.setSize(18) choices5GRAPHIC.setTextColor("red") choices5GRAPHIC.draw(win) #in the shell, this prints all the definitions on a different line random order. for i in choices: print(" ") print(i) typedResponse = win.getKey() guess = typedResponse #if you wanted to use the shell only, then get input via below #guess = input("Which definition is this? 1, 2, 3, 4, or 5") #converts guess 1 to computer counting of item 0 guess = (int(guess) - int(1)) #cleans up the corrected definition from the previous question (or the placeholder text from the start) endText.undraw() endText2.undraw() endText3.undraw() #ask if [content of shuffled list item that you picked] = [item 0 (our only item) in correct list] if choices[guess] == correct[0]: scoreText.undraw() totalText.undraw() print("correct!") score = score + 1 total = total + 1 print("SCORE: ",score, "out of ", total) print("----------------------------------------------------------------------") print(" ") questionGRAPHIC.undraw() choices1GRAPHIC.undraw() choices2GRAPHIC.undraw() choices3GRAPHIC.undraw() choices4GRAPHIC.undraw() choices5GRAPHIC.undraw() #this prints placeholder text to the shell endText = Text(Point((5*6)*HEIGHT,((1/2)*WIDTH))," ") endText.setTextColor("red") endText.setSize(30) endText.draw(win) #if your guess is not the same as the answer key elif choices[guess] != correct[0]: scoreText.undraw() totalText.undraw() print("wrong answer***") #this prints the correct definition to the shell so you can learn for next time print(question, ": ", correct[0]) total = total + 1 print("SCORE: ",score, "out of ", total) print("----------------------------------------------------------------------") print(" ") questionGRAPHIC.undraw() choices1GRAPHIC.undraw() choices2GRAPHIC.undraw() choices3GRAPHIC.undraw() choices4GRAPHIC.undraw() choices5GRAPHIC.undraw() correctPrintable = str(correct[0]) #this prints the correct definition to the Zelle graphics window so you can learn for next time endText = Text(Point(HEIGHT/2,725), correctPrintable) endText.setTextColor("red") endText.setSize(30) endText.draw(win) endText2 = Text(Point(HEIGHT/2,750), question) endText2.setTextColor("red") endText2.setSize(15) endText2.draw(win) endText3 = Text(Point(HEIGHT/2,775), sent) endText3.setTextColor("red") endText3.setSize(15) endText3.draw(win) def main(): setUp(WIDTH,HEIGHT) if __name__ == "__main__": main()
''' 基本数据类型 1.Number(数字) 2.String(字符串) 3.List(列表) 4.Tuple(元组) 5.Sets(集合) 6.Dictionary(字典) ''' #整形变量 count = 100 #浮点型变量 miles = 100.0 #字符串 name = "fayuan" print(count) print(miles) print(name) #连续多个变量赋值 a, b, c, d = 20, 5.5, True, 4 + 3j print(type(a)) print(type(b)) print(type(c)) print(type(d)) print(isinstance(a, int))
a1 = 2 # Varaibles cannot start with a number b = a1 # B is undefined, it's value cannot be given to a1 x = 2 y = x + 4 # is it 6? No, the defined x was lowercase, case matters in variables, this will throw an error, change uppercase to lower. from math import tan,pi # math should be lowercase print(tan(pi)) # print statements need parenthesis in Python 3 pi = 3.14159 # You want an int, not a string or anything, no quotes. print (tan(pi)) c = 4**3**2**3 _ = ((c-78564)/c + 32) # Too many parenthesis, eliminate 1 discount = '12%' # This needs to be a string or needs to be .12 if you want to use it in calculations. AMOUNT = -120 # Negative numbers would just have a negative out front amount = '120$' # If you want to show the money sign then you need to make this a string with quotes. address = 'hpl@simula.no' # The email is a string, add quotes And = 'duck' # and is a protected word in Python, change it a bit, duck is also not defined, And cannot equal it, make it a string class1 = "INF1100, gr 2" # class is protected as well, use same quotes at beginning and end continue_ = x > 0 rev = fox = True Persian = ['a human language'] true = fox is rev in Persian # The last line of the code moves from right to left. First Python checks if rev is in Persian. Asking if True is in 'a human language'. It is not and so it returns False. Then fox is False ask if True is equal to False, not true, returns False, and so true is equated to False.
def next_letter(c, key): if ord(c) + key <= 90: return chr((ord(c) + key)) return chr((ord(c) + key) - 26) def previous_letter(c, key): if ord(c) - key >= 65: return chr((ord(c) - key)) return chr((ord(c) - key) + 26) def cipher_wheel_crypt(phrase, key): result = "" for c in phrase.upper(): if c != " ": result = result + next_letter(c, key) else: result = result + c return result def cipher_wheel_decrypt(phrase, key): result = "" for c in phrase.upper(): if c != " ": result = result + previous_letter(c, key) else: result = result + c return result
import matplotlib.pyplot as plt import numpy as np import pandas as pd #Import CSV into Pandas DataFrame df = pd.read_csv('OlympicsWinter.csv',usecols=["Year", "Sport", "Country", "Gender", "Event", "Medal"]) #Replace spaces in col names with underscore and sets all to lowercase df.columns = df.columns.str.strip().str.lower().str.replace(' ', '_') #Filter columns (like country) df = df[(df.sport == "Curling")] #Group dataframe by gender, count medals, unstack and reset index to convert data back into table format df1 = df.groupby('country')['medal'].value_counts().unstack().reset_index() df1.loc[:,'Row_Total'] = df1.sum(numeric_only=True, axis=1) df1 = df1.sort_values('Row_Total', ascending=False) #print df1 to make sure data looks right #print(df1) # set width of bar barWidth = 0.25 # set height of bar (used as the Y Axis in plt.bar bars1 = df1.Gold bars2 = df1.Silver bars3 = df1.Bronze # Set position of bar on X axis in plt.bar (this creates the spacing between the bars or they would overlap) r1 = np.arange(len(bars1)) r2 = [x + barWidth for x in r1] r3 = [x + barWidth for x in r2] # Make the plot plt.bar(r1, bars1, color='Gold', width=barWidth, edgecolor='white', label='Gold') plt.bar(r2, bars2, color='Silver', width=barWidth, edgecolor='white', label='Silver') plt.bar(r3, bars3, color='#cd7f32', width=barWidth, edgecolor='white', label='Bronze') # Add xticks on the middle of the group bars and uses df1.gender as the text value plt.xticks([r + barWidth for r in range(len(bars1))], df1.country) #Give it a title plt.title("Curling Medals by Country") #Give the x and y axes a title plt.ylabel("Medal Counts") # Adjust the margins plt.subplots_adjust(bottom= 0.2) # show me the money plt.legend(loc=1) plt.show()
# you can simply [::-1] def reverser(string: str): result = "" for i in range(len(string)-1, -1, -1): result += string[i] return result
from typing import List def inserter(items: List, string: str) -> None: items = items.copy() for i in range(len(items)): items[i] = string + str(items[i]) return items
from typing import Dict def generator(n: int) -> Dict[int, int]: result = dict() for i in range(1, n+1): result[i] = i ** 2 return result print(generator(15))
def reverse(n): rev = 0 while n > 0 : rem = n % 10 rev = rev * 10 +rem n =n//10 return rev print(reverse(12345))
from math import sqrt def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def primesquare(l): flag=0 if len(l)==1: n=l[0] if(sqrt(n)%1==0): return True else: for i in range(0,len(l)): if(sqrt(l[i])%1==0): if(i==0): if(isprime(l[i+1])==True): flag=1 else: if(isprime(l[i-1])==True): if(isprime[i+1]==True): flag=1 else: flag=0 else: flag=0 if(flag==0): return False else: return True print(primesquare([4,5,9,11])) '''import math import operator def square(l): lis = [] nl = [] for i in range(len(l)): x = l[i] ** 0.5 lis = lis + [x] final = [math.floor(x) for x in lis] #return lis #return final x = list(map(operator.sub,lis,final)) #return x for i in x: if not i == 0: return False return True print(square([16,9,26])) def prime(n): count = 0 for i in range(1,n+1): if n % i == 0: count = count +1 if count == 2: return True else: return False #print(prime(11)) def checkprime(l): x = list(filter(prime,l)) return x #print(checkprime([2,6,5,7])) def primesquare(l): x = checkprime(l) print(l) if (l[::2] == x and l[1:][::2]) or (l[1:][::2] and l[::2] == x) : return True #print(primesquare([5,16,101,36,27])) '''
import itertools, time PUZZLE_INPUT = 'day_1_input.txt' def get_puzzle_input(puzzle_file): with open(puzzle_file) as file_input: return [int(line.rstrip('\n')) for line in file_input] def find_first_duplicate(changes): freq = 0 found = set() for change in itertools.cycle(changes): freq += change if freq in found: return freq found.add(freq) t = time.process_time() changes = get_puzzle_input(PUZZLE_INPUT) first_duplicate = find_first_duplicate(changes) elapsed = round(time.process_time() - t, 4) print(f'first duplicate frequency: {first_duplicate}') print(f'in {elapsed} seconds')
# 创建dict字典 dict1 = {'A': '11', 'B': '22', 'C': '33'} # dict特征1:根据key获取value print(dict1['B']) # dict特征2:修改value dict1['A'] = 11 print(dict1) # dict特征3:del删除 del dict1['C'] print(dict1) # dict特征4:clear清空 # dict1.clear() # print(dict1) # dict特征5:加入新的元素 dict1['C'] = 33 print(dict1) # 创建defaultdict from collections import defaultdict df1 = defaultdict(int) df2 = defaultdict(set) df3 = defaultdict(str) df4 = defaultdict(list) # 访问不存在的key值并不会报错而是返回默认类型初始值 print(df1[1],df2[1],df3[1],df4[1]) # Output:0 set() [] # OrderedDict创建 from collections import OrderedDict od1 = OrderedDict() od1['A'] = 1 od1['B'] = 2 od1['C'] = 3 print(od1) # Output:OrderedDict([('A', 1), ('B', 2), ('C', 3)]) # 与普通字典dict作对比 d2 = dict() d2['A'] = 1 d2['B'] = 2 d2['C'] = 3 print(d2) # Output:{'B': 2, 'C': 3, 'A': 1} # 创建Counter from collections import Counter s = 'hello' c = Counter(s) print(c) # Output: Counter({'l': 2, 'e': 1, 'o': 1, 'h': 1})
# set特性1不存在重复值 s1 = {1,1,2,3,4} # print(s1) # Output:{1, 2, 3, 4} # set特征2访问是无序的,不支持通过索引访问集合元素 # set特征3是可变的,支持加入不同类型的元素,同时发现加入字符串输出时在第一个,也证明了无序性 s1.add('python') # print(s1) # Output:{'python', 1, 2, 3, 4} # set特征3:续-但是不能向set中加入可变容器例如列表、字典-->会报错unhashable type:‘list’ # s1.add([1,2]) # print(s1) # Output:TypeError: unhashable type: 'list' # set特征4:update(item) 注意这里的update不再是更新修改,而是将item拆分后多个子元素加入集合 s1.update('hi') # print(s1) # Output:{1, 2, 3, 4, 'h', 'python', 'i'} # set特征5:remove(item)移除操作,需要注意当你移除不存在的元素会报错KeyError s1.remove('h') # print(s1) # Output:{1, 2, 3, 4, 'python', 'i'} # s1.remove(100) # print(s1) # Output:KeyError: 100 # set特征6:union(联合), intersection(交集), difference(差集)和sysmmetric difference(对称差集) s1 = {6,4,3,4,5} s2 = {1,2,3,7,4} # 求交集操作,选取s1和s2都存在的元素 s3 = s1 & s2 # 求并集操作,选取s1和s2中全部元素 s4 = s1 | s2 # 求差集操作,将去除s1中在s2也存在的元素 s5 = s1 - s2 # 与非操作,将在两个set中均存在的元素去除 s6 = s1^s2 # =====程序员专用分割线===== # frozenset冻结的集合,冻结后不能再添加或者删除元素,注意添加/移除元素要报错 fs1 = frozenset({1,1,2,3,4}) print(fs1)
__author__="albert" __date__ ="$Mar 19, 2012 1:26:31 AM$" # Puzzle_1: string with unique characters def unique_char(string): letters = [] for i in string: if i in letters: return "not all are unique!" else: letters.append(i) return "You have a unique string!" #print unique_char("abcdefg") # Puzzle_2: reverse a c-style null-terminated string def reverse_string(string): return string[::-1] # print reverse_string("albert") # Puzzle_3: Design an algorithm and write code to remove the duplicate characters in a string # without using any additional buffer. NOTE: One or two additional variables are fine. def removeDuplicate(string): charList = list(string) for i, ch in enumerate(charList): if ch in charList[:i] or ch in charList[i+1:]: while ch in charList: charList.remove(ch) return ''.join(charList) #print removeDuplicate("abcccdef") # Puzzle_4: Write a method to decide if two strings are anagrams or not. def anagramCheck(string1,string2): if string1[::-1] == string2: return "Yes, they are anagrams." else: return "No, they are not anagrams." # print anagramCheck("albert","trebla") # Puzzle_4: Write a method to replace all spaces in a string with def stringReplacement(string): return string.replace(' ','%20') def stringReplacement2(string): stringList = string.split() print list(string) return '%20'.join(stringList) # print stringReplacement2('This is a smooth operator!') # Puzzle_5: Given an image represented by an NxN matrix, where each pixel in the image is 4 # bytes, write a method to rotate the image by 90 degrees. Can you do this in place? def rotateMatrixStatic(imageMatrix): matrixSize = len(imageMatrix) newMatrix = [[] for i in range(matrixSize)] for i,columnValue in enumerate(imageMatrix): for j,rowValue in enumerate(imageMatrix[i]): newMatrix[i].append(imageMatrix[j][i]) # newMatrix[i].reverse() ======Reversing a list is importnant!======= return newMatrix def printMatrix(imageMatrix): for i,columnValue in enumerate(imageMatrix): for j,rowValue in enumerate(imageMatrix[i]): print '[', rowValue, ']', #notice the trailing ',' which eliminates the newline character print '\n', #testMatrix = [[(1,2,3,4),(1,2,3,4),(1,2,3,4),(1,2,3,4),(1,2,3,4)],[0,0,0,0,0], #[0,0,0,0,0],[0,0,0,0,0],[(1,2,3,4),(1,2,3,4),(1,2,3,4),(1,2,3,4),(1,2,3,4)]] #printMatrix(testMatrix) #print #printMatrix(rotateMatrixStatic(testMatrix)) # Puzzle_6: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and # column is set to 0. def rowColumnNulifier(matrix): rowIndex = [] #Nullifying rows for i,columnValue in enumerate(matrix): if 0 in matrix[i]: rowIndex.append(i) #Nullifying columns for i,columnValue in enumerate(matrix): if 0 in matrix[i]: columnIndex = [] for j, rowValue in enumerate(matrix[i]): if rowValue == 0: columnIndex.append(j) for k,columnValue2 in enumerate(matrix): for l in columnIndex: matrix[k][l] = 0 #columnIndex = matrix[i].index(0) =========Nice tool right here!======== for i in rowIndex: matrix[i]=[0]*len(matrix[i]) #break return matrix #printMatrix([[1,2,3],[4,5,6],[7,0,8],[9,1,2],[3,4,5]]) #print #printMatrix(rowColumnNulifier([[1,2,3],[4,5,6],[7,0,8],[9,1,2],[3,4,5]])) # Write coding for Grub puzzle: ArrayLeader in linear time! def arrLeader(A): for i, value in enumerate(A): if A.count(value) > len(A)/2: return A[i] return -1 def arrLeader2(A): dict = {} if len(A) == 0: return -1 if len(A) == 1: return A[0] for i, value in enumerate(A): try: dict[value] += 1 except: dict[value] = 1 maxKey = max(dict,key = lambda a: dict.get(a)) print dict print maxKey print dict[maxKey] print len(A)/2 if dict[maxKey] > len(A)/2: return maxKey else: return -1 #print arrLeader2([1,0]) def arrLeader3(A): counter = 0 preValue = 0 for i, value in enumerate(sorted(A)): try: preValue = sorted(A)[i-1] except: preValue = value if value == preValue: counter+=1 if counter>(len(A)/2): return value return -1 #print arrLeader3([3,1,1,1,1,1,5,1,0,9]) #positive_int_generator = lambda n: big_o.datagen.integers(100000, 0, 10000) #best, others = big_o.big_o(arrLeader2, positive_int_generator, n_repeats=1) #print best # Puzzle_7: Assume you have a method isSubstring which checks if one word is a substring of # another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using # only one call to isSubstring (i.e., waterbottle is a rotation of erbottlewat). def isSubstring(string1,string2): if len(string1) != len(string2): return "Not sublists of each other." if len(string1)==0: return "The strings are empty." if string1 == string2: return "Yes, those 2 strings are subs." for i, char in enumerate(string1): #print string1[:i] #print string1[i:] if string1[:i] in string2 and string1[i:] in string2: return "Yes, those 2 strings are subs." return "Not sublists of each other." # print isSubstring("albert","talber")
from selenium import webdriver #Need to manually install selenium #To open Firefox, download geckodriver: https://github.com/mozilla/geckodriver/releases #To open Chrome, download chromedriver (please pay attention to your Chrome version number and download the same version number for chromedriver): https://sites.google.com/a/chromium.org/chromedriver/home #browser = webdriver.Firefox() #this now works. Maybe I need to restart the computer aftr downloading geckodriver and placing it on the PATH environment variable. browser = webdriver.Chrome() #I made a path environment variable linking to C:\Users\Dell\AppData\Local\Programs\Python\Python38, where my geckodriver and chromedriver applications are saved. #If you don't do this, you need to place the absolute filename in those parentheses. #DO NOT CLOSE the geckodriver/ chromedriver window that pops up when running the program. #Example goal: search 'scholarship' on the DLSU website and return results on Chrome. browser= webdriver.Chrome() browser.get('https://www.dlsu.edu.ph/search_gcse/?q=') searchElem = browser.find_element_by_id('gsc-i-id3') #ALWAYS run this before using send_keys searchElem.send_keys('scholarship') #the submit() function didn't work in the DLSU website. So I have to resort to clicking the search button. submitButton = browser.find_element_by_css_selector('#___gcse_2 > div > div > form > table > tbody > tr > td.gsc-search-button > button') submitButton.click() browser.back() #previous page browser.forward() #next page browser.refresh() #refresh browser.quit() #close browser
#kode karyawan kode = input("Masukkan kode karyawan : ") #nama karyawan nama = input("Masukkan nama karyawan : ") #golongan gol = input("Masukkan golongan : ") if (gol == "A") or (gol == "a"): gaji_pokok = 10000000 potongan = 2.5 elif (gol == "B") or (gol == "b"): gaji_pokok = 8500000 potongan = 2.0 elif (gol == "C") or (gol == "c"): gaji_pokok = 7000000 potongan = 1.5 elif (gol == "D") or (gol == "d"): gaji_pokok = 5500000 potongan = 1.0 print("=====================================") print(" STRUK RINCIAN GAJI KARYAWAN ") print("-------------------------------------") #tampilan nama karyawan print("Nama Karyawan :",nama, "(Kode:",kode,")") #tampilan golongan print("Golongan :",gol) print("-------------------------------------") #gaji pokok print("Gaji Pokok : Rp ",gaji_pokok) #potongan potong = gaji_pokok*potongan/100 print("Potongan (",potongan,"%) : Rp ",potong) print("------------------------------------- -") print("Gaji Bersih : Rp ",gaji_pokok-potong)
#Indo indo = float(input("Masukkan nilai Bhs Indonesia : ")) #Ipa ipa = float(input("Masukkan nilai IPA : ")) #Mat mat = float(input("Masukkan nilai Matematika : ")) if (indo > 59) and (ipa > 59) and (mat > 70): print("Status Kelulusan : LULUS") else: print("Status Kelulusan : TIDAK LULUS") print("Sebab :") if (indo < 60): print("- Nilai Bhs Indonesia kurang dari 60") if (ipa < 60): print("- Nilai IPA kurang dari 60") if (mat == 70): print("- Nilai Matematika tidak lebih dari 70") elif (mat <= 70): print("- Nilai Matematika kurang dari 70")
print('----------------------------------') print(' Harga Buah ') print('----------------------------------') print({'apel' : 5000, 'jeruk' : 8500, 'mangga' : 7800, 'duku' : 6500}) hargabuah = {'apel' : 5000, 'jeruk' : 8500, 'mangga' : 7800, 'duku' : 6500} maks = max(hargabuah['apel'], hargabuah['jeruk'], hargabuah['mangga'],hargabuah['duku']) def hargamax(): for i in hargabuah: if maks == hargabuah[i]: print('Harga Paling Mahal : ', i) hargamax()
import random # komputer memilih angka secara acak dari 1 s.d 100 angka = random.randint(1,100) print('Hai, nama saya Destri, saya telah memilih sebuah bilangan bulat secara acak antara 0 s/d 100. Silakan tebak ya!!!') teks_petunjuk = 'Tebakan Anda : ' score = 100 score_min = 0 tebakan = False nomor_tebakan = 0 while not tebakan: tebak = input(teks_petunjuk) tebak = int(tebak) nomor_tebakan = nomor_tebakan + 1 score = 100-nomor_tebakan*2 if tebak == angka: tebakan = True elif tebak > angka: print('Hehehe...Bilangan tebakan anda terlalu besar') else: print('Hehehe...Bilangan tebakan anda terlalu kecil') if tebakan: print('Yeeee...Bilangan tebakan anda BENAR :-)') if score < score_min: print('Score Anda: ',score_min) else: print('Score Anda: ',score)
#kode karyawan kode = input("Masukkan kode karyawan : ") #nama karyawan nama = input("Masukkan nama karyawan : ") #golongan gol = input("Masukkan golongan : ") if (gol == "A") or (gol == "a"): gaji_pokok = 10000000 potongan = 2.5 tunjangan = gaji_pokok*10/100 tunjangan_anak = gaji_pokok*5/100 elif (gol == "B") or (gol == "b"): gaji_pokok = 8500000 potongan = 2.0 tunjangan = gaji_pokok*10/100 tunjangan_anak = gaji_pokok*5/100 elif (gol == "C") or (gol == "c"): gaji_pokok = 7000000 potongan = 1.5 tunjangan = gaji_pokok*10/100 tunjangan_anak = gaji_pokok*5/100 elif (gol == "D") or (gol == "d"): gaji_pokok = 5500000 potongan = 1.0 tunjangan = gaji_pokok*10/100 tunjangan_anak = gaji_pokok*5/100 #status status = input("Masukkan status(1:Menikah,2:Belum Menikah) : ") if (status == "1") or (status == "menikah") or (status =="Menikah"): anak = int(input("Masukkan jumlah anak : ")) print("============================================") print(" STRUK RINCIAN GAJI KARYAWAN ") print("--------------------------------------------") #tampilan nama karyawan print("Nama Karyawan :",nama, "(Kode:",kode,")") #tampilan golongan print("Golongan :",gol) #status menikah print("Status Menikah :",status) if (status == "1") or (status == "menikah") or (status =="Menikah"): print("Jumlah Anak :",anak) else: print("Jumlah Anak : -") print("--------------------------------------------") #gaji pokok print("Gaji Pokok : Rp ",gaji_pokok) if (status == "1") or (status == "menikah") or (status =="Menikah"): print("Tunjangan Istri/Suami : Rp ",tunjangan) print("Tunjangan Anak : Rp ",tunjangan_anak*anak) else: print("Tunjangan Istri/Suami : - ") print("Tunjangan Anak : - ") print("-------------------------------------------- +") #gaji kotor if (status == "1") or (status == "menikah") or (status =="Menikah"): gaji_kotor = gaji_pokok+tunjangan+tunjangan_anak*anak print("Gaji Kotor : Rp ",gaji_kotor) else: print("Gaji Kotor : Rp ",gaji_pokok) #potongan if (status == "1") or (status == "menikah") or (status =="Menikah"): potong = gaji_kotor*potongan/100 print("Potongan(",potongan,"%) : Rp ",potong) else: print("Potongan(",potongan,"%) : Rp ",gaji_pokok*potongan/100) print("-------------------------------------------- -") if (status == "1") or (status == "menikah") or (status =="Menikah"): print("Gaji Bersih : Rp ",gaji_kotor-potong) else: print("Gaji Bersih : Rp ",gaji_pokok-gaji_pokok*potongan/100)
def sum(*myData): # init values sum = 0 i = 0 # menjumlahkan semua data dalam myData for data in myData: sum += data i +=1 # hitung jumlah jumlah = sum print('Jumlah: ',jumlah) def average(*myData): # init values sum = 0 i = 0 # menjumlahkan semua data dalam myData for data in myData: sum += data i +=1 # hitung rata-rata average = sum/i print('Rata-rata: ',average) def maks(*mydata): # init values maksimal = 0 # data terbesar dalam myData for data in mydata: if data > maksimal: maksimal = data maks = maksimal print('Nilai Maksimum: ',maksimal) def min(*myData): # init values minimum = 100 # data terbesar dalam myData for data in myData: if data < minimum: minimum = data min = minimum print('Nilai Minimum: ',minimum)
import numpy as np from matplotlib import pyplot as plt data = np.random.binomial(1, 0.25, (100000, 1000)) epsilon = [0.5, 0.25, 0.1, 0.01, 0.001] tosses = np.arange(1, 1001) def plot_means(): for i in range(5): plt.plot(tosses, np.cumsum(data[i]) / tosses) plt.xlabel("Number of coins tosses") plt.ylabel("Mean value") plt.show() def plot_variances(): for eps in epsilon: plt.plot(tosses, np.minimum(1, 1 / (4 * tosses * (eps ** 2))), 'r', label='Chebyshev Bound') plt.plot(tosses, np.minimum(1, 2 * np.exp(-2 * tosses * (eps ** 2))), 'b', label='Hoeffding Bound') plt.plot(tosses, np.sum(abs((np.cumsum(data, axis=1) / tosses) - 0.25) >= eps, axis=0) / 100000, 'g', label='Percentage') plt.xlabel("Number of coins tosses") plt.ylabel("Probability") plt.title(r"$\epsilon$ = " + str(eps)) plt.legend() plt.show() plot_means() plot_variances()
""" Simple implementation of (Fisher's) Linear Discriminant Analysis. Thanks to: https://www.python-course.eu/linear_discriminant_analysis.php The L. D. Matrix is a transformation matrix which best separates the instances of different classes in data projection. """ import sklearn.base import numpy as np import scipy.linalg class LDA(sklearn.base.TransformerMixin): def __init__(self, max_dim: int = -1): self.max_dim = int(max_dim) self.classes = np.empty(0) self.cls_freqs = np.empty(0) self.eig_vals = np.empty(0) self.transf_mat = np.empty(0) def _scatter_within(self, X: np.ndarray, y: np.ndarray): """This measure describes how scattered are each class.""" scatter_within = np.array( [ np.cov(X[y == cls, :], ddof=cls_freq - 1, rowvar=False) for cls, cls_freq in zip(self.classes, self.cls_freqs) ] ).sum(axis=0) return scatter_within def _scatter_between(self, X: np.ndarray, y: np.ndarray): """This measure describes the separation between different classes.""" class_means = np.array([X[y == cls, :].mean(axis=0) for cls in self.classes]) total_mean = X.mean(axis=0) scatter_factor = class_means - total_mean scatter_between = np.array( [ freq * np.outer(sf, sf) for freq, sf in zip(self.cls_freqs, scatter_factor) ] ).sum(axis=0) return scatter_between def _get_eig(self, sw, sb): """Get eigenval/vec from (ScatterWithin)^(-1)*(ScatterBetween) mat.""" sw_inv = np.eye(sw.shape[0]) sw_inv = scipy.linalg.solve( sw, sw_inv, assume_a="pos", overwrite_b=True, check_finite=False ) return np.linalg.eigh(np.matmul(sw_inv, sb)) def _project(self, eig): """Get the K (``num_dim``) most expressive eigenvalues/vectors.""" eig_vals, eig_vecs = eig eig_vals, eig_vecs = zip( *sorted(zip(eig_vals, eig_vecs), key=lambda item: item[0], reverse=True)[ : self.max_dim ] ) return eig_vals, eig_vecs def fit(self, X, y): """Fit dataset into LDA model.""" X = np.asfarray(X) y = np.asarray(y) _, num_col = X.shape self.classes, self.cls_freqs = np.unique(y, return_counts=True) sw = self._scatter_within(X, y) sb = self._scatter_between(X, y) self.max_dim = self.max_dim if self.max_dim >= 1 else num_col self.max_dim = min(self.max_dim, self.classes.size - 1, num_col) eig = self._get_eig(sw, sb) eig_vals, eig_vecs = self._project(eig) self.eig_vals = np.array(eig_vals) self.transf_mat = np.concatenate(eig_vecs).reshape(num_col, self.max_dim) return self def transform(self, X, y=None): """Create transf. matrix which best separates the fitted data proj.""" return np.dot(X, self.transf_mat) def wilks_lambda(self): """Compute Wilks' Lambda measure using eigenvalues of L. D. matrix.""" return np.prod(1.0 / (1.0 + self.eig_vals)) def canonical_corr(self): """Calculate canonical correlation values from L. D. matrix.""" return (self.eig_vals / (1.0 + self.eig_vals)) ** 0.5 if __name__ == "__main__": from sklearn import datasets X, y = datasets.load_iris(return_X_y=True) model = LDA() ans = model.fit_transform(X, y) print("Transformation Matrix:", model.transf_mat, sep="\n", end="\n\n") print("Eigenvalues of L. D. matrix:", model.eig_vals, end="\n\n") print("Canonical Correlation:", model.canonical_corr(), end="\n\n") print("Wilks' Lambda:", model.wilks_lambda())
# -*- coding: utf-8 -*- """ Created on Tue June 11 10:56:03 2019 @author: Paul """ import numpy as np def p(prices_historical=None, demand_historical=None, information_dump=None): """ this pricing algorithm returns a random price for the first three time periods and then returns a weighted moving average of the competitor prices. input: prices_historical: numpy 2-dim array: (number competitors) x (past iterations) it contains the past prices of each competitor (you are at index 0) over the past iterations demand_historical: numpy 1-dim array: (past iterations) it contains the history of your own past observed demand over the last iterations information_dump: some information object you like to pass to yourself at the next iteration """ # Check if we are in the very first call to our function and then return a random price if prices_historical is None and demand_historical is None: # Initialize our Information Dump information_dump = { "Message": "Very First Call to our function", "Number of Competitors": None, "Time Period": 1 } random_prices = np.round(np.random.uniform(30, 80), 1) return (random_prices, information_dump) else: # Get current Time Period and store in information dump current_period = prices_historical.shape[1] + 1 information_dump["Time Period"] = current_period # Update information dump message information_dump["Message"] = "" # Get number of competitors from information dump if information_dump["Number of Competitors"] != None: n_competitors = information_dump["Number of Competitors"] else: n_competitors = prices_historical.shape[0] - 1 information_dump["Number of Competitors"] = n_competitors # In the first three periods we still use random prices if current_period <= 3: random_prices = np.round(np.random.uniform(30, 80), 1) return (random_prices, information_dump) # From the fourth period onwards we use the moving average elif current_period > 3: # Get last 3 competitor prices for each competitor last_prices = prices_historical[1:, -3:] # Compute Mean of oldest, middle and newest prices separately oldest_prices_mean = np.mean(last_prices[:,0]) middle_prices_mean = np.mean(last_prices[:,1]) newest_prices_mean = np.mean(last_prices[:,2]) # Combine means using separate weights next_price = np.round(0.2*oldest_prices_mean + 0.3 * middle_prices_mean + 0.5 * newest_prices_mean, 1) return (next_price, information_dump)
''' Created on Aug 30, 2018 @author: Manikandan.R ''' print ('Running Fibonacci') a, b = 0, 1 while a < 10: print(a, end=',') a, b = b, a + b print ('Handling Strings') alphas = "abcdefghijklmnopqrstuvwxyz" index = len(alphas) // 2 alpha1 = alphas[: index] alpha2 = alphas[index :] print ('alphas: ' + alphas) print ('alpha1: ' + alpha1) print ('alpha2: ' + alpha2) print ('Handling Lists') lists = [1, 2, 3, 4, 5, 6, 7, 8, 9] print ('My List: ', lists) print ('4th element from start: ', lists[4]) print ('1st element from end: ', lists[-1])
def factorial(x): if (x < 2): return 1 else: return (x * (factorial(x-1)))
#Program porównujący ilość pizzy pomiędzy trzema pizzami z reztauracji #Znajdź restaurację i za pomocą wbudowanej biblioteki #Dane nazwa_restauracji, nazwa_pizzy, 3xrozmiar_pizzy, 3xcena_pizzy import sys import math wyniki = sys.argv def printing_pizza(): pizza1 = [] pizza2 = [] pizza3 = [] pizza1.append(wyniki[1:5]) pizza2.append(wyniki[1:3]) pizza3.append(wyniki[1:3]) pizza2.append(wyniki[5:7]) pizza3.append(wyniki[7:9]) print(pizza1) print(pizza2) print(pizza3) def porownaj(wyniki): printing_pizza() koszt = [] ilosc = [] rozmiar1 = str(wyniki[3]) cena1 = str(wyniki[4]) rozmiar2 = str(wyniki[5]) cena2 = str(wyniki[6]) rozmiar3 = str(wyniki[7]) cena3 = str(wyniki[8]) rozmiar1 = int(rozmiar1) rozmiar2 = int(rozmiar2) rozmiar3 = int(rozmiar3) cena1 = int(cena1) cena2 = int(cena2) cena3 = int(cena3) pi = 3.14 pole1 = (rozmiar1 * rozmiar1 * pi)/2 pole2 = (rozmiar2 * rozmiar2 * pi)/2 pole3 = (rozmiar3 * rozmiar3 * pi)/2 najlepsza = cena1 / pole1 naj = "Najmniejsza pizza jest najbardziej opłacalna" if najlepsza > cena2 / pole2: najlepsza = cena2 / pole2 naj = "Średnia pizza jest najbardziej opłacalna" if najlepsza > cena3 / pole3: najlepsza = cena3 / pole3 naj = "Największa pizza jest najbardziej opłacalna" print(naj) porownaj(wyniki)
from datetime import date,datetime import traceback from pathlib import Path def convert_date_to_excel_number(datevalue): """ Convert datetime value into numeric value :param datevalue: python datetime value. :type datevalue: date. :returns: int -- Number equivalent to datetime. >>> convert_date_to_excel_number(date(2019,2,21)) 43517 """ offset = 693594 current = date(datevalue.year, datevalue.month, datevalue.day) n = current.toordinal() return (n - offset) def xlnumdate_to_datetime(xldate): """ Convert date numeric value into python datetime :param xldate: numeric value of date. :type xldate: int. :returns: datetime -- Datetime equivalent to given xldate. >>> xlnumdate_to_datetime(43517) 2019-02-21 00:00:00 """ dt = datetime.fromordinal(datetime(1900, 1, 1).toordinal() + xldate - 2) return datetime(dt.year,dt.month,dt.day)
class A(object): class_var = 3.14 def __init__(self): self.instance_var = 6.28 # # if __name__ == '__main__': print('\nClass variable can be accessed thru class itself or an instance. However instance variable can be only accessed thru an instance:') print(A.class_var) print(A().class_var) print(A().instance_var) print('\nClass variable modified thru an instance will not affected the class or other instances:') a = A() a.class_var = -3.14 print(a.class_var) print(A.class_var) print(A().class_var) print('\nClass variable modified thru class itself will affect other instances:') A.class_var = -6.28 print(A.class_var) print(A().class_var) #
x = 1 def fun1(x): print('id(x):{} at the top of func1'.format(id(x))) x = 2 print('id(x):{}, id(2):{} after the assignment'.format(id(x), id(2))) # print('####### fun1 #######') fun1(x) print(x) # 1 a = [] def fun2(a): print('id(a):{} at the top of func2'.format(id(a))) a.append(1) print('id(a):{} after the assignment'.format(id(a))) # print('####### fun2 #######') fun2(a) print(a) # [1] class PersonStr: name = 'aaa' # p1 = PersonStr() p2 = PersonStr() print('####### Member variable in Class PersonStr #######') print('id(p1.name):{} before assignment, and value of p1.name:{}'.format(id(p1.name), p1.name)) p1.name = 'bbb' print('id(p1.name):{} after assignment, and value of p1.name:{}'.format(id(p1.name), p1.name)) print('id(p2.name):{} and id(PersonStr.name):{} are unchanged'.format(id(p2.name), id(PersonStr.name))) class PersonArr: name = [] # p1 = PersonArr() p2 = PersonArr() print('####### Member variable in Class PersonArr #######') print('id(p1.name):{} before append op, and value of p1.name:{}'.format(id(p1.name), p1.name)) p1.name.append(1) print('id(p1.name):{} after append op, and value of p1.name:{}'.format(id(p1.name), p1.name)) print('id(p2.name):{} and id(PersonArr.name):{} are unchanged'.format(id(p2.name), id(PersonArr.name)))
def buy_nug_calc(num,min=0,twinty=0,nine=0,six=0): if min==20: twinty = twinty+1 if min==9: nine = nine+1 if min==6: six = six+1 if num==0: print("="*49) print('|\tSix = '+str(six)+' Nine = '+str(nine)+" Twinty = "+str(twinty)+"\t\t|") # print("="*50) return True elif num<0: return False else: return buy_nug_calc(num-20,20,twinty,nine,six) or buy_nug_calc(num-9,9,twinty,nine,six) or buy_nug_calc(num-6,6,twinty,nine,six) while(True): nug_value = int(input("\nInsert Nuggets: ")) if buy_nug_calc(nug_value) == True: result = "|\t -- Pattern Possible --\t\t|" else: result = "="*49+ "\n|\t -- Pattern Not Possible --\t\t|" print(result) print("="*49)
"""potential_dates = [{"name": "Julia", "gender": "female", "age": 29, "hobbies": ["jogging", "music"], "city": "Hamburg"}, {"name": "Sasha", "gender": "male", "age": 18, "hobbies": ["rock music", "art"], "city": "Berlin"}, {"name": "Maria", "gender": "female", "age": 35, "hobbies": ["art"], "city": "Berlin"}, {"name": "Daniel", "gender": "non-conforming", "age": 50, "hobbies": ["boxing", "reading", "art"], "city": "Berlin"}, {"name": "John", "gender": "male", "age": 41, "hobbies": ["reading", "alpinism", "museums"], "city": "Munich"}] """ def select_dates(potential_dates): names = [] for person in potential_dates: if person["age"] > 30 and person["city"] == "Berlin" and 'art' in person["hobbies"]: names.append(person['name']) return ', '.join(names) """ Dictionary comprehension names = [person['name'] for person in potential_dates if person["age"] > 30 and person["city"] == "Berlin" and 'art' in person["hobbies"]] print(', '.join(names)) """
x=5 x=input("Enter value of x:") y=10 y=input("Enter value of y:") #create a temporary varibles and swap the values temp=x x=y y=temp print("The value of x after swapping:{}"format(x)) print("The value of y before swapping:{}"format(y))
# Python program to convert km to mts: num11 = float(input("Enter a number in kms = ")) num12 = num11 * 0.62 print(num12)
# some_input = "0 2 7 0" some_input = "2 8 8 5 4 2 3 1 5 5 1 2 15 13 5 14" known_states = set() state_idx = {} def find_max(memory): """ :param memory: the list :return: the index of the first maximum value """ import operator index, value = max(enumerate(memory), key=operator.itemgetter(1)) return index def distribute(max_idx, memory): val = memory[max_idx] length = len(memory) memory[max_idx] = 0 idx = max_idx for i in range(val, 0, -1): if idx == length - 1: idx = 0 else: idx += 1 memory[idx] += 1 def create_fingerprint(memory): # ";".join(memory) # [int(i) for i in some_input.split()] from functools import reduce return reduce(lambda x, y: str(x) + ";" + str(y), memory) def record_memory_state(memory, step): orig_len = len(known_states) fingerprint = create_fingerprint(memory) known_states.add(fingerprint) already_seen = orig_len == len(known_states) if not already_seen: state_idx[fingerprint] = step return already_seen def process_memory(memory, step): max_idx = find_max(memory) distribute(max_idx, memory) return record_memory_state(memory, step) def part1(memory): done = False step = 0 while not done: step += 1 done = process_memory(memory, step) print("memory is now {}".format(memory)) return step def test(): my_list = [-1, 2, 4, 2, 5, 5, 5] import operator index, value = max(enumerate(my_list), key=operator.itemgetter(1)) print("test: {}".format(index)) for i in range(10, 0, -1): print("test2: {}".format(i)) def main(): memory = [int(i) for i in some_input.split()] print("memory is {}".format(memory)) step_count = part1(memory) print("It took {} steps".format(step_count)) fingerprint = create_fingerprint(memory) print("The cycle count is {}".format(step_count - state_idx[fingerprint])) # test() if __name__ == "__main__": main()
# Days In Row! # # This program takes as input a start day, month, and year. Then, it calculates # the number of days total from 0 to the start date, and subtracts that number # from the total days from 0 to the end date. It adds "1" to this to show how # many days in a row, and it return an integer of the days in a row. # # This program returns how many days in a row something has occured, assuming # that there have been no breaks in between the start date and today, and adds # 1. # (As in, if I started something on Monday, and did that thing Monday, Tuesday, # and Wednesday, I would have done this 3 days in a row. But since Wednesday's # date minus Monday's date is only 2, we add 1 for days in a row.) def is_leap_year(year): if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: return True return False def daysBetweenDates(start_year, start_month, start_day, end_year, end_month, end_day): total_days_start = 0 total_days_today = 0 daysOfMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] daysOfLeap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # getting the total days in start_year for y in range(0, start_year): if is_leap_year(y): total_days_start += 366 else: total_days_start += 365 # getting the total days in month 1 for m in range(1, start_month + 1): if m == 1: total_days_start = total_days_start elif m > 1: if is_leap_year(start_year): total_days_start += daysOfLeap[m-2] else: total_days_start += daysOfMonths[m-2] # getting the total days in start_day total_days_start += start_day - 1 # getting the total days in end_year for y in range(0, end_year): if is_leap_year(y): total_days_today += 366 else: total_days_today += 365 # getting the total days in end_month for m in range(1, end_month + 1): if m == 1: total_days_today = total_days_today elif m > 1: if is_leap_year(end_year): total_days_today += daysOfLeap[m-2] else: total_days_today += daysOfMonths[m-2] # getting the total days in end_day total_days_today += end_day - 1 age_in_days = total_days_today - total_days_start return age_in_days def days_in_row(start_year, start_month, start_day, end_year, end_month, end_day): return daysBetweenDates(start_year, start_month, start_day, end_year, end_month, end_day) + 1
__author__ = "Niketan Rane" from collections import deque class Queue: def __init__(self, max_size=10**7): self.queue = deque() self.front = -1 def push(self, item): self.queue.append(item) def pop(self): return self.queue.popleft() def peek(self): if self.queue: return self.queue[0] def is_empty(self): return not bool(self.queue) def size(self): return len(self.queue) def __str__(self): printed = "<" + str(self.queue) + ">" return printed if __name__ == "__main__": queue = Queue() for i in range(10): queue.push(i) print("Queue demonstration:\n") print("Initial queue: " + str(queue)) print("pop(): " + str(queue.pop())) print("After pop(), the queue is now: " + str(queue)) print("peek(): " + str(queue.peek())) queue.push(100) print("After push(100), the queue is now: " + str(queue)) print("is_empty(): " + str(queue.is_empty())) print("size(): " + str(queue.size()))
'''Quarta aula como criar interações entre o computador e o usuário, vendo o funcionamento das funções print() e input(), diretamente usando Variáveis.''' #No Python todos os comandos são considerados funções e todas as # funções tem parenteses ().2018 print('Olá mundo')# mostra o texto dentro de aspas print (7+4) #mostra o resultado do calculo da expressão matématica sem aspas print ('7' + '4') #desta forma o Sinal de + não soma e sim junta as sentenças # ser usado tambem uma , para juntar em casos que um outro vai ser melhor. # utilize as variaves = objetos, sempre em letra minuscula. # as variaveis recebem dados usando-se o sinal de = chamado em python recebe, # exemplo: ....nome = João nome ='Rodrigo' idade= 25 peso = 72.8 print(nome, idade, peso) # se fosse usado sinal de mais não juntaria pois # só junta mensagem com mensagem numero com numero # recebendo função especifica se usa o input declara a mensagem na tela e # envia para dentro da variavel o valor digitado nome = input('Qual seu nome?') # exemplo dia = 17 mes = 'Mar' ano = 1978 print('você nasceu',dia,'do mes de',mes,'do ano de ',ano)
#Exercício Python 031: Desenvolva um programa que pergunte a distância de uma #viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por Km para viagens #de até 200Km e R$0,45 parta viagens mais longas. distancia = float(input('\033[7;30;45mDe quantos Km éa distancia da sua viajem\033[m')) print('***'*20) print(' \033[7;30;45mVocê esta prestes a começar uma viagem de {} km.\033[m'.format(distancia)) print('***'*20) preço = distancia * 0.50 if distancia <= 200 else distancia * 0.45 print(' \033[7;30;45mO preço de sua passagem sera de R$ {:.2f}\033[m '.format(preço))
'''Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra "A", em que posição ela aparece a primeira vez e em que posição ela aparece a última vez.''' frase = str (input('escreva uma frase')).upper() .strip() #neste caso foi # possivel usar o upper na 'str e o strip para eliminar espaços' print('\033[0;31;0mA letra A aparece {} vezes na frase.'.format(frase.count ('A'))) print('A primeira letra A aparece na posição {}'.format(frase.find('A')+1)) # find procura da # esquerda para direta print ('A ultima letra A apareceu na posição {}'.format(frase.rfind('A')+1)) #rfind procura #da direita #para esquerda
'''Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu.''' from random import randint from time import sleep computador = randint(0,5) # faz o computador pensar um numero de 0 a 5 e joga na variavel computador. print('\033[0;31;0m-=-\033[m'*20) # cria uma linha de 20 caracteres print('\033[0;31;0m Vou Pensar em um numero entre 0 e 5. Tente Adivinhar...\033[m') print('\033[0;31;0m-=-\033[m'*20) # cria uma linha de 20 caracteres jogador = int(input('\033[0;31;0m Em que numero eu pensei?\033[m')) # Jogador tenta adivinhar print('\033[0;30;41m PROCESSANDO...\033[m') sleep(3) # do metodo time faz o computador # dormir conforme if jogador == computador: print('\033[0;31;0m PARABÉNS! Você conseguiu me vencer!\033[m') else: print('\033[0;31;0m GANHEI! eu pensei no numero \033[0;31;0m{} \033[0;31;0m e não no \033[0;31;0m{}!' '\033[m'.format(computador, jogador)) print()