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 :retu...
# 输入一棵二叉树,求该树的深度。 # 从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径, # 最长路径的长度为树的深度。 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 :retu...
# 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): """ 判断字符串是否是回文(只考虑字母和数字) :para...
# 把只包含因子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时 ...
# 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。 # 例如输入一个长度为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 number...
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.appe...
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 = ...
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 ...
# -*- 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() de...
""" 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ę przel...
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: T...
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(mer...
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) d...
""" 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表格中每位导购的客单价. 思路是正则匹配(...
""" 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) #pr...
""" 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("readli...
""" 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...
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],low...
#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...
""" 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.rst...
# -*- 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('Plea...
""" 质数又称素数。一个大于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 # pr...
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...
# -*- 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,...
# -*- 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.') ...
# -*- 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] *...
# -*- coding:utf-8 -*- class Solution: def LastRemaining_Solution(self, n, m): """ 首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。 每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中, 从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友, 可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。 请你试着想下,...
# -*- coding:utf-8 -*- class Solution: def replaceSpace(self, s): """ 请实现一个函数,将一个字符串中的每个空格替换成“%20”。 例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。 对于 Python 来说,自带的特性已经处理了这个问题,如果面试官同意的话,就使用它。 如果面试官不同意,那我们继续思考。 算法及证明 遍历字符串, 如果不是空格,那么将该字符串...
# -*- 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 的字符串 ...
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]...
#!/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 g...
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 ...
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]: # 如...
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,...
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): ...
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...
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 t...
""" 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 ...
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(): ...
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] ...
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_l...
""" 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): ...
'''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 wil...
# 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 # ...
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.o...
#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 equ...
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...
'''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...
#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...
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...
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 ...
''' 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' == ...
''' 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 =...
''' 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 * 1...
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('-----...
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("Za...
# Katie Williams katieswill@gmail.com 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...
#!/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(w...
#!/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]) numPos...
#!/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: ...
#!/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", ...
#-*- 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 #sette...
#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(...
"""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, ...
"""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 ...
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....
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 ...
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...
# 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.str...
#!/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会调用操作系统提供...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 在程序运行的过程中,如果发生了错误,可以事先约定返回一个错误代码, # 这样,就可以知道是否有错,以及出错的原因。 # 在操作系统提供的调用中,返回错误码非常常见。 # 比如打开文件的函数open(), # 成功时返回文件描述符(就是一个整数),出错时返回-1。 # 用错误码来表示是否出错十分不便, # 因为函数本身应该返回的正常结果和错误码混在一起, # 造成调用者必须用大量的代码来判断是否出错: # def foo(): # r=some_function() # if r==(-1): # re...
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 p...
#!/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中,实例的变量名如果以...
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": r...
#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. ...
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='non...
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 numb...
''' 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等价。注...
''' Created on 2015年10月13日 @author: admin 字典(dictionary)是除列表以外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。 两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。 字典用"{ }"标识。字典由索引(key)和它对应的值value组成 ''' myDict = {}; myDict['name'] = "张三"; myDict['age'] = 26; myDict['school'] = '清华大学'; print(myDict); otherDict = {'name' ...
#!/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()