text
stringlengths
37
1.41M
import math import random import pygame class Vector(object): """ The basic 2d vector object for directions and things """ def __init__(self, x = 0, y = 0): self.x = x self.y = y def getMag(self): #Returns the magnitude of the vector return math.sqrt(self.x**2 + self.y**2) def norm(self): #Return the un...
def hard_easy(a, b): result = 0 for _ in range(abs(a)): result += abs(b) if (a < 0 and b > 0) or (a > 0 and b < 0): result = -result elif a == 0 or b == 0: result = 0 print("Only '+' and '-' operations:", result) print(" Expected:", a * b) hard_easy(...
#Devuelve la lista sin elementos repetidos def categorias_repuestos(cat): salida = [] for n in cat: if(not n in salida): salida.append(n) return salida #Devuelve el indice en el cual un elemeno se ecuentra con respecto a una lista en unos indices ya dados def faltan_por_categoria(codigo...
from BankingApp import MinimumBalanceAccount from BankingApp import Accounts from BankingApp import WithdrawAmount from BankingApp import DepositAmount from BankingApp import FundTransfer accounts = Accounts() minimum_balance = 500 fundTransfer = FundTransfer() global account def accountCreation(): global accou...
""" If 0 ≤ C[a] < 1, then (a, b) is multiplicative only if C[a] = 0 If 1 < C[a] < 2, then C[a] / (C[a] - 1) > 2, therefore C[b] > 2. So, C[b] > C[a], but this is impossible because C[a] ≥ C[b] (because the array is sorted). If C[a] > 2 then the pair is multiplicative for any C[b] where C[b] ≥ C[a] / (C[a] - 1) """ ...
surveyList = [] surveyInt = [] # Displays menu to user to select option def menu(): print("0 - Quit") print("1 - Display the menu") print("2 - Display all the survey information") print("3 - Given a department display the number of customers that answered the survey and the average result") print("...
# -*- coding: utf-8 -*- """ Created on Thu Jan 30 09:12:00 2014 @author: koenigin """ def grid_part(): """Draws the top of a 2 x 2 grid""" line = '+ - - - - + - - - - +' column = '| | |' print(line) print(column) print(column) print(column) print(column) def sma...
""" Indra Ratna CS-UY 1114 Lab 3 """ import datetime days = 0 x = input("What is your birthday in yyyymmdd form?") y = (datetime.datetime.now().strftime("%Y%m%d")) print("Your date of birth is "+x+ " and today is "+ str(y)) user_day = str(int(x)%100) user_month = x[4:6] user_year= x[0:4] today_day = str(in...
import time def countdown(n): while n>0: print(n) time.sleep(1) n-=1 if n==0: print('DONE') countdown(20)
def dictionary_of_metrics(items): """ Takes in a list of integers and returns a dictionary of the five number summary. The function returns numerical values rounded to two decimal places. Args: items: list of integers Returns: dict (dictionary): a dict with keys 'max', 'median', 'mi...
''' Assignment #3 Intro to AI: 8 Puzzle using A* Daniel Quintana Menjivar Inspired by: https://www.youtube.com/watch?v=GuCzYxHa7iA ''' import time import random import collections import itertools class Node: # reprents a Solver node def __init__(self, puzzle, parent=None, action=None): self.puzzle = puz...
def merge_sort(input_array): if len(input_array) > 1: mid = len(input_array) // 2 input_array1 = input_array[:mid] input_array2 = input_array[mid:] merge_sort(input_array1) merge_sort(input_array2) # Create indexes for the 1st sorted array, second a...
import argparse import os parser = argparse.ArgumentParser(description="""This script creates a new sqlite database, based on text_blob scores of each youtube comment.""") parser.add_argument("--src", dest="src", type=str, default="/../../../../../scratch/manoelribeiro/...
import keyword class KeyValueStorage: """Wrapper class for a file that works as key-value storage. Each key-value pair in the file is separated by "=" symbol, example: name=kek last_name=top song_name=shadilay power=9001 Values can be strings or integer numbers. If a valu...
""" Write a context manager, that suppresses passed exception. Do it both ways: as a class and as a generator. >>> with suppressor(IndexError): ... [][2] """ from contextlib import contextmanager from typing import Iterator class Suppressor: """Context manager, that suppresses passed exception. Attribut...
#define a class for a generic enemy class Enemy: # Constructor # Name - The name of the enemy # Health - How much HP the enemy currently has # Damage - How much damage the enemy can do def __init__(self, name, health, damage): self.name = name self.health = health self.damag...
# imports the function tan and pi from the math module from math import tan, pi def polysum(n, s): """ This function adds the area of a polygon to the length of a polygon returning the value with an accuracy of 4 places to the right of the decimal point. The function accepts 2 parameters. n is the nu...
#!/usr/bin/python3 # Takes in input from stdin as a csv file, reads it according to a config file, and prints to standard out a file with only data numbers, one per line, or an N if no data # The first line in output is the name # If there is an error in parsing the file, such as an out-of-bounds number, warn the user...
def y1(x): if x != 0: return 2 / x return 'NO' def y2(x): return (2 * x) + 3**x x = -5 while x >= -5 and x <= 5: print('*', end='\n') print('x = ',x) print('y1 = ', y1(x)) print('y2 = ', y2(x)) x = x + 1/2
import math x = 2 print(math.pi) if x >= -math.pi and x <= math.pi: y = math.cos(3*x) print(y) elif x < -math.pi or x > math.pi: y = x print(y)
def arifm(a, b, c): return (a + b + c)/3 uslov = input("zhelayete nachatj? (y/n)") while uslov != 'n': a = int(input('vvidite pervoje chislo a')) b = int(input('vvedite vtoroye chislo b')) c = int(input('vvedite tretje chislo c')) print(arifm(a, b, c)) uslov = input("prodolzhit? (y/n)") else:...
import random import sys import os #define classes and functions for 3 different 3D shapes class Circle(): def __init__(self, radius=1): self.__radius = radius self.display() def find_area(self): a = self.__radius * self.__radius * 3.142 return(a) def setRadius(self, rad):...
import random player_one_score = 0 player_two_score = 0 def run_game(): game_type = choose_game_type() player_one_name = set_player_name() player_two_name = set_player_name() while player_one_score < 2 and player_two_score < 2: if game_type == "1": player_one_gesture = choose_gest...
''' You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Return a list of integers representing the size of these parts. Example 1: Input: s = "ababcbacadefegdehijhklij" Output: [9,7,8] Explanation: The partition is "ababcbaca",...
''' A complex number can be represented as a string on the form "real+imaginaryi" where: real is the real part and is an integer in the range [-100, 100]. imaginary is the imaginary part and is an integer in the range [-100, 100]. i2 == -1. Given two complex numbers num1 and num2 as strings, return a stri...
''' Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1. An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others. A subsequence of a string s i...
''' A message containing letters from A-Z can be encoded into numbers using the following mapping: 'A' -> "1" 'B' -> "2" ... 'Z' -> "26" To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106"...
class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ def recursion(s,i,j): if i==j or i>j: return print("swapping : " , s[i],s[j]) ...
import numpy as np x = np.array([[1, 2], [3, 4]]) print(x) print(type(x)) y = np.array([[2, 4, 6], [8, 10, 12], [14, 16, 18]]) print(y) print(type(y)) """ Perceber o ponto após os números para forçar a troca de inteiro e decimal """ z = np.array([[1, 3], [5, 7]], dtype = float) #dtype = foat ou dtype = int print(z...
num = int(input('Enter a number: ')) assert num >= 0, "Somente números positivos" print('You entered: ', num) # Se digitar 100 >> You entered: 100 """ Se digitar menor que 0 File "22_assert.py", line 2, in <module> assert num >= 0 AssertionError: Somente números positivos """ try: num = int(input('Enter a number:...
c = 'copia de texto' # c2 NÃO é cópia, é referência de c c2 = c # ´Cópias do texto c2 = list(c) c2 = c[:] import copy c2 = copy.copy(c) lista_a = [1, 2, [3, 4]] lista_b = lista_a[:] copylista_b = copy.copy(lista_a) deepcopylista_b = copy.deepcopy(lista_a) # Subtituiu o 3 pelo 10 lista_a[2][0] = 10 print(lista_a) ...
import pandas as pd # quadros de dados fornecidos import matplotlib.pyplot as plt # suporte para plotagem df = pd.read_csv("pima-data.csv") print(df.shape) print(df.head(5)) print(df.tail(5)) print(df.isnull().values.any()) def plot_corr(df, size=11): """ Function plots a graphical c...
fibonacci = (lambda n, first=0, second=1: "" if n == 0 else str(first) + "\n" + fibonacci(n - 1, second, first + second)) print(fibonacci(10), end="") fibonacci = (lambda n, first=0, second=1: [] if n == 0 else [first] + fibonacci(n - 1, second, first + second)) print(fibonacci(10))
import functools def mult(x, y): print("x=", x, " y=", y) return x * y fact = functools.reduce(mult, range(1, 4)) print('Factorial of 3: ', fact) """ x= 1 y= 2 x= 2 y= 3 Factorial of 3: 6 """ from functools import reduce def soma(x1, x2): return x1 + x2 # Saída: 10 print(reduce(soma, [1, 2, 3, 4])) ...
try: print("try block") x=int(input('Enter a number: ')) y=int(input('Enter another number: ')) z=x/y except ZeroDivisionError: print("except ZeroDivisionError block") print("Division by 0 not accepted") else: print("else block") print("Division = ", z) finally: print("finally block"...
class person: totalObjects = 0 def __init__(self): person.totalObjects = person.totalObjects + 1 @classmethod def showcount(cls): print("Total objects: ", cls.totalObjects) p1 = person() p2 = person() person.showcount() # Total objects: 2 p1.showcount () # Total objects: 2
# 1. e 2. Digital as somas dos caracteres: soma_um = int(input ('Digitar a soma do "primeiro" com o "segundo"' + ' caracteres da senha (da esquerda para a direita) = ')) soma_dois = int(input ('Digitar a soma do "segundo" com o "terceiro"' + ' caracteres da senha (da esquerda para a direita) = ')) soma_tres = int(input...
import math def sigmoid(x): return 1 / (1 + math.exp(-x)) print(sigmoid(1.10)) # 0.7502601055951177 print(sigmoid(1.00)) # 0.7310585786300049 print(sigmoid(0.90)) # 0.7109495026250039 print(sigmoid(0.70)) # 0.6681877721681662 print(sigmoid(0.50)) # 0.6224593312018546 print(sigmoid(2.31)) # 0.9097018552970803 print...
"""Pseudo-Código Inicio digitar coeficiente_a digitar coeficiente_b digitar coeficiente_c Se a = 0 Então Se b != 0 Então Imprimir "A equação possui uma única raiz" r_um <- -c/b Imprimir r_um Senão b = 0 Então Imprimir "Indeterminação/Singul...
import functools import operator foldl = lambda func, acc, xs: functools.reduce(func, xs, acc) result = foldl(operator.sub, 0, [1, 2, 3]) print(result) # -6 result = foldl(operator.add, 'L', ['1', '2', '3']) print(result) # L123 # FOLDL Function def foldl(func, acc, xs): return functools.reduce(func, xs, acc) prin...
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] transposta = [] for i in range(len(matrix[0])): linha_transposta = [] for linha in matrix: linha_transposta.append(linha[i]) transposta.append(linha_transposta) # [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] print(transposta) transposta = ...
# Create a global variable `A`. A = 5 def impure_sum(b): # Adds two numbers, but uses the # global `A` variable. return b + A def pure_sum(a, b): # Adds two numbers, using # ONLY the local function inputs. return a + b print(impure_sum(5)) # 10 print(pure_sum(4, 6)) # 10 # Abordagem tradicio...
num_iter = int(input("Digitar o valor do número máximo para a sequência de Farey = ")) F = [] """ for i in range(1, num_iter + 1, 1 : for j in range(i, num_iter + 1, 1) : F.append(i / j) print(F) F = set(F) F = sorted(F) #Classificar o set """ i = 1 while i <= num_iter: j = i while j <= ...
def LineCounter(filename): with open(filename, 'r') as f: return [line for line in f] def count(lines): return len(lines) arquivo = LineCounter('nome_errado.txt') print(count(arquivo)) # 7 print(arquivo) # ['Toque Frágil (Walter print(count(arquivo)) # 7 print(arquivo) # ['Toque Frágil (Walter
from tkinter import * window = Tk() btn = Button(window, text="This is Button widget", fg='blue') btn.place(x=80, y=100) lbl = Label(window, text="This is Label widget", fg='red', font=("Helvetica", 16)) lbl.place(x=60, y=50) txtfld = Entry(window, text="This is Entry Widget", bd=5) txtfld.place(x=80, y=150) window.ti...
import numpy as np import matplotlib.pyplot as plt a = -1 b = -2 c = -15 x = np.arange(-10, 10, 0.01) print(x) print(type(x)) f = a * x ** 2 + b * x + c print(f) print(type(f)) plt.plot(x, f, color="g", marker="*", linestyle="--") plt.xlabel("x") plt.ylabel("f") plt.title("Função Quadráti...
import math as mt x = float(input("Digitar o valor da tangente: ")) n = int(input("Digitar o valor para a quantidade de termos da séria Taylor-MacLaurin: ")) inicio = 1 passo = 2 radianos = 0 k = 2 #variável auxiliar para alternar o valor do sinal do coeficiente """ O parâmetro final 2 * n é para dar a posssibilida...
r = range(10) print(r) # Python 3 range(0, 10) Lazy evaluation # Python 2.x [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(r[3]) # 3 """ # Python 2.x r = xrange(10) print(r) # xrange(10) lst = [x for x in r] print(lst) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] """ numbers = range(10) iterator = iter(numbers) print(numbers) # range(0,...
# -*- coding: utf-8 -*- """ Lecture 3 - Introduction into AI Programming with Python @author: Dominik Jung (dominik.jung42@gmail.com) """ # Dataframes with pandas import pandas as pd speed = [290, 330, 345] car = [718, 911, 918] df = pd.DataFrame() df["CAR"] = car df["SPEED"] = speed df.loc[1:] df.loc[2] df.loc[:, ...
# 입력 값을 변수 두개에 저장하기 a, b = input('문자열 두개를 입력하세요: ').split() print(a) print(b) a = int(a) b = int(b) print(a + b) print(int(a) + int(b)) a, b = map(int, input('숫자 두 개를 입력하세요: ').split()) print(a + b)
grade = int(input()) if grade >= 90: print("A") elif grade <90 and grade >=80: print("B") elif grade <80 and grade >= 70: print("C") elif grade <70 and grade >= 60: print("D") elif grade <60: print("F")
def outerfunc(a,b): def innerfunc(): sum=a+b return sum moresum = innerfunc()+8 return moresum result = outerfunc(5,10) print(result)
#CSI31 Sabina Akter convert.py #A program to convert Celsius temps to Fahrenheit def intro (): print("This program converts Celsius tempurature to fahrenheit tempurature.") print() return def main(): intro() for i in range(5): celsius= eval(input("What is the Celsius temperature...
#CSI31 Sabina Akter convert.py #A program to converts distances measured in kilometers to miles def intro (): print("This program converts kilometer to miles.") print() return def main(): intro() k = eval(input(" What is the distance in kilometers?")) m= 0.62* k print() ...
"""JonathanBalewiczA2Q1 COMP 1012 SECTION A01 INSTRUCTOR Bristow ASSIGNMENT: A2 Question 1 AUTHOR Jonathan Balewicz VERSION 2018-02-03 PURPOSE: Calculate Statistics of the average dietary energy supply adequacy percentage """ mean=0 entries=0 print("Summarizing <foodData.csv>") file=open("foodData.csv") headers=f...
- Python Lesson 1 - By Karl Brown Here is a series of shorthand tutorials to help individuals learn Python. I will be improving them as more individuals attempt them, and extending them as interest forces me to reach the end of my lessons. - Tools - http://learnpython.org/ - Guide that helps me progress my lessons h...
class Agent(): # return an index of a chosen move def move(self, state): return NotImplementedError('Class {} does not implement move()'.format(self.__class__.__name__)) # return a list of valid indices def valid_moves(self, state): valid = [] for i in range(0, 8): ...
def judge_sum(non_a_sum, a_num): if a_num == 0: return non_a_sum, 0 else: maxsum = non_a_sum + a_num need_eleven = 0 # 尝试所有A能否取11 for i in range(a_num + 1): temp = non_a_sum + i * 11 + (a_num - i) if temp > 21: break if ...
number = int(input()) command = [] for i in range(number): command.append(input()) command.sort() test = input() for item in command: if item[0:len(test)] == test: print(item)
names={'Mike':95, 'Bob':77, 'Ken':89} print(names) print(names['Bob']) #用key赋值 names['Adam']=67 print(names) #刷新 names['Adam']=68 print(names) #key不存在的情况 if 'Thomas'in names: print(names['Thomas']) print(names.get('Thomas')) print(names.get('Thomas', -1)) #删除key print(names) print(names.pop('Bob')) print(names)
number = 0 number = int(input()) students = {} while number != 0: temp = input().split() choice = int(temp[0]) if choice == 1: if temp[1] in students: print('Students already exist') else: students[temp[1]] = (temp[2], int(temp[3]), int(temp[4]), int(temp[5])) ...
class Restaurant: def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurant(self): print('Restaurant\'s name is: ' + self.restaurant_name + '\nCuisine_type is: ' + se...
######################################################### # Fred14 Setup the Left Arm Servos ######################################################### # We will be using the following services: # Servo Service ######################################################### # I Fred's Left Arm, we have the Bicep Rota...
from cs50 import get_int height = get_int("height: ") while True: if height > 0 and height <= 8: break else: height = get_int("height: ") line = height while (line != 0): for l in range(line - 1): print(" ", end="") for j in range(height - (line - 1)...
first = float(input("Enter first Number => ")) sec = float(input("Enter Second Number => ")) opr = str(input("Enter Operation (+, -, *, /) => ")) if opr == "+": total = first + sec elif opr == "-": total = first - sec elif opr == "*": total = first * sec elif opr == "/": total = first / sec ...
class Employee: raise_amount = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' # method def fullname(self): return '{} {}'.format(self.first, self.last) def ap...
#sets: A set is an unordered collection with no duplicate elements #membership testing and eliminating duplicate entries showroom = {'Acura', 'BMW', 'Honda', 'Toyota'} print(len(showroom)) print("----------Showroom Length---------------") showroom.add('Acura') print(showroom) print("----------Showroom Add Acura-----...
def function1(): print "Hi. I'm function 1." def function2(): print "Hi. I'm function 2." def function3(): print "Hi. I'm function 3" def error_function(): print "Invalid Option" def test1(): while 1: code = raw_input('Enter "one", "two", "three", or "quit": ') if code=...
import os # VALIDOR EN CONSUMO DE GOLOSINAS # MOSTRAR VALORES catidad_caramelos=0 precio_caramelo=0.0 cantidad_chupetines=0 precio_chupetin=0.0 cantidad_galletas=0 precio_galleta=0.0 # INPUT catidad_caramelos=int(os.sys.argv[1]) precio_caramelo=float(os.sys.argv[2]) cantidad_chupetines=int(os.sys.argv[3]) precio_chupe...
import os # VALIDOR EN TRIANGULO RECTANGULO # MOSTRAR VALORES cat1=0.0 cat2=0.0 # INPUT cat1=float(os.sys.argv[1]) cat2=float(os.sys.argv[2]) # OUTPUT print(cat1) print(cat2) # PROCESSING import math hipotenusa= math.sqrt(cat1**2+cat2**2) print("hipotenusa=", hipotenusa) # CONDICIONAL MULTIPLE # si en la hipotenusa...
import os # MOSTRAR VALORES nombre="" t_grado_fahrenheit=0.0 # INPUT nombre=os.sys.argv[1] t_grado_fahrenheit=float(os.sys.argv[2]) # OUTPUT print("################################") print(" TEMPERATURA DE UNA PERSONA ") print("################################") print("NOMBRE:", nombre) print("TEMPERATURA EN GRAD...
import os # TRIANGULO RECTANGULO # MOSTRAR VALORES cat1=0.0 cat2=0.0 # INPUT cat1=float(os.sys.argv[1]) cat2=float(os.sys.argv[2]) # PROCESSING import math hipotenusa= math.sqrt(cat1**2+cat2**2) # OUTPUT print(cat1) print(cat2) # VERIFICADOR triangulo=(hipotenusa>6.0) # CONDICION DOBLE # si el la hipotenusa es may...
import os # ASISTENCIAS A CLASES # MOSTRAR VALORES estudiante="" asistencia1=0 asistencia2=0 asistencia3=0 asistencia4=0 asistencia5=0 asistencia6=0 asistencia7=0 asistencia8=0 # INPUT estudiante=os.sys.argv[1] asistencia1=int(os.sys.argv[2]) asistencia2=int(os.sys.argv[2]) asistencia3=int(os.sys.argv[2]) asistencia4=...
import speech_recognition as sr from time import ctime import time import os from gtts import gTTS def speak(audioString): print(audioString) tts = gTTS(text=audioString, lang='en') tts.save("audio.mp3") os.system("mpg321 audio.mp3") def recordAudio(): # Record Audio r = sr.Recognizer() w...
lista=[] num1=int(input( " digite um numero")) lista.append(num1) num2=int(input(" digite outro numero")) lista.append(num2) a= max(lista) b= min(lista) c = a%b lista.append(c) while lista[len(lista)-1] != 0: d = lista[len(lista)-2] % lista[len(lista)-1] lista.append(d) print (" O Mdc entre %s...
import sys from termcolor import colored, cprint import time import random while True: print("="*40) print(" JOGO JUNKENPO - AUTOR -- dougras") print("="*40) a = int(input(" Digite \n\n 0 pedra \n 1 para papel \n 2 para tesoura\n")) if a == 0 : a = "pedra" e...
# K-Nearest-Neighbor dient zur Klassifizierung (Algorithmus) import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from helper import plot_classifier df = pd.read_csv("classification.csv") # Welche S...
num=int(input('enter the number'))#564 result=0 while(num!=0): digit=num%10#4 result=result*10+digit num=num//10 print(result)
# limit=int(input('enter the limit')) # lst=lst() # for i in range(1,limit+1): # lst.append(i) # print(lst) limit=int(input('enter the limit')) lst1=list() lst2=list() for i in range(1,limit+1): if (i%2==0): lst1.append(i) else: lst2.append(i) print(lst1,lst2)
class person: def person_1(self,name,age,gender): self.name=name self.age=age self.gender=gender def printperson(self): print('name',self.name) print('age',self.age) print('gender',self.gender) obj=person() obj.person_1('ajay',24,'male') obj.printperson() obj...
num=int(input('enter num')) def fact(num): fact=1 for i in range(1,(num+1)): fact=fact*i print(fact) fact(num)
num=int(input('ENTER THE NUMBER')) sum=0 i=1 res=0 while(i<=num): res=num+10*res sum+=res i+=1 print(sum)
first=[1,2,3] second=[4,5,6] pairs=[(i,j) for i in first for j in second] print(pairs) #squares squares=[i**2 for i in first] print(squares) #connditioning using list comprehension fir=[1,2,3,4,5,6,7] data=[i-1 if i<5 else i+1 for i in fir] print(data) #using elif data=[i+1 if i>5 else i-1 if i<5 else 5 for i in f...
employees={101:{'empid':101,'name':'raju','designation':'mech','salary':15000},102:{'empid':102,'name':'ramu','designation':'mech','salary':25000},103:{'empid':103,'name':'riju','designation':'ec','salary':35000},104:{'empid':104,'name':'roju','designation':'eee','salary':10000}} count=1 for i in employees: # print...
""" ====================================================================================== Probability, Paradox, and the Reasonable Person Principle http://nbviewer.jupyter.org/url/norvig.com/ipython/ProbabilityParadox.ipynb Vocabulary: P(E, D) The probability of event E, given probability distribution D d...
from collections import Counter, deque import random import matplotlib.pyplot as plt from prob_intro import ProbDist ## The board: a list of the names of the 40 squares ## As specified by https://projecteuler.net/problem=84 board = """GO A1 CC1 A2 T1 R1 B1 CH1 B2 B3 JAIL C1 U1 C2 C3 R2 D1 CC2 D2 D3 ...
def memoize(f): value = None has_value = False def memoized(): nonlocal value, has_value if has_value: return value value = f() has_value = True return value return memoized
#Dictionary to store the roman numerals and arabic equivalents roman = {'I':1, 'V':5, 'X': 10, 'L':50, 'C':100, 'D':500,'M':1000} print("This takes a user input Roman numeral and converts to equivalent Arabic Numeral") conv = list(input("\nEnter Roman Numeral to convert [ROMAN NUMERAL IN ALL CAPS]! \n")) sum = ...
l = [1,5,2,8,5,8,3,3,10,11] # to test def merge(arr, l, mid, r): n1 = mid -l +1 n2 = r - mid #cretae temp arrays L = [0 for i in range(n1)] R = [0 for i in range(n2)] #copy data to L and R for i in range(0, n1): L[i] = arr[l+i] for i in range(0, n2): R[i] = arr[mid+1+i] # Merge temp arrays back i=...
name = input("name:") age=int(input("age:")) #下行出错 age是数字型,不能与字符串相加 #print("Information of Name "+name+" \nName:"+name+"\nAge:"+age) print("Information of Name %s \nName:%s\nAge:%s" %(name,name,age)) msg = ''' Information of Name %s Name:%s Age:%d ''' %(name,name,age) print(msg) msg = ''' Information of Name %s Name:%s...
def find_number_of_bits(number: int) -> int: bits = 0 while number: number >>= 1 bits += 1 return bits
import random import warnings warnings.filterwarnings("ignore") # rand_arr=[] rand_arr = [5,4,3,2,1] # for _ in range(100): # rand_arr.append(random.uniform(0.0,1.0)) ctr_swap=0 ctr_comp=0 def insertion(arr): for index in range(1,len(arr)): currentvalue = arr[index] position = index while position>0 and ar...
""" Name : Raghav Dev Kukreti Group : B1 Roll No : 2017082 Python code to calculate rank of a matrix. """ # Formulate the matrix of dimension MxN def create_matrix(m, n): matrix = [] for i in range(0,m): matrix.append([]) for j in range(0,n): matrix[i].append(int(input('Enter element at (...
"""Description: Given an input of an array of digits num, return the array with each digit incremented by its position in the array. For example, the first digit will be incremented by 1, the second digit by 2 etc. Make sure to start counting your positions from 1 and not 0. incrementer([1,2,3]) => [2,4,6] Your re...
#Title screen function def titleScreen(): hangmanWord = """ _ _ | | | | | |__| | __ _ _ __ __ _ _ __ ___ __ _ _ __ | __ |/ _` | '_ \ / _` | '_ ` _ \ / _` | '_ \ | | | | (_| | | | | (_| | | | | | | (_| | | | | |_| ...
""" Just an implementation of linear search. """ import timing import search_in def linear_search(list, value): """ Searches for a value in a list linearly! """ for i, val in enumerate(list): if (val == value): print(">> Found {} in the list at index {}.".format(value, i)) ret...
# # @lc app=leetcode.cn id=9 lang=python3 # # [9] 回文数 # # https://leetcode-cn.com/problems/palindrome-number/description/ # # algorithms # Easy (56.00%) # Total Accepted: 78.2K # Total Submissions: 139.6K # Testcase Example: '121' # # 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 # # 示例 1: # # 输入: 121 # 输出: true # #...
import re import convertToMiles import convertToKilometers class Convert: def __init__(self):() def convert(self, distance, unit): if unit == convertToKilometers.kilometerUnit: return self.convertMiles(distance) elif unit == convertToMiles.milesUnit: return self.convertKilometers(distance) else: retur...
# Modify your student dictionary program from lists_tuples_dictionaries/dictionaries3.py # so that it is two separate programs. One should create the data and store it, while the # other should load the data and use it. Note that you can dump or load the entire # dictionary at once using pickle. import pickle prin...
# This exercise extends the username check program from usinglists3.py. # Write a program which maintains a list of usernames. It should # repeatedly show a menu with the following options: # Add a new username to the list # Read in a name and check whether it is in the list # Read in a name and append it t...