text
stringlengths
37
1.41M
# https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/582/week-4-january-22nd-january-28th/3619/ # Smallest String With A Given Numeric Value # The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, # so the numeric value of a is 1, the numeric v...
# https://leetcode.com/problems/minimum-index-sum-of-two-lists/description/ # 599. Minimum Index Sum of Two Lists # Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings. # You need to help them find out their common interest with the...
# leetcode 300 -- Longest Increasing Subsequence # https://leetcode.com/problems/longest-increasing-subsequence/description/ # Given an unsorted array of integers, find the length of longest increasing subsequence. # For example, # Given [10, 9, 2, 5, 3, 7, 101, 18], # The longest increasing subsequence is [2, 3, 7, 1...
# https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/545/week-2-july-8th-july-14th/3384/ # 3Sum # Given an array nums of n integers, are there elements a, b, c in nums such that # a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. # Note: # The solution set must not...
# https://leetcode.com/problems/sum-of-subarray-minimums/description/ # 907. Sum of Subarray Minimums # Given an array of integers A, find the sum of min(B), where B ranges over every (contiguous) subarray of A. # Since the answer may be large, return the answer modulo 10^9 + 7. # Example 1: # Input: [3,1,2,4] # O...
# https://leetcode.com/explore/challenge/card/april-leetcoding-challenge-2021/595/week-3-april-15th-april-21st/3710/ # Remove All Adjacent Duplicates in String II # Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from # s and removing them causing the left and the right si...
# https://leetcode.com/problems/license-key-formatting/description/ # 482. License Key Formatting # You are given a license key represented as a string S which consists only alphanumeric # character and dashes. The string is separated into N+1 groups by N dashes. # Given a number K, we would want to reformat the st...
''' Collatz conjecture - A conjecture with 2 rules proposed: 1. If the number is even, divide it by 2. 2. If the number is odd, multiply it by 3 and add 1. The conjecture states for any positive integer, the final result following these steps will always be 1. I learnt how to use matplotlib and numpy to generate...
import pygame #prints instruction instruction = """ n - to clear page or while holding left mouse to fill entire screen with the held color b - blue g - green r - red z - black x - white s - switch shape rectangle / circle scroll up - increase size scroll down - decrease size ...
#!/usr/bin/env python3 import cs50 def main(): # get the height of the pyramid from the user while True: print("Height: ", end="") height = cs50.get_int() if height >= 0 or height <= 23: break # create the pyramid using loops for i in range(height): ...
class MyHashMap: def __init__(self): """ Initialize your data structure here. """ self.buckets = 1000 # 键值块,哈希桶 self.itemsPerBuckect = 1001 # 产生冲突的“拉链”块 self.hashmap = [[] for _ in range(self.buckets)] # _表示临时变量,仅用一次,后面无需用到 ...
class Solution: # 类似于两分查找的思想,从两端进行查找,逐渐更新最大值 def maxArea(self, height): """ :type height: List[int] :rtype: int """ l, r = 0, len(height) - 1 max_area = 0 while l < r: temp = min(height[l], height[r]) * (r - l) max_area = max(max_a...
import random from turtle import Turtle, Screen s = Screen() s.bgcolor("black") s.title("Turtle Race") is_on = False s.setup(width=1000, height=700) user_bet = s.textinput(title="your bet", prompt="on which turtle you will make your guess ? ") is_on = True colors = ["green", "blue", "orange", "red", "pink", "yellow"] ...
SENHA = input("digite a sua senha:") if SENHA == 'batatafrita': print("Acesso permitido!!") else: print("Você não tem acesso ao sistema")
'''37) Escreva um algoritmo em PORTUGOL que determine todos os divisores de um dado número N''' divisores = [] contador = 0 divisor = 0 numero = int(input("Informe um número:")) for divisao in range (numero): resto_divisao = numero %2 divisor = numero if resto_divisao == 0: divisores.append(divisor...
NUM = int(input("Digite um número:")) RESTO_DIV = NUM % 2 if RESTO_DIV == 0: print("O numero é par") else: print("O número é ímpar")
import math a = int(input("Digite um valor para A: ")) b = int(input("Digite um valor para B: ")) c = int(input("Digite um valor para C: ")) delta = (b * b) - 4 * a * c if delta < 0: print("A equação não possui raizes reais") else: if delta == 0: raiz = (-1 * b + math.sqrt(delta)) / (2 * a) p...
#15 - Escreva um algoritmo em PORTUGOL que receba oito números do usuário e imprima o logaritmo de cada um deles na base 10 import math contador = 0 while contador < 8: num = int(input("Informe um número:")) print(f'O logaritimo do número informado equivale a: {math.log(num, 10)}') contador +=1
#12 - Escreva um algoritmo em PORTUGOL que receba dez números do usuário e imprima o quadrado de cada número. contador = 0 while contador < 10: num = int(input("Informe um número:")) print(f'O quadrado do número informado equivale a: {num**2}') contador +=1
#30 - Escreva um algoritmo em PORTUGOL que leia 20 números e imprima a soma dos positivos e o total de números negativos. numeros = [] soma = 0 for contador in range(5): numero = int(input("Digite um número por favor: ")) numeros.append(numero) for numero in numeros: if numero >= 0: soma += numero...
PRODUTO = float(input("Digite o valor do produto:")) if PRODUTO < 20: LUCRO_45 = PRODUTO + PRODUTO * 0.45 print("O valor de revenda é: RS", LUCRO_45) else: LUCRO_30 = PRODUTO + PRODUTO *0.30 print("O valor de revenda é: RS", LUCRO_30)
SALARIO = float(input("Informe o salário:")) REAJUSTE_30 = SALARIO + (SALARIO * 0.3) REAJUSTE_25 = SALARIO + (SALARIO * 0.25) REAJUSTE_20 = SALARIO + (SALARIO * 0.20) REAJUSTE_15 = SALARIO + (SALARIO * 0.15) REAJUSTE_10 = SALARIO + (SALARIO * 0.10) if SALARIO <= 600: REAJUSTE_30 print("O Salário reajustado é: R...
Q = [] contador = 0 ocorrencias = 20 while contador < ocorrencias: numero = int(input("Digite um número por favor:")) while numero <= 0: numero = int(input("Digite um número por favor:")) else: if numero > 0: Q.append(numero) contador +=1 n_pos = Q.index(max(Q)) print(f...
#25 - Criar um algoritmo em PORTUGOL que leia dez números inteiros e imprima o maior e o segundo maior número da lista. maior = None for contador in range(10): numero = int(input("Digite um numero por favor: ")) if (contador==0): maior = numero else: if numero > maior: segundo_ma...
class Memoize: def __init__(self, fn): self.fn = fn self.memo = {} def __call__(self, *args): if args not in self.memo: self.memo[args] = self.fn(*args) return self.memo[args] @Memoize def lcs(strA, strB): if len(strA) == 0 or len(strB) == 0: return 0 ...
""" ConcatWordsApp: Author: Patrick Dizon 3/6/2016 This script provides the following results: - Longest words, - Second longest words - The number of longest words """ import timeit import itertools from collections import deque class Word(object): ''' Word object stores a word ...
from tkinter import * from backend import Database database = Database("books.db") class Window(object): def __init__(self, window): self.window = window self.window.wm_title("BookStore") label1 = Label(window, text = "Title") label1.grid(row = 0, column = 0) label2 = ...
""" Python Web Development Techdegree Project 1 - Number Guessing Game -------------------------------- """ import random BREAK_WORDS = ["q", "quit", "break", "exit"] MIN_NUMBER = 1 MAX_NUMBER = 20 high_score = 0 num_of_guesses = 0 def pluralize_try(num): if num == 1: return "try" return "tries" ...
test = '(define square\n(lambda (x) (* x x)))' def int_convert(string): if string.isdigit(): return int(string) return string def tokenize(code): """ Split code into lexemes (either strings or parentheses) Lexemes are separated by spaces or newlines (or parentheses) """ lexemes =...
#!/usr/bin/python3 """ Unlocked the boxes """ def canUnlockAll(boxes): """ Look if the box is unlocked or not Return true if is unlocked or false """ # Look to the unlocked boxes unlocked_box = [0] for i in unlocked_box: for j in boxes[i]: if j < len(boxes): ...
#! /usr/bin/env python3.3 """ This program runs a basic blackjack game. Currently it is just you versus the dealer. """ import cards #Set custom values for face cards and ace def set_custom_value(deck): d = list(deck) for card in d: if card.value in ['jack', 'queen', 'king']: card.custom_v...
################################# # # Lotto number generator for # the norwegian lottery system # # Created by: Jan Brekke # Website: https://www.digitalbrekke.com # ################################# import time import random from os import system, name def clear(): # Windows terminal if name == 'nt': ...
from dataclasses import dataclass, field from typing import List, Optional, Union @dataclass class Option: """Defines an option attached to a module. Options are typically booleans, although can sometimes be integers or enums. Options that have a `number` defined can be changed during playback as if the...
import numpy as np class dice: def __init__(self): self.eyes = 1 def __lt__(self, other): return True if self.eyes < other.eyes else False def __str___(self): return str(self.eyes) + " " def roll_dice(self): self.eyes = np.random.randint(1, 6) class ScoreCard: ...
# imc = peso / altura ^2 print("Vamos calcular seu IMC") peso = input("Primeiro, digite seu peso: ") altura = input("Agora digite sua altura em centimetros: ") imc = round((int(peso) / int(altura) ** 2) *10000, 2) print("Seu IMC é: ", imc) if imc >= 18.5 and imc <= 24.9: print("Seu peso está normal, parabéns.")...
# 나의 답1 bugger = [] for i in range (3): bugger.append(int(input())) coke=int(input()) for coke_price in range(3): bugger[coke_price] = bugger[coke_price] +coke-50 soda=int(input()) for soda_price in range(3,len(bugger)): bugger[soda_price] = bugger[soda_price] +soda-50 print(min(bugger)) # 나의 답2 bugg...
# 나의 답 - count 함수를 까먹고 있었다. numlist = [] for i in range (3): numlist.append(int(input())) A = numlist[0] B = numlist[1] C = numlist[2] total = str(A*B*C) totalnumlist = [] zero = 0 one = 0 two = 0 three = 0 four= 0 five = 0 six = 0 seven = 0 eight= 0 nine = 0 for num in total: if num...
testcount = int(input()) for i in range (testcount): test = input() sum=0 count=0 for word in test: if word == "O": count+=1 if word=="X": count = 0 sum+=count print(sum)
def fib(n): if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return fib(n-1) + fib(n-2) memo = {} def fib_v2(n): if n in memo: return memo[n] elif n == 0: return 0 elif n == 1 or n == 2: return 1 else: memo[n] = fib_v2(n-1) + ...
class Node(object): def __init__(self, val): self.val = val self.pointer = None class SLL(object): def __init__(self): self.head = None def push_front(self, key): new_node = Node(key) if self.head: new_node.pointer = self.head self.head = ...
from graph_constructor import GraphConstructor from fastest_route_calculator import FastestRouteCalculator START_STATION = 'H' END_STATION = 'L' routes = [] # Procces the input: print "Input:" while True: input_str = raw_input() route = input_str.split(" ") if input_str == "": break else: ...
n = int(input("Digite um número: ")) ant1 = 1 ant2 = 1 for i in range(0, n): if i <= 1: print("1") else: print(ant1+ant2) temp = ant1 ant1 = ant1 + ant2 ant2 = temp
""" The Ball class will contain all information related to ball movement and ball location. The Ball class will contain the attributes: - x (int) - y (int) - color (Vector3) The ball class will contain the methods: - move (self, speed) - check_bounds (self) - calcSlope (self) - bounce (self, player_y) - respawn(self)...
# -*- coding: utf-8 -*- import random def quicksort(array): def partition(arr, left, right): pivot = left while left < right: while left < right and arr[right] >= arr[pivot]: right -= 1 while left < right and arr[left] <= arr[pivot]: left += ...
import math import math as mt # from math import log, pi # from numpy import asarray def main(): a = 5 print(type(a)) alist = [1, 2, 'a'] print(type(alist)) heights = [5, 4, 6, 7, 3, 5] heights.sort() print(heights) alist.reverse() print(alist) astring = 'hello world' ...
import sys cache = {} def WaysToSplit(n, k): """Number of ways to partition n using piles of at most size k""" if n == 1 and k >= 1: return 1 if n == 0 and k >= 0: return 1 if n < k: return WaysToSplit(n, n) if n < 0: print "Something went wrong" sys.exit(1) if k < 0: print "Someth...
import sqlite3 import matplotlib.pyplot as plt import matplotlib.dates as mdates from dateutil import parser from matplotlib import style import seaborn as sns import pandas as pd DB_NAME = "sensehat.db" #reference: # https://pythonprogramming.net/graphing-from-sqlite-database/ #https://sta...
from string import ascii_letters from exceptions import ( NoAsciiDetected, WrongFileName, WrongNumberOfLines, UndefinedFileName, FileNotFound, NoTextToProcess, DecodeError ) import json def check_if_ascii(letter): ''' Function returns True if argument is an alphabet ...
import time def calcProd(): prdct=1 for i in range(1,100000): prdct=prdct * 2 return prdct starttime=time.time() prod = calcProd() endtime = time.time() print("the result is %s digits long." % (len(str(prod)))) print("took %s seconds to calculate." % (endtime - starttime))
# Python3 集合 # 集合(set)是一个无序的不重复元素序列 # 可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典 # 创建格式: # parame = {value01,value02,...} # 或者 # set(value) basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} print(basket) # 这里演示的是去重功能 {'apple', 'orange', 'banana', 'p...
#! /user/bin/python3 # -*- coding:utf-8 -*- # Python3 字符串 # 字符串是 Python 中最常用的数据类型。我们可以使用引号( ' 或 " )来创建字符串 # 创建字符串很简单,只要为变量分配一个值即可。例如: var1 = 'Hello World!' var2 = "Runoob" # Python 访问字符串中的值 # Python 不支持单字符类型,单字符在 Python 中也是作为一个字符串使用 # Python 访问子字符串,可以使用方括号来截取字符串,如下实例: print ("var1[0]: ", var1[0]) # H print ("var2[1:...
import functools as ft def actual_args(fn): """Make function wrapper that saves actual arguments as function attributes. The actual arguments are saved into the wrapper's args and kwargs attributes. >>> @actual_args ... def spam(x, y=None, z=1): ... return dict(args=spam.args, kwargs=spam...
import itertools as it class NoClobberDict(dict): """ A dictionary whose keys may be assigned to at most once. """ def __init__(self, d=(), **kwargs): self.update(d, **kwargs) def __setitem__(self, key, value): """ Assign value to self[key]. If self[key] ex...
from matplotlib import pyplot as plt import math import numpy as np #plt.style.use("seaborn") #print(plt.style.available) #Show available styles #plt.xkcd() #Comic style #Create 3 lists of points x = np.arange(-4*math.pi, 4*math.pi, math.pi/16) sin_y = [math.sin(i) for i in x] cos_y = [math.cos(i) for i in x] #Plot...
import math # Definir as variaveis x = 0 x0 = 0 x1 = 1 tol = 5e-4 k = 0 # Definir uma função def f(x): f = x**3 - 9*x +3 return f xa1 = x0 x = x1 while math.fabs(f(x)) > tol or math.fabs(x1-x0) > tol: if math.fabs(f(x)) < tol: print ("A raiz é : ",x) break else: xa2 = xa1 ...
from SLLNode import Node class DeleteSLL: def __init__(self): self.start = None def DeleteFirstNode(self): self.start = self.start.next def DeleteLastNode(self): temp = self.start while(temp): temp = temp.next if(temp.next.next is None): ...
''' On the flip side, sometimes you'll be working with a derived class (or subclass) and realize that you've overwritten a method or attribute defined in that class' base class (also called a parent or superclass) that you actually need. Have no fear! You can directly access the attributes or methods of a superclass ...
def digit_sum(n): sum = 0 n = str(n) for digit in n: sum += int(digit) return sum
"Importing Random Module" import random #Setting the list of wrods to be guessed into the list 'set' set = ['santosh', 'hari', 'dadi', 'bagal', 'ganguly'] #Choosing the random word to be guessed to start word = random.choice(set) #Converting the string of the variable word into a list called word1 word1 = list(word)...
def pigen(): pi = 4 yield pi coof = -3 while True: pi += 4 / coof coof *= -1 coof += 2 if coof > 0 else -2 yield pi
""" Directions: Given an integer n, print its first 10 multiples. Each multiple n x i (where i <= i <= 10) should be printed on a new line in the form: n x i = result. Input: single integer, n Constraints: 2<= n <= 20 Output: Print 10 lines of output; each line i ((where i <= i <= 10) contains the res...
from functions import negation '''Function that receives a list of sentences in their final form to be printed and lays them out onto the console, to be picked up by the prover''' def output_file(sol): # F = open("cnf.txt",'w') # print("OUTPUT FILE:") # print("CNF form: ") for elem in sol: ...
import math def dist(p, q): ''' RETURN THE EUCLIDAN DISTANCE BETWEEN TWO N-TUPLES PARAM p: A tuple contaning a point, formatted (x-coord, y-coord, z-coord, etc.) PARAM q: A tuple formatted (x-coord, y-coord, z-coord, etc.) PARAM dim: The dimension of both tuples RETURN: If the computation cannot be perfo...
def transposta(matriz): transposta = [] for c in range(len(matriz[0])): linha = [] for l in range(len(matriz)): elemento = matriz[l][c] linha.append(elemento) transposta.append(linha) return transposta print(transposta([[2,3,0],[-1,-2,-1]]))
def multiplica(mat1, mat2): matrizes = [] for i in range(len(mat1)): linha = [] for j in range(len(mat2[0])): elemento = 0 for k in range(len(mat2)): elemento = elemento + mat1[i][k] * mat2[k][j] linha.append(elemento) matrizes...
class SinglyLinkedListNode: def __init__(self, data): self.data = data self.next = None def insertAtPosition(head,position,data): node = SinglyLinkedListNode(data) index = 0 iterator = head while iterator is not None: if index == position: tmp = iterator.next ...
import time from threading import Thread, Lock N = 1000000 i = 0 def incr(): # Cette fonction incrémente `N` fois la variable globale `i`. global i for _ in range(N): i += 1 def incr_with_lock(lock): global i for _ in range(N): # On utilise le verrou le moins longtemps possible ...
import turtle from time import sleep T = turtle.Turtle() def drawTree(level, size): """level = number of layers further to go""" if level == 0: # Draw one tree T.forward(20*size) T.backward(10*size) T.left(45) T.forward(10*size) T.backward(10*size) T.rig...
import sys #遍历list list_ = ['a','b','x','d','s'] #创建迭代器 it = iter(list_) print('迭代器的类型:',type(it)) #for for ele in it: print(ele) print('===================') #while list = [1, 2, 3, 4] it = iter(list) # 创建迭代器对象 while True: try: print(next(it)) except StopIteration: sys.exit()
import random #number --随机数函数 #从序列中随机挑选一个元素出来 list_ = ['高存','大王','妞子','粪池'] tuple_ = ('高存','大王','妞子','粪池') print("----随机获取序列中的元素---------------------") for index in range(len(list_)): ele = random.choice(list_) list_.remove(ele) print(ele) print("----随机获取序列中的元素---------------------") for index in range(len(...
import random class Triangles: # creating a global class variable amount_of_triangles = 0 # init function controls all other class functions def __init__(self, amount_to_generate): self.generate_amount = int(amount_to_generate) for amount in range(amount_to_generate): ...
"""2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """ import math def smallest_divis_number(max_num): """return the smallest positive number even...
#region Basic Informations #pip install holidays """ Customers often like to know when their orders are delivered, so we want to calculate an expected delivery date. We deliver orders within 1-2 work days in Denmark. If the order is placed before 15:00 (danish time) on a work day the customer can expect the...
print("MUHAMMAD SOHAIB - 18B-054-CS - SECTION A") print("LAB NO:5 (HOME TASK) ") print("25-NOV-2018") print("QUESTION NO:7") import math def projectile(initial_velocity,angle): angle = math.radians(angle) gravity = 9.8 max_height = (initial_velocity**2)*((math.sin(angle))**2) / (2*gravity) ti...
print("MUHAMMAD SOHAIB - 18B-054-CS - SECTION A") print("LAB NO:5") # Program 1 count = 0 f = eval(input("Enter your final condition where you want to break the loop:")) while(count<f): print("The value of count:",count) count = count+1 print("I am using while loop:,count","time.")
str = "mahnoortesthunt.com" str2 = "testingSchool" str3 = "mahnoor" print(str[0:5]) print(str + " " + str2) print(str3 in str) var = str.split(".") print(var) str4 = " great " print(str4.strip()) print(str4.lstrip()) print(str4.rstrip())
def sum(a): return a*(a+1)//2 n=0 primeset=[2] t=2 candidate=3 counter=1 while len(primeset)<100: if candidate%primeset[n]==0: n=0 candidate+=2 continue elif primeset[n]>np.sqrt(candidate): primeset.append(candidate) n=0 print(...
number = 0 variables = "" def fizz_buzz(num, var): fizzarray = [] # doneTODO: Create an empty array outside the loop to store data var = variables num = number while num < 100: # Reset var to prevent issues of adding buzz to buzz or buzz to fizzbuz var = "" #print(num) ...
import sys # https://www.w3schools.com/python/python_tuples.asp # https://www.w3schools.com/python/python_datatypes.asp def addition(values): x = values[0] y = values[1] try: x = int(x) y = int(y) except ValueError: print("Invalid inputs, Must be integers") sum=x+y prin...
def check_taken(choice, board): if str(board.moves[int(choice)]) in turns: print("Position taken try another spot: ") return True else: return False def _create_quit_string(): return " or ".join([", ".join(quitting_chars[:-1]),quitting_chars[-1]]) # quit_string = " or "...
friends = ["a", "b", "c", "d", "e"] # using "-" starts from back of list" ie -2 would be "d" # indexing stats at 0 at "a" position print(friends[0]) # prints selected index location as start and everything after print(friends[1:]) # prints from index upto index "ie: "index position 3" w...
import sys def get_user_inputs(): num1 = "" num2 = "" while True: num1 = input("Enter first Number: ") if not num1.isnumeric(): print("invalid input, must be a number") else: break while True: num2 = input("Enter second Number: ") if not nu...
balance = float(input("Outstanding balance on the credit card: ")) annualInterestRate = float(input("Annual interest rate: ")) remaining = balance payment = 0 while remaining > 0: remaining = balance payment += 10 for n in range(12): unpaid = remaining - payment remaining = round(...
class class01: def __init__(self, name, family, age, address, code): self.name = name self.family = family self.age = age self.address = address self.code = code def my_def(self): print("Name : " + self.name + " \n" + "Family : " + self.family + ...
# import data on Star Wars movies from swapi database api # return a list of Start Wars movies ordered by the length of their opening crawls import requests # opens the requests module to import data through api resp = requests.get('https://swapi.dev/api/films/') #gets the data from the api provided...
target = int(input("Hello. What is your target mark out of 100 for this exam? ")) ans = input("Would you like to know your actual result as a grade? ").lower() if ans == "yes": mark = int(input("What mark did you get out of 100? ")) if mark >= 90: grade = "A" elif mark >= 80: grade = "B" ...
""" Set variable to be rand int 1-10 ask user input guess print output if guess is correct loop 6 times let them know if guess too high let them know if guess too low """ import random guesses = 0 number = random.randint(1,10) guess = int(input("Hello. I have chosen a random number 1-10 can you guess what it is? ")...
yearOne = input('How many games won in year 1? ') yearTwo = input('How many games won in year 2? ') yearThree = input('How many games won in year 3? ') yearFour = input('How many games won in year 4? ') yearFive = input('How many games won in year 5? ') average = (yearOne + yearTwo + yearThree + yearFour + yearFive) /...
import random class ChessBoard: """Class for implementing chessboard, takes JSON as argument""" #Idea is, that always is new board created when JSON is received #Can handle multiple games this way, without own instance for each player on the web #Very simple move making. Board is calculating all possi...
# Program to sort alphabetically the words form a string provided by the user # Define sentence word = "Hello this Is an Example With cased letters" # Split string by space, then sort the splitted string, and then put the string back together word = ' '.join( sorted( word.split() ) ) # word.split() - Splits stri...
# A small frog wants to get to the other side of the road. The frog is # currently located at position X and wants to get to a position greater than # or equal to Y. The small frog always jumps a fixed distance, D. # Count the minimal number of jumps that the small frog must perform to reach # its target. import math X...
# Demonstrates use of the regular expression module. # Due to the importance of this topic I gave it its own file. import re import pprint text = ''' <header> <div class="container"> <div class="row"> <div class="col-md-4"> <a class="bc_logo" href="https://www.bleepingcomputer.com/"><img src="https://www.bleepstatic.c...
import reprlib import pprint import textwrap import locale # reprlib is a version of repr() that limits the output displayed. print('Normal repr:', repr(set('supercalifragilisticexpialidocious'))) print('reprlib:', reprlib.repr(set('supercalifragilisticexpialidocious'))) print() # pprint is short for 'pretty print'. ...
# Demonstrates use of decorators with classes in python. def time_this(old_fn): print('decorating') def decorated(*args, **kwargs): print('starting timer') import datetime before = datetime.datetime.now() x = old_fn(*args, **kwargs) after = datetime.datetime.now() ...
# Demonstrates various list methods from collections import deque from functools import reduce import bisect # List names are plural by convention # Lists are considered mutable objects, thus when var = list is used, the list # is passed by reference instead of by value. As a result, any changes to list # will affect ...
import random import re from measure_time import measure_time @measure_time def word_with_most_occurrences(input_string): sentences = re.split("\s+|,|/.|/?|!", input_string) maxx = 0 returned_word = '' word_count = dict() for word in sentences: if word in word_count: word_coun...
import random from measure_time import measure_time @measure_time def char_with_most_occurrences(input_string): maxx = 0 returned_character = '' char_count = dict() for character in input_string: if character in char_count: char_count[character] += 1 else: char...
""" 作者:北辰 日期:02/06/2019 功能:比较内存效率,从命令行运行: python -m memory_profiler compare_memory.py """ from itertools import chain @profile def list_comp_memory(): """使用普通的列表""" sample_size = 10000 my_data = [i for i in range(sample_size)] @profile def generator_expr_memory(): """使用生成器""" sample...
""" 作者:北辰 日期:06/06/2019 功能:Python多线程中的Pool类使用示例 """ import multiprocessing def get_result(num): """Trivial function used in multiprocessing example""" process_name = multiprocessing.current_process() print("Current process:",process_name,", Input Number:",num) return 10*num if __name__ ==...
""" 作者:北辰 日期:26/05/2019 功能:兽人之袭游戏设计模式之简单工厂:使用python特有的方法来实现创建新的招募角色 """ # Some dummy classes to represent factory products (not documented) class ElfRider: pass class Knight: pass class OrcRider: pass class DwarfFighter: pass class Fairy: pass class Wizard: pass class ElfLord: ...