text
stringlengths
37
1.41M
""" Implement a function that shows all the friends in a user's extended social network and chain of friendships that link them. The number of connections between one user and another are called the degrees of separation. How will the performance scale as more users join? Implement a feature that creates large numbers...
class Dado: def __init__(self,musica,cantor,genero): self._musica = musica self._cantor = cantor self._genero = genero def __str__(self): return f'Musica: {self._musica}\nCantor: {self._cantor}\nGênero: {self._genero}' class No: def __init__(self,dado=None,proximo=None): ...
noOfTest = int(input('enter the number of test')) for eactTest in range(noOfTest): noOfPlayers = int(input('number of player')) print(noOfPlayers-1)
n = int(input()) arr = list(map(int, input().split())) # optimal approach a = 1 b = arr[0] for i in range(2, n+1): a ^= i for i in range(1, n-1): b ^= arr[i] print(a ^ b) # First Approach # keep = {} # for num in arr: # keep[num] = True # missingNumber = 1 # for i in range(1, n+1): # if i not in kee...
Lista=[] i=0 n=int(input('Digite o Tamanho da Lista \n')) while i<n: Lista.append(int(input('Digite um valor para Posição {} '.format(i)))) i+=1 x=int(input('Digite o valor para Buscar:\n')) print("O Valor {} Aparece {}vez(es) na Lista".format(x,Lista.count(x))) #Exercicio Da Lista de Vetores #def Calculo(I,Lis...
while True: try: length = int(input("Give the length of the fibonacci series (must be positive): ")) start = int(input("Give the starting number: ")) break except: print("Give a valid number.") fibo = [0,1] if start < 2: for i in range(length-1): fibo.append(fib...
from math import sqrt tri_number=0 count=0 while True: num_divisors=0 count+=1 tri_number+=count for i in range(1,int(sqrt(tri_number))+1): if tri_number%i==0: num_divisors+=2 if num_divisors>=500: print tri_number,num_divisors break
import cv2 as cv import numpy as np img = cv.imread('C:/OPENCV/photo/boston.jpg') #顯示圖片 #cv.imshow('boston',img) #關閉圖片秒數 # 定義圖片平移 def translate(img,x,y): # x軸平移x,y軸平移y transMat = np.float32([[1,0,x],[0,1,y]]) dimension = (img.shape[1],img.shape[0]) return cv.warpAffine(img,transMat,dimension) translat...
''' this algorithm is aimed at sorting the list obeject under a given constraint ''' import random def compare_list(d1,d2): if d1[len(d1)-1]>d2[len(d2)-1]: return 1 elif d1[len(d1)-1]<d2[len(d2)-1]: return -1 else: return 0 def insertSort(A): #this is sub program for sorting of l...
def dpMakeChange(coinValueList,change): ''' Given a list of coin values and a desired amount of change, find the least amount of coins necessary to make that value''' minCoins = [0] * (change + 1) #minCoins remembers the minimum amount of coins required to make each value temp = [] #temp stores the coins we want to...
import random from brain_games.game_engine import game rules = 'Find the greatest common divisor of given numbers.' # Расчёт делителей (вывод в кортеж) def get_divider(number): divider = 1 result = () while divider <= number: if (number % divider == 0): result = result + (divider, ) ...
""" @file @brief Various functions to process text """ def replace_comma_by_point(file) : """ replaces all commas by point in a file (do that inplace) @param file file to process """ with open(file,"r") as f : text = f.read() text = text.replace(",",".") with open(file,"w")...
# importing csv module import csv import datetime # csv file name filename = "distance.csv" # initializing the titles and rows list fields = [] rows = [] # reading csv file with open(filename, 'r') as csvfile: # creating a csv reader object csvreader = csv.reader(csvfile) # extracting field names throug...
from itertools import combinations def solution(clothes): answer = 0 cloths = {} for arr in clothes: if arr[1] not in cloths.keys(): cloths[arr[1]] = [arr[0]] else: cloths[arr[1]].append(arr[0]) print(cloths) print(list(combinations(cloths))) return answ...
def convert(n): T = "0123456789ABCDEF" q, r = divmod(n, 3) if q == 0: return T[r] else: return convert(q) + T[r] def solution(n): answer = '' temp_answer = str(convert(n)) for ans in temp_answer: if ans == '0': answer +='4' elif ans == '1': ...
from collections import deque def solution(bridge_length, weight, truck_weights): answer = 1 visited = deque() bridge_truck = [] while True: if len(visited) > 0 and visited[0][0] + bridge_length == answer: visited.popleft() bridge_truck.pop(0) if len(tru...
def totalcal(li): if len(li) > 2: t3 = templist.pop() t2 = templist.pop() t1 = templist.pop() telist = [t1, t2, t3] return calculation(telist) else: return 'error' def calculation(li): result = 0 if '.' in li: return 'error' else: if...
def solution(arrangement): answer = 0 stacklist = list() minus = 0 for arrange in arrangement: if arrange == '(': minus = 0 stacklist.append(arrange) else: minus += 1 stacklist.pop() if minus == 1: answer += len(...
str = "" t = int(input()) a = "" for i in range(t): li = list(map(int, input().split())) if li[0] > li[1]: a = ">" elif li[0] < li[1]: a = "<" else: a = "=" str += f'#{i+1} {a}\n' print(str)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 二叉树的中序遍历(使用栈): 中序遍历的顺序为**左-根-右**,具体算法为: - 从根节点开始,先将根节点压入栈 - 然后再将其所有左子结点压入栈,取出栈顶节点,保存节点值 - 再将当前指针移到其右子节点上,若存在右子节点,则在下次循环时又可将其所有左子结点压入栈中 """ class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def ino...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ LeetCode 第 20 号问题:有效的括号 解决方案: 遍历整个字符串 1、左半括号直接进栈 2、右半括号分三种情况进行判断: 1)整个栈为空,直接返回False 2)取出栈顶元素,作为key,查找右半括号,判断是否与字符相等,不相等直接返回False 3、遍历完成后,判断栈是否为空,不为空返回False,否则返回True """ def is_valid_parenthese(string): left_par = {"{":"}","[":"]","(":")"} result = [] ...
# coding=utf-8 """Advent of Code 2015, Day 1""" current_floor = 0 current_position = 1 first_basement = None with open("input.txt") as f: for char in f.read(): if char == "(": current_floor += 1 elif char == ")": current_floor -= 1 if current_floor < 0 and first_bas...
# coding=utf-8 """Advent of Code 2015, Day 20, Part 2""" import itertools def get_factors(n): # noinspection LongLine,PyPep8 """ Calculate the factors of a number. Source: http://stackoverflow.com/questions/6800193/what-is-the-most-efficient-way-of-finding-all-the-factors-of-a-number-in-python :p...
# coding=utf-8 """Advent of Code 2015, Day 5, Part 1""" import re def is_nice_string(string): """ Determines whether a string is nice. :param string: the candidate string to check :return: whether the string is nice (boolean) """ return has_three_vowels(string) and has_double_letter(string) a...
# numpy is used for creating fake data import numpy as np import matplotlib.pyplot as plt # Create data data_group1 = np.random.normal(100, 10, 200) data_group2 = np.random.normal(80, 30, 200) data_group3 = np.random.normal(90, 20, 200) # combine these different datasets into a list data_to_plot = [data_group1, data_...
import numpy as np x = np.array([1, 2, 3, 4, 5]) print(x < 2) # less than print(x >= 4) # greater than or equal x = np.array([1, 2, 3, 4, 5]) # Elements for which multiplying by two is the same as the square of the value (2 * x) == (x ** 2) #> array([False, True, False, False, False], dtype=bool) x = np.arange(10...
''' We can create a pivot table using pivot_table; we can set index =‘Director’ (row of the pivot table) and get the yearly revenue information by setting columns = ‘Year’:''' import pandas as pd movies_df = pd.read_csv("IMDB-Movie-Data.csv") movies_df_title_indexed = movies_df.set_index('Title') # Let's calculate th...
n = int(input('Enter: ')) count = 1 while count <= 12: print('{} x {} = {}'.format(n, count, n*count)) count += 1
#odd number bewteen 1 and 20 for i in range(1, 21, 2): print(i,end='') print() #a. count in 10s from 0 to 100 for i in range(0, 101, 10): print(i,end='') print() #b. count down from 20 to 1 for i in range(20, 0, -1): print(i,end='') print() #c. print n stars Number = int(input ("Enter number of stars:")) fo...
"""import unicodecsv enrollments = [] f = open('/home/aman/Desktop/Udacity/Introduction to Data Analysis/enrollments.csv', 'rb') reader = unicodecsv.DictReader(f) for row in reader : enrollments.append(row) f.close() print enrollments[0] print enrollments[1] """ #using with option to avoid the use of close...
import bpy from random import random # In blender, put all attractors in a Collection called "Attractors" # this will grab all objects associated with that collection attractors = bpy.data.collections["Attractors"].objects # Setup Random Range function def rr(num): rand = (random() * 2 * num)-num re...
import cv2 img = cv2.imread('test1.jpg') print('Original Dimensions : ', img.shape) width = 550 height = 450 dsize = (width, height) # resize image resized = cv2.resize(img, dsize, interpolation=cv2.INTER_AREA) print('Resized Dimensions : ', resized.shape) cv2.imshow("Resized image", ...
# Árvore binária de busca class Node: """ Classe que representa o nó da árvore""" def __init__(self, val): self.value = val self.left = None self.right = None def insert(self, data): # Se o valor já existir if self.value == data: return False # Caso o valor sej...
import sys import csv f = open('../Data/missing.csv', encoding='utf8') rows = csv.reader(f) # next() me separa la primer línea de lo que le paso como parámetro y luego trabaja con las líneas siguientes headers = next(rows) costo_total = 0 for i, row in enumerate(rows, start=1): try: costo_total += float(r...
def donde_insertar(lista, x, verbose = False): '''Búsqueda binaria Precondición: la lista está ordenada Devuelve p tal que lista[p] == x, si x está en lista o devuelve la posición donde se podría insertar x para que la lista permanezca ordenada (si x no está en la lista); ''' if verbose: ...
def propagar_al_vecino(l): modif = False n = len(l) for i,e in enumerate(l): if e==1 and i<n-1 and l[i+1]==0: l[i+1] = 1 modif = True if e==1 and i>0 and l[i-1]==0: l[i-1] = 1 modif = True return modif def propagar(l): m = l.copy() ...
def columnas_palabras(p1, p2): if len(p1) != len(p2): p_mas_larga = max(len(p1), len(p2)) p1 = p1.ljust(p_mas_larga) p2 = p2.ljust(p_mas_larga) for i, k in zip(p1, p2): print(i, k) print(columnas_palabras("hola", "mundo"))
def busqueda_secuencial_(lista, x): '''Si x está en la lista devuelve el índice de su primera aparición, de lo contrario devuelve -1. Además devuelve la cantidad de comparaciones que hace la función. ''' comps = 0 # inicializo en cero la cantidad de comparaciones pos = -1 for i,z in enumera...
numeros = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(f'{numeros[0]:8d} {numeros[1]:>3d} {numeros[2]:>3d} {numeros[3]:>3d} {numeros[4]:>3d} {numeros[5]:>3d} {numeros[6]:>3d} {numeros[7]:>3d} {numeros[8]:>3d} {numeros[9]:>3d}') print('--------------------------------------------') tablas = {} for i in range(10): tabla =...
import random def generar_lista(n, m): '''Devuelve una lista ordenada de n elementos diferentes entre 0 y m-1''' l = random.sample(range(m), k = n) l.sort() return l def generar_elemento(m): '''Devuelve un elemento aleatorio en el mismo rango de valores''' return random.randint(0, m-1) def ma...
##Author: Steve Gonzalez ##Date: 09/20/2017 ##Class: CIS 1400-003 ##Program: Lab 5 Largest and Smallest ##Descr: ## This program will prompt the user to input ## a series of numbers of their choosing and ## will display the largest and smallest of ## the series of numbers # A module to describe the functio...
#!/usr/bin/env python3 ''' Given two strings S and T of equal length, the Hamming distance between S and T, denoted dH(S,T), is the number of corresponding symbols that differ in S and T. usage: python counting_point_mutations.py rosalind_hamm.txt ''' __author__ = 'George Carvalho' import sys def hamming_distance...
""" 使用input()函数获取键盘输入 使用int()函数将输入的字符变成整数 使用print()函数输出带占位符的字符串 %d 整数占位符 %f 浮点数占位符 %% 百分号 %s 字符串 Version: 0.1 Author: Ailin a = int(input("请输入任意数字a:")) b = int(input("请输入数字b=")) print("%d + %d = %d" % (a,b,a+b)) print("%d - %d = %d" % (a ,b, a-b)) print("%d * %d = %d" % (a, b, a*b )) print("%d / %d = %f" % (a, b,a/b ...
from random import randint def roll_dice(n=2): total = 0 for _ in range(n): total += randint(1,6) return total """ def add(a=0,b=0,c=1): return a+b+c """ def add(*a): total = 0 for i in a: total += i return total print(roll_dice(5)) print(roll_dice() ) print(add(1,2,3)) pr...
""" 斐波那契数列的特点是数列的前两个数都是1, 从第三个数开始,每个数都是它前面两个数的和, 形如:1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...。 Version: 0.1 Author: Ailin """ """ num = int(input("您想取前多少位数值?")) x = 1 y = 1 if num <= 0: print("您的输入有误!") elif num == 1: print("斐波那契数列前%d个数值为" % num ,1) elif num == 2: print("斐波那契数列前%d个数值为" % num ,1,1) els...
""" 用for...in循环实现1~100求和 Version: 0.1 Author: Ailin """ """ sum = 0 for x in range(1,101): sum += x print(sum) """ """ 100内的偶数求和 Version: 0.1 Author: Ailin """ sum = 0 for x in range(2,101,2): sum += x print(sum)
scores = {'爱林':100,'李新慧':60,'狄仁杰':76} print(scores) item1 = dict(one =1 ,two=2,three=3,four=4) item2 = dict(zip(['a','b','c','d'],'1235')) item3 = {num:num**2 for num in range(1,10)} print(item1,item2,item3) print(scores['李新慧']) for key in scores: print(f'{key}:{scores[key]}') scores['爱林'] = 150 scores['诸葛'] = 140 ...
def is_pallindrome(x): """判断是不是回文数 is_pallindrome = True i = 1 num = x while num >= 10: num /= 10 i += 1 for j in range(i): if x // (10**j)%10 != x // (10**(i-j-1))%10: is_pallindrome = False break return is_pallindrome """ total = 0 ...
VERSION = (1, 3, 3) def get_version(version=None): ''' Calculate package version based on a 3 item tuple. In addition verify that the tuple contains 3 items ''' if version is None: version = VERSION else: assert len(version) == 3 return '{0}.{1}.{2}'.format(*(x for x in ver...
""" 字典是一种可变容器模型,可以储存任意类型对象 """ d = {1:"zhang3", 2:"li4"} # 一对一对的 key:value print(d) keys = d.keys() # 获取所有的key #keys = d.get() # 访问 print(keys) for i in keys: print(i) print(d[i]) # 添加 # d[3]= "test" # print(d) # d.setdefault(4,"aaa") # print(d) # 更新 d[4] = "bbb" print(d) # delete # r = d.pop(4) ...
""" 循环的中断 1. break 2. continue // 结束本轮循环,进入下一次循环 """ i = 1 while True: i = i+1 print(i) if i == 10: print("=10") continue print("this") print("next") if i ==15: break
# It is a nice day. Let's get start # @Author : Boya # @Time : 01/05/2020 09.05 # Lambda表达式 又叫匿名函数 # 格式: lambda 参数列表:表达式 f = lambda x: x + x r = f(1) # print(r) # map 函数: 迭代传参入函数进行计算,返回的是地址 map_demo = map(f, [1, 2, 3, 4]) # print(map_demo) # print(list(map_demo)) # # print(list(map(str,[1, 2, 3, 4]))) # red...
class Perro(): def __init__(self, n, e, p): self.nombre = n self.edad = e self.peso = p def ladrar(self): if self.peso >= 8: print("GUAU, GUAU") else: print("guau, guau") def __str__(self): return "Perro {}, e: {}, p: {}".format(s...
user= input("Enter Alphabet") b=reversed(user) if list(user)==list(b): print("Yes Palindrome") else: print("No Palindrome")
# エラトステネスの篩 def sieve(n): num = [True]*(n+1) num[0] = num[1] = False for i in range(2,int(n**0.5)+1): if num[i]: for j in range(i**2, n+1, i): num[j] = False return num # 自然数が素数か素数じゃないかだけ # 素数のリストが欲しいなら↓ # return [i for i in range(2,n+1) if num[i]] # def eratosthenes(limit): # pr...
s = input() n = len(s) op = n - 1 ans = 0 for i in range(2**op): opm = [''] * op for j in range(op): if ((i >> j) & 1): opm[op - 1 - j] = '+' formula = '' for j in range(op): formula += s[j] + opm[j] formula += s[-1] ans += eval(formula) print(ans)
def lp(): return list(map(int, input().split())) def mp(): return map(int, input().split()) def main(): n = int(input()) a = [] if n == 1: print('Not Prime') exit() while n % 2 == 0: n //= 2 a.append(2) f = 3 while f**2 <= n: if n % f == 0: a.append(f) n //= f else: ...
class UnionFind(): # uf(n) def __init__(self, n): self.self.par = [-1]*n def find(self, x): if self.par[x] == x: return x else: return self.find(self.par[x]) # 経路縮約 def unite(self, x, y): rx = self.find(x) # rootにする ry = self.find(y) if rx == ry: return False if self.par[rx] > self....
arr = [5, 2, 9, 5, 6] for i in range(len(arr)): print(arr[-i], end=' ') # Result # 6 5 9 2 5
x = 5 y = 10 z = x x = y y = z print(f'The value of x is {x} and y is {y}') # Result # The value of x is 10 and y is 5
from functools import reduce nested_list = [["A", "B", "C"], ["D", "E", "F"], ["G", "H", "I"]] target_list = [] for one_nested_list in nested_list: target_list += one_nested_list print(f"First pythonic way {target_list}") # OR target_list_v2 = reduce(lambda x,y: x+one_nested_list, nested_list) print(f"Second pyt...
s = "The quick brown fox jumps over the lazy dog" word = "" s += " " freq = {} for i in range(len(s)): ch = s[i].lower() if ch != ' ': word += ch else: if word not in freq: freq[word] = 0 freq[word] += 1 word = "" print("Sentence:\n" + s) print("\nWord frequen...
words = ["one", "two", "three", "four", "five"] nums = [1, 2, 3, 4, 5] table = dict(zip(words, nums)) print(f"List 1: {words}") print(f"List 2: {nums}") print(f"Table: {table}") # Result # List 1: ['one', 'two', 'three', 'four', 'five'] # List 2: [1, 2, 3, 4, 5] # Table: {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'f...
arr = [5, 2, 9, 5, 6] element = 9 for i in arr: if i == element: print("Exists") # Result # Exists
''' Advanced Algorithms and Data Structures FT BSc Computer Science (Year 3) Goldsmiths, University of London Static / Adaptive Huffman Coding by Wojciech Tyziniec "Huffman codes compress data very effectively: savings of 20% to 90% are typical, depending on the characteristics of the data being compressed. ...
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 04 # Questão.: 4.6.6 # Autor...: Fábio Procópio # Data....: 04/06/2019 estatura = float(input("Estatura do aluno: ")) '''Como não há nenhuma estatura a ser comparada, neste momento, o primeiro aluno tem a maior e a menor estatura''' m...
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 02 # Questão.: 2.8.2 # Autor...: Fábio Procópio # Data....: 18/02/2019 from math import pi raio = float(input("Raio da circunferência (cm): ")) cump = 2 * pi * raio print("Cumprimento = {:.2f}cm".format(cump))
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 03 # Questão.: 3.6.1 # Autor...: Fábio Procópio # Data....: 31/05/2019 num = int(input("Digite um número: ")) if num %2 == 0: quadrado = num ** 2 print("{} é par e o seu quadrado é {}.".format(num, quadrado)) else: cubo = num ...
import csv with open("./astronauts.csv", newline='') as csvfile: reader = csv.DictReader(csvfile) ...
class Solution: def thirdMax(self, nums: List[int]) -> int: x = len(nums) max1 = None max2 = None max3 = None if x < 3: return max(nums) for i in nums: if i == max1 or i == max2 or i == max3: continue if max1 == None...
"""Data model classes for a crime database """ from flask import Flask from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class Category(db.Model): """Data model for a category.""" __tablename__ = 'categories' category_id = db.Column(db.Integer, primary_key=True, autoincrement=True) category_...
""" Etch a Sketch game on Raspberry Pi Coded by Jenna Beach (040777966) Last modified: 03/12/2020 Algorithm: """ from gfxhat import lcd, fonts from PIL import Image, ImageFont, ImageDraw from click import getchar def clearScreen(lcd): lcd.clear() lcd.show() def displayText(text, lcd, x, y)...
from json import JSONDecodeError, JSONDecoder, loads def decode_non_delimited_json(content_unicode_str): """ If you have a non delimited text file with valid json. You can use this to read everything. """ decoder = JSONDecoder() decode_index, content_length = 0, len(content_unicode_str) o...
from queue import Queue from graph import Graph # First we need to create a graph using the collection we're given def create_graph_from(ancestors): # create a graph instance g = Graph() # Loop through all pairs in ancestors # Note: In the Graph class `add_vertex` checks... # ..to make sure th...
n = int(input()) digits = list(input().split()) def max_num(lst): n = len(lst) for i in range(n - 1): for i in range(n - 1 - i): if lst[i] + lst[i+1] < lst[i + 1] + lst[i]: lst[i], lst[i + 1] = lst[i + 1], lst[i] return lst digits = max_num(digits) result = '' for digi...
#This is a class for implementing Queue class Q: def __init__(self): self.__que=[] def queue(self,val): self.__que.append(val) def dequeue(self): x=self.__que[0] del(self.__que[0]) return x def sizee(self): return len(self.__que) # A class to create no...
""" Monte Carlo Tic-Tac-Toe Player """ import random #import poc_ttt_gui import poc_ttt_provided as provided #import codeskulptor #codeskulptor.set_timeout(10) # default value is 5 seconds. # Constants for Monte Carlo simulator # You may change the values of these constants as desired, but # do not chan...
""" Principles of Computing - week 2 Clone of 2048 game. Daehan Hong """ import random # Change of drawing VAl1 or VAl2 on new tile - number shows chance of drawing VAl1 NEW_TILE_CHANCE = 90 # out of 100, can use 0 - 1 (we can use) #available values of NEW tile NEW_TILE_VAL1 = 2 NEW_TILE_VAL2 = 4 #...
#!/usr/bin/env python # -*- coding: utf-8 -*- try: int([1,2,3]) except (ValueError,TypeError): #esto maneja errores de valor, por eso ValueError print "Eso no es un numero o no se puede convertir ese tipo de datos" #esto era un diccionario #d = {"a" : 1} #print d["b"] """ si no hago try escapa del...
''' Written in Python 3.7 using Selenium Function that scrapes the web to update the value of the dollar Returns a float value ''' from selenium import webdriver from selenium.webdriver.chrome.options import Options def dollar_today_scrap(): options = Options() options.add_argument('--headless') driver...
__author__ = 'Jeffrey' def get_user_name(): user_name = str(input("Please enter your name.")) name_file = open("name.txt", mode="w", encoding="utf-8") name_file.write(user_name) name_file.close() get_user_name() def printing_name_file(): name_file = open("name.txt", mode="r") name = name_fi...
__author__ = 'Jeffrey' class GuitarError(Exception): def __init__(self, value): super().__init__(value) class Guitars: def __init__(self, name="", year=0, cost=0): self.name = name self.year = year self.cost = cost if year < 0: raise GuitarError("Age cann...
n=int(input(" ")) sum=1 while(n!=0): sum=sum*n n=n-1 print(sum)
# Naive Method def pig_it(text): l = list(map(str,(text).split(" "))) pun = ["!","?",","] b = "" m = [] for i in l: if i in pun: m.append(i) else: b = i[1:] + i[:1] + "ay" m.append(b) return " ".join(m) print(pig_it('Hello world !')) # Pro Ve...
# VERSION-1 def filter_list(l): 'return a new list with the strings filtered out' d = [e for e in l if isinstance(e,int)] return d # VERSION-2 def filter_list1(l): return [e for e in l if isinstance(e,int)] print(f"Output by VERSION-1 : {filter_list([1,2,'a','b'])}") print(f"Output by VERSION-2...
def pascals_triangle(n): def fact(n): f = 1 i = 1 while i<=n: f = f*i i+=1 return f lines = n m = [] for x in range(lines): for y in range(x+1): y = fact(x)//(fact(y)*fact(x-y)) m.append(y) y = ...
# Finding nth finbacci with math formulae module import math n = int(input()) fi = 1.618034 x = (fi**n - (1-fi)**n)/math.sqrt(5) print(math.floor(x)) import math m = int(input()) n = float(m) fi = 1.618034 try: x = (fi**(n-1) - (1-fi)**(n-1))/math.sqrt(5) print(math.floor(x)) print('Alive' if math.floor...
def solution(st, limit): return st[0:limit] + '...' if limit < len(st) else st print(solution('Testing String', 3))
n = int(input()) if n%3==0: if n%2==0: print(0) else: print(1) else: print(-1)
# Calculates the Factorial of a given number import itertools as it import operator as op def factorials_nums(n): result = list(it.accumulate(it.chain([1], range(1, 1 + n)), op.mul)) return result[-1] for _ in range(int(input())): x = int(input()) print(factorials_nums(x)) # By Recusrion def fact(n):...
import itertools as it import operator as op def factorials_nums(n): result = list(it.accumulate(it.chain([1], range(1, 1 + n)), op.mul)) return result[-1] for _ in range(int(input())): n,x,y = map(int,input().split()) fact_N = factorials_nums(n) fact_X = factorials_nums(x) fact_Y = factorials...
class Trie: def __init__(self): self.children = {} self.endWord = False class WordDictionary: #直覺兩種方法 trie, hashmap def __init__(self): self.root = Trie() def addWord(self, word): cur = self.root for w in word: if w not in cur.children: ...
class Solution: def kthSmallest(self, root, k): #給一個binary search tree #return 第k小的value #core concept 他是一顆binary search tree #直覺1 -> inorder traversal -> asc sorted order #dfs + inorder traversal #keep array 直到第k個數字出現 arr = [] stack = [] ...
''' Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). ''' class Solution: def threeSumClosest(self, nums, target): result = nums[0] + nums[1] + nums[2] nums.sort() nLen = len(nums) for i in range(nLen...
''' Implement pow(x, n), which calculates x raised to the power n (i.e., xn). Example 1: Input: x = 2.00000, n = 10 Output: 1024.00000 Example 2: Input: x = 2.10000, n = 3 Output: 9.26100 Example 3: Input: x = 2.00000, n = -2 Output: 0.25000 Explanation: 2^-2 = 1/2^2 = 1/4 = 0.25 ''' class Solution: def myP...
class ListNode: def __init__(self, val = 0, next = None): self.val = val self.next = next class Solution: def hasCycle(self, head): #簡單說就是判斷linked list有沒有cycle #floyed's algorithm #fast, slow pointer if not head: return False slow, fast = he...
class Solution: def hashTagString(self, s): result = '#' for i in s: result += i result += '#' return result def findMaxWidthIdx(self, s): print(s) idx = 0 maxWidth = -1 sLen = len(s) for i in range(sLen): ...
''' Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only. Example 1: Input: s = "Hello World" Output: 5 Explanation: The last word is "World" with length 5. Example 2: ...
''' 給定matrix, 把matrix 中0 的上下左右全都改成0 ''' class Solution: def setZeroes(self, matrix): #試試看能不能O(1)搞定 #set column mapping, row mapping #traversal matrix, 0 -> update row mapping column mapping #traversal matrix, update from row mapping column mapping ...
class Solution: def uniquePaths(self, m, n): #一個m*n矩陣 #從左上到右下有幾種unique path if m == 0 or n == 0: return 0 #dp[i][j] = i,j格的unique path dp = [[0 for _ in range(n)] for _ in range(m)] for i in range(m): for j in ran...