text
stringlengths
5
121k
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="", database="Sunway" ) print(mydb) mycursor = mydb.cursor() mycursor.execute("SHOW TABLES LIKE 'students'") result = mycursor.fetchone() if result: print("Table exists") else: mycursor.execute("CREATE TA...
x=int(input("enter first number")) y=int(input("enter second number")) sum_of_numbers = x+y print("the sum is: {}" .format(sum_of_numbers))
""" Demonstrates how numbers can be displayed with formatting. The format function always returns a string-type, regardless of if the value to be formatted is a float or int. """ amount_due = 15000.0 monthly_payment = amount_due / 12 print("The monthly payment is $", monthly_payment) print("The monthly payment is $...
""" Demonstrates a Loop and a Half """ while True : entry = input("Enter the value z: ") if entry == "z" : break print("Thank you!") print() """ #Creates an infinite while loop while True: #Declares a variable named userNum and prompt the user #to enter a number between 1 and 10. #Assign...
""" Demonstrates converting ints and floats. Uncomment the other section to demonstrate the conversion of float data to int data. """ int_value1 = 35 float_value1 = float(int_value1) print(int_value1) print(float_value1) print() """ #Declares a variable named float_value2 and assigns it the value 23.8...
import tkinter import tkinter.messagebox def main() : test_window = tkinter.Tk() test_window.wm_title("My Window") test_button = tkinter.Button(test_window, text="Click Me!", command=showdialog) test_button.pack(...
""" Tire Object. """ class Tire() : def __init__(self, pressure_in, radius_in) : self.pressure = pressure_in self.radius = radius_in def getpressure(self) : return self.pressure def setpressure(self, pressure_in) : if isinstance(pressure_in, int) : if pressure_in >= 0 and press...
""" Demonstrates what happens when you change the value of a parameter. """ def main(): value = 99 print("The value is", value) changeme(value) print("Back in main the value is", value) def changeme(arg): print("I am changing the value.") arg = 0 print("Now the value is", arg) main()
""" Demonstrates returning values from functions """ def main() : num1 = int(input("Enter a number: ")) num2 = int(input("Enter another number: ")) total = printsum(num1, num2) print("The total is", total) def printsum(x, y) : return x + y main()
""" Demonstrates arithmetic with mixed ints and floats. Uncomment each section to demonstrate different mixed number operations. """ value1 = 10 value2 = 20 total1 = value1 + value2 print(total1) print() """ #Declares a variable named value3 and assigns it the value 90.5 value3 = 90.5 #Declares a var...
import tkinter def main() : test_window = tkinter.Tk() test_window.wm_title("My Window") test_entry = tkinter.Entry(test_window, width=10) test_entry.pack() tkinter.mainloop() main()
def average_len(records): """Returns the average len for records""" RecordLength = [len(i) for i in records] return sum(RecordLength) / len(RecordLength) def average_len_taxa(records, depth): """Returns the average length for the top level taxa""" if depth is None: depth = int(0...
print("Hi, i will check all singns in value.") some_value = input("Please enter value (as integer):") signs_list = [] for one_sign in some_value: signs_list.append(one_sign) print(f"Total list is: {signs_list}") for one_sign in some_value: print(f"{one_sign} => {int(one_sign) * '@'}")
python_version = 3.8 print("Hi, I want to say hello to you!") name = input("Please, give me your name:") print(f"Welcome {name}, my name is Python (version {python_version}).")
def DynamicProgrammingSingleSellProfit(arr): if len(arr) == 0: return 0 profit = 0 cheapest = arr[0] for i in range(1, len(arr)): cheapest = min(cheapest, arr[i]) profit = max(profit, arr[i] - cheapest) ...
class Node: def __init__(self,data): self.__data=data self.__next=None def get_data(self): return self.__data def set_data(self,data): self.__data=data def get_next(self): return self.__next def set_next(self,next_node): ...
class Stack: def __init__(self,max_size): self.__max_size=max_size self.__elements=[None]*self.__max_size self.__top=-1 def is_full(self): if(self.__top==self.__max_size-1): return True return False def is_empty(self): if(s...
''' Created on Feb 21, 2019 @author: vijay.pal01 ''' def find_new_salary(current_salary,job_level): if(job_level==3): new_salary = 0.15*current_salary + current_salary elif(job_level==4): new_salary = 0.07*current_salary + current_salary elif(job_level==5): new_...
''' Created on Mar 14, 2019 @author: vijay.pal01 ''' class Node: def __init__(self,data): self.__data=data self.__next=None def get_data(self): return self.__data def set_data(self,data): self.__data=data def get_next(self): return...
''' Created on Mar 21, 2019 @author: vijay.pal01 ''' def build_index_grid(rows, columns): result_list = [] for i in range(rows): list1 = [] for j in range(columns): list1.append(str(i)+","+str(j)) result_list.append(list1) return result_list ...
''' Created on Mar 20, 2019 @author: vijay.pal01 ''' def count_decoding(digit_list): n=len(digit_list) count = [0]*(n+1) count[0]=1 count[1]=1 for i in range(2, n+1): count[i] = 0 if(digit_list[i-1] > 0): count[i] = count[i-1] if(di...
''' Created on Feb 21, 2019 @author: vijay.pal01 ''' def make_amount(rupees_to_make,no_of_five,no_of_one): five_needed=rupees_to_make//5 one_needed=rupees_to_make%5 if(five_needed<=no_of_five and one_needed<=no_of_one): print("No. of Five needed :", five_needed) print("No. of One...
''' Created on Mar 12, 2019 @author: vijay.pal01 ''' class Customer: def __init__(self,customer_name,quantity): self.__customer_name=customer_name self.__quantity=quantity def validate_quantity(self): if(self.__quantity in range (1,6)): return True ...
''' Created on Mar 18, 2019 @author: vijay.pal01 ''' def find_unknown_words(text,vocabulary): list1 = [] text = text.split() for i in text: if i not in vocabulary: list1.append(i) if(len(list1)!=0): return set(list1) else: return -1 text...
def list_details(lst): print("Present size of the list:") print("Size:", len(lst)) lst.append("Mango") lst.append("Banana") lst.append("Apple") print("\nSize of the list after adding some items") print("Size:", len(lst)) print("\nInserting a new item at the...
''' Created on Mar 5, 2019 @author: vijay.pal01 ''' class Customer: def __init__(self): self.customer_name = None self.bill_amount = None def purchases(self): bill_amount = self.bill_amount amount = 0.95*bill_amount return amount def pays_bill(self,a...
''' Created on Feb 21, 2019 @author: vijay.pal01 ''' def convert_currency(amount_needed_inr,current_currency_name): current_currency_amount=0 if(current_currency_name=="Euro"): current_currency_amount = 0.01417*amount_needed_inr elif(current_currency_name=="British Pound"): ...
''' Created on Mar 6, 2019 @author: vijay.pal01 ''' class Flower: def __init__(self): self.__flower_name = None self.__price_per_kg = None self.__stock_available = None def get_flower_name(self): return self.__flower_name def get_price_per_kg(self): ...
def find_product(num1,num2,num3): product=0 if(num1==7): product = num2*num3 elif(num2==7): product = num3 elif(num3==7): product = -1 else: product = num1*num2*num3 return product product=find_product(7,6,2) print(product)
''' Created on Feb 21, 2019 @author: vijay.pal01 ''' def calculate_loan(account_number,salary,account_balance,loan_type,loan_amount_expected,customer_emi_expected): eligible_loan_amount=0 bank_emi_expected=0 eligible_loan_amount=0 if(account_balance>=100000): if(account_...
a=eval(input("enter a list")) n=len(a) num=int(input("a number to find")) beg=0 end=n-1 for beg in range(0,end+1): mid=(beg+end)//2 if num==a[mid]: flag=1 break elif num<a[mid]: end=mid-1 flag=0 elif num>a[mid]: ...
s=input() a=[] for i in s: a.append(i) a.reverse() listToStr = ''.join(map(str, a)) if(s== listToStr): print("Pallindrome") else: print("Not a Pallindrome")
def Fibonacci_Loop(number): old = 1 new = 1 for itr in range(number - 1): tmpVal = new new = old old = old + tmpVal return new def Fibonacci_Loop_Pythonic(number): old, new = 1, 1 for itr in range(number - 1): new, old = old, old + new return new print(Fib...
grades = ['A', 'C', 'E', 'F', 'F', 'B', 'D'] def remove_fails(grade): return grade != 'F' print([grade for grade in grades if grade !='F'])
"""Practice with dictionaries.""" __author__ = "730389910" def invert(first: dict[str, str]) -> dict[str, str]: """Inverts a dictionary.""" switch: dict[str, str] = {} for key in first: value: str = first[key] switch[value] = key return switch def favorite_color(colors: dict[...
"""Unit tests for dictionary functions.""" from exercises.ex06.dictionaries import invert, favorite_color, count __author__ = "730389910" def test_invert_one() -> None: """Test for first.""" tester: dict[str, str] = {} assert invert(tester) == {} def test_invert_two() -> None: """Test for seco...
from typing import List class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ if not matrix: return row = len(matrix) col = len(matrix[0]) is_sign = False for...
class Solution(object): def replaceSpace(self, s): """ 时间复杂度和空间复杂度都是O(n) """ list_s = list(s) original_end = len(s) n_space = 0 for ss in s: if ss == ' ': n_space += 1 list_s += ['0'] * 2 * n_sp...
''' ----------------------------------- Capture Trajectory Demonstrations from a Pointer Device ​ Usage: 1- run the file 2- press mouse left-button and hold 3- start drawing 4- release mouse left-button to stop 5- program shows the captured data 6- use terminal to save data ​ ​ Author: Reza A...
''' Exposes a class and three functions that perform an amazing calculation based on user inputs. ''' def add_two_then_square(value): return 2 + value * value def plus_ten(value): return value + 10 def subtract_one(value): return value - 1 class FormulaRunner: def __init__(self, input): se...
''' FileName: convert_input_to_set.py Author: John Delgado Created Date: 8/7/2020 Version: 1.0 Initial Development This will take the sys.stdin input and convert it into a set and then return the set ''' def convert_input_to_set(inputVales,debug): if(not inputVales): raise Exception("Input is empty. Ple...
def format_player_list(players): if players.online == 0: return "There is currently nobody online" if players.max: result = f"There are {players.online}\{players.max} players online" else: result = f"There are {players.online} players online" if players.sample: plist = ...
def calculateTotalSavings(month,pastSavings): if(month in pastSavings): return pastSavings[month] else: total=calculateTotalSavings(month-1,pastSavings)+calculateTotalSavings(month-2,pastSavings) pastSavings[month]=total return total noOfMonths=int(input()) pastSavings={} pastSavings...
from flask import Flask, render_template, request app = Flask(__name__,template_folder="./src/views") @app.route("/",methods = ["GET", "POST"]) def home(): if(request.method == "GET"): return render_template('index.html') else: if(request.form["input1"] != "" and request.form["input2"] != "")...
def main(): from numpy import random num1 = random.randint(100) num2 = random.randint(100) print(num1, '+', num2, '= ___ ') correctAnswer = num1 + num2 userAnswer = getUserAnswer() checkAnswer(userAnswer, correctAnswer...
import sqlite3 conn = sqlite3.connect("my.db") c = conn.cursor() c.execute("DROP TABLE IF EXISTS cities") c.execute('''CREATE TABLE cities (rank integer, city text, population integer)''') c.execute('INSERT INTO cities VALUES(?, ?, ?)', (1, '상하이', 2415000)) c.execute('INSERT INTO cities VALUES(:rank, :city, :po...
from bs4 import BeautifulSoup html = """ <html> <head> <title>The Dormouse's story</title> </head> <body> <h1>this is h1 area</h1> <h2>this is h2 area</h2> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters <a href="http://example.com/elsie" class="sister...
t = 'ABCDEF' for c in t: print('EX1-1 - ', c) print() w = iter(t) while True: try: print('EX1-2 - ', next(w)) except StopIteration: break print() from collections import abc print('EX1-3 - ', hasattr(t, '__iter__')) print('EX1-3 - ', isinstance(t, abc.Iterable)) print() print() ...
inputList = [] fileName = ".\\adventofcode2018\\Day1\\input.txt" def calibrateOutput (input, output): output = output + input return output; def findRepeatedFrequency(providedList): processedList = {0} frequency = 0 while True: for change in providedList: frequency ...
s1 = {1, 2, 3, 4, 5} s2 = {5, 6, 7, 8} s3 = {9, 10, 11} print(s1.isdisjoint(s2)) print(s1.isdisjoint(s3)) print(s2.isdisjoint(s3))
s = 'vwmfkxdz' temp = "" total = "" for i in range(len(s)-1): if len(temp) == 0: temp = s[i] if temp[-1] <= s[i+1]: temp += s[i+1] if temp == s: total = temp if len(s) == i + 2 and len(temp) > len(total): total = temp else: if len(temp) > le...
""" Helper function to apply reduction for each column of the dataframe grouped by a key. Example of call: grouped_df = original_df.groupby('some_column') aggregating_functions = [ (['column1'], np.mean, (['column2', 'column3'], sum), ([('column_name_new_df', 'column_4_from_original_df'), ('column_name_...
''' Names / Email: Carlos Diaz cdiaz29@students.kennesaw.edu College of Computing and Software Engineering Department of Computer Science --------------------------------------------- CS4308: CONCEPTS OF PROGRAMMING LANGUAGES SECTION W01 – SPRING 2020 --------------------------------------------- Module 4 ...
import nltk nltk.download('stopwords') nltk.download('punkt') nltk.download('wordnet') from nltk.corpus import stopwords from nltk import word_tokenize import string from nltk.stem.wordnet import WordNetLemmatizer lemmatizer = WordNetLemmatizer() punct = set(string.punctuation) stop_word_list = set(stopwords.words('en...
class Solution: def kidsWithCandies(self, candies, extraCandies): candies = [2,3,5,1,3] extraCandies = 3 max_candy = max(candies) for index in range(len(candies)): if candies[index] + extraCandies >= max_candy: yield True ...
import random import heapq as pq import heapq def check_neighbors(x1_change, y1_change, snake_block): if (x1_change > 0) and (y1_change == 0): x1_change = 0 y1_change = snake_block elif (x1_change == 0) and (y1_change > 0): x1_change = -snake_block y1_change = 0 elif (x...
class Solution(object): def pal_perm(): input = "Tact Coa" count = {} for x in input.lower(): if x != " " and x in count: count[x] = count[x] + 1 elif x != " " and x not in count: count[x] = 1 odd_count = 0 ...
import commonAOC from collections import Counter import string inputDataFile = commonAOC.loadInputData("d2.txt") total2count = 0 total3count = 0 for line in inputDataFile: count2 = False count3 = False counter = Counter(line) for k in string.ascii_lowercase: letterCount = counter[k] ...
from Crypto.Hash import SHA256 import binascii def create_test_file(): rawhex1 = b'\x11'*1024 rawhex2 = b'\x22'*1024 rawhex3 = b'\x33'*1024 rawhex4 = b'\x44'*773 e1 = open('b1','wb') e2 = open('b2','wb') e3 = open('b3','wb') e4 = open('b4','wb') t1 = open('test11223344','wb') ...
def string_split(): string="a=b;c=d;e=f;g=h" split1=string.split(";") split2=[] for i in split1: convertor1=str(i) convertor2=convertor1.split("=") convertor2=tuple(convertor2) split2.append(convertor2) return split2 print(string_split())
import time consume=2 snooze=10 print("Eating %s GB ..." % consume) str1="@"*1024*1024*1024*consume print("sleeping %s seconds ..." % snooze) time.sleep(snooze) print("All Done")
""" Input The first input line contains a single integer n (1 ≤ n ≤ 1000) — the number of problems in the contest. Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second numbe...
import matplotlib.pyplot as plt from numpy.random import rand import pandas def createData(data_points, filename): if data_points < 5: data_points = data_points * 5 x = rand(data_points, 2) df = pandas.DataFrame(data=x, columns=['x', 'y']) df.to_csv(filename) print("Erzeugte Daten wurden in " + filename +...
def stringMultiply(str): res = '' for i in range(0, len(str), 2): num = int(str[i+1]) for j in range(num): res += str[i] return sorted(res) print(stringMultiply("c4b3g6h1")) print(stringMultiply("f4g5c2n6o2"))
from tkinter import * from counting_polyominos import counting_poly root = Tk() e = Entry(root, width=50) e.pack() def click(): num = e.get() fixed_num = counting_poly({(0, 0)}, set(), [], int(num)) - counting_poly({(0, 0)}, set(), [], int(num)-1) label1 = Label(root, text="fixed("+str(num)+") = " + str...
""" Created on Sat Nov 9 19:21:00 2019 @author: abdullah """ def look_and_say(n): ''' time complexity ~ O(n x 2^n) ''' def next_number(s): result, i = [], 0 while i < len(s): count = 1 while i + 1 < len(s) and s[i] == s[i + 1]: i += 1 ...
""" Created on Wed Nov 6 20:18:28 2019 @author: abdullah """ class BinaryTreeNode: def __init__(self, value, left, right): self.value = value self.left = left self.right = right def generate_binary_trees(num_nodes): """ input: number of nodes in a binary tree output...
""" Created on Wed Nov 6 20:06:57 2019 @author: abdullah """ def generate_power_set(input_set): """ input: a set output: power set of the input set (all subsets of the input set) time complexity ~ O(n x 2^n) space complexity ~ O(n x 2^n) """ def directed_power...
""" PYTHON BASICS PRACTICE Author: Murphy Studebaker Week of 09/02/2019 --- Non-Code Content --- WRITING & RUNNING PROGRAMS Python programs are simply text files The .py extension tells the computer to interperet it as Python code Programs are run from the terminal, which is a low level interaction with the c...
soma = 0 for values in range(11): num = int(input("Digite o numero: ")) soma = soma + num print(f'{soma}')
par = 0 soma = 0 for values in range(50): par = par + 2 print(par) soma = soma + par print(soma) print(soma)
num = int(input('Digite o numero com 3 digitos: ')) primeiro_numero = num % 10 resto = num // 10 segundo_numero = resto % 10 resto = resto //10 terceiro_numero = resto % 10 print(f'{primeiro_numero}{segundo_numero}{terceiro_numero}')
x = int(input("Digite o numero: ")) quarto_numero = x % 10 resto = x // 10 terceiro_numero = resto % 10 resto = resto // 10 segundo_numero = resto % 10 resto = resto // 10 primeiro_numero = resto % 10 print(f'{primeiro_numero}\n{segundo_numero}\n{terceiro_numero}\n{quarto_numero}')
x = int(input('Digite um numero inteiro: ')) print(x)
import math x = float(input("Digite o valor de x: ")) y = float(input("Digite o valor de y: ")) r = math.sqrt(x ** 2 + y ** 2) print(r)
l = [1, 2, 3, 4, 5] even = [x for x in l if x % 2 == 0] print(even) g = lambda x: x**2 print(g(4)) print(dir(l)) class Person(): def __init__(self, name, surname): self.name = name self.surname = surname def __str__(self): return self.name + " " + self.surname def get_name(self):...
def trapezoid(f,a,b,n): ''' Input: f: Function to integrate a: Beginning point b: End point n: Number of intervals. Output: Numerical approximation to the integral ''' assert(b > a) h = float(b-a)/n result = (f(a) + f(b))/2.0 for k in range(1,n): result...
n = input('Enter your full name: ') if n == ('a') or ('e') or ('i') or ('o') or ('u'): n = n.replace('a','') n = n.replace('e', '') n = n.replace('i','') n = n.replace('o','') n = n.replace('u','') if n == ('A') or ('E') or ('I') or ('O') or ('U'): n = n.replace('A','') ...
class Navi(): def __init__(self, x, y): self.x = x self.y = y def newPos(self, x1, y1): self.x = x1 self.y = y1 dot = Navi(0,3) import numpy as np a = [[0,0,0,1,0,0,0,0,0,0], [0,1,1,1,1,1,1,1,1,0], [0,1,0,0,0,0,1,0,1,0], [0,1,1,1,0,1,1,0,1,...
import random class Student(object): """Represents a student.""" def __init__(self, name, number): """All scores are initially 0.""" self.name = name self.scores = [] for count in range(number): self.scores.append(0) def getName(self): """Returns the st...
import random import math def main(): print("Hit 'E' to exit") gussedNumber = input("Guess Number between 1 - 100: ") while gussedNumber.upper() != 'E': if gussedNumber.isdigit() and ( int(gussedNumber) > 0 and int(gussedNumber) <= 100 ): generatedNumber = random.randint(1,10) ...
import random """Juan Bautista Berretta & Jack Reynolds 2016 Reinforcement Learning Project """ GCD = 1.5 """ Ability class to encapsulate the the functionality of different abilities. """ class Ability: def __init__(self, name, damage, cd, cost): self.name = name self.damage =...
def func(a, b = 2, c = "hello"): print(a, b, c) func(2, 100) i =5 def f(arg = i): print(i) i = 6 f() def ff(a, L = []): L.append(a) return L print(ff(1)) print(ff(2)) print(ff(3)) def fff(a, L = None): if L is None: L = [] L.append(a) return L print...
dic = {x : x ** 2 for x in range(10)} for k, v in dic.items(): print(k, v) lst = list(range(10)) for i, e in enumerate(lst): print(i, e) lst1 = [chr(x) for x in range(97, 97 + 26)] lst2 = list(range(97, 97 + 26)) for c, n in zip(lst1, lst2): print('{0} -> {1}'.format(c, n)) print(list(z...
def fib2(n): """定义一个斐波那契数列,不打印,返回一个list""" lst = [] a, b = 1, 1 while(a <= n): lst.append(a) a, b = b, a + b return lst f = fib2(100) print(f) print(type(f)) print (1 in f)
inpp="Sundar:1234567890:Delhi,Raman:234567890:Mumbai" result="" if(',' in inpp): strinpp=inpp.split(',') dummy=0 for i in strinpp: sum=0 dummy+=1 coloninpp=i.split(':') for num in coloninpp[1]: sum+=int(num) result+=coloninpp[0][:2...
while True: a = str(input('Enter number ')) b = int(a[0])+int(a[1])+int(a[2])+int(a[3])+int(a[4]) c = int(a[0])*int(a[1])*int(a[2])*int(a[3])*int(a[4]) print('Sum:',b) print('Product:',c)
import math class triangle: def __init__(self, a=0, b=0, c=0): self.a=a self.b=b self.c=c def __str__(self): if(self.a==self.b==self.c): k='Equal' elif(self.a==self.b!=self.c or self.a==self.c!=self.b or self.b==self.c!=self.a): k='Isos' el...
def func(): A=input('write the number') B=input('write the number') A=int(A) B=int(B) C=int(A+B) D=int(A*B) print('sum',C,'product',A)
def func(): import math A=input('X1') B=input('Y1') C=input('X2') D=input('Y2') E=input('R') A=int(A) B=int(B) C=int(C) D=int(D) E=int(E) F=float(((C-A)**2+(D-B)**2)**0.5) if(F<E): print('inside') else: print('outside')
def pan(a): if(a<0): return else: print(a) pan(a-1)
def grade(a): if(100>=a>=90): print("A") elif(89>=a>=75): print("B") elif(74>=a>=60): print("C") elif(59>=a>=50): print("D") elif(49>=a>=0): print("F")
def tran(e,r): d={} c=len(e) for i in e: d[i]=list() for i in range(c): d[e[i]].append(r[i]) print(d)
""" This file is just to explore how generators works """ from typing import Generator import pytest def test_generator_with_single_empty_yield(): def fn(): yield gen = fn() value = next(gen) assert value is None def test_generator_with_single_empty_yield_double_next(): def fn(): ...
from expression import Choice, Choice1of2, Choice2, Choice2of2, match def test_choice_choice1of2(): xs: Choice2[int, str] = Choice1of2(42) assert isinstance(xs, Choice) assert isinstance(xs, Choice2) with match(xs) as case: for x in Choice1of2.match(case): assert x == 42 ...
""" Psudocode: FOR SINGLY-LINKED LIST TRAVERSAL Go to first ListNode Append ListNode.value to binary number list Go to second ListNode Append ListNode.value to binary number list Repeat until ListNode.next = None FOR BINARY CONVERSION Reverse the list. Loop through list. ...
import random def distance(p1, p2): return ((p1[0] - p2[0])*(p1[0]-p2[0]) + (p1[1] - p2[1]) * (p1[1] -p2[1]))**(1/2) def path_distance(path, cities): dist = 0 for i in range(1, len(path)): dist += distance(cities[path[i-1]], cities[path[i]]) return dist def reproduce(population, cities): ...
n = int(input()) phoneBook = {} for i in range(n): request = [str(x) for x in input().split()] if request[0] == "add": phoneBook[request[1]] = request[2] elif request[0] == "find": number = request[1] phoneBook.setdefault(number,None) person = pho...
import queue def nextNode(trie,currentNode,letter): nextNodes = len(trie[str(currentNode)][1]) if nextNodes == 0: return None else: for i in range(nextNodes): nextNode = trie[str(currentNode)][1][i] if trie[str(nextNode)][0][-1] == letter: ...
def computePrefixFunction(P): s = [0] * len(P) border = 0 for i in range(1,len(P)): while (border > 0) and (P[i] != P[border]): border = s[border-1] if P[i] == P[border]: border += 1 else: border = 0 s[i] = border return s def findAl...