text
stringlengths
37
1.41M
""" Once we have the World, it is possible to thing about its representation. The assumption has been that a part of the world is used as expression for another part fo the world. Classic cryptography provides a starting example. A substitution cipher (dates back to Julius Caesar, cf. Poe's The Gold-Bug) is a basic cry...
# Author ------------- Cecilia Y. Sui # Course ------------- Competition Programming # Program ------------ Sprint Problem #1 import math n = int(input()) p = math.pi for i in range (n): s = [float(i) for i in input().split()] r = s[0]/100/2 l = (s[1] - s[0])/100 rin = r - 0.005 Vout = p * (r**2)...
def dist(i, j): # print(i,j) # print(a[i],b[j]) # rint(ord(a[i]), ord(b[j])) # print(abs(ord(a[i])-ord(b[j]))) global flag if a[i] == "\0": return len(b)-j-1 if b[j] == "\0": return len(a)-i-1 if a[i] == b[j]: return dist(i+1, j+1) if flag: # even c1 =...
n = int(input()) for i in range(n): l = input().split() row, col, s = int(l[0]), int(l[1]), l[2] s = [int(a) for a in s] lists = [[] for a in range(col)] # lists as cols flag = True # b's turn for val in s: lists[val-1].append(1 if flag else 2) flag = not flag for l in lis...
def run(): letras = input('Ingrese su nombre: ') for letra in letras: print(letra.upper()) if __name__ == '__main__': run()
import time import future from future import Future from future import ThreadedExecutor import task from task import Task #New task which is a future import task2 from task2 import Task as Task2 """ What we want is not to keep polling futures done method or get blocked while calling the result method. Neither do we ...
import matplotlib.pyplot as plt # Stack plots are used when two or more data sets are going to be shown on the same set of axes, # or you want to break down one data set by their components. And we're interested in the sums. days = [1,2,3,4,5] sleeping = [7,8,6,11,7] eating = [2,3,4,3,2] working = [7,8,7,2,2] playin...
import time import datetime import numpy as np import pandas as pd def calctime(a = float): time_a = time.time() time.sleep(a) time_b = time.time() timepassed = time_b - time_a calculated = timepassed - a print(datetime.datetime.fromtimestamp(time_a)) return timepassed, calculated print(ca...
#!/usr/bin/env python # -*- coding: utf-8 -*- print ("Welcome to BV Unit converter! Transfer kilometers to miles in an easy way!") x = "no" while True: km = int(raw_input("Please enter the number of kilometers You wish to convert: ")) miles = km * 0.621371 print miles y = raw_input("Do You want to do...
str1 = "Hello!" str2 = "Hi!" str3 = """ok, goodbye!""" print(str(str1)) print(str2) print(str3) print(str1 + str3)
import pygame, random, time pygame.init() screen = pygame.display.set_mode((200,100)) screen.fill((0,255,0)) pygame.display.flip() time.sleep(2) c = 0 while 1: c += 1 if( ( c % 2) == 0 ): screen.fill((0,255,0)) else: screen.fill((0,0,255)) i = random.randint(200,100) j = random.randint(200,100) k = random....
import random print('Guessing game') # Guess the correct number in 3 guesses. If you don’t get it right after 3 guesses you lose the game. # Give user input box: 1. To capture guesses, # print(and input boxes) 1. If user wins 2. If user loses # Tip:( remember you won’t see print statements durng execution, so If y...
from math import * def printPrime(m,n): for i in range(m,n+1): c=0 for j in range(2,i): if(i%j==0): c=1 break else: continue if(c==1): continue else: print(i,end=" ") m=int(input("Ente...
import os import sys import json import csv import xmltodict # pip install xmltodict import pprint # Print a simple help def help(): print("Python example converter for AL\n") print("Usage:") print("al.py --in <input file name> --out <output name> --print <txt|html>") print("Valid file formats/extensions: .json, ...
#pybank import os # Module for reading CSV files import csv #set lists up and counters Total_Count = 0 Total_Months = [] Net = 0 Total_Net = [] Monthly_Change = [] Date = [] Greatest_Increase = 0 Greatest_Increase_Month = 0 Greatest_Decrease = 0 Greatest_Decrease_Month = 0 #define file path to open csvpath = os.pa...
#programa que leia um conjunto de números (termos) do teclado e imprima o produto de todos esses números numtermos=0 numtermos=int(input("Entre com o numero de termos: ")) lista = [] produto=1 aux=0 if numtermos == 0: print ("zero") for i in range (numtermos): termo=int(input("Digite aqui o valor d...
#Exercício 6 (4.5) lista=[] contador=0 quantidade=int(input('Digite aqui o número de coordenadas a serem inseridas: ')) for i in range(quantidade): valor=float(input('Digite aqui a coordenada a ser inserida'+ str(i+1)+':')) lista.append(valor) for i in range(len(lista)): if (lista[i])<0: ...
while True: n=int(input('Entre com um número: ')) if n<0: print('Entrada inválida') elif n%2==0: print('É par') a= int(input('Deseja executar o programa novamente? (0-Nã0) (1-sim))')) if a==0: break else: print('É impar') a= ...
# print("hello world!") #字符串 # print(2333) #整数 # print(2.333) #小数 浮点数 # print(True) #布尔值 True False # print(()) # 元组 # print([]) #数组 # print({}) #字典 # """ # 大鹏一日同风起 # 扶摇直上九万里 # """ # print('haha',2333,2.333) # print("哈哈" + "嘻嘻") #字符串的拼接 # print("哈"*100) # print(2<3) # #变量 赋值 # na...
day_miles = float(input('How many miles do you drive a day>')) gasmile= float(input('Whats the gas mileage of your car (miles per gallon)>')) energy = float(input('What was the price of your energy bill last month (dollars)>')) print('How often do you eat meat and dairy') print('3. I have meat and dairy in alomst e...
''' #1 Length of a string def strsize(a): count = 0 for i in a: count = count + 1 print(count) #2 Frequency count in s = 'google.com' for each letter s = 'google.com' e = {} for i in s: if i not in e: e.update({i:s.count(i)}) #3 Get a string made of the first 2 and the last 2 chars from ...
from collections import deque def solution(s): stack = [] queue = deque(list(s)) while queue: que_pop = queue.popleft() if len(stack) ==0: stack.append(que_pop) elif stack[-1] == que_pop: stack.pop() else: stack.append(que_pop) if l...
import sys # For stoping the executions of a function B = [0,1,2,3,4,5,6,7,8] def p(): print(B[0],B[1],B[2]) # These will prints Board on Screen print(B[3],B[4],B[5]) print(B[6],B[7],B[8]) print() A1=eval(input("choose an option for player 1: ")) ...
""" Given a binary tree t and an integer s, determine whether there is a root to leaf path in t such that the sum of vertex values equals s. This is what this tree looks like: 4 / \ 1 3 / / \ -2 1 2 \ / \ 3 -4 -3 Input/Output [execution time limit] 4 seconds (p...
# ===== PROBLEM1 ===== # Exercise 1 - Introduction - Say "Hello, World!" With Python print("Hello, World!") # Exercise 2 - Introduction - Python If-Else import math import os import random import re import sys if __name__ == '__main__': n = int(input().strip()) if n%2!=0: print("Weird") if n%2==0: if (2<...
# -*- coding: utf-8 -*- """ Created on Mon Sep 9 11:35:39 2019 @author: Phalin Pancholi """ class bigin(str): def __init__(self, s_int = ''): self.s_int = s_int def __gt__(self, other): if len(self.s_int) == len(other.s_int): return self.s_int > other.s_int el...
def solution(s): s_list = [] for char in s: if char.isupper(): s_list.append(" ") s_list.append(char) return "".join(s_list) s1 = "helloWorld" s2 = "camelCase" s3 = "breakCamelCase" print(solution(s1)) print(solution(s2)) print(solution(s3))
def decrypt(encrypted_text:str, n:int) -> str: """ Returns the original String that is encrypted using encrypt """ while n > 0: text_list = list(encrypted_text) second_element = text_list[:len(text_list)//2] print(second_element,end="\n") other_element = text_list[len(tex...
def valid_parenthesis(strings): """ Assumes strings to be a string of valid_parenthesis returns true if the order of parenthesis is correct otherwise false """ Count = 0 for char in strings: if char == '(' and Count >= 0: Count += 1 if char == ')': Count -...
def cakes(recipe, available): """ Assumes recipe and available to be dictionary returns no of cakes that can be made from given data """ temp = [] for e in recipe.keys(): if e not in available.keys(): return 0 temp.append(available[e]//recipe[e]) return min(temp)
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Feb 23 15:16:22 2017 @author: Henrik Calculate a pdf given a coordinate file and periodic table file. Approximates charges as points only """ import math as m import matplotlib.pyplot as plt def tableloader(): """load pereodic table in dictonary tab...
import pandas as pd import numpy as np # concatenating df1 = pd.DataFrame(np.ones((3,4))*0,columns=['a','b','c','d']) df2 = pd.DataFrame(np.ones((3,4))*1,columns=['a','b','c','d']) df3 = pd.DataFrame(np.ones((3,4))*2,columns=['a','b','c','d']) print("df1:",df1) print("df2:",df2) print("df3:",df3) res = pd.concat([df...
import matplotlib.pyplot as plt import numpy as np plt.figure() x = np.linspace(-3,3,50) y = x**2 plt.plot(x,y) plt.xlim((-3,3)) plt.ylim((-1,10)) # gca = 'get current axis' ax = plt.gca() ax.spines['right'].set_color('none') # 右边框消失 ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') # 将x轴和底边框绑...
import re from util.enums import Player from piece import Queen, Rook, Bishop, Knight CHAR_TO_CLASS = { 'q': Queen, 'r': Rook, 'b': Bishop, 'n': Knight, } def use_unicode(board): if board.character_map.unicode: while True: c = input('would you like to use unicode chess figures...
# http://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning def minimax(game, player, depth, max_depth): if game.game_over() or depth >= max_depth: return game.heuristic_value(player), [] best_score = -float('inf') if game.current_player == player else float('inf') best_moves = [] for move in ...
import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # Achieves an average of 88% Accuracy. This is abysmal! def SoftmaxRegression(): """Performs a Softmax Regression of MNIST data""" sess = tf.Int...
"""This file implements a Node, a very simple class that simply has a left and a right child (both Nodes or None), and a value. Team: Jocelyn, Kevin, Nicholas Author: Nicholas """ from functools import total_ordering # neat trick @total_ordering # now every comparison function is defined. Neato! class Node: ...
#This file reverses the order of lines in the file so that the script can #access the draws from older to newer. Download the DownloadAllNumbers.txt #from the California Lottery site, and open it with a text editor. Remove #the top five lines of the file. Run this script, and it will dump the #file into "reversed.tx...
# セット(sets): 重複しないリスト # {}をつかう fruits = {'apple', 'peach', 'lemon', 'grapes', 'apple', 'peach'} print(fruits) # listみたいに要素の概念がないので指定するとエラーになる # print(fruits[0]) # Error # len()を使って数を取得することはできる print(len(fruits))
# 変数代入してみる a = "Hell World" print(a) ''' 命名規則 snake_case 文字から始まる 文字、数字 _(アンダースコアを使う) Case sensitive(Hellとhellは別の変数) ''' # 変数 hello = "konnichiwa" world = "sekai" print(hello + world) # format # 文字列メソッドの呼び方 print("{} {}".format(hello, world)) name = "John" print("Hey, {}!! How are you doing?".format(name)) print...
# for else fruits = ['apple', 'peach', 'grapes', 'banana'] for fruit in fruits: choice = input(f"あなたの探しているフルーツは{fruit}ですか? y/n") if choice == "y": print("好きなフルールが見つかってよかったです") break elif choice == "n": print("そうですか、、、") else: print("y/nで入力してください") else: print("ループが...
l= input().split() i=0 s=0 f=0 for i in l: if i=="True": s=s+1 if i=="False": f=f+1 if f==0: print("Not one False") elif s>=1: print("At least one True") elif s==0: print("All false")
import random toothpicks = int(input("How many toothpicks to start with? ")) onTurn = 0 while toothpicks > 0: if onTurn == 1: toTake = random.randint(1, min(3, toothpicks)) print("Computer took", toTake, "toothpicks") else: message = "Player " + str(onTurn + 1)+ " on turn, " + str(toothpicks) + " toothpicks rem...
class Rectangle: def __init__(self, width, heigth): self.width = width self.heigth = heigth def set_width(self, new_width): self.width = new_width def set_height(self, new_heigth): self.heigth = new_heigth def get_area(self): return self.width * self.heigth...
try: hours = int(input('Enter hours: ')) rate = float(input('Enter rate: ')) except: print('Error, please enter numeric input') quit() if hours > 40: total = (hours - 40) * 1.5 * rate + 40 * rate else: total = hours * rate print(f'Pay: {total}')
file_name = input('Enter file name: ') try: file_handler = open(file_name) except: print('File could not be found.') quit() count = 0 words = dict() for line in file_handler: line = line.rstrip() words_at_line = line.split() for word in words_at_line: if word in words: break w...
import re file_handler = open(input('Enter file name: ')) confidence_values = list() for line in file_handler: line = line.rstrip() confidence_val_lines = re.findall('X-.*-Confidence:\s([0-9.]*)', line) for val in confidence_val_lines: if val not in confidence_values: confidence_values...
file_name = input('Enter file name: ') try: file_handler = open(file_name) except: print(f'File not found: {file_name}') quit() domains = dict() for line in file_handler: line = line.rstrip() if not line.startswith('From'): continue words = line.split() domain = words[1].split('@')[1] # ...
""" This module defines the Player class and dictates how the player sprite will interact with other sprites, the world as well as platforms. The class also dictates gravity, movement speed, and creates the sprite animation loops. """ import pygame import sys import os from sprite_sheet import Sprite_sheet ...
test = [ [1, 2, 3, 4, 5], [12, 7, 2, 9, 1], [99, 2, 7, 1,] ] def intersection(arrays): """ And we need to compute the _intersection_, that is, numbers that exist in all lists. """ cache = {} result = [] count = 1 for arr in arrays: for i in arr: ...
#Class to store account data #Actions include Withdrawal, Deposit, and Set Balance class Account: def __init__(self, balance: int, account_name: str): self.Balance = balance self.Account_Name = account_name def Withdraw(self, balance_change): if (self.Balance - balance_change) < 0: ...
# How do I find the maximum and minimum values in an unsorted array of integers def Findmum(Arraylist): min = 999 max = 0 for i in Arraylist: maxtem = i mintem = i if max < maxtem: max ^= maxtem maxtem ^= max max ^= maxtem if min > mintem: ...
#!/usr/bin/env python """ Simple example showing node and relationship creation plus execution of Cypher queries """ from __future__ import print_function # Import Neo4j modules from py2neo import neo4j, cypher # Attach to the graph db instance graph_db = neo4j.GraphDatabaseService("http://localhost:7474/db/data/")...
"""CLI application for a prefix-notation calculator.""" from arithmetic import (add, subtract, multiply, divide, square, cube, power, mod, ) while True: equation = input(">") acceptable_operands = ["+","-","*","/","square","cube","pow","mod"] tokenized_equation = equation.split(" "...
class Temp: """ Klass för att hantera temperaturer i Kelvin, Fahrenheit och Celsius """ nollC = 273.15 nollF = 255.3722 #F-nollan i Kelvin def __init__(self): self.K = 0 #Temperatur i Kelvin def setK(self,K): ...
#convert elevator floors inp = input('Europe Floor?') usf = int(inp) + 1 print ('Europe Floor', inp, 'is','US floor', usf)
#!/usr/bin/env python # coding: utf-8 # # Desafio 1 # # Para esse desafio, vamos trabalhar com o data set [Black Friday](https://www.kaggle.com/mehdidag/black-friday), que reúne dados sobre transações de compras em uma loja de varejo. # # Vamos utilizá-lo para praticar a exploração de data sets utilizando pandas. Vo...
# Multiple Linear Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.preprocessing import LabelEncoder, OneHotEncoder from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import statsmodels.api as sm...
#!/usr/bin/env python import random __all__ = [ 'makepasswd' ] def makepasswd(length = 8, strings = None): """Generates a password The strings parameter contains a list of strings, at least one character of each string in the list is used """ strings = strings or [ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '...
from display import * from draw import * from matrix import * screen = new_screen() color = [ 0, 255, 255 ] matrix = new_matrix(4, 4) print ("matrix") print_matrix(matrix) print ("identity ") ident(matrix) print_matrix(matrix) m1 = [[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4]] print ("m1 " ) print_matrix(m1) print (...
#!/usr/bin/env python # coding: utf-8 # In[4]: # Importing the required libraries from docx import Document from docx.enum.text import WD_COLOR_INDEX # Setting input and output file names input_file=input('Enter the input file name/path') document = Document(input_file) output_file='removed_highlights.docx' color=...
num_of_rows = 0 months = 0 dates = [] profit_Loss = [] total_values = 0 avg_change = 0 max_value = 0 min_value = 0 #Import CSV data import os import csv budgetCSV = os.path.join("Resources","budget_data.csv") with open(budgetCSV) as csv_file: csv_reader = csv.reader(csv_file, delimiter=",") csv_header = ...
import random import time import os import sys number_of_correct_letters = 0 def randomize_password(password):#takes in password, spits out mixed letters output = "" while(len(password) != 0): random_pos = random.randint(0,len(password)-1)#get rand pos in string random_char = password[random_pos...
#!/usr/bin/env python """Implement PKCS#7 padding A block cipher transforms a fixed-sized block (usually 8 or 16 bytes) of plaintext into ciphertext. But we almost never want to transform a single block; we encrypt irregularly-sized messages. One way we account for irregularly-sized messages is by padding, creating a...
# encoding:utf-8 # 冒泡排序 def bubble_sort(lst): for i in range(len(lst)): found = False for j in range(1, len(lst)-i): if lst[j-1] > lst[j]: lst[j-1], lst[j] = lst[j], lst[j-1] found = True if not found: # 没有发生交换 break ...
import math import random def relatively_prime(a, b): # a > b while b != 0: temp = b b = a % b a = temp if a == 1: return True else: return False def Fermat(num): flag = True TestList = [] for i in range(30): # 产生一个整数b,满足(b,num)=1 b = ...
""" Assignment 3 Name: 陳彥呈 Student Number:109502569 Course 2020-CE1003-B """ def find_prime(n): for i in range(2,int(n/2)+2): if n%i==0: print(n,"N") return print(n,"Y") return def find_factor(n): print("1 N") for i in range(2,int(n/2)+2): if n%i==0: find_prime(i) find_prime(n) return num = int(inpu...
a = input() b = input() print("OR: ",end='') for i in range(0,len(a)): if a[i]=='1' or b[i]=='1': print("1",end='') else: print("0",end='') print("\nAND: ",end='') for i in range(0,len(a)): if a[i]=='1' and b[i]=='1': print("1",end='') else: print("0",end='') print("\nXOR: ",end='') for i in range(0,len(a))...
# Help Sofia write a decrypter for the passwords that Nikola # will encrypt through the cipher map. A cipher grille is # a 4×4 square of paper with four windows cut out. Placing # the grille on a paper sheet of the same size, the encoder # writes down the first four symbols of his password inside # the windows (see ...
"""var1 = "This is cool" var2 = 10 var3 = 20 var4 = 30 var5 = "Yeahhh" """ #print(var1+var5); #print(var2+var3+var4); #print(var1 + str(var2)); #print(10* "Hello \n") """print("Enter two number for addition"); Num1 = input() Num2 = input() print(int(Num1)+int(Num2)); print("Enter Number"); n1 = inpu...
#grosary = {"bhendi","Potato","Banana","Oil","Sugar"} #List #print(grosary) number = [2,5,9,1,6,8,4,7,8] #List print(number[0::-1]) #number.sort() #number.reverse() #number.append(10) #number.insert(2,12) #number[1] = 13 #number.pop() #print(number) #tp = (1,2,3,6,9,5,8,7) #Tupple #print(tp) ...
def palindrome(word): for i in range(0,len(word)//2): if word[i]!=word[-i-1]: return False return True print(palindrome('토마토'))
import pygame from random import choice class Cell(pygame.sprite.Sprite): w, h = 16, 16 def __init__(self, x, y, maze): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([self.w, self.h]) self.image.fill((255, 255, 255)) self.rect = self.image.get_rect() ...
from operator import add #import sys def printMatrix(matrix): for i in range(0, len(matrix)): print(matrix[i]) #Dim-Input from user while True: try: row = int(input("Number of rows: ")) break except ValueError: print("ERROR: Not a valid number") while True: try: ...
#!/usr/bin/python3 # Open mapFile, this file must already exist mapFile = open("map_file") # Empty space to hold the contents of mapFile storageLine="[" # Go line by line and retrieve contents of mapFile for mapLine in mapFile: storageLine = storageLine + '"' + mapLine.rstrip() + '",' # replaced last "," with "...
#!/usr/bin/env python # coding: utf-8 # In[4]: #!/usr/bin/env python # coding: utf-8 #The rules of Pig are simple. The game features two players, whose goal is to reach 100 points first. Each #turn, a player repeatedly rolls a die until either a 1 is rolled or the player holds and scores the sum of the #rolls (i.e....
# Enter a line of text and find the most common word counts = dict() line = raw_input("Enter a line of text: ") words = line.split() print 'Words: ', words bigcount = None bigword = None for word in words: counts[word] = counts.get(word,0) + 1 print " Total count: ",counts for word,count in counts.items(): ...
# def prima_functie(): # pass # def message(): # print("enter a value: ") # message() # def hello(name): # print('Hello', name) # name = input("Enter your name: ") # hello(name) # de cautat diferenta parametru si argument # def message(what, number='2'): # param default la final # """ # :param w...
#!/usr/bin/env python """Calculate Shannon entropy for a file or stdin""" # Python 2.x backwards compatibility from __future__ import division, print_function import sys import math def byte_count(input_file): """Count the frequency of distinct bytes in a file descriptor""" counts = [0] * 256 with input...
from move import Move # TippyMove is a subclass of Move class TippyMove(Move): ''' A move in the tippy game. amount: int -- amount to subtract from current value. ''' def __init__(self, position): ''' (TippyMove, int) -> NoneType Initialize a new TippyMove that to be marked on t...
# Script: caesar.py # Desc: encrypt and decrypt text with a Caesar cipher # using defined character set with index # Author: Scott Bean # Created: 23/9/17 """The code for the frequency analysis in caesar_crack is adapted from https://www.nayuki.io/res/automatic-caesar-cipher-breaker-javascript/automatic-c...
# Given the integer N - the number of minutes that is passed since midnight - how many hours and minutes are displayed # on the 24h digital clock? # The program should print two numbers: the number of hours(between 0 and 23) # and the number of minutes (between 0 and 59) # For example, if N = 150 minutes have passed si...
"""Module to download data from Yahoo! Finance""" import dateparser import requests from datetime import datetime from io import BytesIO import pandas as pd class YahooFinanceDownloader: """Download data from Yahoo! Finance from the start_date to the end_date""" def __init__(self, ticker, start_date, end_...
#!/usr/bin/python import sys import re n = int(sys.stdin.readline()) contacts = "" for i in range(n): [command,name] = sys.stdin.readline().strip().split(' ') if command == "add": contacts = contacts + name + "," elif command == "find": pattern = "(^|,)" + re.escape(name) print(l...
#Using python 2.3 from random import randint flag = 0 board = [] for i in range(10): board.append(["-"]*10) def print_board(board): for i in board: print " ".join(i) print_board(board) def random_row(board): return randint(0,len(board)-1) def random_col(board): return randint(0,len...
k = float(input("Digite um peso em quilogramas: ")) l = k / 0.45 print("O peso digitado é de {} quilogramas, esse peso convertido é {:.2f} libras" .format(k,l))
k = float(input("Digite uma velocidade em Kilometros: ")) m = k/3.6 print("A velocidade digitada é de {} km/h, essa velocidade convertida é {:.2f} m/s" .format(k,m))
# Generate an HTML file with user input for title and the content of a # single paragraph import webbrowser def gen_html_file(entry, title="Default Title", open_output=False): output = """<!DOCTYPE html> <html> <head> <title>{title}</title> </head> <body> <p>{...
class M_M_1(object): def __init__(self, lamda, muy): self.lamda = float(lamda) self.muy = float(muy) def isVaild(self): return self.Rho() < 1 def Rho(self): return self.lamda/self.muy def P0(self): """Xac xuat hang doi khong co khach hang""" if not self...
import random Dealer_Cards=[] Player_Cards=[] Total_Player=0 Total_Dealer=0 #Deal the cards #Dealer Cards while len(Dealer_Cards) != 2: Dealer_Cards.append(random.randint(1,11)) if len(Dealer_Cards) == 2: print("Dealer has ",Dealer_Cards) # Player Cards while len(Player_Cards) != 2: Player_Cards.a...
fruits1 = int(input('how many are your peach?')) fruits2 = int(input('how many are your apples?')) fruits = (fruits1 + fruits2) print(fruits)
#!/usr/bin/env python3 """ Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the mo...
#!/usr/bin/env python3 """ Given two strings text1 and text2, return the length of their longest common subsequence (LCS). A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" i...
#!/usr/bin/env python3 """ Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. Note: - The same word in the dictionary may be reused multiple times in the segmentation. - You may ...
#!/usr/bin/env python3 """ Given a collection of numbers that might contain duplicates, return all possible unique permutations. EXAMPLES: Input: [1,1,2] Output: [ [1,1,2], [1,2,1], [2,1,1] ] NOTE: - Work on permutation.py first. REFERENCE: - https://leetcode.com/problems/permutations-i...
#!/usr/bin/env python3 """ Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn't banned, and that the answer is unique. Words in the list of banned words are given in lowercase, and free of punctuatio...
#!/usr/bin/env python3 """ Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. EXAMPLE: Input: nums = [-1,2,1,-4], target = 1 Output: 2 E...
#!/usr/bin/env python3 """ You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where: - Each 0 marks an empty land which you can pass by freely. - Each 1 marks a building ...
#!/usr/bin/env python3 """ Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph. Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors. TECHNIQUES: - REFERENCE: - https://www.geeksforgeeks.org/clone-an-undirected-graph/ - https://...
#!/usr/bin/env python3 """ Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. Example:...