text
stringlengths
37
1.41M
# Given a binary tree and a sum, determine # if the tree has a root-to-leaf path such that adding up # all the values along the path equals the given sum. class Solution: def hasPathSum(self, root, sum): """ 判断从根到叶子节点的值之和是否有等于sum的 :param root: TreeNode :param sum: int :return: bool """ # 如果是空树 if not root: return False # 如果只有根节点,并且根节点的值等于sum if root.val == sum and not root.left and not root.right: return True # 递归判断对左右节点的情况,每次需要将sum减去节点的值 return self.hasPathSum(root.left, sum - root.val) \ or self.hasPathSum(root.right, sum - root.val)
# 输入一棵二叉树,求该树的深度。 # 从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径, # 最长路径的长度为树的深度。 class Solution: def TreeDepth(self, pRoot): if not pRoot: return 0 return max(self.TreeDepth(pRoot.left), self.TreeDepth(pRoot.right)) + 1
# Given an index k, return the kth row of the Pascal's triangle. # # For example, given k = 3, # Return [1,3,3,1]. # # Note: # Could you optimize your algorithm to use only O(k) extra space? class Solution: def getRow(self, rowIndex): """ 计算帕斯卡三角形的制定行数的元素 :param rowIndex: int :return: list """ row = [1] for i in range(rowIndex): # 使用列表推导式迭代x+y的值 # 其中x和y分别等于[0] + row和row + [0]的第一列和第二列 row = [x + y for x, y in zip([0] + row, row + [0])] return row if __name__ == '__main__': solution = Solution() print(solution.getRow(3))
# Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. # # For example, # "A man, a plan, a canal: Panama" is a palindrome. # "race a car" is not a palindrome. class Solution: def isPalindrome(self, s): """ 判断字符串是否是回文(只考虑字母和数字) :param s: str :return: bool """ # 分别得到第一个和最后一个字符的索引 i, r = 0, len(s) - 1 # 判断回文只需要判断一半 while i < r: # 当左边字符索引小鱼右边字符串并且 # 左字符串属于字母和数字时 while i < r and not s[i].isalnum(): i += 1 # 当左边字符索引小鱼右边字符串并且 # 右字符串属于字母和数字时 while i < r and not s[r].isalnum(): r -= 1 # 为了判断相等,均转换为小写去判断是否相等 if s[i].lower() != s[r].lower(): return False # 左字符向后移动一个 i += 1 # 右字符向前移动 r -= 1 return True if __name__ == '__main__': solution = Solution() print(solution.isPalindrome('A man, a plan, a canal: Panama'))
# 把只包含因子2、3和5的数称作丑数(Ugly Number)。 # 例如6、8都是丑数,但14不是,因为它包含因子7。 # 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。 class Solution: def GetUglyNumber_Solution(self, index): if index < 1: return index # 使用一个列表保存丑数 res = [1] i = 0 j = 0 k = 0 # 当丑数数量不等于index时 while len(res) != index: # 求出当前丑数*2 *3 *5中的最小值 minV = min(res[i] * 2, res[j] * 3, res[k] * 5) # 将最小值放入丑数列表 res.append(minV) # 判断当前丑数*2 *3 *5是否小于等于丑数 if res[i] * 2 <= minV: i += 1 if res[j] * 3 <= minV: j += 1 if res[k] * 5 <= minV: k += 1 # 返回最后一个丑数 return res[-1] if __name__ == '__main__': s = Solution() print(s.GetUglyNumber_Solution(5))
# 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。 # 例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。 # 由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0 class Solution: def MoreThanHalfNum_Solution(self, numbers): # 求的数组长度的一半 mid = len(numbers) / 2 # 遍历数组 for i in numbers: # 判断数组中元素出现的次数 if numbers.count(i) > mid: return i return 0 if __name__ == '__main__': s = Solution() print(s.MoreThanHalfNum_Solution([1, 2, 3, 2, 2, 2, 5, 4, 2]))
from node import Node class LinkedList: def __init__(self): self.head = None self.tail = None def contains_node(self, data): node = self.head position = 1 results = [] while node is not None: if node.contains_data(data): results.append(position) node = node.next position = position + 1 if results: print(f'This node is located at position {results} in the list') else: print('This node was not found!') return results def add_to_beginning(self, data): node = Node(data) node.next = self.head self.head = node def append_node(self, data): node = Node(data) if self.head is None: self.head = node self.tail = node return else: self.tail.next = node self.tail = self.tail.next #temporary_node = self.head #while temporary_node.next is not None: #temporary_node = temporary_node.next #temporary_node.next = node
import random as rnd from random import randint from random import choice import string names = ["king", "miller", "kean"] domains = ["net", "com", "ua"] num_min = 100 num_max = 999 symb_min = 5 symb_max = 7 def email(names, domains): name = (rnd.choice(names)) domain = (rnd.choice(domains)) stringa = (''.join(choice(string.ascii_lowercase) for i in range(randint(symb_min, symb_max)))) number = rnd.randint(num_min, num_max) mail = (f" {name}.{number}@{stringa}.{domain}") return mail eemail = email(names, domains) print(eemail) # 2. Написать функцию, которая генерирует и возвращает строку случайной длинны. # Минимальную и максимальную длину строки ограничить с помощью параметров min_limit, max_limit, передаваемых в функцию. def len_random(min_limit, max_limit): result = "".join(choice(ascii_letters) for _ in range(randint(min_limit, max_limit))) return result print(len_random(5, 10)) def transform_text(text): index = 0 text = list(text) while index + 10 < len(text): possible_symbols = [", ", " ", "\n", " " + str(randint(1, 50)) + " "] space_point = randint(2, 10) index += space_point text[index] = choice(possible_symbols) text.append(".") text = "".join(text) text = text.title() # если только первая буква большая, то capitalize, если хотим чтобы некоторые буквы были маленькими - используем функцию ниже return text # print(transform_text(len_random(100,140))) def add_lower_case(text): # опционально, если я хочу чтобы случайным образом буквы в начале слова были маленькими / большими i = 0 text = list(text) while i + 3 < len(text): upper_point = randint(1,3) i += upper_point text[i] = text[i].lower() return "".join(text) print(add_lower_case(transform_text(len_random(150,200))))
import random import queue class Domino: def __init__(self): self.stock_pieces = [] self.computer_pieces = [] self.player_pieces = [] self.domino_snake = queue.deque() def distribution(self): all_pieces = list() next_player = None # initialization of dominoes for i in range(7): for j in range(i, 7): all_pieces.append([i, j]) random.shuffle(all_pieces) self.stock_pieces = all_pieces[:14] self.computer_pieces = all_pieces[14:21] self.player_pieces = all_pieces[21:] del all_pieces # determination of the next player for i in range(6, -1, -1): if [i, i] in self.computer_pieces: self.computer_pieces.remove([i, i]) self.domino_snake.append(str([i, i])) next_player = 'player' break elif [i, i] in self.player_pieces: self.player_pieces.remove([i, i]) self.domino_snake.append(str([i, i])) next_player = 'computer' break return next_player def snake_display(self): snake = list(self.domino_snake) if len(snake) <= 6: print("".join(snake)) else: print("".join(snake[:3]), "...", "".join(snake[-3:]), sep="") def play(self, pieces, position): if position < 0: piece = pieces.pop(abs(position) - 1) if int(self.domino_snake[0][1]) == piece[0]: piece.reverse() self.domino_snake.appendleft(str(piece)) elif position > 0: piece = pieces.pop(abs(position) - 1) if int(self.domino_snake[-1][-2]) == piece[1]: piece.reverse() self.domino_snake.append(str(piece)) elif position == 0: if len(self.stock_pieces): pieces.append(self.stock_pieces.pop(0)) def legal_move(self, pieces, position): snake_queue = None piece = pieces[abs(position) - 1] if position > 0: snake_queue = int(self.domino_snake[-1][-2]) elif position < 0: snake_queue = int(self.domino_snake[0][1]) if snake_queue in piece or position == 0: return True else: return False def computer_ia(self): count = [] for i in range(7): nb_snake = "".join(self.domino_snake).count(str(i)) nb_computer = sum([j.count(i) for j in self.computer_pieces]) count.append(nb_snake + nb_computer) scores = {} for i, piece in enumerate(self.computer_pieces): # scores[str(piece)] = count[piece[0]] + count[piece[1]] scores[i+1] = count[piece[0]] + count[piece[1]] scores = sorted(scores.items(), key=lambda t: t[1]) scores.reverse() return scores def check_end_game(self): first_car = self.domino_snake[0][1] last_car = self.domino_snake[-1][-2] end = True if len(self.player_pieces) == 0: print("Status: The game is over. You won!") elif len(self.computer_pieces) == 0: print("Status: The game is over. The computer won!") elif first_car == last_car and str(self.domino_snake).count(first_car) >= 8: print("Status: The game is over. It's a draw!") else: end = False return end def start(self): next_player = self.distribution() if next_player: while True: print(70 * "=") print(f"Stock size: {len(self.stock_pieces)}") print(f"Computer pieces: {len(self.computer_pieces)}") print() self.snake_display() print() print("Your pieces:") [print(i + 1, ":", j, sep="") for i, j in enumerate(self.player_pieces)] print() print("Computer", self.computer_pieces, sep='\n') if self.check_end_game(): break if next_player == 'player': print("Status: It's your turn to make a move. Enter your command.") while True: try: user_choice = int(input()) except ValueError: print("Invalid input. Please try again.") continue if abs(user_choice) <= len(self.player_pieces): if not self.legal_move(self.player_pieces, user_choice): print("Illegal move. Please try again.") continue else: self.play(self.player_pieces, user_choice) next_player = 'computer' break else: print("Invalid input. Please try again.") continue elif next_player == 'computer': print("Status: Computer is about to make a move. Press Enter to continue...") input() position = 0 for position_piecce in [i[0] for i in self.computer_ia()]: if self.legal_move(self.computer_pieces, position_piecce): position = position_piecce break elif self.legal_move(self.computer_pieces, -position_piecce): position = -position_piecce break self.play(self.computer_pieces, position) next_player = 'player' domino_party = Domino() domino_party.start()
# -*- coding:utf-8 -*- name = [[],[],[],[],[]] with open('firstdata.txt') as f: for line in f: for each in enumerate(line.split()): name[each[0]].append(float(each[1])) a,b,e,c,d= name print(a) print(b) print(c) print(d) print(e)
#!/usr/bin/env python # coding: utf-8 # In[13]: # JAMEEL KHALID # 200901082 # BS-CS-01-B from collections import deque class Stack: def __init__(self): self.container = deque() def push(self, val): self.container.append(val) def pop(self): return self.container.pop() def is_empty(self): return len(self.container)==0 def size(self): return len(self.container) def top(self): return self.container[-1] stack = Stack() equ = input("Enter Equation: ") condition = True x = 0 try: for i in equ: if i =='[' or i=='(' or i=='{': stack.push(i) elif i ==']' or i==')' or i=='}': stack.pop() if stack.size()==0: for i in range(0, len(equ)): if equ[i] == '"': if x % 2 == 0: x += 1 if equ[i+1] ==')'or equ[i+1] ==']'or equ[i+1] =='}'or equ[i+1] =='"': condition = False else: condition = True else: condition = True x += 1 if x % 2 == 0: condition = True else: condition = False if condition: print("True") else: print("False") except: print("False") # In[ ]: # In[ ]:
""" Przypomnienie+: 1. typy danych 2. sprawdzanie typu przy użyciu type() 3. instrukcje warunkowe - ify 4. print() 5. zamiana jednego typu danych na drugi: int(), float(), str() i bool() 6. zadanie: Napisz program, który przyjmie nazwę waluty, na ktorą chcemy zamienić złotowki i przyjmie kwotę, ktorą na tę walutę przeliczy 1 euro = 4.2671 zl 1 dolar = 3.8399 zl 1 GBP = 4.9378 zl Za pomocą # można komentować, tzn. zapisać linijkę, którą python zignoruje. W przypadku potrójnych cudzysłowów, jak to zrobiłam tutaj, ignoruje całą zawartość pomiędzy nimi. Można to wykorzystywać np., żeby sprawdzać działanie tylko określonych linijek kodu. """ #6 - program: print('Wybierz kwote oraz walute') waluta = input("waluta: ") kwota = input('kwota: ') if waluta == "euro": print(float(kwota)/ 4.2671) if waluta == "dolar" : print(float(kwota)/ 3.8399) if waluta == "funt" : print(float(kwota)/ 4.9378) """ LISTY Struktura, które może zawierać wiele różnych wartości, zapisywane w [ ], np. [11, 4, "item", 7.98, True, 9, "item2"] Każdy element listy ma przypisany index, tzn. pozycję w tej liście. >>>są one liczone od 0<<< ["a", "b", "c", "d", "e"] 0 1 2 3 4 Elementy można wywoływać, podając ich indexy: """ animals = ['cat', 'rat', 'deer', 'elephant', 'bat', "dog", "mouse"] print(animals[0]) #wyswietli 'cat' print(animals[5]) #wyswietli 'dog' """ Można też wywoływać kilka elementów, stosując slicing. Podajemy przedział [początek:koniec], przy czym uwaga: >>>przedział jest prawostronnie otwarty, tzn. nie wyświetli się element z indexem równym koniec<<<: """ print(animals[0:3]) #wyswietli ['cat', 'rat', 'deer'] print(animals[1:4]) """ Kiedy nie poda się początku i/lub końca, to wyświetli się wszystko z danej "strony": """ print(animals[:4]) print(animals[2:]) print(animals[:]) """ Elementy można numerować też od tyłu, tj. ["a", "b", "c", "d", "e"] -5 -4 -3 -2 -1 """ print(animals[-3]) print(animals[-3:-1]) """ W slicingu można też określić, co ile elementów się przeskakuje [początek:koniec:skok] """ print(animals[::1]) #wszystkie elementy, bo co jeden print(animals[::2]) #co drugi element print(animals[::-1]) #lista od tyłu """Listy można też zagnieżdżać (nesting), tzn. umieszczać listy w listach""" gniazdo = ["kura", "gęś", "kaczka", ["wróbel", "gołąb", "dzięcioł"]] print(gniazdo[3]) #wyświetlenie 3 elementu, czyli zagnieżdżonej listy print(gniazdo[3][1]) #wyświetlenie 1 elementu z zagnieżdżonej listy """ Przy użyciu indeksowania można też podmieniać wartości. Zmiana dzieje się momentalnie, nie trzeba nadpisywać""" gniazdo[2] = "sraczka" print(gniazdo) """Listy można dodawać do siebie (konkatenacja) i mnożyć""" lista1 = [1, 2, 3] lista2 = [4, 5, 6] print(lista1 + lista2) print(lista1 * 3) """ Listy mają specjalne funkcje i metody, takie jak: """ print( len(lista1) ) #od length, wyświetlenie długości (liczby elementów) """ Jaki będzie len(gniazdo)? 4 czy 6? """ print( min(lista1) ) #najmniejsza wartosc print( max(lista1) ) #najwieksza wartosc #tez dla stringowych wartości: owoce = ["borowka", "gruszka", "ananas", "pomidor", "truskawka", "cukinia"] print(min(owoce)) print(max(owoce)) # *Ciekawostka: kolejność wg ASCII owoce.append("jablko") #dodawanie na koncu wartosci podanej w nawiasie print(owoce) """ Przykładowa lista takich możliwości: https://www.programiz.com/python-programming/methods/list Warto zapoznać się chociaż z częścią, np. remove, count, index i w razie potrzeby wyszukiwać - często daną operację, którą byśmy chcieli zrobić, można wykonać za pomocą już istniejącej metody i tak jest łatwiej. Można sprawdzać, czy dany element znajduje się w liście lub czy się w niej nie znajduje za pomocą "in" i "not in" -> wynik: True albo False """ print( "borowka" in owoce ) #zwraca True print( "ziemniak" in owoce ) #zwraca False #analogicznie print( "marchewka" not in owoce ) #zwraca True """ in i not in można wykorzystywać do konstruowania instrukcji z ifami, np.: """ if "pomidor" in owoce: print("Pomidor to też owoc, przynajmniej wg botaników")
import random import numpy as np """ Generates a linearly seperable set of points @param func: The target seperator (function should take in one argument, a list with values for each variable @param nVars: Number of variables taken in by the function @param nPoints: The number of points to generate @return points: The points that were generated @return classes: Classifications of each generated point according to the function provided """ def generatePoints(func, nVars, nPoints): points = [] classes = [] for i in range(nPoints): sgn = 0 while(sgn == 0): temp = [random.randint(-100,100) for _ in range(nVars)] sgn = np.sign(func(temp)) points.append(temp) classes.append(sgn) return points, classes
def merge(list1, list2): # implement your solution here i=0 j=0 while i < len(list1): if list2[j]>=list1[i]: list2.insert(j,list1[i]) i+=1 j+=1 else: j+=1 return list2 list1 = [1,3,8,19] list2 = [5,6,11,12,21] print str(merge(list2, list1)) # keep testing # another comment, yes, keep testing
from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen('https://treehouse-projects.github.io/horse-land/index.html') soup = BeautifulSoup(html.read(), 'html.parser') print(soup.prettify()) print(soup.title) divs = soup.find_all('div', {"class": "featured"}) for div in divs: print(div) divs2 = soup.find_all('div') for div in divs2: print(div) # find method finds first matching element div = soup.find('div', {'class': 'featured'}) print(div) featured_header = soup.find('div', {'class': 'featured'}).h2 # get_text() method removes tags print(featured_header.get_text()) # for button in soup.find(attrs={'class':'button button--primary'}): # print(button) # Gives the same result: for button in soup.find(class_='button button--primary'): print(button) for link in soup.find_all('a'): print(link.get('href'))
""" python正则提取CSV文件数据计算导购客单价.py 题目来源 https://github.com/FGFW/FCNNIC 依山居 4:36 2015/11/22 看了看python自带的csv库貌似也没能解决啥问题, 干脆就自己用正则来写了代码量出乎意料的少. 在线查本csv表格 http://t.cn/RU3hoB0 下载csv表格 http://t.cn/RU3haTL 计算公式为: 导购日客单价=导购日成交金额/日客单数 每个相同的单据编号为1单,也就是去重后得到该导购的日客单数 导购日成交金额=导购完成的日所有单总和,也可以小计中倒数第二列直接提取 要求:计算出CSV表格中每位导购的客单价. 思路是正则匹配(导购)小计得到导购名字,顺便把该导购成交金额提取了。 然后再集合解析正则匹配该导购所有单并去重,一条语句得到日客单数。 """ import re rec=re.compile("\((.+)\)小计.+,.+,(\d+.\d+),.*") with open("0914零售数据.csv") as f: cf=f.read() f.close() dglist=re.findall(rec,cf) #得到格式如[('顾意珍', '480.00'), ('张彩菊', '505.00'),..] for d,t in dglist: #迭代dglist,如d得到顾意珍,t得到她的当天销售额480.00 rec=re.compile("%s,\d+-\d+-\d+,(\w+-\d+),"%d) #用导购名字拼成正则串,那么匹配到的都是她的单子 多少单=len({l for l in re.findall(rec,cf)}) #相同的单号只算一个单,正则查找的结果放在集合, #集合中元素不能重复,相当于去重处理,所以len长度可以得到该导购的单量 客单价=float(t)/多少单 #t还是字符串,需要转成float再计算 print("导购:%s 日成交金额: %s 日客单价:%3.2f 日单量:%s" %(d,t,客单价,多少单)) try: input("回车退出") except SystemError: pass """ 输出: >>> 导购:顾意珍 日成交金额: 480.00 日客单价:26.67 日单量:18 导购:张彩菊 日成交金额: 505.00 日客单价:28.06 日单量:18 ... """
""" python正则表达式一列文本转成三列.py 依山居 8:18 2015/11/12 总结,我自己生成了百万行来测试,文本文件8M大,内容为1-999999 运行耗时1秒左右 """ print("运行中..."*3) import re import time start=time.time() out=open("out.txt","w+") reg=re.compile(r"(.*)\n(.*)\n(.*)\n") with open("a.txt") as f: txt=f.read() f.close() result=re.sub(reg,r"\1 \2 \3\n",txt) #print(result) out.write(result) out.close() end=time.time() pt=end-start print("运行耗时:",pt) try: input("按回车退出") except SyntaxError: pass
""" python列表切片处理DEL文件断行.py 这版的代码是之前列表切片版的改进,目的是把DEL文件中不以引号开头的行与上一行连接 下一行不以引号开头则清除行后的空白字符,包括\n,在写入的时候就自动与上一行连接了。 http://www.bathome.net/thread-38164-1-1.html """ import time start=time.time() print("运行中..."*3) txt=[] with open("a.txt") as f: txt=f.readlines() end=time.time() pt=end-start print("readlines运行耗时:",pt) ln=len(txt) print("需要处理的文件行数:",ln) end=time.time() pt=end-start print("len(txt)运行耗时:",pt) #为了防指针越界,所以rn需要减1 #flines=[txt[r] if ('\"' in txt[r+1][0]) else txt[r].rstrip() for r in range(ln-1)] #与上一行等效写法 flines=[txt[r] if (txt[r+1].startswith('\"')) else txt[r].rstrip() for r in range(ln-1)] end=time.time() pt=end-start print("flines运行耗时:",pt) with open("out.txt","w+") as f: f.writelines(flines) #补上最后一行 f.write(txt[-1]) f.close() txt[:]=[] flines[:]=[] end=time.time() pt=end-start print("运行耗时:",pt) try: input("按回车退出") except SyntaxError: pass """ 测试结果,列表切片和模式匹配处理速度相当,670M的文本,大约60-70秒左右, 包括写入时间,算出处理速度大约是每秒处理10M左右。 实际发现内存占用峰值会高出好几倍,python 进程会短时占用好几个G内存的情况。 """
""" python正则匹配肇事车牌照号 http://www.bathome.net/thread-16242-1-1.html 依山居 4:50 2015/11/25 """ import re aabb=["%d*%d=%d" %(r,r,r*r) for r in range(1,100)] aabb=str(aabb) result=re.findall(r"(\d)\1\*\1\1=(\d)\2(\d)\3",aabb) [print(b*2+c*2) for a,b,c in result] #正则还能这样写 print(re.sub(r".*=(\d)\1(\d)\2.*",r"\1\1\2\2\n",aabb))
""" python format替换模板文件中的字符串3.py 问题来源 http://www.bathome.net/thread-37777-1-1.html 几天不写代码,手生... 今天路上看到format和%s替换模板文件的用法。写出来巩固一下。 """ import random import os #先把模板中需要替换的地方改成:{关键词[0]}这样的格式,就可以直接用format直接替换。 moban=""" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>{关键词[0]}{关键词[1]}{关键词[2]}{关键词[3]}</title> <meta name="keywords" content="{关键词[0]}{关键词[1]}{关键词[2]}{关键词[3]}" /> <meta name="description" content="{关键词[0]}努力打造{关键词[1]}影视导航系统为最好的{关键词[3]}影视系统!" /> </head> 上下标签比如关键词1要一样。 <li>Copyright © 2015 {关键词[0]} all rights reserved. <a href="/detail/map.html" target="_blank">网站地图</a></li> </body> </html> """ with open("host.txt",encoding="utf-8") as f: host=[r.rstrip() for r in f.readlines()] with open("key.txt",encoding="utf-8") as f: key=[r.rstrip() for r in f.readlines()] for h in host: dirs="./"+h+"/"+"www."+h+"/" if not os.path.exists(dirs): os.makedirs(dirs) with open(dirs+"index.html","w+",encoding="utf-8") as f: f.write(moban.format(关键词=random.sample(key,4)))
import string lowercase=string.ascii_lowercase uppercase=string.ascii_uppercase f=open("a.txt","r") def l2u(): txt=f.read() for r in range(0,26,1): txt=txt.replace(lowercase[r],uppercase[r]) return(txt) def u2l(): txt=f.read() for r in range(0,26,1): txt=txt.replace(uppercase[r],lowercase[r]) return(txt) #print(l2u()) print(u2l())
#python统计文件夹内的所有文件的数量和总大小 #依山居 12:37 2015/11/5 import os dirs=os.listdir("..") print(dirs)
""" 提取csv文件中指定列位置的数值大于指定值的行.py http://bbs.bathome.net/thread-40087-1-1.html 2016年4月17日 09:10:03 codegay """ import csv with open("Inspection00002.txt",encoding="utf-8") as f: txt=csv.reader(f) with open("result.txt","w",encoding="utf-8") as csvw: result=csv.writer(csvw) result.writerow(['Chip No.', 'Chip ID', 'bump No.', 'Core No.', 'SRO', 'bump group', 'CAD X', 'CAD Y', 'X coordinate', 'Y coordinate', 'alignment', 'total height', 'plane height', 'bump height', 'bump coplanarity', 'bump caw', 'bump diameter', 'Judge'])#表头 for r in txt: if "." in r[13] and float(r[13])>45: print(r) result.writerow(r) """ ['7', 'A019', '1', '1', '0', '2', '-4152.32', '431.57', '-44147.51', '40431.56', '2.37', '108.95', '66.28', '56.67', '1.53', '-0.36', '46.41', 'OK '] ['7', 'A019', '4', '1', '0', '2', '-4150', '-56.49', '-44144.57', '39941.83', '2.7', '108.66', '66.82', '55.84', '1.05', '0.06', '46.41', 'OK '] ['7', 'A019', '9', '1', '0', '2', '-4150', '-710.21', '-44148.43', '39288.81', '3.04', '109.1', '67.33', '55.77', '1.19', '0.37', '47.24', 'OK '] ['7', 'A019', '21', '1', '0', '1', '-4150', '-2279.12', '-44146.79', '37718.52', '3.44', '110.48', '66.99', '55.49', '1.92', '-0.38', '44.73', 'OK '] [Finished in 0.1s] """
""" python个位数统计.py http://www.nowcoder.com/questionTerminal/a2063993dd424f9cba8246a3cf8ef445 codegay 2016年4月1日 11:02:20 """ def ff1(n): kv={k:str(n).count(k) for k in set(str(n))} [print(r,":",kv[r]) for r in sorted(kv.keys())] ff1(24242424567)
""" 读取文本内容并在每行行尾添加系列数字.py http://www.bathome.net/thread-38881-1-1.html 依山居 2016年1月4日 20:53:41 完全逐行处理再逐行写入 """ import time start=time.time() print("运行中..."*3) #生成0000-9999,用了楼上的思路 sq=[str(r)[1:]+"\n" for r in range(10000,20000)] with open("数据.txt") as fa,open("result.txt","a+") as fb: for l in fa: sn=l.rstrip() for s in sq: fb.write(sn+s) end=time.time() pt=end-start print("运行耗时:",pt) try: input("按回车退出") except SyntaxError: pass """ 数据.txt一万行129-143秒 result.txt 1.2GB 我了个去,发生了什么。逐行处理再逐行写入反而比较快。 """
# -*- coding: utf-8 -*- """ @author: Damian """ import numpy as np #Useful function to ask the user for a numerical opction. def num_opt(liminf,limsup): try: integer=int(float(input('>>'))) while integer < liminf or integer > limsup: #while liminf > integer > limsup: print('Please type an integer number between',liminf,'and',limsup) integer=int(float(input('>>'))) except: print('Please type a number') return integer #Dictionary to generate password and Encrypt/Decrypt a message. alphabet={'q':'+', 'w':'x', 'e':'3', 'r':'|', 't':'/', 'y':'>','u':'{', 'i':'<', 'o':'(', 'p':']', 'a':'@', 's':'#', 'd':'$', 'f':'%', 'g':'¬', 'h':'&', 'j':'*', 'k':'¿', 'l':'¡', 'z':'-', 'x':'_', 'c':'!', 'v':'?', 'b':'8', 'n':']', 'm':')', ' ':' ', 'ñ':'ñ'} print('Welcome to GEME, Encryptor, Decryptor and Secure Password Generator.') print('Now I ask you what would you like to do?') print('Please choose an option with an integer number.') print('1. Generate a Secure Password. \n') print('2. Encrypt or Decrypt a Message (according to our system).') opc=input('>>') try: aux=int(opc) if aux==1: print('You choose the first opction. We are going to generate you a password.') print('Please type how many characters needs your password, between 4 and 12.') size=num_opt(4,12) print('Your password will have',size,'characters.') print('Will the password have only numbers or alphanumeric characters?') print('If you choose Alphanumeric, you will get a password with even amount of digits.') print('You only will have to remove the last or the firs one of i.') print('Type 1 to Only Numbers') print('Type 2 to Alphanumeric') typ=num_opt(1,2) password=list() if typ==1: for i in range(size): x=np.random.randint(1,9) y=str(x) password.append(y) p=''.join(password) print('Take note, your password is:',p) else: print('We are going to create the password with some information of you,') print('which you will type without accent mark.') print('It doesn´t matter if answers are real or don´t') print('What is your birthdate? Please in this format: dd-month-aaaa') birthdate=input('>>') while '-' not in birthdate: print('Please, in this format: dd-mm-aaaa') birthdate=input('>>') print('What is your first name?') n=input('>>') name=n.lower() print('And what is your last name?') lastn=input('>>') lastname=lastn.lower() birth=list() for i in birthdate: if i != '-': birth.append(i) else: continue if size==4: for i in range(2): password.append(name[i]) for i in range(2): password.append(lastname[i]) elif size > 4 and size <= 6: for i in range(3): password.append(name[i]) for i in range(3): password.append(lastname[i]) elif size > 6 and size <= 8: for i in range(3): password.append(birth[i]) for i in range(3): password.append(name[i]) for i in range(2): password.append(lastname[i]) elif size > 8 and size <= 10: for i in range(3): password.append(birth[i]) for i in range(3): password.append(name[i]) for i in range(2): password.append(birth[-(i+1)]) for i in range(2): password.append(lastname[i]) else: for i in range(4): password.append(birth[i]) for i in range(3): password.append(name[i]) for i in range(2): password.append(birth[i+6]) for i in range(3): password.append(lastname[i]) for i in range(len(password)): for k in alphabet.keys(): if password[i]==k: password[i]=alphabet[k] p=''.join(password) print('Take note, your password is',p) elif aux==2: print('What would you like to do, encrypt or decrypt a message (according to our system)?') print('1. Encrypt') print('2. Decrypt') crypt=num_opt(1,2) if crypt==1: print('Write the message you like to encrypt.') message=input('>>') messagetoen=message.lower() messageen=list() for i in messagetoen: for j in alphabet.keys(): if i==j: x=alphabet[j] messageen.append(x) m=''.join(messageen) print('Your encrypted message is "',m,'".') else: print('Write the encrypted message you have.') message=input('>>') messagetode=message.lower() messagede=list() for i in messagetode: for k, v in alphabet.items(): if i==v: x=k messagede.append(x) m=''.join(messagede) print('Your decrypted message is "',m,'".') else: print('Please type 1 or 2.') except: print('Please type a number.') print('\nProgram has finished')
""" 质数又称素数。一个大于1的自然数,除了1和它自身外,不能被其他自然数整除的数叫做质数 对正整数n,如果用2到之间的所有整数去除,均无法整除,则n为质数 """ # 判断是否为质数 def prime(num): if num == 2: return True if num > 2: for i in range(2, int(num ** 0.5) + 1): if num % i == 0: # print(num, "不是素数") return False # print(num, "是素数") return True # print(num, "不是素数") return False if __name__ == '__main__': prime(11)
def get_random_color(): """Generate rgb using a list comprehension """ import random r, g, b = [random.random() for i in range(3)] return r, g, b, 1
# -*- coding: utf-8 -*- import unittest from .convert import Solution, TreeNode s = Solution() root = TreeNode(10) left = TreeNode(6) right = TreeNode(14) left_right = TreeNode(8) right_left = TreeNode(12) root.left = left root.right = right left.right = left_right right.left = right_left class TestMiddleTraverse(unittest.TestCase): def test_not_empty(self): got = s.middle_traverse(root) want = [left, left_right, root, right_left, right] self.assertEqual(want, got) class TestConvert(unittest.TestCase): def test_empty(self): self.assertEqual(None, s.Convert(None)) def test_not_empty(self): new_root = s.Convert(root) want_traverse = [6, 8, 10, 12, 14, 12, 10, 8, 6] self.assertEqual(want_traverse, self.traverse_double_linked_list(new_root)) def traverse_double_linked_list(self, double_linked_list): """先遍历 right,然后遍历 left,忽略 None""" results = [] cur_node = double_linked_list while cur_node.right: results.append(cur_node.val) cur_node = cur_node.right while cur_node: results.append(cur_node.val) cur_node = cur_node.left return results
# -*- coding: utf-8 -*- import unittest from .merge_sort import merge_sort cmp = lambda x, y: True if x < y else False class Test(unittest.TestCase): def test_empty_list(self): got = merge_sort([], cmp) want = [] self.assertEqual(want, got) def test(self): a_list = [9, 7, 8, 3, 2, 1] got = merge_sort(a_list, cmp) want = [1, 2, 3, 7, 8, 9] self.assertEqual(want, got)
# -*- coding:utf-8 -*- import unittest from .reverse_sentence import Solution s = Solution() class Test(unittest.TestCase): def test_empty(self): got = s.ReverseSentence('') want = '' self.assertEqual(want, got) def test(self): got = s.ReverseSentence('I am a student.') want = 'student. a am I' self.assertEqual(want, got)
# -*- coding:utf-8 -*- class Solution: def reOrderArray(self, array): # write code here """ loop [2, 1, 3, 4, 5] if current element is odd: * 2 * 1 exchange with 1st element when 1st element is even [1, 2, 3, 4, 5] * 3 exchange with latest element whose prior element is odd [1, 3, 2, 4, 5] * 5 if we do as above, we will get [1, 3, 5, 4, 2] that will break the relative order. we should delete it and insert instead exchange directly. """ for index, element in enumerate(array): if element % 2 != 0: inserted_index = index for j in range(inserted_index - 1, -1, -1): if array[j] % 2 != 0: inserted_index = j + 1 break elif j == 0: inserted_index = 0 if inserted_index != index: self._insert(array, index, inserted_index) return array def _insert(self, array, index, inserted_index): """ exchange index with index - 1 until index == inserted_index [1, 2, 3, 4] 1 3 [1, 2, 4, 3] 1 2 [1, 4, 2, 3] 1 [1, 3, 2, 4, 5, 6] 2 4 [1, 3, 2, 5, 4, 6] 2 3 [1, 3, 5, 2, 4, 6] 2 2 """ while index > inserted_index: array[index], array[index-1] = array[index-1], array[index] index -= 1
# -*- coding:utf-8 -*- class Solution: def LastRemaining_Solution(self, n, m): """ 首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。 每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中, 从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友, 可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。 请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1) 将上面抽象为: 0 ~ (n - 1) 这 n 个数字排成一个圆圈,从数字 0 开始每次从这个圆圈 里删除第 m 个数字。求圆圈里最后剩下的数字。当 n、m 都等于 0 时,返回 -1。 比如 0->1->2->3->4 ↑ ↓ <----------- 当 m = 3 时,删除的前 4 个数字是 2、0、4、1。 算法1: 使用数组模拟环,我们将数组的最后一个索引看成是第一个索引。第 m 个数字相当于 (当前索引 + m - 1) % 当前数组长度 如果数组中含有多于 1 个元素,则一直删除当前索引后的第 m 个,删除之后当前的索引 就还是停留在对应的位置,符合题目要求。 跳出(while 长度大于 1)的循环后,数组中只剩下一个元素,即为结果。 复杂度分析: 时间复杂度:O(n^2)。pop() 操作:n + n - 1 + ... + 1 = O(n^2) 空间复杂度:O(n)。用于储存的数组。 """ if m == 0 and n == 0: return -1 nums = list(range(n)) i = 0 while len(nums) > 1: i = (i + m - 1) % len(nums) nums.pop(i) return nums[0]
# -*- coding:utf-8 -*- class Solution: def replaceSpace(self, s): """ 请实现一个函数,将一个字符串中的每个空格替换成“%20”。 例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。 对于 Python 来说,自带的特性已经处理了这个问题,如果面试官同意的话,就使用它。 如果面试官不同意,那我们继续思考。 算法及证明 遍历字符串, 如果不是空格,那么将该字符串直接加入结果 否则,将 %20 加入结果。 由于是遍历操作,所以处理了字符串为空的边界情况。 复杂度分析 时间复杂度:遍历一遍,为 O(n) 空间复杂度:O(n)。假设原字符串是 n 个空格,那么新字符串的长度为 3n,O(3n) = O(n)。 自带的为 O(m*n),m 是子字符串的长度,这里是 1,所以与自带的 replace 的复杂度相同。 :param s: 原字符串 :return: """ replaced_string = '' for raw_s in s: if raw_s == ' ': replaced_string += '%20' else: replaced_string += raw_s return replaced_string
# -*- coding:utf-8 -*- class Solution: def LeftRotateString(self, s, n): """ 把字符串前面的若干个字符移动到字符串的尾部。 比如输入 'abcdefg' 和 2,则输出为 'cdefgab'。 算法1: real_rotate = n % length。结果等于 real_rotate 后的字符串与 real_rotate 前的字符串 进行拼接。 复杂度分析: 时间复杂度:O(n)。拼接出长度为 n 的字符串 空间复杂度:O(1) """ if not s: return s real_rotate = n % len(s) return s[real_rotate:] + s[:real_rotate]
import math num1, num2 = int(input()), int(input()) Sum = abs(int((num1 + num2)*100)/100.0) dif = abs(int((num1 - num2)*100)/100.0) Pro = abs(int((num1 * num2)*100)/100.0) Quo = abs(int((num1 / num2)*100)/100.0) print ("Sum:%.2f\nDifference:%.2f\nProduct:%.2f\nQuotient:%.2f" % (Sum,dif,Pro,Quo))
IN = [int(i) for (i) in (input().split())] def tri(a, b, c): if a>0 and b>0 and c>0 and a+b>c and a+c>b and b+c>a: if a*a+b*b==c*c or a*a+c*c==b*b or b*b+c*c==a*a: return 1 elif a*a+b*b<c*c or a*a+c*c<b*b or b*b+c*c<a*a: return 2 else: return 3 else: return 0 ans = tri(IN[0],IN[1],IN[2]) if ans==0: print("Not Triangle") elif ans==1: print("Right Triangle") elif ans==2: print("Obtuse Triangle") elif ans==3: print("Acute Triangle")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @TIME: 2020/4/13 14:53 # @Author: K # @File: Class.py # class Student(object): # def __init__(self, name, gender): # self.__name = name # self.__gender = gender.lower() # # def get_gender(self): # return self.__gender # # def set_gender(self, gender): # if gender.lower() in ('male', 'female'): # self.__gender = gender.lower() # # # # 测试: # bart = Student('Bart', 'Male') # print(dir(bart)) # if bart.get_gender() != 'male': # print('测试失败!') # print(bart.get_gender()) # else: # bart.set_gender('female') # if bart.get_gender() != 'female': # print('测试失败!') # else: # print('测试成功!') class Student(object): count = 0 def __init__(self, name): self.name = name Student.count = Student.count + 1 # 测试: if Student.count != 0: print('测试失败!') else: bart = Student('Bart') if Student.count != 1: print('测试失败!') else: lisa = Student('Bart') if Student.count != 2: print('测试失败!') else: print('Students:', Student.count) print('测试通过!')
vowels = 'aeiou' # create your list here str_ = input() print([vowel for vowel in str_ if vowel in vowels])
height = int(input()) for i in range(0, height * 2, 2): print(("#" * (i + 1)).center(height * 2))
# text-box # dropdown # checkbox # radio button # open file dialog # submit button -> all inputs need to be filled # show data # clear data # about # Saya Farhan Nurzaman mengerjakan evaluasi Tugas Praktikum 3 DPBO # dalam mata kuliah Desain dan Pemrograman Berorientasi Objek # untuk keberkahanNya maka saya tidak melakukan kecurangan seperti yang telah dispesifikasikan. # Aamiin. from tkinter import * from tkinter import messagebox from tkinter import filedialog from PIL import ImageTk,Image from Data import Data imageFile = "" data = [] gambar = [] def submit(): global imageFile if input1.get() != "" and input2.get() != "" and input3.get() != "" and imageFile != "": temp = Data(input1.get(),input2.get(),input3.get()) input1.delete(0,'end') input2.delete(0,'end') input3.delete(0,'end') input1.focus() data.append(temp) img = ImageTk.PhotoImage(Image.open(imageFile).resize((400,400),Image.ANTIALIAS),'rb') gambar.append(img) messagebox.showinfo(message ="Success!") imageFile ="" else : messagebox.showwarning(message ="Please input all fields") # label1 = Label(root, text = input1.get()) # label1.grid(row=6,column=1) # label2 = Label(root, text = input2.get()) # label2.grid(row=7,column=1) # label3 = Label(root, text = input3.get()) # label3.grid(row=8,column=1) def lihatGambar(index,nama): top = Toplevel() top.title("Viewing Picture : " + nama) b_exit = Button(top, text="Exit", command=top.destroy) b_exit.pack() canvas = Canvas(top) canvas.pack(fill="both",expand=True) canvas.create_image(0,0,anchor = "nw" , image = gambar[index]) def clearData(): confirm = messagebox.askyesno("Are you sure?",message="You are about to clear all data, are you sure?") if len(data) != 0: if confirm: data.clear() messagebox.showinfo(message="All data has been cleared") else: messagebox.showwarning("No data", message="There is no available data.") def showData(): if len(data) != 0: top = Toplevel() top.title("Viewing Data") show = LabelFrame(top,text="Viewing Data:") show.pack(padx=10,pady=10) lblIndex = Label(show,text="No",borderwidth=1,relief="solid",width=5) lblIndex.grid(row = 0,column=1,pady = 5) lblNim = Label(show,text = "NIM",width = 15 , borderwidth=1,relief="solid").grid(row=0,column=2,pady = 5) lblNama = Label(show,text = "NAMA",width = 15 , borderwidth=1,relief="solid").grid(row=0,column=3,pady = 5) lblKelas = Label(show,text = "KELAS",width = 15 ,borderwidth=1, relief="solid").grid(row=0,column=4,pady = 5) for i,h in enumerate(data): lblIndex = Label(show,text=i+1,borderwidth=1,relief="solid",width=5) lblIndex.grid(row = i+1,column=1,pady = 5) lblNim = Label(show,text = h.getNim(),width = 15 , borderwidth=1,relief="solid").grid(row=i+1,column=2,pady = 5) lblNama = Label(show,text = h.getNama(),width = 15 , borderwidth=1,relief="solid").grid(row=i+1,column=3,pady = 5) lblKelas = Label(show,text = h.getKelas(),width = 15 ,borderwidth=1, relief="solid").grid(row=i+1,column=4,pady = 5) showPicture = Button(show,text = "Show Picture!",command=lambda index=i : lihatGambar(index,h.getNama())) showPicture.grid(row=i+1,column=5) b_exit = Button(show, text="Exit", command=top.destroy) b_exit.grid(row=len(data)+1, column=5) else: messagebox.showwarning("No data", message="There is no available data.") def openFile(): global imageFile imageFile = filedialog.askopenfilename(filetypes = (("All image files","*.jpg *.jpeg *.png"),("JPG/JPEG","*.jpg *.jpg"),("PNG","*.png"))) def about(): top = Toplevel() top.title("About") frame = LabelFrame(top,text = "About",padx=50,pady=50) frame.pack(padx=50,pady=50) Nama = "Farhan Nurzaman" Nim = "1904908" tampilkanLabel = Label(frame,text = "Nama : " + Nama + "\n" + "NIM : " + Nim,anchor="w").grid(row=0,column=0,sticky="w") b_exit = Button(frame, text="Exit", command=top.destroy) b_exit.grid(row=5, column=1) root = Tk() root.title("Tugas Praktikum 3 - 1904908 Farhan Nurzaman") # root.geometry("500x500") inputLabels = ["Nama","NIM","Kelas"] frameKiri = Frame(root) frameKiri.grid(row=0,column=0) frameKanan = Frame(root) frameKanan.grid(row=0,column=1,padx=75) input1 = Entry(frameKiri) topPad = Label(frameKiri,text="",pady=10) topPad.grid(row=0) labelTop = Label(frameKiri,text="Input your data!",pady=10) labelTop.grid(row=1,column=2) input1.grid(row=2,column = 2, padx = 5,pady = 10) lblInput1 = Label(frameKiri,text = inputLabels[0]).grid(row=2,column=1, sticky = "W") input2 = Entry(frameKiri) input2.grid(row=3,column = 2,padx = 5,pady = 10) lblInput2 = Label(frameKiri,text = inputLabels[1]).grid(row=3,column=1, sticky = "W") input3 = Entry(frameKiri) input3.grid(row=4,column = 2,padx = 5,pady = 10) lblInput3 = Label(frameKiri,text = inputLabels[2]).grid(row=4,column=1, sticky = "W") openImage = Button(frameKiri,text="Open Image", command = openFile) openImage.grid(row=5,column = 2,pady=5) submit = Button(frameKiri, text="Submit", command = submit) submit.grid(row=6,column=2,pady=5) labelApp = Label(frameKanan,text ="Tugas Praktikum 3", font = (44)) labelApp.grid(row=0,column=1) show = Button(frameKanan, text="Show Data",command=showData) show.grid(row=1,column=1,pady=5) clear = Button(frameKanan, text="Clear Data",command=clearData) clear.grid(row=2,column=1,pady=5) about = Button(frameKanan, text="About",command=about) about.grid(row=3,column=1,pady=5) b_exit = Button(root, text="Exit", command=root.quit) b_exit.grid(row=5, column=1,pady=15) root.mainloop()
import sys import copy def bubble_sort(arr): _sorted_arr = copy.copy(arr) flag = True for i in range(1, len(_sorted_arr)): # 两两比较,大的浮在后边,共比较n-1次 if flag: flag = False # 假设未交换 for j in range(0, len(_sorted_arr)-i): if _sorted_arr[j] > _sorted_arr[j+1]: # 如果第j个元素大于后一个,则两者交换 _sorted_arr[j], _sorted_arr[j+1] = _sorted_arr[j+1], _sorted_arr[j] flag = True # 说明有交换 return _sorted_arr def selection_sort(arr): _sorted_arr = copy.copy(arr) for i in range(len(_sorted_arr)-1): # 一共找n-1次,因为最后一次只剩最后一个元素了 min_index = i for j in range(i+1, len(_sorted_arr)): # 从已排好序的元素以后开始找 if _sorted_arr[j] < _sorted_arr[min_index]: min_index = j if min_index != i: # 下标不一致则交换值 _sorted_arr[min_index], _sorted_arr[i] = _sorted_arr[i], _sorted_arr[min_index] return _sorted_arr def insertion_sort(arr): _sorted_arr = copy.copy(arr) for i in range(1, len(_sorted_arr)): # 把前i个看成是有序序列 to_be_inserted_value = _sorted_arr[i] # 要插入的值 j = i while j > 0 and to_be_inserted_value < _sorted_arr[j-1]: # 将要插入的值与有序序列的各个值逐一比较, 若小于,则有序序列整体向右移动 _sorted_arr[j] = _sorted_arr[j-1] j -= 1 if j != i: _sorted_arr[j] = to_be_inserted_value return _sorted_arr def shell_sort(arr, h_interval=3): """ 希尔排序:未完成 :param arr: :param h_interval: :return: """ _sorted_arr = copy.copy(arr) h = 1 while h < len(_sorted_arr): h = h*h_interval + 1 while h > 0: for i in range(h, len(_sorted_arr)): # 左边的是有序的 j = i-h to_be_inserted_value = _sorted_arr[j] def quick_sort(arr): """ 快速排序 :param arr: :return: """ _sorted_arr = copy.copy(arr) def _quick_sort(_sorted_arr, left, right): """ :param _sorted_arr: :param left: :param right: :return: """ if left >= right: return pivot = partition(_sorted_arr, left, right) _quick_sort(_sorted_arr, left, pivot-1) _quick_sort(_sorted_arr, pivot+1, right) def partition(_sorted_arr, left, right): """ 分区,返回pivot :param _sorted_arr: :param left: :param right: :return: """ pivot = left index = pivot+1 for i in range(index, right+1): if _sorted_arr[i] < _sorted_arr[pivot]: # 比基准值小, # 遇到比基准值小的元素会跟index指向的元素交换位置,可能导致不稳定 _sorted_arr[index], _sorted_arr[i] = _sorted_arr[i], _sorted_arr[index] index += 1 _sorted_arr[pivot], _sorted_arr[index-1] = _sorted_arr[index-1], _sorted_arr[pivot] return index-1 _quick_sort(_sorted_arr, 0, len(_sorted_arr)-1) return _sorted_arr if __name__ == '__main__': to_be_sorted_array = [10,12,3,5,8,7,9] after_sorted_array = quick_sort(to_be_sorted_array) print(after_sorted_array)
import pickle import os def save_model(model, name, path): """ Saves model to a pickle file Args: model (object): Model name (str): model file name path: path to save model """ model_file_path = os.path.join(path, f'{name}.sav') pickle.dump(model, open(model_file_path, 'wb')) def load_model(name, path): """ Loads model from a path Args: name (str): Name of model file path (str): Path in which model is saved Returns: Loaded model """ model_file_path = os.path.join(path, f'{name}.sav') loaded_model = pickle.load(open(model_file_path, 'rb')) return loaded_model
class Matrix: def __init__(self, rows, cols): self.matrix = self._create_blank(rows, cols) self.rows = rows self.cols = cols def _create_blank(self, rows, cols): mat = [] for i in xrange(0, rows): mat.append([]) for j in xrange(0, cols): mat[i].append((i*cols)+(j)+1) return mat def print_matrix(self): for i in xrange(0, self.rows): output = '|' for j in xrange(0, self.cols): output += ' ' + str(self.matrix[i][j]) output += ' |' print(output) def get_elem(self, row, col): return self.matrix[row-1][col-1] def rotate(self): new_mat = self._create_blank(self.cols, self.rows) for i in xrange(0, self.cols): for j in xrange(0, self.rows): new_mat[i][j] = self.matrix[self.rows-1-j][i] temp = self.cols self.cols = self.rows self.rows = temp self.matrix = new_mat if __name__ == '__main__': a = Matrix(4,3) a.print_matrix() a.rotate() print('') a.print_matrix()
from single_linklist import Node from ex7 import merge_lists def detect_loop(n): head = n n = n.next while n.next: if n == head: return t n = n.next return None if __name__ == '__main__': a = Node.list_to_link([1,2,3]) b = Node.list_to_link([5,4,3]) c = merge_lists(a, b) print(c) print(detect_loop(c))
sum = 2 #求和,1不是素数 for i in range(3, 100): for a in range(2, i):#对一个数挨个求模,判断是否为素数 if i % a == 0: break elif a == i-1:#点睛之笔! sum += i print(sum)
#温度转换实例 tempstr = input("请输入一个带符号的数值:")#F\f表示华式温度 C\c表示摄氏度 if tempstr[-1] in ['F','f']:#如果输入是华式温度 C = (eval(tempstr[0:-1])-32)/1.8 '''索引和切片,索引分为正索引和负索引, 正索引以第一个字符(0)开始,负索引以最后一个字符(-1)开始; 切片是指取字符串中的一段,[x:y],包含x,但不包含y; eval()函数用于去掉字符或字符串的引号''' print("对应的摄氏温度为{:.2f}C".format(C)) #print函数的格式化 elif tempstr[-1] in ['C','c']:#当输入为摄氏度时 F = eval(tempstr[0:-1])*1.8+32 print("对应的华式温度为{:.2f}".format(F)) else: print("输入格式错误")
""" Using PriorityQueue as Heap. """ class PriorityQueue: """Docstring for PriorityQueue""" def __init__(self, degree = 2, contents = []): self.degree = degree self.data = list(contents) self.size = len(contents) parentIndex = (self.size-2) // self.degree for i in range(parentIndex,-1,-1): self.__siftDownFromTo(i, self.size-1) def __repr__(self): return "PriorityQueue(" + str(self.degree) + "," + str(self.data) + ")" def __str__(self): return repr(self) def __bestChildOf(self, parentIndex, toIndex): firstChildIndex = parentIndex * self.degree + 1 endIndex = min(parentIndex * self.degree + self.degree, toIndex) if firstChildIndex > endIndex: return None bestChildIndex = firstChildIndex for k in range(firstChildIndex, endIndex+1): if self.data[k] < self.data[bestChildIndex]: bestChildIndex = k return bestChildIndex def __siftDownFromTo(self, fromIndex, toIndex): parentIndex = fromIndex done = False while not done: childIndex = self.__bestChildOf(parentIndex, toIndex) if childIndex == None: done = True elif self.data[parentIndex] > self.data[childIndex]: self.data[parentIndex], self.data[childIndex] = \ self.data[childIndex], self.data[parentIndex] parentIndex = childIndex else: done = True def __siftUpFrom(self, fromIndex): childIndex = fromIndex done = False while not done: parentIndex = (childIndex-1) // self.degree if childIndex == 0: done = True elif self.data[childIndex] < self.data[parentIndex]: self.data[childIndex], self.data[parentIndex] = \ self.data[parentIndex], self.data[childIndex] childIndex = parentIndex else: done = True def enqueue(self, item): if self.size == len(self.data): self.data.append(item) else: self.data[self.size] = item self.__siftUpFrom(self.size) self.size += 1 def dequeue(self): if not self.isEmpty(): rv = self.data[0] lastEl = self.data[self.size-1] self.data[0] = lastEl self.size -= 1 if self.size > 0: self.__siftDownFromTo(0, self.size-1) return rv raise IndexError("pop from empty PriorityQueue") def isEmpty(self): return self.size == 0 def main(): lst = [100,10,20,25,5,8,2] h = PriorityQueue(2, lst) print(h) h.dequeue() h.enqueue(1) print(h) # lst = [100,10,20,25,5,8] # h = PriorityQueue(2,lst) # print(h) # lst = [] # h = PriorityQueue(2,lst) # print(h) # lst = [100,10,20,25,5,8] # h = PriorityQueue(3,lst) # print(h) if __name__ == "__main__": main()
def changeme(mylist): "This changes a passed list into this function" #mylist.append([1,2,3,4]); mylist=[1,2,3,4]; print "Inside values:", mylist return; mylist=([10,20,30,40]) changeme(mylist) print "Outside values:", mylist
"""Home page shown when the user enters the application""" import streamlit as st import awesome_streamlit as ast import plotly.graph_objects as go import pandas as pd import altair as alt from altair import Chart, X, Y, Axis, SortField, OpacityValue import numpy as np # pylint: disable=line-too-long def write(): """Used to write the page in the app.py file""" with st.spinner("Loading Home ..."): ast.shared.components.title_awesome("") # read CSV df = pd.read_csv("https://raw.githubusercontent.com/hannahkruck/VIS_Test1/Develop/map.csv", encoding ="utf8", sep=";") # Remove 'overall' and 'Überseeische Länder und Hoheitsgebiet' indexNames = df[ df['destinationCountry'] == 'Overall' ].index df.drop(indexNames , inplace=True) indexNames = df[ df['homeCountry'] == 'Overall' ].index df.drop(indexNames , inplace=True) indexNames = df[ df['destinationCountry'] == 'Überseeische Länder und Hoheitsgebiete' ].index df.drop(indexNames , inplace=True) indexNames = df[ df['homeCountry'] == 'Überseeische Länder und Hoheitsgebiete' ].index df.drop(indexNames , inplace=True) # Berechnung der Anzahl aller Antragssteller in einem Land nach Jahr (diese Daten sind nur von Europa verfügbar) # Speichern in neu erstellten Zeile 'sum' df['sum']=df.groupby(['destinationCountry','year'])['total'].transform('sum') #Datentabelle ausblenden # return df # df = load_data() # Delete all cells, except one year! a = 2018 indexNames = df[ df['year'] != a ].index df.drop(indexNames , inplace=True) # In[6]: #Vollbild verwenden #st.set_page_config(layout="wide") # Map with colours (Number of asylum applications) fig = go.Figure(data=go.Choropleth( locations = df['geoCodeDC'], z = df['sum'], text = df['destinationCountry'], colorscale = 'Blues', #Viridis autocolorscale=False, reversescale=False, marker_line_color='darkgray', marker_line_width=0.5, colorbar_tickprefix = '', colorbar_title = 'Number of asylum applications' )) fig.update_layout( title_text='Asylum seekers in Europe in the year %s' % a, geo=dict( showframe=False, showcoastlines=False, projection_type='equirectangular' ), autosize=True, width=1500, height=1080, ) #--------------------Slider Steps------------------------------------# #https://stackoverflow.com/questions/46777047/how-to-make-a-choropleth-map-with-a-slider-using-plotly st.plotly_chart(fig) st.slider("Timeline Years", 2010, 2019) #Sidebar st.sidebar.header("Filters") st.sidebar.multiselect("Select Age", ("All", "under 18", "18 - 35", "26 - 35", "36 - 45")) st.sidebar.multiselect("Select Gender", ("All", "Male", "Female", "Other/unknown")) st.sidebar.multiselect("Select Origin Country", ("All", "Belgium", "Bulgaria", "Czech Republic", "Denmark", "Germany", "Estonia", "Ireland", "Greece", "Spain")) st.sidebar.multiselect("Select Destination Country", ("All", "Belgium", "Bulgaria", "Czech Republic", "Denmark", "Germany", "Estonia", "Ireland", "Greece", "Spain")) #Datentabelle einblenden # st.dataframe(data=df)
def merge_sort(arr: list): l = len(arr) if l > 1: mid = l//2 left = arr[:mid] right = arr[mid:] merge_sort(left) merge_sort(right) i=j=k=0 while i < len(left) and j < len(right): if left[i] <= right[j]: arr[k] = left[i] i+=1 else: arr[k] = right[j] j+=1 k+=1 while i < len(left): arr[k] = left[i] i+=1 k+=1 while j < len(right): arr[k] = right[j] j+=1 k+=1 if __name__ == '__main__': arr = list(map(int, input().strip().split())) merge_sort(arr) print(arr)
import heapq import random class Node: def __init__(self, char, freq): self.value = (char, freq) self.left = None self.right = None class MyHeap: def __init__(self): self.__actual_item_list = {} self.heap = [] def push(self,item: Node): self.__actual_item_list[item.value[0]] = item char = item.value[0] freq = item.value[1] heapq.heappush(self.heap, (freq, char)) def pop(self): if len(self.heap) > 0: freq, char = heapq.heappop(self.heap) return self.__actual_item_list.pop(char) else: return None def print_huffman_codes(root: Node, path: str): if root.left == None and root.right == None: print(f'code : {path} - char : {root.value[0]}') else: if root.left: print_huffman_codes(root.left, path+'0') if root.right: print_huffman_codes(root.right, path+'1') def list_freq_node_list(text: str): s = text.strip() freq = {} for i in s: if i in freq: freq[i] = freq[i] + 1 else: freq[i] = 1 node_list =[] for key in freq: node_list.append(Node(key, freq[key])) return node_list def huffman_encode(text: str): # node list n_list = list_freq_node_list(text) # create a heap with a tupple (freq, node) h = MyHeap() for n in n_list: h.push(n) # create huffman tree while len(h.heap) > 0: if len(h.heap) == 1: break s1 = h.pop() s2 = h.pop() # create a intermediate node and append it into tree temp = Node(str(random.randint(1,10000)), s1.value[1]+s2.value[1]) temp.left = s1 temp.right = s2 # add temp to heap h.push(temp) # print the codes for each character root = h.pop() print_huffman_codes(root,'') if __name__ == '__main__': text = input('Enter any text: ') huffman_encode(text)
""" Given a matrix of m * n elements, return all elements of the matrix in spiral order Example: [ [1,2,3], [4,5,6], [7,8,9] ] returns [1,2,3,6,9,8,7,4,5] [ [1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16] ] returns [1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10] """ def spiral(a): m = len(a[0]) #3 n = len(a) #3 top = 0 bottom = m - 1 #2 left = 0 right = n - 1 #2 direction = 0 myArr = [] while top <= bottom and left <= right: if direction == 0: for i in range(left, right + 1): myArr.append(a[top][i]) top += 1 direction = 1 elif direction == 1: for i in range(top, bottom + 1): myArr.append(a[i][right]) right -= 1 direction = 2 elif direction == 2: for i in range(right, left - 1 , -1): myArr.append(a[bottom][i]) bottom -= 1 direction = 3 elif direction == 3: for i in range(bottom, top - 1 , -1): myArr.append(a[i][left]) left += 1 direction = 0 return myArr a = [ [1,2,3], [4,5,6], [7,8,9] ] b = [ [1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16] ] c = [ [1] ] print(spiral(b))
'''Given a non-empty array of integers, every element appears twice except for one. Find that single one.''' def singleton(arr): ''' finds the single element in the array Uses the XOR operator where n ^ n = 0 and n ^ 0 = n therefore, every duplicating number's XOR will equal 0 and the result will equal the unique number ''' import pdb pdb.set_trace() result = 0 for i in arr: result = result ^ i return result myarr = [4, 1, 2, 1, 2] print(f'heres using xor {singleton(myarr)}') def singleton2(arr): myset = set(arr) return (2 * sum(myset) - sum(arr)) print(f'heres using the sum {singleton2(myarr)}')
# from functools import reduce # import operator # class Solution: # ''' # rearranges the numbers in the list to the next greater permutations of the number # if there's no such available arrangement, you should return a sorted list # the replacements must also be in place; no .remove/.pop/.append # ''' # def nextPermutation(self, nums): # '''the base method called that initiates the checks in the class''' # # check whether its a len(list)=1 list to avoid out of bound errors later on # if len(nums) == 1: # return nums # split = self.get_split(nums) # if split == -1: # nums.sort() # return nums # else: # change_index = self.get_largest(nums, split) # self.swap(nums, split, change_index) # self.reverse(nums, split + 1) # def get_split(self, nums): # '''this finds the index to which the larger index is found when comparing every two''' # i = len(nums) - 1 # while i >= 0: # if nums[i] <= nums[i - 1]: # i -= 1 # else: # break # return i - 1 # def get_largest(self, nums, i): # '''find the largest int in the list''' # j = len(nums) - 1 # while j > i and j >= 0: # if nums[j] > nums[i]: # break # else: # j -= 1 # return j # def swap(self, nums, i, j): # '''does the swapping in the array''' # nums[i], nums[j] = (nums[j], nums[i]) # def reverse(self, nums, begin): # ''' # reverses the integers where begin is what the int on the left # and end is the one on the right. We call swap from here to swap the integers # ''' # start = begin # end = len(nums) - 1 # while start < end: # self.swap(nums, start, end) # start += 1 # end -= 1 # x = Solution() # lsit = [2, 2, 0, 2, 2] # print(x.nextPermutation(lsit)) # # def get_split(nums): # # i = len(nums) - 1 # # while i >= 0: # # if nums[i] < nums[i - 1]: # # i -= 1 # # else: # # break # # return i - 1 # # def get_largest(nums, i): # # j = len(nums) - 1 # # while j >= i: # # if nums[j] > nums[i]: # # break # # else: # # j -= 1 # # return j # # def swap(nums, i, j): # # nums[i], nums[j] = (nums[j], nums[i]) # # def reverse(nums, begin): # # start = begin # # end = len(nums) - 1 # # while start < end: # # swap(nums, start, end) # # start += 1 # # end -= 1 # # def lex(myList): # # ''' # # rearranges the numbers in the list to the next greater permutations of the number # # if there's no such available arrangement, you should return a sorted list # # the replacements must also be in place; no .remove/.pop/.append # # ''' # # split = get_split(myList) # # if split == -1: # # myList.sort() # # return myList # # else: # # change_index = get_largest(myList, split) # # swap(myList, split, change_index) # # reverse(myList, split + 1) # # lis = [5, 1, 1] # # print(lex(lis)) '''reverse an integer''' def reverser(x): my_Str = str(x) reversedInt = 0 modulus = 10 if x < 0: iterator = len(my_Str) - 1 m = x * -1 else: iterator = len(my_Str) m = x while iterator != 0: reversedInt = reversedInt * 10 reversedInt = reversedInt + m % modulus m //= modulus iterator -= 1 if x < 0: return reversedInt * -1 return reversedInt print(reverser(-321))
import unittest from unittest.mock import patch from generator import get_password_length, password_combination_choice, password_generator """ Unit Testing Documentation (Real Python): https://realpython.com/python-testing/#writing-your-first-test Unit Test Module Documentation : https://docs.python.org/3/library/unittest.html """ class TestGenerator(unittest.TestCase): """Test password length collection method. Enter nothing and the result should be 8 Args: unittest ([type]): [description] Returns: [type]: [description] """ @patch('builtins.input', return_value="") def test_default_length(self, input): self.assertEqual(get_password_length(), 8) """ Test password length collection method. Enter 12 and the result should be 12 Returns: [type]: [description] """ @patch('builtins.input', return_value="12") def test_length_twelve(self, input): self.assertEqual(get_password_length(), 12) """ Test password length collection method. Enter any string, Returns: [type]: [description] """ @patch('builtins.input', return_value="8") def test_length_string(self, input): self.assertEqual(get_password_length(), 8) """ Test the combination choice method. enter invalid data to get all TRUE output """ @patch('builtins.input', side_effect=["h", "e", "w"]) def test_combo_default_invalid(self, input): self.assertEqual(password_combination_choice(), [True, True, True]) """ Test the combination choice method. no entries (" ") to get all TRUE output """ @patch('builtins.input', side_effect=["", "", ""]) def test_combo_default_empty(self, input): self.assertEqual(password_combination_choice(), [True, True, True]) """ Test the combination choice method. enter one invalid entry to get all TRUE output """ @patch('builtins.input', side_effect=["True", "Nope", "True"]) def test_combo_one_invalid(self, input): self.assertEqual(password_combination_choice(), [True, True, True]) """ Should return message asking to restart program and value of none """ def test_passgen_NONE(self): default_length = 12 all_false = [False, False, False] self.assertEqual(password_generator(all_false, default_length), None) if __name__ == '__main__': unittest.main()
#importing unittest module import unittest class TestingStringMethods(unittest.TestCase): #string equal def test_string_equality(self): #if both arguments are equal then its a success self.assertEqual('ttp' * 5, 'ttpttpttpttpttp') #comparing 2 strings def test_string_case(self): # if both arguments are equal the its a success self.assertEqual('tutorialspoint'.upper(), 'TUTORIALSPOINT') # checking whether a string is upper or not def test_is_string_upper(self): #used to check whether the staement is True of False # the result of expression inside the **assertTrue** must be True to pass the test case # the result of expression inside the **assertFalse** must be False to pass the test case self.assertTrue('TUTORIALSPOINt'.isupper()) self.assertFalse('TUTORIALSpoint'.isupper()) #running the tests unittest.main()
for i in range(int(input())): for a in range(1, i + 2): print(a, end='') print()
'''Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final, de acordo com a média atingida: - Média abaixo de 5.0: REPROVADO - Média entre 5.0 e 6.9: RECUPERAÇÃO - Média 7.0 ou superior: APROVADO''' n1 = float(input('Primeira Nota: ')) n2 = float(input('Segunda Nota: ')) media = (n1 + n2) / 2 if media < 5: print('Você foi REPROVADO') elif media >=5 and media < 7: print('Você está em RECUPERAÇÃO') elif media >= 7: print('Você foi APROVADO') print('Sua média foi {:.1f}'.format(media))
'''Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo que ele foi multado. A multa vai custar R$7,00 por cada Km acima do limite.''' vel = float(input('Qual a velocidade atual do carro? Km/h ')) if vel > 80: multa = (vel - 80) * 7 print('MULTADO! Você excedeu o limite permitido que é de 80Km/h \nVocê deve pagar uma Multa de R${:.2f}!'.format(multa)) else: print('OK, Você está na velocidade que a via permite, \nFaça uma ótima viagem!')
#leia preços e nome do produto #pergunte se quer continuar #total gasto na compra #quantos produtos custam mais que 1000 #nome do produto mais barato total = totmil = menor = cont = 0 while True: produto = str(input('Nome do Produto: ')) preço = float(input('Preço: R$')) cont += 1 total += preço if preço > 1000: totmil += 1 if cont == 1: menor = preço else: if preço < menor: menor = preço resp = ' ' while resp not in 'SN': resp = str(input('Quer continuar? [S/N] ')).strip().upper() if resp == 'N': break print('{:-^40}'.format(' FIM DO PROGRAMA ')) print('O total da compra foi R${:.2f}'.format(total)) print('Temos {} produtos custando mais de R$1.000'.format(totmil)) print('O produto mais barato custa R${:.2f}'.format(menor))
n = int(input('Digite um Número: ')) an = n-1 su = n+1 print('O número digitado foi {}, Seu antecessor é {}, Seu Sucessor é {}.'.format(n, an, su))
'''Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado.''' from time import sleep casa = float(input('Qual o valor da casa? R$ ')) salario = float(input('Quanto você ganha mensal? R$ ')) tempo = int(input('Em quantos anos você pretende pagar? ')) parcela = casa / (tempo * 12) meses = tempo * 12 aprov = salario * 30 / 100 print('Simulando a sua parcela ficará em\n{}x de R${:.2f}'.format(meses, parcela)) print('Verificando aprovação... ') sleep(5) if aprov >= parcela: print('Seu financiamento foi aprovado! Parabéns') else: print('Seu financiamento foi NEGADO! Procure um avalista ...')
import random def quick_sort(unordered_list): size = len(unordered_list) if (size < 2): return unordered_list pivotIndex = random.randrange(0, size) pivot = unordered_list[pivotIndex] minor_list = [] major_list = [] for i, val in enumerate(unordered_list): if (i != pivotIndex and val < pivot): minor_list.append(val) continue if (i != pivotIndex and val >= pivot): major_list.append(val) return quick_sort(minor_list) + [pivot] + quick_sort(major_list) # ----------- Tests ----------- def test_short_list(): unordered_list = [5, 8, 12, 67, 43, 56, 9] assert quick_sort(unordered_list) == [5, 8, 9, 12, 43, 56, 67] def test_medium_list(): unordered_list = [5, 45, 100, 8, 12, 56, 99, 3, 67, 80, 43, 56, 9, 140] assert quick_sort(unordered_list) == [3, 5, 8, 9, 12, 43, 45, 56, 56, 67, 80, 99, 100, 140]
''' Funções (def) em Python - * args **kwargs - Aula 16 (parte 3) ''' def func(*args): print(*args) var = func(1,2,3,4,5) def func(*args): print(args) var = func(1,2,3,4,5) lista = [1,2,3,4,5,6] n1, n2, *n = lista print(n1,n2, n)
n1 = 10 n2 = 0 while not n1 == 1: print(n2,n1) n1 = n1 - 1 n2 = n2 + 1 print('\nJeito dois\n') contador = 10 for valor in range(10): print(valor,contador) contador -= 1 for r in range(10,1,-1): print(r) for p, r in enumerate(range(10,1,-1)): print(p,r)
''' Tipos de Dados str - Strings - Textos int - inteiro - 12345 0 -5 -200000 7 32 float - real/ponto flutuante - 10.5 20.2 0.0 -5.0 bool - booleano/lógico - True/False (10 == 10) ''' print('Junior') print(type('Junior')) print('Junior', type('Junior')) print('10' ,type('10')) print(10, type(10)) print('String' == "String" ,type('String' == "String")) #com uma aspas ou duas, de toda forma são iguais print(10 == 10, type(10 == 10)) print(False, type(False)) print(5.0, type(5.0)) # Type Casting / Conversão de tipos print('\n',5.0, type(5.0) , bool(5.0),sep='') print(5.0, type(5.0), int(5.0)) # print('Junior', type('Junior'), int('Junior')) # assim dara erro pq não tem como converter uma string com caracteres em um numerio inteiro print('5.0', type('5.0'), int('5.0'))
''' For in em Python Iteradno strings com for Função range(start=0, stop, step =1) ''' # texto = 'Python' # for n, letra in enumerate(texto): # print(n, letra) for numero in range(2,10,2): #Função range(start=0, stop, step =1) print(numero) for numero in range(20,10,-1): #Função range(start=0, stop, step =1) print(numero) for n in range(100): if n % 8 == 0: print(n)
''' Operadores aritmeticos: + = soma ou concatena (Pode ser chamado de poliformismo por ter uma mesma ação utilizando o mesmo operador) - = subtração * = multilplicação / = divisão // = divisão inteira ** = exponenciação % = resto da divisão () = altera a ordem de precedencia ''' print('Multiplicação:','10 * 10 = ',10 * 10) print('Soma:','10 + 10 = ',10 + 10) print('Concatenando:','10 + 10 = ','10' + '10') print('Subtração:','10 - 10 = ', 10 - 10) print('Divisão:','10 / 10 = ',10 / 10) print('Divisão inteira:','10 // 10 = ',10 // 10) print('Exponenciação:','10 ** 10 = ',10 ** 10) print('Resto da Divisão:','10 % 10 = ', 10 % 10) print('Alterando Ordem de prescedencia:','(5+2*10) = ',(5+2*10)) print('Alterando Ordem de prescedencia:','(5+2)*10 = ',(5+2)*10) print('\n','$'*80,sep='') print('\nConcatenando:','10 + 10 = ','10' + str(10))
def page(count, p): if p<3: begin=1 end=8 elif p<count-4: begin=p-3 end=p+4 else: begin=count-8 end=count for i in range(begin, end+1): print(i) page(100, 1) print('--------------') page(100, 5) print('--------------') page(100, 29) print('--------------') page(100, 99)
def phoneVerification(phoneNumber): if len(phoneNumber) == 9: return True elif len(phoneNumber) == 13: return True else: return False phoneNumber = input("Zadej telefonní číslo: ") phoneNumber = phoneNumber.replace(" ", "") verified = phoneVerification(phoneNumber) if verified: textSMS = input("Zadej text zprávy: ") def textPrice (textSMS): import math zprava = math.ceil(len(textSMS)/180) cena = zprava * 3 return cena cena = textPrice(textSMS) print(f"Výsledná cena SMS je {cena} Kč.") else: print("Chyba ověření. Zadej číslo znovu.")
# Katie Williams [email protected] 2016/01/30 this is code to work on loops books = ["Tale of Two Cities","Happy Potter","Lord of the Rings"]; nums = list(range(100)); for book in books: print(book)
#!/usr/bin/python from collections import defaultdict def shorten_string(words): h_word = defaultdict(lambda: 0) word = list(words) for letter in word: h_word[letter] += 1 ret = "" for letter in list(set(word)): ret += letter + str(h_word[letter]) return ret print shorten_string("TESTTTTTT")
#!/usr/bin/python from operator import attrgetter class Address(object): def __init__(self, zip, city, country): self.data = dict() self.data["zip"] = zip self.data["city"] = city self.data["country"] = country def __str__(self): return str(self.data["city"]) + " " + str(self.data["zip"]) + " " + str(self.data["country"]) class Person(object): def __init__(self, name, age, gender, address): self.data = dict() self.data["name"] = name self.data["age"] = age self.data["gender"] = gender self.data["address"] = address def __getattr__(self, key): return self.data[key] def __str__(self): return "Name: " + str(self.data["name"]) + "\nAge: " + str(self.data["age"]) + "\nSex: " + str(self.data["gender"]) + "\nAddress: " + str(self.data["address"]) + "\n" class Solution(object): def __init__(self): self.people = list() def __str__(self): ret = "" for index in range(len(self.people)): ret += "\n---Index[" + str(index) + "]---\n" ret += str(self.people[index]) return ret def addPerson(self, p): self.people.append(p) def sort(self, key): if "." in key: keyArr = key.split(".") self.people.sort(key=lambda x: x.data[keyArr[0]].data[keyArr[1]]) else: self.people.sort(key=lambda x: x.data[key]) a1 = Address(95134, "San Jose", "USA") a2 = Address(12345, "Seattle", "USA") p1 = Person("Ishan", 28, "Male", a1) p2 = Person("Alexa", 2, "Female", a2) s = Solution() s.addPerson(p1) s.addPerson(p2) s1 = Solution() s1.addPerson(p1) s1.addPerson(p2) s2 = Solution() s2.addPerson(p1) s2.addPerson(p2) print "\nOriginal:\n------------\n"+ str(s1) s1.sort("name") print "\nSorted By Name:\n-------------\n" + str(s1) print "\nOriginal:\n------------\n"+ str(s2) s2.sort("address.zip") print "\nSorted By Zipcode:\n-------------\n" + str(s2) print "\nOriginal:\n------------\n"+ str(s) s.sort("address.city") print "\nSorted By City:\n-------------\n" + str(s)
#!/usr/bin/python class Trie(object): def __init__(self): self.root = dict() def _isValidWord(self, word): if not isinstance(word, basestring): print "Skipping since not valid word" return False return True def addWord(self, word): if not self._isValidWord(word): return False letters = list(word) current = self.root _end = '_end_' for letter in letters: current = current.setdefault(letter, {}) #if not current.has_key(letter): # current[letter] = {} #current = current[letter] current[_end] = _end def findWordInTrie(self, word): if not self._isValidWord(word): return False letters = list(word) current = self.root for x in letters: if current.has_key(x): print x current = current[x] else: return False return True def getWords(self, current, word): _end = '_end_' words = list() if current.keys() == None: word.append(word) return words for letter in current.keys(): word = word + letter words.append(self.getWords(current[letter], word)) def suggest(self, word): if not self._isValidWord(word): return None _end = '_end_' letters = list(word) suggestions = list() d_word = "" current = self.root for letter in letters: if current.has_key(letter): d_word += letter if current.has_key(_end): suggestions.append(d_word) current = current[letter] suggestions.append(self.getWords(current, word)) return suggestions t = Trie() t.addWord("Hello") t.addWord("World") print t.root.items() print t.findWordInTrie("World") print t.suggest("Wor") x = dict()
#!/usr/bin/python def metroCard(lastNumberOfDays): numDaysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31] numPossibilities = [] for i in range(12): if lastNumberOfDays == numDaysInMonth[i]: x = i + 1 x = x % 12 numPossibilities.append(numDaysInMonth[x]) numPossibilities = set(numPossibilities) return list(numPossibilities) print metroCard(30) print metroCard(31) print metroCard(28)
#!/usr/bin/python def isPalindrome(s): strArr = list(s) n = len(s) i = 0 print n for i in range(n/2): print i if strArr[i] != strArr[n-i-1]: return False return True print isPalindrome("test") print isPalindrome("abcba") print isPalindrome("abba")
#!/usr/bin/python class Keypad(object): def __init__(self): self.keys = [x for x in range(10)] self.keys += ['*', '#', '<-'] self.console = "" self.keypad = dict() ascii = 65 self.keypad[0] = ['*'] self.keypad[1] = ['~'] keyID = 2 while(ascii < 88): count = 3 if keyID == 7 or keyID == 9: count = 4 for i in range(count): if keyID not in self.keypad: self.keypad[keyID] = list() self.keypad[keyID].append(chr(ascii)) ascii += 1 keyID += 1 if chr(ascii) == 'z': break def __str__(self): return str(self.keys) k = Keypad() arr = [4,4,4,7,7,7,7,4,4,2,6,6]
#!/usr/bin/python """ Given a string s, find all its potential permutations. The output should be sorted in lexicographical order. Example For s = "CBA", the output should be stringPermutations(s) = ["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]; For s = "ABA", the output should be stringPermutations(s) = ["AAB", "ABA", "BAA"]. Input/Output [time limit] 4000ms (py) [input] string s A string containing only capital letters. Guaranteed constraints: 1 <= s.length <= 5. [output] array.string All permutations of s, sorted in lexicographical order. """ def permutaions(start, end='', arr=[]): if len(start) == 0 and end not in arr: arr.append(end) else: for i in range(len(start)): permutaions(start[0:i] + start[i+1:], end + start[i], arr) return arr def stringPermutations(s): return sorted(permutaions(s))
#-*- coding: utf-8 -*- class Programa: def __init__(self, nome, ano): self._nome = nome.title() self.ano = ano self._likes = 0 @property #getter def likes(self): return self._likes def dar_likes(self): self._likes += 1 @property #getter def nome(self): return self._nome @nome.setter #setter def nome(self,nome): self._nome = nome class Filme(Programa): def __init__(self, nome, ano, duracao): super().__init__(nome, ano) self.duracao = duracao class Serie(Programa): def __init__(self, nome, ano, temporadas): super().__init__(nome, ano) self.temporadas = temporadas vingadores = Filme('vingadores - guerra infinita', 2018, 160) atlanta = Serie('atlanta', 2018, 2) vingadores.dar_likes() vingadores.dar_likes() vingadores.dar_likes() atlanta.dar_likes() atlanta.dar_likes() print(f'Nome: {vingadores.nome} - Likes: {vingadores.likes}') print(f'Nome: {atlanta.nome} - Likes: {atlanta.likes}')
#INFORMATION: This script is designed to read the Sydian template, parse through each row, and then send an e-mail to #the relevant users identified in that row #Eliminates duplicates in each row of the string def uniquify(string): output = "" seen = set() for row in string.split("\n"): seen = set() for word in row.split(): if word not in seen: output += (word + " ") seen.add(word) output+= "\n" return output import openpyxl #To modify excel import win32com.client as win32 #To work with outlook import sys #For system exit functionality #ask for name of the excel file print("What is the name of the excel file that you are using (format: example.xlsx)?") name = input() #Load workbook with given name (must be in same folder) and worksheet try: wb = openpyxl.load_workbook(name) ws = wb.active except: #errors out if wrong file format or name print("Could not load your excel workbook. Enter any key to exit.") start = input() sys.exit(130) #Gather data about the Sydian spreadsheet (Note: SubHeaders may be removed for a generic function) print("Which row is the header information in?") HeaderRow = int(input()) #Specify the first row of data to parse through print("What is the first row in which there is user data?") FirstRow = int(input()) #Specificy which column contains the users unique identified to convert into an email address print("Which column(enter an integer value) is the SSO/e-mail address in?") SSO = int(input()) #value to append is set here print("Do you want to append something to the SSO column(ex. append '@gmail.com')? Yes or no?") start = input() if start.upper() == "YES": print ("What do you want to append?") emailappend = input() print ("The e-mail format will be example"+emailappend+'.') else: print("Nothing will be appended.") emailappend = "" #Calcualte the max row and column used in the spreadsheet MaxRow = ws.max_row MaxColumn = ws.max_column print("We have detected " + str(MaxRow) + " rows and " + str(MaxColumn) + " columns in total.") #Starting Sequence print("To start, type anything and hit enter") start = input() #Definitions UserUsage = "" #Create an empty string to save the message body for rows in range (FirstRow, MaxRow+1,1): #iterate across all the rows starting at specified start row #If there is no e-mail address/SSO to use, skip the iteration if (str(ws.cell(row=rows,column=SSO).value) == "None"): continue #appends the e-mail address recipient = str(ws.cell(row=rows,column=SSO).value) + emailappend # iterates through every column for columns in range(1,MaxColumn+1,1): # Variables to simplify visibility for code below data = str(ws.cell(row=rows, column=columns).value) headerstring = str(ws.cell(row=HeaderRow, column=columns).value) # NOTE: The code below is specifically designed for the Sydian template, a general case would not need any # subheaders or subsubheaders or workarounds for merging. Simply form the UserUsage string as follows: # UserUsage+=(headerstring + ": " + data + "\n") # skip adding column data if the column entry is blank if (data == "None"): continue #Data exists else: UserUsage+=(headerstring + ": " + data + "\n") #Ignore a blank string / do not attempt to build a message if (UserUsage == ""): continue #Create the outlook message outlook = win32.Dispatch("outlook.application") mail = outlook.CreateItem(0) mail.To = recipient mail.Subject = "Notification" #clean up formatting UserUsageSend = str(UserUsage).replace(" ", " ") #Below can remove non-unique entries within each row if it looks unsightly #UserUsageSend = uniquify(UserUsageSend) mail.body = str(UserUsageSend) #Verify with the user whether they truly want to send out the e-mails based on a printed sample if (rows == FirstRow): print("\n" + str(UserUsageSend)) print("Shown above is a sample message. Are you sure you want to send?" " (reply 'yes' or this script will quit)? This prompt message will not" " be repeated for the rest of the messages.") emailmode = input() #Exit if user types anything but yes case-insensitive if (emailmode.upper() != "YES"): sys.exit(130) #Send mail mail.send #Reset user message and move on to the next row UserUsage="" #On script completion print("Complete. Enter anything to exit.") start = input() sys.exit(130)
"""Happy Numbers: Iterating the sum of the squares of the digits terminates with one""" def sum_of_squares(n): """Return the sum of the squares of the digits of n""" ret = 0 while n: ret += (n % 10) ** 2 n = n // 10 return ret def happy(n): """Return True when n is a happy number, False otherwise A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers (or sad numbers). [http://en.wikipedia.org/wiki/Happy_number] """ encountered = set() while n != 1: encountered.add(n) n = sum_of_squares(n) if n in encountered: return False return True
"""Binary Search: A simple task, easy to get wrong""" import unittest def binary_search(n, ns): """Search a list of ns for an element n Returns the index of n when n is in the list, or -1 if n is not found. Assumes the list is sorted in ascending order. """ lo, high = 0, len(ns) - 1 while lo <= high: mid = (lo + high) / 2 if ns[mid] == n: return mid elif ns[mid] < n: lo = mid + 1 elif ns[mid] > n: high = mid - 1 return -1 class TestBinarySearch(unittest.TestCase): """Test the implementation of binary search""" def test_power_2(self): """Test with a list of power of 2 length First check all items in the list can be found, then check we fail high and low properly """ for i in range(256): self.assertEqual(binary_search(i, list(range(256))), i) self.assertEqual(binary_search(-1, list(range(256))), -1) self.assertEqual(binary_search(-411, list(range(256))), -1) self.assertEqual(binary_search(256, list(range(256))), -1) self.assertEqual(binary_search(411, list(range(256))), -1) def test_non_power_2(self): """Test a list of non power of 2 length First check all items in the list can be found, then check we fail high and low properly """ for i in range(200): self.assertEqual(binary_search(i, list(range(200))), i) self.assertEqual(binary_search(-1, list(range(200))), -1) self.assertEqual(binary_search(-411, list(range(200))), -1) self.assertEqual(binary_search(200, list(range(200))), -1) self.assertEqual(binary_search(411, list(range(200))), -1) def test_equal_list(self): """Test a list containing all equal elements Check we find the element, and fail and low properly """ self.assertNotEqual(binary_search(1, [1]*10), -1) self.assertEqual(binary_search(0, [1]*10), -1) self.assertEqual(binary_search(2, [1]*10), -1) if __name__ == "__main__": unittest.main()
anagrams = {} def build_anagrams(): with open("wordlist") as fin: for line in fin: word = line.strip().lower() if not word.isalpha(): continue index = list(word) index.sort() index = "".join(index) anag_list = anagrams.get(index, set()) anag_list.add(word) anagrams[index] = anag_list build_anagrams() def find_anagrams(word): index = list(word) index.sort() index = "".join(index) return anagrams[index] def find_largest_class(): biggest = [] for val in anagrams.itervalues(): if len(val) > len(biggest): biggest = val return biggest
import random def gcd(a, b): while b != 0: a, b = b, a % b return a def lcm(a, b): return a * b / gcd(a, b) def pollard(n): b = 10 a = random.randrange(2, n - 1) while b <= 10**6: k = reduce(lcm, range(1, b+1)) g = gcd(a, n) if g > 1: return g d = gcd(a**k - 1, n) if 1 < d < n: return d if d == 1: b *= 10 if d == n: a = random.randrange(2, n-1) return -1
def kaprekar(k): n = 1 power = 10 while power <= k: power *= 10 n += 1 x = k ** 2 x, y = x % power, x // power if x + y == k: return True return False if __name__ == "__main__": print [x for x in range(1, 1000) if kaprekar(x)]
upside = {0: 0, 1: 1, 6: 9, 8: 8, 9: 6} def is_upside(n): digits = [] updigs = [] while n: dig = n % 10 if dig not in upside: return False digits.append(dig) updigs.append(upside[dig]) n /= 10 updigs.reverse() return digits == updigs def upside_n(n): upnums = [] for i in range(n): if is_upside(i): upnums.append(i) return upnums
# Python内建的filter()函数用于过滤序列。 # 和map()类似,filter()也接收一个函数和一个序列。 # 和map()不同的是,filter()把传入的函数依次作用于每个元素, # 然后根据返回值是True还是False决定保留还是丢弃该元素。 # 例如,在一个list中,删掉偶数,只保留奇数,可以这么写: def is_odd(n): return n%2==1 list(filter(is_odd,[1,2,4,5,6,9,10,15])) # [1,5,9,15] # 把一个序列中的空字符串删掉,可以这么写: def not_empty(s): return s and s.strip() list(filter(not_empty,['A','','B',None,'C',' '])) # ['A','B','C'] # 可见用filter()这个高阶函数, # 关键在于正确实现一个“筛选”函数。 # 注意到filter()函数返回的是一个Iterator, # 也就是一个惰性序列,所以要强迫filter()完成计算结果, # 需要用list()函数获得所有结果并返回list。 # 用filter求素数 # 计算素数的一个方法是埃氏筛法,它的算法理解起来非常简单: # 首先,列出从2开始的所有自然数,构造一个序列: # 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... # 取序列的第一个数2,它一定是素数, # 然后用2把序列的2的倍数筛掉: # 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... # 取新序列的第一个数3,它一定是素数, # 然后用3把序列的3的倍数筛掉: # 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... # 取新序列的第一个数5,然后用5把序列的5的倍数筛掉: # 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... # 不断筛下去,就可以得到所有的素数。 # 用Python来实现这个算法,可以先构造一个从3开始的奇数序列: def _odd_iter(): n=1 while True: n=n+2 yield n # 注意这是一个生成器,并且是一个无限序列。 # 然后定义一个筛选函数: def _not_divisible(n): return lambda x:x%n>0 # 最后,定义一个生成器,不断返回下一个素数: def primes(): yield 2 it=_odd_iter() # 初始序列 while True: n=next(it) # 返回序列的第一个数 yield n it=filter(_not_divisible(n),it) # 构造新序列 # 这个生成器先返回第一个素数2,然后, # 利用filter()不断产生筛选后的新的序列。 # 由于primes()也是一个无限序列, # 所以调用时需要设置一个退出循环的条件: # 打印1000以内的素数: for n in primes(): if n<1000: print(n) else: break # 注意到Iterator是惰性计算的序列, # 所以我们可以用Python表示“全体自然数”, # “全体素数”这样的序列,而代码非常简洁。 # 小结 # filter()的作用是从一个序列中筛出符合条件的元素。 # 由于filter()使用了惰性计算, # 所以只有在取filter()结果的时候, # 才会真正筛选并每次返回下一个筛出的元素。 # 练习 # 回数是指从左向右读和从右向左读都是一样的数, # 例如12321,909。请利用filter()筛选出回数: # def is_palindrome(n): # pass # 测试: # output = filter(is_palindrome, range(1, 1000)) # print('1~1000:', list(output)) # if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]: # print('测试成功!') # else: # print('测试失败!') def is_palindrome(n): s=str(n) if s[0:]==s[::-1]: return n # 测试: output = filter(is_palindrome, range(1, 1000)) print('1~1000:', list(output)) if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]: print('测试成功!') else: print('测试失败!')
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python支持多种图形界面的第三方库,包括: # Tk # wxWidgets # Qt # GTK # 等等。 # 但是Python自带的库是支持Tk的Tkinter, # 使用Tkinter,无需安装任何包,就可以直接使用。 # 本章简单介绍如何使用Tkinter进行GUI编程。 # Tkinter # 我们来梳理一下概念: # 我们编写的Python代码会调用内置的Tkinter,Tkinter封装了访问Tk的接口; # Tk是一个图形库,支持多个操作系统,使用Tcl语言开发; # Tk会调用操作系统提供的本地GUI接口,完成最终的GUI。 # 所以,我们的代码只需要调用Tkinter提供的接口就可以了。 # 第一个GUI程序 # 使用Tkinter十分简单,我们来编写一个GUI版本的“Hello, world!”。 # 第一步是导入Tkinter包的所有内容: from tkinter import * # 第二步是从Frame派生一个Application类,这是所有Widget的父容器: class Application(Frame): def __init__(self,master=None): Frame.__init__(self,master) self.pack() self.createWidgets() def createWidgets(self): self.helloLabel=Label(self,text='Hello, world!') self.helloLabel.pack() self.quitButton=Button(self,text='Quit',command=self.quit) self.quitButton.pack() # 在GUI中,每个Button、Label、输入框等,都是一个Widget。 # Frame则是可以容纳其他Widget的Widget,所有的Widget组合起来就是一棵树。 # pack()方法把Widget加入到父容器中,并实现布局。 # pack()是最简单的布局,grid()可以实现更复杂的布局。 # 在createWidgets()方法中,我们创建一个Label和一个Button, # 当Button被点击时,触发self.quit()使程序退出。 # 第三步,实例化Application,并启动消息循环: app=Application() # 设置窗口标题 app.master.title('Hello Wordl') # 主消息循环 app.mainloop() # GUI程序的主线程负责监听来自操作系统的消息,并依次处理每一条消息。 # 因此,如果消息处理非常耗时,就需要在新线程中处理。 # 运行这个GUI程序,可以看到下面的窗口: # https://cdn.liaoxuefeng.com/cdn/files/attachments/00141049329759550860dddd40c49d0806bbf0b3cf7d2f7000 # 点击“Quit”按钮或者窗口的“x”结束程序。 # 输入文本 # 我们再对这个GUI程序改进一下,加入一个文本框,让用户可以输入文本, # 然后点按钮后,弹出消息对话框。 from tkinter import * import tkinter.messagebox as messagebox class Application(Frame): def __init__(self,master=None): Frame.__init__(self,master) self.pack() self.createWidgets() def createWidgets(self): self.nameInput=Entry(self) self.nameInput.pack() self.alertButton=Button(self,text='Hello',command=self.hello) self.alertButton.pack() def hello(self): name=self.nameInput.get() or 'world' messagebox.showinfo('Message','Hello, %s' % name) app=Application() # 设置窗口标题: app.master.title('Hello World') # 主消息循环: app.mainloop() # 当用户点击按钮时,触发hello(), # 通过self.nameInput.get()获得用户输入的文本后, # 使用tkMessageBox.showinfo()可以弹出消息对话框。 # 程序运行结果如下: # https://cdn.liaoxuefeng.com/cdn/files/attachments/001410493505348d04f0ae2b4274939ab7cbad2c9301f2f000 # 小结 # Python内置的Tkinter可以满足基本的GUI程序的要求, # 如果是非常复杂的GUI程序,建议用操作系统原生支持的语言和库来编写。
#!/usr/bin/env python # -*- coding: utf-8 -*- # 在程序运行的过程中,如果发生了错误,可以事先约定返回一个错误代码, # 这样,就可以知道是否有错,以及出错的原因。 # 在操作系统提供的调用中,返回错误码非常常见。 # 比如打开文件的函数open(), # 成功时返回文件描述符(就是一个整数),出错时返回-1。 # 用错误码来表示是否出错十分不便, # 因为函数本身应该返回的正常结果和错误码混在一起, # 造成调用者必须用大量的代码来判断是否出错: # def foo(): # r=some_function() # if r==(-1): # return (-1) # # do something # return r # # def bar(): # r=foo() # if r==(-1): # print('Error') # else: # pass # 一旦出错,还要一级一级上报,直到某个函数可以处理该错误(比如,给用户输出一个错误信息)。 # 所以高级语言通常都内置了一套try...except...finally...的错误处理机制,Python也不例外。 # try # 让我们用一个例子来看看try的机制: try: print('try...') r=10/0 print('result:',r) except ZeroDivisionError as e: print('except:',e) finally: print('finally...') print('END') # 当我们认为某些代码可能会出错时,就可以用try来运行这段代码, # 如果执行出错,则后续代码不会继续执行, # 而是直接跳转至错误处理代码,即except语句块,执行完except后, # 如果有finally语句块,则执行finally语句块,至此,执行完毕。 # 上面的代码在计算10 / 0时会产生一个除法运算错误: # try... # except:division by zero # finally... # END # 从输出可以看到,当错误发生时,后续语句print('result:', r)不会被执行, # except由于捕获到ZeroDivisionError,因此被执行。 # 最后,finally语句被执行。然后,程序继续按照流程往下走。 # 如果把除数0改成2,则执行结果如下: # try... # result:5 # finally... # END # 由于没有错误发生,所以except语句块不会被执行, # 但是finally如果有,则一定会被执行(可以没有finally语句)。 # 你还可以猜测,错误应该有很多种类, # 如果发生了不同类型的错误,应该由不同的except语句块处理。 # 没错,可以有多个except来捕获不同类型的错误: try: print('try...') r=10/int('a') print('result:',r) except ValueError as e: print('ValueError:',e) except ZeroDivisionError as e: print('ZeroDivisionError:',e) finally: print('finally...') print('END') # int()函数可能会抛出ValueError, # 所以我们用一个except捕获ValueError, # 用另一个except捕获ZeroDivisionError。 # 此外,如果没有错误发生,可以在except语句块后面加一个else, # 当没有错误发生时,会自动执行else语句: try: print('try...') r=10/int('2') print('result:',r) except ValueError as e: print('ValueError:',e) except ZeroDivisionError as e: print('ZeroDivisionError:',e) else: print('no error!') finally: print('finally...') print('END') # Python的错误其实也是class,所有的错误类型都继承自BaseException, # 所以在使用except时需要注意的是, # 它不但捕获该类型的错误,还把其子类也“一网打尽”。比如: # try: # foo() # except ValueError as e: # print('ValueError') # except UnicodeError as e: # print('UnicodeError') # 第二个except永远也捕获不到UnicodeError, # 因为UnicodeError是ValueError的子类, # 如果有,也被第一个except给捕获了。 # Python所有的错误都是从BaseException类派生的, # 常见的错误类型和继承关系看这里: # https://docs.python.org/3/library/exceptions.html#exception-hierarchy # 使用try...except捕获错误还有一个巨大的好处,就是可以跨越多层调用, # 比如函数main()调用foo(),foo()调用bar(),结果bar()出错了, # 这时,只要main()捕获到了,就可以处理: def foo(s): return 10/int(s) def bar(s): return foo(s)*2 def main(): try: bar('0') except Exception as e: print('Error:',e) finally: print('finally...') # 也就是说,不需要在每个可能出错的地方去捕获错误, # 只要在合适的层次去捕获错误就可以了。 # 这样一来,就大大减少了写try...except...finally的麻烦。 # 调用栈 # 如果错误没有被捕获,它就会一直往上抛, # 最后被Python解释器捕获,打印一个错误信息,然后程序退出。 # 来看看err.py: # err.py: # def foo(s): # return 10/int(s) # # def bar(s): # return foo(s)*2 # # def main(): # bar('0') # # main() # 执行,结果如下: # $ python3 err.py # Traceback (most recent call last): # File "err.py", line 11, in <module> # main() # File "err.py", line 9, in main # bar('0') # File "err.py", line 6, in bar # return foo(s) * 2 # File "err.py", line 3, in foo # return 10 / int(s) # ZeroDivisionError: division by zero # 出错并不可怕,可怕的是不知道哪里出错了。 # 解读错误信息是定位错误的关键。 # 我们从上往下可以看到整个错误的调用函数链: # 错误信息第1行: # Traceback (most recent call last): # 告诉我们这是错误的跟踪信息。 # 第2~3行: # File "err.py", line 11, in <module> # main() # 调用main()出错了,在代码文件err.py的第11行代码, # 但原因是第9行: # File "err.py", line 9, in main # bar('0') # 调用bar('0')出错了,在代码文件err.py的第9行代码, # 但原因是第6行: # File "err.py", line 6, in bar # return foo(s) * 2 # 原因是return foo(s) * 2这个语句出错了, # 但这还不是最终原因,继续往下看: # File "err.py", line 3, in foo # return 10 / int(s) # 原因是return 10 / int(s)这个语句出错了, # 这是错误产生的源头,因为下面打印了: # ZeroDivisionError: integer division or modulo by zero # 根据错误类型ZeroDivisionError,我们判断,int(s)本身并没有出错, # 但是int(s)返回0,在计算10 / 0时出错,至此,找到错误源头。 # 出错的时候,一定要分析错误的调用栈信息,才能定位错误的位置。 # 记录错误 # 如果不捕获错误,自然可以让Python解释器来打印出错误堆栈,但程序也被结束了。 # 既然我们能捕获错误,就可以把错误堆栈打印出来,然后分析错误原因, # 同时,让程序继续执行下去。 # Python内置的logging模块可以非常容易地记录错误信息: # err_logging.py # import logging # def foo(s): # return 10/int(s) # # def bar(s): # return foo(s)*2 # # def main(): # try: # bar('0') # except Exception as e: # logging.exception(e) # # main() # print('END') # 同样是出错,但程序打印完错误信息后会继续执行,并正常退出: # $ python3 err_logging.py # ERROR:root:division by zero # Traceback (most recent call last): # File "err_logging.py", line 13, in main # bar('0') # File "err_logging.py", line 9, in bar # return foo(s) * 2 # File "err_logging.py", line 6, in foo # return 10 / int(s) # ZeroDivisionError: division by zero # END # 通过配置,logging还可以把错误记录到日志文件里,方便事后排查。 # 抛出错误 # 因为错误是class,捕获一个错误就是捕获到该class的一个实例。 # 因此,错误并不是凭空产生的,而是有意创建并抛出的。 # Python的内置函数会抛出很多类型的错误, # 我们自己编写的函数也可以抛出错误。 # 如果要抛出错误,首先根据需要,可以定义一个错误的class,选择好继承关系, # 然后,用raise语句抛出一个错误的实例: # err_raise.py # class FooError(ValueError): # pass # def foo(s): # n=int(s) # if n==0: # raise FooError('invalid value: %s' % s) # return 10/n # foo('0') # 执行,可以最后跟踪到我们自己定义的错误: # $ python3 err_raise.py # Traceback (most recent call last): # File "err_throw.py", line 11, in <module> # foo('0') # File "err_throw.py", line 8, in foo # raise FooError('invalid value: %s' % s) # __main__.FooError: invalid value: 0 # 只有在必要的时候才定义我们自己的错误类型。 # 如果可以选择Python已有的内置的错误类型(比如ValueError,TypeError), # 尽量使用Python内置的错误类型。 # 最后,我们来看另一种错误处理的方式: # err_reraise.py # def foo(s): # n = int(s) # if n==0: # raise ValueError('invalid value: %s' % s) # return 10 / n # # def bar(): # try: # foo('0') # except ValueError as e: # print('ValueError!') # raise # # bar() # 在bar()函数中,我们明明已经捕获了错误, # 但是,打印一个ValueError!后, # 又把错误通过raise语句抛出去了,这不有病么? # 其实这种错误处理方式不但没病,而且相当常见。 # 捕获错误目的只是记录一下,便于后续追踪。 # 但是,由于当前函数不知道应该怎么处理该错误, # 所以,最恰当的方式是继续往上抛,让顶层调用者去处理。 # 好比一个员工处理不了一个问题时,就把问题抛给他的老板, # 如果他的老板也处理不了,就一直往上抛,最终会抛给CEO去处理。 # raise语句如果不带参数,就会把当前错误原样抛出。 # 此外,在except中raise一个Error, # 还可以把一种类型的错误转化成另一种类型: # try: # 10 / 0 # except ZeroDivisionError: # raise ValueError('input error!') # 只要是合理的转换逻辑就可以, # 但是,决不应该把一个IOError转换成毫不相干的ValueError。 # 小结 # Python内置的try...except...finally用来处理错误十分方便。 # 出错时,会分析错误信息并定位错误发生的代码位置才是最关键的。 # 程序也可以主动抛出错误,让调用者来处理相应的错误。 # 但是,应该在文档中写清楚可能会抛出哪些错误,以及错误产生的原因。 # 练习 # 运行下面的代码,根据异常信息进行分析,定位出错误源头,并修复: # from functools import reduce # # def str2num(s): # return int(s) # # def calc(exp): # ss = exp.split('+') # ns = map(str2num, ss) # return reduce(lambda acc, x: acc + x, ns) # # def main(): # r = calc('100 + 200 + 345') # print('100 + 200 + 345 =', r) # r = calc('99 + 88 + 7.6') # print('99 + 88 + 7.6 =', r) # # main() from functools import reduce def str2num(s): try: return int(s) except ValueError as e: return float(s) except ValueError as e2: print('except:',e2) def calc(exp): ss = exp.split('+') ns = map(str2num, ss) return reduce(lambda acc, x: acc + x, ns) def main(): r = calc('100 + 200 + 345') print('100 + 200 + 345 =', r) r = calc('99 + 88 + 7.6') print('99 + 88 + 7.6 =', r) main()
def power(x): return x*x power(5) # 25 power(15) # 225 def power(x,n): s=1 while n>0: n=n-1 s=s*x return s power(5,2) # 25 power(5,3) # 125 # 设置n的默认值为2 def power(x,n=2): s=1 while n>0: n=n-1 s=s*x return s # 此时,调用power(5)相当于调用power(5,2) power(5) # 25 power(5,2) # 25 def enroll(name,gender,age=6,city='Beijing'): print('name',name) print('gender',gender) print('age',age) print('city',city) enroll('Bob','M',7) enroll('Adam','M',city='Tianjin') # 关于函数定义的时候,默认参数有个特别需要注意的地方 # 定义默认参数要牢记一点:默认参数必须指向不变对象! def add_end(L=None): if L is None: L=[] L.append('END') return L # 为什么要设计str、None这样的不变对象呢? # 因为不变对象一旦创建,对象内部的数据就不能修改, # 这样就减少了由于修改数据导致的错误。 # 此外,由于对象不变,多任务环境下同时读取对象不需要加锁, # 同时读一点问题都没有。 # 我们在编写程序时,如果可以设计一个不变对象, # 那就尽量设计成不变对象。 # 可变参数 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 # 利用可变参数之后 def calc(*numbers): sum=0 for n in numbers: sum=sum+n*n return sum calc(1,2,3) # 14 calc(1,3,5,7) # 84 # 定义可变参数和定义一个list或tuple参数相比, # 仅仅在参数前面加了一个*号。 # 在函数内部,参数numbers接收到的是一个tuple, # 因此,函数代码完全不变。 # 但是,调用该函数时,可以传入任意个参数,包括0个参数 calc(1,2) # 5 calc() # 0 # 已有一个list或tuple,要调用一个可变参数 # 可以在list或tuple前加一个*号, # 把list或tuple的元素变成可变参数传进去 nums=[1,2,3] calc(nums[0], nums[1], nums[2]) # 简化写法 calc(*nums) # 14 # *nums表示把nums这个list的所有元素作为可变参数传进去。 # 关键字参数 # 可变参数允许你传入0个或任意个参数, # 这些可变参数在函数调用时自动组装为一个tuple。 # 而关键字参数允许你传入0个或任意个含参数名的参数, # 这些关键字参数在函数内部自动组装为一个dict。 # 请看示例: def person(name,age,**kw): print('name:',name,'age:',age,'other:',kw) person('Michael',30) # name:Michael age:30 other:{} 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函数里,我们保证能接收到name和age这两个参数, # 但是,如果调用者愿意提供更多的参数,我们也能收到。 # 试想你正在做一个用户注册的功能, # 除了用户名和年龄是必填项外,其他都是可选项, # 利用关键字参数来定义这个函数就能满足注册的需求。 # 和可变参数类似,也可以先组装出一个dict, # 然后,把该dict转换为关键字参数传进去: extra = {'city': 'Beijing', 'job': 'Engineer'} person('Jack', 24, city=extra['city'], job=extra['job']) #简化写法 person('Jack', 24, **extra) # name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'} # **extra表示把extra这个dict的所有key-value # 用关键字参数传入到函数的**kw参数, # kw将获得一个dict,注意kw获得的dict是extra的一份拷贝, # 对kw的改动不会影响到函数外的extra。 # 命名关键字参数 # 对于关键字参数, # 函数的调用者可以传入任意不受限制的关键字参数。 # 至于到底传入了哪些,就需要在函数内部通过kw检查。 # 仍以person()函数为例,我们希望检查是否有city和job参数: def person(name,age,**kw): if 'city' in kw: # 有city参数 pass if 'job' in kw: # 有job参数 pass print('name:',name,'age:',age,'other:',kw) # 但是调用者仍可以传入不受限制的关键字参数: person('Jack',24,city='Beijing',addr='Chaoyang',zipcode=123456) # 如果要限制关键字参数的名字,就可以用命名关键字参数, # 例如,只接收city和job作为关键字参数。 # 这种方式定义的函数如下: def person(name,age,*,city,job): print(name,age,city,job) # 和关键字参数**kw不同, # 命名关键字参数需要一个特殊分隔符*, # *后面的参数被视为命名关键字参数。 # 调用方式如下: person('Jack',24,city='Beijing',job='Engineer') # Jack 24 Beijing Engineer # 如果函数定义中已经有了一个可变参数, # 后面跟着的命名关键字参数就不再需要一个特殊分隔符*了: def person(name,age,*args,city,job): print(name,age,args,city,job) # 命名关键字参数必须传入参数名,这和位置参数不同。 # 如果没有传入参数名,调用将报错: # person('Jack', 24, 'Beijing', 'Engineer') # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # TypeError: person() takes 2 positional arguments but 4 were given # 由于调用时缺少参数名city和job, # Python解释器把这4个参数均视为位置参数, # 但person()函数仅接受2个位置参数 # 命名关键字参数可以有缺省值,从而简化调用: def person(name,age,*,city='Beijing',job): print(name,age,city,job) # 由于命名关键字参数city具有默认值,调用时,可不传入city参数: person('Jack',24,job='Engineer') # Jack 24 Beijing Enginneer # 使用命名关键字参数时,要特别注意, # 如果没有可变参数,就必须加一个*作为特殊分隔符。 # 如果缺少*, # Python解释器将无法识别位置参数和命名关键字参数: def person(name,age,city,job): # 缺少*,city和job被视为位置参数 pass # 参数组合 # 在Python中定义函数, # 可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数, # 这5种参数都可以组合使用。 # 但是请注意,参数定义的顺序必须是: # 必选参数、默认参数、可变参数、命名关键字参数和关键字参数。 # 比如定义一个函数,包含上述若干种参数: 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) # 在函数调用的时候, # Python解释器自动按照参数位置和参数名把对应的参数传进去。 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} # 最神奇的是通过一个tuple和dict,你也可以调用上述函数: args = (1, 2, 3, 4) kw = {'d': 99, 'x': '#'} f1(*args, **kw) # 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': '#'} # 所以,对于任意函数, # 都可以通过类似func(*args, **kw)的形式调用它, # 无论它的参数是如何定义的。 # 虽然可以组合多达5种参数,但不要同时使用太多的组合, # 否则函数接口的可理解性很差。 # 小结 # Python的函数具有非常灵活的参数形态, # 既可以实现简单的调用,又可以传入非常复杂的参数。 # 默认参数一定要用不可变对象, # 如果是可变对象,程序运行时会有逻辑错误! # 要注意定义可变参数和关键字参数的语法: # *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的习惯写法, # 当然也可以用其他参数名,但最好使用习惯用法。 # 命名的关键字参数是为了限制调用者可以传入的参数名, # 同时可以提供默认值。 # 定义命名的关键字参数在没有可变参数的情况下不要忘了写分隔符*, # 否则定义的将是位置参数。 # 练习 # 以下函数允许计算两个数的乘积, # 请稍加改造,变成可接收一个或多个数并计算乘积: # def product(x, y): # return x * 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('测试成功!') def product(*x): if len(x)==0: raise TypeError('请输入数字!') for i in x: if not isinstance(i,(int,float)): raise TypeError(i,'错误的数据类型') sum=1 for i in x: sum=sum*i return sum # 测试 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('测试成功!')
#!/usr/bin/env python # -*- coding: utf-8 -*- # 在Class内部,可以有属性和方法, # 而外部代码可以通过直接调用实例变量的方法来操作数据, # 这样,就隐藏了内部的复杂逻辑。 # 但是,从前面Student类的定义来看, # 外部代码还是可以自由地修改一个实例的name、score属性: # bart=Student('Bart Simpson',59) # bart.score # 59 # bart.score=99 # bart.score # 99 # 如果要让内部属性不被外部访问, # 可以把属性的名称前加上两个下划线__, # 在Python中,实例的变量名如果以__开头, # 就变成了一个私有变量(private), # 只有内部可以访问,外部不能访问, # 所以,我们把Student类改一改: class Student(object): def __init__(self,name,score): self.__name=name self.__score=score def print_score(self): print('%s:%s' % (self.__name,self.__score)) # 改完后,对于外部代码来说,没什么变动, # 但是已经无法从外部访问实例变量.__name和实例变量.__score了: bart=Student('Bart Simpson',59) # bart.__name # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # AttributeError: 'Student' object has no attribute '__name' # 这样就确保了外部代码不能随意修改对象内部的状态, # 这样通过访问限制的保护,代码更加健壮。 # 但是如果外部代码要获取name和score怎么办? # 可以给Student类增加get_name和get_score这样的方法: # class Student(object): # ``` # # def get_name(self): # return self.__name # # def get_score(self): # return self.__score # 如果又要允许外部代码修改score怎么办? # 可以再给Student类增加set_score方法: # class Student(object): # ``` # # def set_score(self,score): # self.__score=score # 你也许会问,原先那种直接通过bart.score = 99也可以修改啊, # 为什么要定义一个方法大费周折? # 因为在方法中,可以对参数做检查,避免传入无效的参数: # class Student(object): # ``` # # def set_score(self,score): # if 0<=score<=100: # self.__score=score # else: # raise ValueError('bad score') # 需要注意的是,在Python中,变量名类似__xxx__的, # 也就是以双下划线开头,并且以双下划线结尾的,是特殊变量, # 特殊变量是可以直接访问的,不是private变量, # 所以,不能用__name__、__score__这样的变量名。 # 有些时候,你会看到以一个下划线开头的实例变量名, # 比如_name,这样的实例变量外部是可以访问的, # 但是,按照约定俗成的规定,当你看到这样的变量时,意思就是, # “虽然我可以被访问,但是,请把我视为私有变量,不要随意访问”。 # 双下划线开头的实例变量是不是一定不能从外部访问呢? # 其实也不是。 # 不能直接访问__name是因为Python解释器对外把__name变量改成了_Student__name, # 所以,仍然可以通过_Student__name来访问__name变量: bart._Student__name # Bart Simpson # 但是强烈建议你不要这么干, # 因为不同版本的Python解释器可能会把__name改成不同的变量名。 # 总的来说就是,Python本身没有任何机制阻止你干坏事,一切全靠自觉。 # 最后注意下面的这种错误写法: # bart=Student('Bart Simpson',59) # bart.get_name() # # Bart Simpson # bart.__name='New Name' # 设置__name变量 # bart.__name # # New Name # 表面上看,外部代码“成功”地设置了__name变量, # 但实际上这个__name变量和class内部的__name变量不是一个变量! # 内部的__name变量已经被Python解释器自动改成了_Student__name, # 而外部代码给bart新增了一个__name变量。不信试试: # bart.get_name() # get_name()内部返回self.__name # Bart Simpson # 练习 # 请把下面的Student对象的gender字段对外隐藏起来, # 用get_gender()和set_gender()代替,并检查参数有效性: # class Student(object): # def __init__(self, name, gender): # self.name = name # self.gender = gender # # 测试: # bart = Student('Bart', 'male') # if bart.get_gender() != 'male': # print('测试失败!') # else: # bart.set_gender('female') # if bart.get_gender() != 'female': # print('测试失败!') # else: # print('测试成功!') class Student(object): def __init__(self, name, gender): self.name = name self.__gender = gender def get_gender(self): return self.__gender def set_gender(self,gender): if gender=='male' or gender=='female': self.__gender=gender # 测试: bart = Student('Bart', 'male') if bart.get_gender() != 'male': print('测试失败!') else: bart.set_gender('female') if bart.get_gender() != 'female': print('测试失败!') else: print('测试成功!')
def binary_space(array, code, position, low, high): mid = (high + low) // 2 if position < len(code) - 1: if code[position] == "F" or code[position] == "L": return binary_space(array, code, (position + 1), low, (mid)) elif code[position] == "B" or code[position] == "R": return binary_space(array, code, (position + 1), (mid + 1), high) else: return ( array[mid + 1] if code[position] == "B" or code[position] == "R" else array[mid] ) puzzle = open("input.txt").read().strip().split("\n") rows = list(range(0, 128)) columns = list(range(0, 8)) all_ids = list(range(99, 975)) found_ids = set() for code in puzzle: row = code[:7] col = code[7:] row_a = binary_space(rows, row, 0, 0, len(rows) - 1) col_a = binary_space(columns, col, 0, 0, len(columns) - 1) found_ids.add((row_a * 8) + col_a) print(set(all_ids) - found_ids)
#ensures that all words are words from the alphabet def validatedInput(word): while(True): for c in word: #if s is not part of the alphabet, capitalized or not, if not((ord(c) >= 65 and ord(c) <= 90) or (ord(c) >= 97 and ord(c) <= 122)): word = raw_input("Try Again. Enter a new word: ") break return word def LetterHistogram(word): LetterHistogram = {} for c in word: # when there are no values in key s to get, make the first value 0. # then right after add by 1. now the key at letterhistogram has incremented by one value # loop through the entire word, treating each character as a key and record occurances as # the value LetterHistogram[c] = LetterHistogram.get(c,0)+1 return LetterHistogram #long variables because this for loop is cryptic and I need all the help i can get def printHistogram(dictionary): # for each character, bring up the values of the occurances at each character # key within the dictionary in question for character, occurances in dictionary.items(): print "%d occurances of %s" % (occurances,character) def getLetterHistogram(): dictionary = {} word = validatedInput(raw_input("Enter a word: ")) dictionary = LetterHistogram(word) printHistogram(LetterHistogram(word))
name = raw_input("WHAT IS YOUR NAME? ") name = name.upper() name_length = len(name) sentence = "HELLO, %s\nYOUR NAME HAS %d CHARACTERS IN IT" % (name,name_length) print sentence
def outer(): def inner(): # chi co effect tren var in function nonlocal x x = "nonlocal" print("inner:", x) # update x='nonlocal' print("inner: id: ", id(x)) # update x='nonlocal' x = 'nonlocal' print("id: ", id(x)) inner() print("outer:", x) # update x='nonlocal' print(f"{'nonlocal':-^80}") outer() print(f"{'nonlocal':-^80}") def foo(): x = 20 def bar(): global x # outside function update x=25 x = 100 print("id: ", id(x)) print("Before calling bar: ", x) # x=20 local print("Calling bar now") bar() print("After calling bar: ", x) # x=20 local print("id: ", id(x)) # x = 20 print(f"{'global':-^80}") foo() print("x in main: ", x) # outside function x=25 print(f"{'global':-^80}")
import sys def avgCalcUI(): """ Simple mean/avg calculator implementation -- takes in User-Input via command prompt then computes and displays average """ ### Local Vars array = [] numerator = 0 denominator = 0 avg = 0 try: print("\n----- Welcome! ------") user_input = input("Please input a number: ") except ValueError: print("Error: Input must be of type 'int'") else: while user_input != "end": array.append(user_input) user_input = input("Please input a number -- input 'end' to stop: ") for i in range(len(array)): numerator += int(array[i]) denominator = len(array) # for i in range(len(array)): # print(array[i]) # print(type(array[i])) # if type(array[i]) not in [int]: # array.pop() avg = numerator/denominator return "\nComputing average of your inputs...\n\n\nYour average is: " + str(avg) def maxValInArray(l): """ Return max value in list """ temp = l[0] for i in range(len(l)-1): if l[i] > temp: temp = l[i] maxVal = temp return maxVal def findElementInArray(l,n): """ Find element in array first implementation is python-specific, second (in comments) is general """ if n in l: return True return False # boolVar = False # for i in range(len(l)-1): # if n == l[i]: # boolVar = True # return boolVar def binarySearchForElement(l,n): """ Binary Search for an element in sorted array, return position of element """ low = 0 high = len(l)-1 while low <= high: mid = int((low+high)/2) if n < l[mid]: high = mid-1 elif n > l[mid]: low = mid+1 else: return mid return "Element not in array" def inputIntoHashMap(n): """ Input elements in array arg as key elements in a dict (hashmap) """ d = {} position = 0 #d[n] = "hello world" for i in n: d[i] = position position += 1 return d def checkStringHasOnlyUniqueChars(word): """ Basically, make sure there are no diplicates; Return true if there are duplicate(s); else false """ return len(word) != len(set(word)) #set removes duplicates; ###iterative version # seen = set() # for x in word: # if x in seen: return True # seen.add(x) # return False def duplicatesInString(word): """ Return duplicates in a string argument as a list """ s = set() duplicates = [x for x in word if x in s or s.add(x)] return duplicates def reverseString(word): """ Reverse a string, return result as a string """ result = "" j = -1 for i in range(len(word)): result += (word[j-i]) return result def removeDuplicates(word): """ Remove duplicates in string arg, return answer as string """ ans = "" for i in word: if i not in duplicatesInString(word): ans += i return ans def verifyAnagram(word1, word2): """ Anagram is how 'iceman' and 'cinema' use same letters but in different combination This function verifies if two word arguments are an anagram of eachother """ for i in word1: for j in word2: if i in set(word2) and j in set(word1) and (len(set(word1)) == len(set(word2))): return True return False def placeCharInSpaces(words): """ Place '%20' in empty spaces of string arg; return modified string """ ans = "" for i in words: if i == " ": i = "%20" ans += i return ans def allPermsOfString(string, step = 0): # if we've gotten to the end, print the permutation if step == len(string): print("".join(string)) # everything to the right of step has not been swapped yet for i in range(step, len(string)): # copy the string (store as array) string_copy = [character for character in string] # swap the current index with the step string_copy[step], string_copy[i] = string_copy[i], string_copy[step] # recurse on the portion of the string that has not been swapped yet (now it's index will begin with step + 1) allPermsOfString(string_copy, step + 1) def sortArrayRecur(arg): if len(arg) == 0: return arg pivot = arg[0] smaller = ([i for i in arg[1:] if i<pivot]) larger = ([i for i in arg[1:] if i>=pivot]) return sortArrayRecur(smaller) + [pivot] + sortArrayRecur(larger) if __name__ == '__main__': #print(avgCalcUI()) #lst = [1,2,3,7,4,5,6] #print(maxValInArray(lst)) #lst = [1,2,3,7,4,5,6] #print(findElementInArray(lst,4)) #lst = [1,2,3,4,5,6,7] #print(binarySearchForElement(lst,3)) #lst = [1,2,3,4,5,6,7] #print(inputIntoHashMap(lst)) #arg = "helol" #print(checkStringHasOnlyUniqueChars(arg)) #arg = "test" #print(duplicatesInString(arg)) #arg = "test" #print(reverseString(arg)) #arg = "test" #print(removeDuplicates(arg)) #arg1 = "testx" #arg2 = "etstt" #print(verifyAnagram(arg1, arg2)) #arg = "collection of words" #print(placeCharInSpaces(arg)) #arg = "abcde" #print(allPermsOfString(arg)) #arg = [1,3,2,5,6] #print(sortArrayRecur(arg))
''' Created on 2015年10月14日 @author: admin == 等于 - 比较对象是否相等 (a == b) 返回 False。 != 不等于 - 比较两个对象是否不相等 (a != b) 返回 true. <> 不等于 - 比较两个对象是否不相等 (a <> b) 返回 true。这个运算符类似 != 。 > 大于 - 返回x是否大于y (a > b) 返回 False。 < 小于 - 返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。注意,这些变量名的大写。 (a < b) 返回 true。 >= 大于等于 - 返回x是否大于等于y。 (a >= b) 返回 False。 <= 小于等于 - 返回x是否小于等于y。 (a <= b) 返回 true。 ''' a = 10; b = 20; print(a == b); print(a > b); print(a < b); print(a != b); print(a >= b); print(a <= b);
''' Created on 2015年10月13日 @author: admin 字典(dictionary)是除列表以外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。 两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。 字典用"{ }"标识。字典由索引(key)和它对应的值value组成 ''' myDict = {}; myDict['name'] = "张三"; myDict['age'] = 26; myDict['school'] = '清华大学'; print(myDict); otherDict = {'name' : '李四', 'age' : 23, 'school' : '浙江大学'}; print(otherDict); print(myDict.get("name")); print(myDict['age']); print(myDict.keys()); print(myDict.values());
#!/usr/bin/env python ''' 計算誤差の例題プログラム 桁落ち誤差の例題 ''' import math def calc(x): print("x=", x) res1 = math.sqrt(x+1) - math.sqrt(x) res2 = 1 / (math.sqrt(x+1) + math.sqrt(x)) print("通常の計算:\t", res1) print("有理化後の計算:\t", res2) def main(): calc(1e15) calc(1e16) if __name__ == '__main__': main()