text
stringlengths
5
121k
variable_1 = input("Ingrese una palabra: ") variable_2 = input("ingrese otra palabra: ") if len(variable_1) > len(variable_2): print(f"La palabra {variable_1} tiene {len(variable_1) - len(variable_2)} letras mas que {variable_2}") elif len(variable_1) == len(variable_2): print("Las dos palabras tienen el mismo ...
dividendo = int(input("ingrese el dividendo :")) divisor = int(input("ingrese el divisor :")) operacion = dividendo % divisor mensaje = f"El resto obtenido al dividir {dividendo} entre {divisor} es {operacion}" print(mensaje)
numero = int(input("Ingrese un numero: ")) for a in range(0, numero + 1): print(2 ** a)
class MyHashSet: def __init__(self): """ Initialize your data structure here. """ self.keyRange = 769 self.buckets = [[] for i in range(self.keyRange)] def add(self, key: int) -> None: index = key % self.keyRange if key not in self.buckets[index]: ...
def max(num1,num2): if(num1>num2): resert = num1 else: resert = num2 return resert x=eval(input("first number")) y=eval(input("secend number")) print(x,"와",y,"중 큰수는",max(x,y),"이고 작은수는",min(x,y),"이다")
height = (float(input('what is your height(in cm):')))/100 weight = float(input('what is your weight(in kg):')) BMI = float(weight/(height*height)) if BMI < 18.4: print('your BMI is',BMI, ',too light!') elif 18.5 <= BMI <= 23.9: print('your BMI is', BMI, ',perfect!') elif 24 <= BMI <= 26.9: print('your BMI ...
class Node(): def __init__(self,data): self.data = data self.next = None class LinkedList(): def __init__(self): self.head = None def appendNode(self,data): node = Node(data) if self.head == None: self.head = node else: current_node ...
""" data = "123" ways_of_encodig("123") ways_of_encodig("23") + ways_of_encodig("3") 1 + 1 +1 """ def ways_of_encodig(message): global ways_of_encofing if len(message)==0: return 1 if message[0]=="0": return 0 if len(message)==1: return 1 ...
def is_colourful(number): seen_numbers = set() number_str = str(number) for i,digit_str in enumerate(number_str): product = 1 for j in range(i,len(number_str)): product=int(number_str[j]) * product if not (i==0 and j == len(number_str)-1): if prod...
import os def median(historical_expenditures,d): i = 0 number_visited = 0 central_point = d//2 if d%2 == 0 else d//2 + 1 while number_visited < central_point: number_visited+=historical_expenditures[i] i+=1 if d%2 == 1: return i-1 else: j = i-1 whil...
class Solution: def check_letter(self,char): if (char>="a" and char<="z") or (char>="0" and char<="9"): return True return False def isPalindrome(self, s: str) -> bool: i = 0 j = len(s)-1 while i<j: if not self.check_letter(s[i].lower()):...
class Solution: def helper(self,current,n,k): if len(current)==k: self.all.append(current) return prev = 0 if len(current)>0: prev = current[-1] for i in range(prev+1,n+1): self.helper(current+[i],n,k) def comb...
seats = open("input.txt","r").readlines() highest = 0 for seat in seats: down = 0 up = 127 left = 0 right = 7 for letter in seat: if letter == "F": up = (down+up)//2 if letter == "B": down = (down+up)//2 if letter == "R": left = (left+right...
class Node(): def __init__(self,data): self.data = data self.next = None class LinkedList(): def __init__(self): self.head = None def appendNode(self,data): node = Node(data) if self.head == None: self.head = node else: current_node ...
class Solution: def frequencySort(self, s: str) -> str: count = dict() for letter in s: if letter not in count: count[letter] = 0 count[letter] +=1 count = {k: v for k, v in sorted(count.items(), key=lambda item: item[1],reverse = True)} ...
orbits = open("input.txt","r").read().split("\n") orbit_dict = dict() in_orbit = set() for orbit in orbits: if orbit!='': planet_1 = orbit.split(")")[0] planet_2 = orbit.split(")")[1] if planet_1 not in orbit_dict: orbit_dict[planet_1] = [] if planet_2 not in orbit_dict: ...
import re def email_extractor(input): match = re.search(r'[\w\.-]+@[\w\.-]+', input) return match.group(0) if __name__ == '__main__': user_input=input("Enter Email information: ") print(email_extractor(user_input))
from dateutil.parser import parse import datetime class DateMonthYear: def __init__(self): pass def date_extractor(self,input): date = parse(input, fuzzy=True) month=date.month switcher={ 1:'January', 2:'February', ...
distanceTravelled = 0; numHours = int(input("Please enter the number of hours you drove: ")); speed = int(input("Please enter the average speed of the vehicle: ")); while (numHours < 0): numHours = int(input("Hours cannot be negative. Please enter the number of hours you drove: ")); while(speed < 0): speed...
def calculatePrice(houseCost): replacement = houseCost * .80; print("The home insurance cost for a house valued at $", houseCost,"requires a minimum insured cost of $", replacement); def main(): print("Home Insurance Cost Estimator"); houseCost = int(input("Enter the replacement cost of the home: ...
def main(): setA = set(open("file1.txt").read().split()); setB = set(open("file2.txt").read().split()); mutualElements = setA.intersection(setB); unionElements = setA.union(setB); exclusiveElements = unionElements - mutualElements; setAelements = unionElements-setB; setBelements = u...
import random; def even_odd(number): if(number % 2 == 0): print("The random number is",number,"and it is even"); print(); else: print("The random number is",number,"and it is odd"); print(); def main(): for x in range (1, 101, 1): number = random.randint(1,1001)...
userAge = int(input('Please enter your age: ')); if userAge < 0 or userAge > 135: print('Please enter a valid age'); else: if userAge <= 1: print('You are an infant'); elif userAge > 1 and userAge < 13: print('You are a child'); elif userAge >= 13 and userAge <= 20: print(...
def calculateInterest(principal, interestRate, months): interestRate /= 100; futureValue = principal * pow(1 + interestRate, months); return futureValue; def main(): principal = float(input("Enter the current savings account balance: ")); while(principal < 0): principal = float(inpu...
import random; def generate_random(): randNum = random.randint(1,3); return randNum; def calculate_winner(userHand, computerHand): if(userHand == 1 and computerHand == 3): print("User Wins"); elif(userHand == 2 and computerHand == 1): print("User Wins"); elif(userHand == 3 an...
tuition = 8000; increase = 0; rate = .08; totalCost = 0; for x in range (0, 5, 1): for y in range(0,4,1): totalCost += tuition; print("Tuition for year " + str(x + 1) + " is: $", format(totalCost,'.2f')); tuition += (tuition * rate); totalCost = 0;
def main(): inputFile = open('text.txt','r'); textFile = inputFile.readlines(); inputFile.close(); docLength = len(textFile); count = 0; numWords = 0; average = 0; totalAvg = []; while count < docLength: textFile[count] = textFile[count].rstrip('\n'); ...
def fatCalorie(fat): calFat = fat * 9; print("The total calories from",fat,"grams of fat is", calFat,"calories"); def carbCalorie(carbs): carbFat = carbs * 4; print("The total calories from", carbs,"grams of carbs is", carbFat, "calories"); def main(): fat = int(input("Enter the amount of fa...
userNum = int(input('Please enter a literal number between 1 ~ 10 you wish to convert to a Roman numeral: ')); if userNum < 0 or userNum > 10: print('Please enter a number between 1 and 10'); else: if userNum == 1: print('I'); else: if userNum == 2: print('II'); else: ...
import random; def main(): randNum = [0] * 10; for x in range(10): randNum[x] = random.randint(0,10); x+=1; userNum = int(input("Please enter a number: ")); print(randNum); numGreater = compareNum(randNum, userNum); print("There are",numGreater,"numbers greater than...
"""Contains a method to check if a file is text or not Derived from code found here http://code.activestate.com/recipes/173220-test-if-a-file-or-string-is-text-or-binary/""" import string, sys text_characters = "".join(map(chr, range(32, 127)) + list("\n\r\t\b")) _null_trans = string.maketrans("", "") def istextfil...
import json from io import open datos = input("ingrese dato " ) datos_separados= datos.split(', ') varCuantosDatosTieneArreglo = len(datos_separados) primeraPosicion = 0 while primeraPosicion < varCuantosDatosTieneArreglo: file = open(datos_separados[primeraPosicion]) data = json.load(...
def convert(s): """ Convert to an int""" try: x = int(s) print("Convertion succeeded! x=",x) except ValueError: print("Convertion failed") x = -1 return x
arquivo = open("arquivo.txt", "r") for linha in arquivo: print(linha) arquivo.close()
""" Plots rings by checking if points on a plane are within the desired ring, then plots those points. Also appends them to a file""" import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d def create_plane (max_rad,dot_dist): """ Creates a plane of dots that encapsulates...
import numpy as np dots_file = open("../sim_results/run16/dots.dat") def get_coordinates(dots_file): """ grabs coordinates of dots from a dots file returns n x 3 array of coordinates """ dots_line_list = [line for line in dots_file] dot_pos_array = np.zeros((50,3)) dot_count = 0 f...
''' Sets are unordered collection of unique items. Sets are mutable, but the elements inside of them are immutable. * Important distinctions is that the cannot contain duplicate keys * Sets are typically used to perform mathmatical operations such as intersection, union, difference and complement. Unlike sequence ty...
from math import log10, ceil ''' Python implementation of Karatsuba algo - Demoing Recursion. I really am totally lost here. ''' def karasuba(x,y): if x < 10 or y < 10: return x*y n = max(int(log10(x) + 1 ), int(log10(y) + 1)) n_2 = int(ceil(n / 2.0)) n = n if n % 2...
class Aliment: def __init__(self, nom, prix, point): self.nom = nom self.prix = prix self.point = point def acheter(self, perso): if perso.argent >= self.prix: print(self.nom + " achat possible") perso.argent = perso.argent - self.prix else: ...
n = int(input("n:")); for i in range(1,n): if i%5 ==0 and i%3 ==0: print("FizzBuzz") elif i%3 ==0: print("Fizz") elif i%5 ==0: print("Buzz") else : print(i)
""" Created on Tue Feb 13 14:27:47 2018 @author: rafaelleite """ import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset_train = pd.read_csv('datasets/real_sales_train.csv') training_set = dataset_train.iloc[:,0:2].values from sklearn.preprocessing import MinMaxScaler sc = MinMaxSc...
def is_even(n): if n % 2 == 0: return True else: return False print(is_even(6)) num = input("Your number here") num = int(num) def even_odd(): global num if num % 2 == 0: return 'Even' else: return 'Odd' print(even_odd())
import gmplot import pandas as pd from random import randint def plot_map(path_to_csv_file, column_with_geo_codes): column_with_geo_codes = int(column_with_geo_codes) latitude = [40.835295] longitude = [-97.700743] df = pd.read_csv(path_to_csv_fi...
def get_prime(): num = 3 yield 2 while True: is_prime = True for j in range(3, num, 2): if num % j == 0: is_prime = False if is_prime: yield num num += 2 g = get_prime() while True: inp = input("Press enter to get next pr...
def getlength(value): print("Length of {} is {}".format(value, len(value))) def main(): value=input("Enter name : ") getlength(value) if __name__ == "__main__": main()
import unittest class ListComprehensionTests( unittest.TestCase ): def test_ListComprehension_01( self ): vz = ( 1, 2, 3, 4 ) l = [ v * 3 for v in vz ] assert l == [ 3, 6, 9, 12 ] def test_ListComprehension_02( self ): vz = ( 1, 2, 3, 4 ) l = [ v * 3 for v in vz if 10 ...
import string def create(data): for n in range(0,5): data.append(0) def traverseInput(data): for i in range(0,5): data.append(raw_input("Fill your data: ")) def traverseShow(data): for x in range(0,5): print(data[x]) def swap(dataA, dataB): temp = dataA dataA = dataB dataB = temp def sort...
import random from math import sqrt, log, ceil, exp class StdRandom: @staticmethod def set_seed(seed=None): random.seed(seed) @staticmethod def uniform(): """ Generate a float number in [0.0, 1.0) :return: a float number in [0.0, 1.0) """ return random...
class RHash: def __init__(self): self.letters = 'acdegilmnoprstuw' self.h = 7 def reverseHash(self, n): result = '' while n > 0: i = n % 37 try: result += ...
class A: def __init__(self): print('init A') def feat1(self): print ('feat1 is working') def feat2(self): print ('f...
import sys def square_num(num): sq = num * num print (sq) square_num(5)
def double_char(txt): solution = '' for i in range(len(txt)): double = 2 * txt[i] solution += double return solution print(double_char("Hello"))
def mult_by_2(x): x = x*2 return x y = 12 z = mult_by_2(y) print(z) myList = [1, 2, 3] def mult2_list(l): for i in range(len(l)): l[i] *= 2 print(myList) mult2_list(myList) print(myList) def makeUpper(string): string = string.upper() return string myString = "hello" make...
class MedianFetcher: def __init__(self): self.median = None self.numbers = [] def insert(self, n): self.numbers.append(n) self.numbers.sort() def get_median(self): if len(self.numbers) == 1: return self.numbers[0] m...
import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize, sent_tokenize from collections import Counter import string text1 = "" fr = open("sample").read() sw = set(stopwords.words('english')) for s in fr.lower().split(): if s not in sw: text1 = text1 + ' ...
num = int(input('Enter the number:')) Reverse = 0 while(num > 0): Reminder = num%10 Reverse = (Reverse * 10) + Reminder num = num // 10 print('Reverse for the Entered number is:%d' %Reverse)
from board import Board from copy import deepcopy from random import choice class AI: def __init__(self, color): self.color = color def minimax(self, current_board, is_maximizing, depth, turn): if depth == 0 or current_board.get_winner() is not None: return self.get_value(current_board) next_tur...
from utils import get_position_with_row_col class Piece: def __init__(self, name): self.name = name self.has_eaten = False def get_name(self): return self.name def get_position(self): return self.name[:-2] def get_color(self): return self.name[-2...
def leer_barril(): barril={ 'producto':input("ingrese producto: "), 'litros':int(input("ingrese los litros por barril: ")), 'proveedor':input("ingrese proveedor: "), 'porc_amarg':int(input("ingrese porcentaje de amargura: ")), 'porc_alcohol':int(input("ingrese porcentaje de alcohol: ")), 'precio':i...
m_2=[[1,2], [4,5]] m_1=[[1,2], [3,4]] objetivo=0 maximo=4 i=0 def busqueda_secuencial(m_1,diml,i): while maximo!=objetivo and i<diml: i=i+1 return maximo maximo=busqueda_secuencial(m_1,2,i) print(maximo)
n=10 def suma(n): if n ==0: return 0 else: return n+suma(n-1) suma(10) print(suma(10)) diml=4 max=0 i=0 arreglo=[] def encontrar_maximo_recursivo(arreglo,i,diml,max): if i == (diml): return max else: if arreglo[i]> max: return encontrar_maximo_recursivo(arreglo,i+1,diml,arreglo[i]) else: r...
def canPlaceFlowers(flowerbed,n): def consecutivethreezeros(arr): count = 0 i = 3 if len(arr) < i: if arr[0] == 0: count += 1 return count else: if arr[0] == 0 and arr[1] == 0: count = count + 1 if arr[l...
def depthSum(nestedList): tot_sum = 0 sum_list = [] if len(nestedList) == 0: return 0 for i in nestedList: sum_list.append((i,1)) while sum_list: element,depth = sum_list.pop(0) if element.isInteger(): tot_sum += depth*element.getInteger() els...
people = ['Jonas', 'Julio', 'Mike', 'Moz'] ages = [25, 30, 31, 39] print(type(people)) print(enumerate(people)) for position in range(len(people)): person = people[position] age = ages[position] print(person, age)
import random import math def get_first_range(): num_range_1 = int(input("\nEnter the first number of the range: ")) return num_range_1 def get_second_range(): num_range_2 = int(input("\nEnter the second number of the range: ")) return num_range_2 def get_user_guess(): user_guess = int(input("...
name1 = input('Enter your name: ') age1 = input('Enter your age: ') gender1 = input('Enter your gender: ') alldata1 = 'Hello! My name is ' + name1 + ". I'm " + age1 + " and I'm a " + gender1 print('1', alldata1) alldata11 = '%s%s%s%s%s%s' % ('Hello! My name is ', name1, ". I'm ", age1, " and I'm a ", gender1) print('2...
from .station import MonitoringStation from .utils import sorted_by_key def stations_level_over_threshold(stations, tol): flood = [] for station in stations: if station in flood: pass elif station.typical_range_consistent() == False or station.relative_water_level() == No...
""" 4、信号量模型 """ import sys, time import random from threading import Thread, Semaphore product = [] mutex = Semaphore(1) full = Semaphore(0) empty = Semaphore(5) class Producer(Thread): def __init__(self, speed): Thread.__init__(self); self.speed = speed; def run(self): while True: ...
import threading import queue import random import time class Producter(threading.Thread): """生产者线程""" def __init__(self, t_name, queue): self.queue = queue threading.Thread.__init__(self, name=t_name) def run(self): for i in range(100): self.queue.put(i...
import time def clock(func): def clocked(*args): t_1 = time.perf_counter() result = func(*args) t_2 = time.perf_counter() name = func.__name__ arg_str = ",".join(repr(arg) for arg in args) print("spend time is {},arg is{}".format(t_2 - t_1, arg_str)) ...
def uniform_cdf(x: float) -> float: """Returns the probability that a uniform random variable is <= x""" if x < 0: return 0 elif x < 1: return x else: return 1 import math SQRT_TWO_PI = math.sqrt(2 * math.pi) def normal_pdf(x: float, mu: float = 0, sigma: float = 1) -> float: r...
def predict(alpha: float, beta: float, x_i: float) -> float: return beta * x_i + alpha def error(alpha: float, beta: float, x_i: float, y_i: float) -> float: """ The error from predicting beta * x_i + alpha when the actual value is y_i """ return predict(alpha, beta, x_i) - y_i from scratch.li...
""" Created on Tue Jul 27 06:10:26 2021 @author: kalai """ x=-3 while x<10: if x<0: x+=1 continue if x==8: break if x%2: print (f'{x} is an odd number') else: print(f'{x} is a even number'); x += 1 else: print('All...
""" Created on Mon Aug 2 06:16:27 2021 @author: kalai """ magic_word = 'abracadabra' search_str = 'a' start_pos=0 iteration_count=len(magic_word)-len(magic_word.replace('a', '') ) for i in range(iteration_count): start_pos=magic_word.index(search_str,start_pos) print('a is present at the position ',start_...
""" Created on Mon Aug 2 06:44:20 2021 @author: kalai """ input_string= 'the quick brown fox jumps over the lazy dog' s_string = set(input_string) opt_string='' opt_string_sort='' for i in s_string: char_count = input_string.count(i) if i != ' ' and char_count>1: opt_string+=str(char_coun...
""" Created on Mon Aug 2 15:03:24 2021 @author: kalai """ i_string = input('Enter a string: ') if len(i_string)>=2: print(i_string[:2]+i_string[-2:]) else: print('')
""" Created on Wed Jul 28 06:22:48 2021 @author: kalai """ import random low_case = ''.join([chr(int(random.randint(97,122))) for i in range(0,3)]) num = chr(random.randint(48,57)) up_case = chr(random.randint(65,90)) special_char = chr(random.randint(33,47)) low_case2 = ''.join([chr(int(random.randint(97,...
""" The code to generate the risk-coverage curve given the model and the test data. It is assumed that the model is implemented using pytorch Usage: $ python >>> import rc >>> rc.draw_curve(model, input_data) # png file saved to the current directory """ import numpy as np import matplotlib.pyplot as plt def d...
import sys import RPi.GPIO as GPIO
class User: user_list = [] def __init__(self,full_name,login_name,email,password_value): ''' Here we call ana array which has the login information and what is needed for the login. ''' self.full_name = full_name self.login_name = login_name self.email = email ...
class student: school = "telusko" def __init__(self,m1,m2,m3): self.m1 = m1 self.m2 = m2 self.m3 = m3 def avg(self): return(self.m1 + self.m2 + self.m3)/3 @staticmethod def info(): print('this is a student class.. in abc mmodule') s1 = student(...
names = ('shaz','naaz','chiku') comps = ('apple','hp','asus') zipped = list(zip(names,comps)) print(zipped) names = ('shaz','naaz','chiku') comps = ('apple','hp','asus') zipped = list(zip(names,comps)) for (a,b) in zipped: print(a,b)
class student: school = "telusko" def __init__(self,m1,m2,m3): self.m1 = m1 self.m2 = m2 self.m3 = m3 def avg(self): return(self.m1 + self.m2 + self.m3)/3 def get_m1(self): return self.m1,self.m2,self.m3 def set_m1(self,a,b,c): self.m1 =a ...
pos = -1 def search(list,n): i = 0 while i < len(list): if list[i] == n: globals()['pos'] = i return True i = i + 1 return False list = [2,3,4,5,6,7,9] n = 2 if search(list,n): print('found at', pos) else: print('not found') list=[4,3,12,34,56,77,89] ...
class A: def __init__(self): print("in A init") def feature1(self): print("feature1 is working") def feature2(self): print("feature2 is working") class B(A): def __init__(self): super().__init__() print("in B init") def feature3(self): pr...
class A: def __init__(self): print("in A init") def feature1(self): print("feature 1-A is working") def feature2(self): print("feature2 is working") class B: def __init__(self): print("in B init") def feature1(self): print("feature 1-B is work...
def is_pelindrome(word): word=word.lower() word1=word new_str='' while len(word1)>0: new_str=new_str+ word1[-1] word1=word1[:-1] print(new_str) if (new_str== word): return True else: return False if is_pelindrome(input("Enter String >>>")): print("yes,this is pelindrome") else: pri...
""" Dynamic programming solution to 0/1 knapsack """ import numpy as np def knapsack(items, weight): """ Maximizes value of items given a weight limit """ opt = np.zeros((len(items)+1, weight+1), dtype = int) for w in range(weight+1): opt[0][w] = 0 for i in range(1,len(ite...
"""Each election result records the voting system used, counts, winners, etc.""" from .utils import sort_dict_desc, make_table class ElectionResult: def __init__(self, voting_system, counts, winners, count_type='Votes', percent_column=True, details=[]): """Creates an election result w...
""" Created on Sun Dec 1 09:54:54 2019 @author: gape """ def task1(): with open('day1.txt') as file: total = 0 for row in file: w = int(row) total += (w / 3) // 1 - 2 print('Task 1 result: ', total) def task2(): with open('day1.txt') as file: ...
def f(x, y): return x ** 2 + y ** 2 def h(x): def curried(y): return f(x, y) return curried fix10 = h(10) for y in range(10): print(f'fix10({y}) = {fix10(y)}')
n=int(input()) for i in range(1,n+1): for j in range(1,n+1): print(i,end="") print()
class Singleton(object): def __new__(cls, *args, **kw): if not hasattr(cls, '_instance'): orig = super(Singleton, cls) cls._instance = orig.__new__(cls, *args, **kw) return cls._instance class MyClass(Singleton): a=1 cls=MyClass() cls2=MyClass() print(id(cls)) print...
def weight_on_planets(): e_weight = float(input("What do you weigh on earth? ")) m_weight = e_weight * 0.38 j_weight = e_weight * 2.34 print("\nOn Mars you would weigh %.2f pounds.\nOn Jupiter you would weigh %.2f pounds." % (m_weight, j_weight)) if __name__ == '__main__': weight_on_plan...
myList = list() while True: try: n = input("Input number: ") if len(n) == 0: break myList.append(float(n)) except ValueError: print("Invalid value") print(myList)
import math a = int(input("Enter a: ")) b = int(input("Enter b: ")) c = int(input("Enter c: ")) d = b ** 2 - 4 * a * c if d < 0: print("The result is a complex value") else: if d == 0: print("x =", (-b / 2 * a)) else: print("x1 =", (-b - math.sqrt(d)) / 2 * a) print("x2 =", (-b + m...
length = int(input("Enter length: ")) t = int(input("Select type (1-4): ")) result = str() if t == 1: i = 0 while i < length: temp = "".ljust(length - i, "*") temp = temp.ljust(length, " ") result += temp + "\n" i += 1 elif t == 2: i = length - 1 while i >= 0: te...
def foo(n): if n == 0: return 0 elif n == 1: return 1 else: return foo(n - 1) + foo(n - 2) try: print("result =", foo(int(input("Enter a number greater than zero: ")))) except (RecursionError, ValueError): print("Incorrect value")
cortege = tuple() while True: text = input("Input text: ") if len(text) == 0: break else: cortege = cortege + (text,) print(cortege)
import random def weighted_random(pairs): if len(pairs) == 0: return None total = sum(pair[0] for pair in pairs) r = random.uniform(0, total) for (weight, value) in pairs: r -= weight if r <= 0: return value def choice_optional(lst): """" Returns random.choic...