text
stringlengths
5
121k
class A(object): def __init__(self): self.n1 = 1 self.n2 = 2 print('A.__init__') super().__init__() def comm(self): print("A.comm()") class B(object): def __init__(self): self.n3 = 3 self.n4 = 4 print('B.__init__') super().__init__()...
class Point: '''Defines simple 2D Points''' def __init__(self): self.x = 10 self.y = 20 def __str__(self): return "Point(x=%d, y=%d)" % (self.x, self.y) def __repr__(self): return "P(x=%d, y=%d)" % (self.x, self.y) def show(self, flag, capital): '''prints the...
a = [ 1, [ 2, [ 3, [ 4, [ 5, [6] ] ] ] ] ] print(a) print(a[0]) print(a[1][1][1][1][1][0]) prin...
swe = input("Name: ") adj = input("Adjective: ") verb1 = input("Verb: ") verb2 = input("Verb: ") famous_person = input("Famous person: ") madlib = ("Hi! My name is " + swe + ". Computer programming is so " + adj + "! It makes me so excited all the time because I love to " + verb1 + "! Stay hydrated and " + verb...
birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'} all_months = 'January February March April May June July August September October November December' while True: print('Enter a name: (blank to quit)') name = raw_input() if name == '': break if not name.isalpha(): p...
import numpy as np import sys ''' Function: Normalization Description: Normalize input data. For vector x, the normalization process is given by normalization(x) = (x - min(x))/(max(x) - min(x)) Input: data dataType: ndarray description: input data Output: normdata dataType: ndarray descrip...
def sentence (phases): q = ('how' , 'what' , 'whare' , 'how') capitalized = phases.capitalize() if phases.startswith(q): return f'{capitalized}?' else : return f'{capitalized}.' result = [] while True : user_input = input('Write something here : ') if user_input == '\end': ...
import operator from collections import Counter from functools import cache from itertools import accumulate c = Counter('gallahad') print(c) c = Counter({'red': 4, 'blue': 2}) print(c) c = Counter(cats=4, dogs=8) print(c) c = Counter() print(c) c = Counter(['...
class Car: def __init__(self, color, mileage): self.color = color self.mileage = mileage def __str__(self): return '__str__ : a {self.color} car with {self.mileage} mileage'.format(self=self) def __repr__(self): return '__repr__ :a {self.color} ca...
''' Linear_Regression2.py Implements Gradient Descent Algorithm ''' import numpy as np import random import matplotlib.pyplot as plt def linear_regression2(): ''' 1. Read training data in to input, output array. 2. Initialize theta0 - y intercept, theta1 - slope of line. 3. Repeat f...
list = [] list[:] = range(0,100) print(list) for i in list[0:16]: print ("{} in binary {:08b}".format(i, i))
def nester(n): """Given a string of digits S, This function inserts a minimum number of opening and closing parentheses into it such that the resulting string is balanced and each digit d is inside exactly d pairs of matching parentheses.Let the nesting of two parentheses within a string be the substring that oc...
for pypart in range(1,11): def pypart(n): for i in range(0, n): for j in range(0, i+1): print("* ",end="") print("\r") n = 5 pypart(n) print(pypart)
def determinegrade(score): if 80 <= score <= 100: return 'A' elif 65 <= score <= 79: return 'B' elif 64 <= score <= 64: return 'C' elif 50 <= score <= 54: return 'D' else: return 'F' count = 0 for name in range(10): name = str(input('Please enter...
import pandas as pd import numpy as np df = pd.DataFrame({ 'Name': ['A','A','A','B','B','B','C','C','C'], 'Data': np.random.randint(0, 100, 9)}) print('df=\n{}\n'.format(df)) groupby = df.groupby('Name') print("Print GroupBy:") for name, group in groupby: print("Name: {}\nGroup:\n{}\n".format(name, gro...
from Projectile import Projectile from World import DELAY class Controls: ''' This class contains controls methods for 'w','a','s','d' keys: start motion for pressed keys and stop motion for released, - and function for shot on left button click. ''' def __init__(self, camera, hero...
class Instructions(): def __init__(self): self.string = "" def get(self, name): getattr(self, name.casefold())() return self def double07(self): self.string = """ Each player starts with 3 life points and 1 action point Defending and attacking cost 1 action point...
deposit = int(input()) years = 0 rate = 1.071 while 50000 < deposit < 700000: deposit = deposit * rate years += 1 print(years)
print("Hello! My name is Aid.") print("I was created in 2020.") print("Please, remind me your name.") name = str(input()) print(f"What a great name you have, {name}!") print("Let me guess your age.") print("Enter remainders of dividing your age by 3, 5 and 7") remainder1 = int(input()) remainder2 = int(input()) remaind...
days = int(input()) food_cost_daily = int(input()) * days flight_return = int(input()) * 2 hotel_cost_nightly = int(input()) * (days - 1) total_cost = food_cost_daily + flight_return + hotel_cost_nightly print(total_cost)
from Day1.Node import Node def puton(root, string): root.forward = Node(string) root.forward.backward = root root = root.forward return root def showcontainasc(node): print(node) if node.forward is not None: showcontainasc(node.forward) root = Node('root') node = root for i in ran...
import pandas as pd def load_data(): People = pd.read_csv("datasrc/People.csv") People = People.where((pd.notnull(People)), None) Attendance = pd.read_csv("datasrc/Attendance.csv") Desks = pd.read_csv("datasrc/Desks.csv") return People, Attendance, Desks def suggest_seat( user: int,Todays_D...
def add(x, y): """Add the two numbers together""" return x + y def subtract(x, y): """Subtract the two numbers and return the output""" return x - y
from random import randrange board = [] for x in range(5): board.append(["O"] * 5) def print_board(board): for row in board: print(' '.join(row)) shipX = randrange(5) shipY = randrange(5) counter = 0 print("Let's play battleship!\nTry and sink my battleship in 4 tries!\n") ...
from sys import stdin first_line = stdin.readline() list = [int(p) for p in first_line.split(' ')] k = 10 def INSERTION_SORT(list): for j in range(1, len(list)): key = list[j] i = j - 1 while (i >= 0) and (list[i] > key): list[i+1] = list[i] i = i - 1 list[...
import itertools lst = [] num = int(input("input number for permutations :- ")) for n in range(num): n = n + 1 lst.append(n) for p in itertools.permutations(lst): print(''.join(str(x) for x in p))
from pynput import keyboard COMBINATIONS = [ {keyboard.Key.shift, keyboard.KeyCode(vk=65)} ] def execute(): """function to execute when a combination is pressed""" print("do something") pressed_vks = set() def get_vk(key): """ Get the virtual key code form a key. these are used so case/sh...
class AllAvg(object): def __init__(self): pass @staticmethod def main(): res = 0 ls = [] while 1: num = input('더할 수를 입력 (0 입력 시 종료) ->') if num == '0': break else: ls.append(num) for i in ls: ...
line = input() fuhao = ("+","-","*","/") def yunsuan(a,b,c): if c == "+": return a+b if c == "-": return b-a if c == "*": return a*b if c == "/": return b/a fuzhan = ["#"] shuzhan = [] all = int(line[0]) for i in line: if i in fuhao: if ((i == "*" or i == "/"...
import numpy as np import matplotlib.pyplot as plt T,n = 1, 100 k = np.linspace(0,T,n) def production(k, alpha = 0.5,A=1): """ This function will define the production process""" return A*k**alpha def savings(Prod, beta = 0.4): return beta*Prod def depreciation(k,delta = 0.1): return (1-delt...
import pygame import math import random RED = (255,0,0) GREEN = (0,255,0) BLUE = (0,0,255) WHITE = (0,0,0) pygame.init() screen_width = 700 screen_height = 400 screen = pygame.display.set_mode([screen_width,screen_height]) clock = pygame.time.Clock() class Ball(): def __init__(self,x,y,col,x_speed,y_spe...
num1 = int(input("Input first number ")) num2 = int(input("Input second number ")) if num1 > num2: print (num1) else: print(num2)
def min(x, y): if x <= y: return x else: return y def sum(x): res = 0 for i in range(x): res += i return res def print_nums(x): for i in range(x): print(i) return print_nums(10) def func(x): res = 0 for i in range(x): res += i return res print(func(4))
def exc(text): assert text!='' print(str(text)+'!') exc('Hi') def test(number): assert number>0, 'Number should be bigger than 0.' print(str(number)) test(10) file=open('test.txt','r') print(file.read()) file.close() filename = input('Укажите файл?: ') file = open(filename,'r') print('В данном файле '+str(len(f...
number = 0 while number <= 10: number +=1 if (number % 2) != 0: continue; print('Четное число ' + str(number))
money = int(input('Withdrawal amount:')) banknotes = [50,100,200,500,1000] for i in banknotes: if money >= 0: change = money // i money -= change * i if change != 0: print ('Get your money!:'+str(change)+'*'+str(i)+'$') else: print ('GoodBye! See later!')
import numpy as np a = np.array(([1,2,3], [4,5,6], [7,8,9])) print("matriks a dengan ukuran", a.shape) print("matriks a dengan ukuran", np.shape(a)) print("transpose matrix a") print(np.transpose(a)) print(a.T) print("flatten matrix a: ") print(a.ravel()) print(np.ravel(a)) print(...
import numpy as np import holoviews as hv hv.extension('bokeh') import bokeh.sampledata bokeh.sampledata.download() import numpy as np from bokeh.layouts import gridplot from bokeh.plotting import figure, show, output_file from bokeh.sampledata.stocks import AAPL, GOOG, IBM, MSF...
row_counter = int(input()) matrix = [[int(num) for num in input().split(', ')] for row in range(row_counter)] even_matrix = [[matrix[row][col] for col in range(len(matrix[row])) if matrix[row][col] % 2== 0]for row in range(len(matrix))] print(even_matrix)
numbers = [int(x) for x in input().split()] min_num = min(numbers) max_num = max(numbers) sum_of_numbers = sum(numbers) print(f'The minimum number is {min_num}') print(f'The maximum number is {max_num}') print(f'The sum number is: {sum_of_numbers}')
number_of_students = int(input()) student_record = {} for _ in range(number_of_students): token = input().split() name = token[0] grade = float(token[1]) if name not in student_record: student_record[name] = [grade] else: student_record[name].append(grade) for name, marks in stude...
from collections import deque DOLL = 150 WOODEN_TRAIN = 250 TEDDY_BEAR = 300 BICYCLE = 400 materials = deque(int(x) for x in input().split()) magic_level = deque(int(x) for x in input().split()) gifts = { 'Doll': 0, 'Wooden train': 0, 'Teddy bear': 0, 'Bicycle': 0 } while materials and magic_level: ...
def check(b,a): if b <= a: print("FFFF") else: print("0000") check(3,2) check(2,2) check(2,3) print("") check(-3,-2) check(-2,-2) check(-2,-3) print("") check(2,-2) check(-2,2)
def fibonacci_recursion(n): if n == 0: return 1 if n == 1: return 1 return fibonacci_recursion(n-1) + fibonacci_recursion(n-2) def fibonacci_memoization(n, table): if n not in table: table[n] = fibonacci_memoization(n-1, table) + fibonacci_memoization(n-2, table) ...
def binary_search(a, x): start = 0 end = len(a)-1 while start <= end: mid = (start+end)//2 if x == a[mid]: return 1 elif x > a[mid]: start = mid + 1 else: end = mid - 1 return 0 n = int(input()) a = list(map(int, input().split())) m = ...
print('Content-type: text/html\n') print('<title>Hello World</title>') for num in range(2, 5000): prime = True for i in range(2,num): if (num%i == 0): prime = False if prime: print(num)
import numpy import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv("data.csv") X = dataset['sqft_living'] Y = dataset['price'] len_x = len(X) len_y = len(Y) x_sum = 0 y_sum = 0 for i in range(0,len_x): x_sum = x_sum + X[i] y_sum = y_sum + Y[i] X_mean = x_sum/len_x Y_mean = y_sum/len...
import random class GeneticAlgorithm: def __init__(self, debug=False): self.population = [] self.debug = debug def randomInit(self): self.population = [random.randint(0,100) for i in range(10)] def fitness(self, val): return abs(val-10) def mutate(sel...
import discord from discord.ext import commands TOKEN = input("Enter discord token: ") bot = commands.Bot(command_prefix='!') @bot.event async def on_ready(): print(f'{bot.user} has connected to Discord!') @bot.event async def on_message(message): if message.author == bot.user: return pri...
import csv import time from datetime import datetime import matplotlib.pyplot as plt import numpy as np import pandas as pd ''' example.csv contains the values for the system. The thing to note about the file is that the sampling periods are not every 1 second. So there might be a value at t = 0s of 200, and...
import cv2 import numpy as np img = np.zeros((512, 512, 3), np.uint8) cv2.line(img, (0, 0), (img.shape[1], img.shape[0]), (0, 255, 0), 3) cv2.rectangle(img, (0, 0), (250, 250), (0, 0, 255), 2) cv2.circle(img, (400, 50), 30, (255, 255, 0), 3) cv2.putText(img, "OpenCV", (300, 200), cv2.FONT_HERSHEY_COMPLEX, ...
number = [1,2,1,3,1,4,1,5] number.remove(number[1]) number[1]="sky" number[3]="star" print(number) num = [1,2,3] num.extend([4,"k",8]) num[1] = 5 print(num) loc1 = num.index(1) print(loc1) number.pop() print(number) number.pop(1) print(number) dir(list)
"""A short script to create wordclouds from a given text and with a """ from PIL import Image from wordcloud import WordCloud from stop_words import get_stop_words import random import numpy as np import matplotlib.pyplot as plt with open("Goethe_Sammler.txt", "r") as f: text = f.read() goethe_mask = np.a...
import turtle as t t.penup() t.setpos(-258,-258) t.pendown() t.speed(0) square_len = 66 pattern1_distance = -7 pattern2_distance = -9 square_num = 8 def square(): t.color('black') t.begin_fill() for i in range(4): t.forward(square_len) t.left(90) t.end_fill() t.penup() t.fo...
import string import operator ALPHABET = string.ascii_uppercase + "ÆØÅ" def vigenere(plaintext, key, algo): op = operator.add if algo.lower() == "encrypt" else operator.sub return "".join( ALPHABET[ ( op( ALPHABET.index(plaintext[i].upper()), ...
A = input("Ingrese un numero: ") B = input("Ingrese otro numero: ") def andfun(A,B): if A == 1 and B == 1: return 1 else: return 0 print(andfun(A,B)) C = input("ingrese un numero binario: ") D = input ("ingrese otro numero binario: ") def orfun(C,D): if C == 1 or D == 1: return 1 else: return 0 pr...
char = raw_input("Ingrese un caracter: ") if char == "A": print("65") if char == "a": print("91")
import time import random originalTime = time.time() temp = originalTime + random.randint(5,10) print('temp:',int(temp),'originalTime:',int(originalTime)) while True: if time.time() > temp: print('temp:',int(temp),'now:',int(time.time())) print('zheli break') break else: print('sleeping') time.sleep(...
''' Exercise: 16.6 Smallest Difference Find the pair with the least difference (one from each array) Example: Input : [1, 3, 15, 11, 2], [23, 127, 235, 19, 8] Output: 3, (11, 8) ''' import sys def merge_sort(arr): def make_partition(arr): if len(arr) <= 1: return arr middle = len(arr) // 2 left = make_...
import time def find_change(results, current_decomposition, n, denominations): """Find changes Arguments results -- accumulate result in an array. Each item is also an array current_decomposition -- decomposition of n in denominations n -- numbe...
""" Created on Wed Oct 14 20:41:46 2015 @author: SSL """ import numpy as np from scipy.special import expit import matplotlib.pyplot as plt def f(x): return expit(np.matrix([0, 1, -.5,.5])*x); x_min = -5; x_max = 5 y_min = -5; y_max = 5 x1 = np.linspace(x_min, x_max, 200) y1 = np.li...
import numpy as np size1 = int(input("Size of first array:")) a = np.empty(size1) for i in range(len(a)): x = float(input("Element:")) a[i]=x print(np.floor(a)) size2 = int(input("Size of second array:")) b = np.empty(size2) for i in range(len(b)): x = float(input("Element:")) b[i]=x print(np.floor...
import pandas as pd import matplotlib.pyplot as plt plt.style.use('seaborn') sp = pd.read_csv('ScatterPlot.csv') print(sp.head()) Food= sp['MonthlyExpenseFood'] Grocery= sp['MonthlyExpenseGrocery'] ratio = sp['Ratio'] plt.scatter(Food, Grocery, c= ratio, cmap= 'rainbow', edgecolor= 'black', linewidth= 1, alpha= 0...
''' Steps: get the text with nltk.corpus.gutenberg.raw() get the tokens with nltk.word_tokenize() get the words by using w.lower() to lowercase the tokens make the frequency distribution with FreqDist get the 30 top frequency words with most_common(30) and print the word, frequency pairs ''' import nltk from nltk impo...
def checkJump(list2): list3=[] jump=0 for i in range(0,len(list2)): if list2[i]==0: list3.append(i) print(list3) for j in range(0,len(list3)-1): if list3[j+1]-list3[j]==1: print("here") pass else: print("there") ...
""" Author: Niall O'Connor # https://app.codility.com/programmers/lessons/7-stacks_and_queues/fish/ You are given two non-empty arrays A and B consisting of N integers. Arrays A and B represent N voracious fish in a river, ordered downstream along the flow of the river. The fish are numbered from 0 to N − 1. If ...
""" ### FILL IN THE GRID PUZZLE Objective: Arange the numbers 1 through 8 in the grid below. +---+---+ | | | +---+---+---+---+ | | | | | +---+---+---+---+ | | | +---+---+ RULES: No consecutive numbers may appear next to each other either vertically, hor...
""" Author: Niall O'Connor # https://app.codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/ A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one...
""" Author: Niall O'Connor # https://app.codility.com/programmers/lessons/9-maximum_slice_problem/max_double_slice_sum/ A non-empty array A consisting of N integers is given. A triplet (X, Y, Z), such that 0 ≤ X < Y < Z < N, is called a double slice. The sum of double slice (X, Y, Z) is the total of A[X + 1] + A[...
def factorial(n): if not n: return 1 else: return n * factorial(n-1) def factorial_for(n): if not n: return 1 else: r = 1 for i in range(1, n+1): r = i*r return r def factorial_while(n): if not n: return 1 else: i...
""" Author: Niall O'Connor # https://app.codility.com/programmers/lessons/7-stacks_and_queues/stone_wall/ You are going to build a stone wall. The wall should be straight and N meters long, and its thickness should be constant; however, it should have different heights in different places. The height of the wall ...
""" Author: Niall O'Connor # https://app.codility.com/programmers/lessons/3-time_complexity/frog_jmp/ A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D. Coun...
""" Author: Niall O'Connor # https://app.codility.com/programmers/lessons/4-counting_elements/frog_river_one/ A small frog wants to get to the other side of a river. The frog is initially located on one bank of the river (position 0) and wants to get to the opposite bank (position X+1). Leaves fall from a tree on...
class Link: empty = () def __init__(self, first, rest=empty): assert rest is Link.empty or isinstance(rest, Link) self.first = first self.rest = rest class Tree: def __init__(self, entry, child=[]): for c in child: assert isinstance(c, Tree) self....
from operator import add, sub def both_positive(x, y): return x > 0 and y > 0 print(both_positive(1, 6)) def a_plus_abs_b(a, b): if b < 0: f = sub else: f = add return f(a, b) print(a_plus_abs_b(1, -5)) def two_of_three(a, b, c): return max(a*a+b*b, a*a+c*c, b*b+c*c) pr...
def gcd(a,b): if b==0: return a else: return gcd(b,a%b) test=int(input()) for i in range(0,test): inp=input() inp=inp.split() a=int(inp[0]) b=int(inp[1]) c=gcd(a,b) print(c)
def calculator(x ,y , operator): if(operator=='+'): return (x + y) if(operator=='-'): return (x - y) if(operator=='*'): return (x * y) if(operator=='/'): return (x / y)
factor = 0 for i in range(0, 100): if (i == 1): continue factor = 1 for j in range(2, i // 2 + 1): if (i % j == 0): factor = 0 break if (factor == 1): print(i, end=" ")
def add_into_list(number, list): list_len = len(list) for i in range(list_len): list[i] = list[i] + number return list list1 = [1, 2, 3, 12, 19, 2] print("Before adding 3: ", list1) list1 = add_into_list(3, list1) print("After adding 3: ", list1)
menu = ['com ga', "com rang", "banh trang","nem"] for index, item in enumerate(menu): print(index + 1,". ", item,sep="") a = int(input("vi tri chu muon thay doi: ")) b = input("sua thanh? ") index = a - 1 menu[index] = b for index, item in enumerate(menu): print(index + 1,". ", item,sep="")
menu = ['T-Shirt', 'Sweater'] while True: YourAnswer = input("Welcome to our shop,what do you want (C,R,U,D)? ") if YourAnswer.upper() == 'C': MyAdd = input("Enter New Item: ") menu.append(MyAdd) print("Our Item",end = ":",sep = "") print(*menu,sep=",") elif YourAnswer.upper...
import unicodedata def cipher(lineNumber): alpha_dict = {} with open("files/input.txt", "r") as instr: line = instr.readlines()[lineNumber] r_line = line.rstrip() instr_list = r_line.split(":") count = int(instr_list[0]) enc_dec = int(instr_list[1]) lang = int(...
import pygame from .board import Board from .constants import WHITE, BLACK, BLUE, SQUARE_SIZE class Game: def __init__(self, win): self.win = win self._init() def _init(self): self.board = Board(self.win) self.turn = WHITE self.valid_moves = [] self.selected = ...
def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) n = int(input("Input a number to compute the factorial : ")) print(factorial(n))
cp = int(input("Enter cost price:")) sp = int(input("Enter selling price:")) loss = 0 profit = 0 if cp > sp: loss = cp - sp print("business ran in loss", loss) elif cp < sp: profit = sp - cp print("congratulations you are in profit", profit) else: print("continue with what you are doing")
a = int(input("Enter a number to find out even or odd:")) if a % 2 == 0: print("the number is even") else: print("the number is odd")
from array import * num = list("i", [4, 7, 2, 0, 8, 6]) print("This is the list before it was removed:"+str(num)) print("Lets remove it") num.remove(2) print("Removing performed:"+str(num))
kilometers = int(input("Enter a distance:")) meter = kilometers*1000 feet = kilometers*3280.84 centimeter = kilometers*100000 inch = kilometers*39370.1 print(kilometers) print(feet) print(centimeter) print(inch)
import math for a in range(1,1001): for b in range(1, 1001): if a + b + math.sqrt(a ** 2 + b ** 2) == 1000: print('a = ' + str(a) + 'b = ' + str(b)) c = math.sqrt(a ** 2 + b ** 2) print(math.sqrt(a ** 2 + b ** 2)) print('answer = ' + str(a * b * c))
import math a=input().split(" ") b=input().split(" ") x1,y1=a x2,y2=b z=math.sqrt(((float(x2) - float(x1))*(float(x2) - float(x1))) + ((float(y2)-float(y1)) *(float(y2)-float(y1)))) print('%.4lf'%z)
def bitstring(num_bits, global_arr): if (num_bits == 0): print(global_arr) else: global_arr[num_bits - 1] = 0 bitstring(num_bits - 1, global_arr) global_arr[num_bits - 1] = 1 bitstring(num_bits - 1, global_arr) def main(): num_bits = input("Give me the number of bit...
''' Write a function called score that meets the specifications below. def score(word, f): """ word, a string of length > 1 of alphabetical characters (upper and lowercase) f, a function that takes in two int arguments and returns an int Returns the score of word as defined by t...
""" Implement the class myDict with the methods below, which will represent a dictionary without using a dictionary object. The methods you implement below should have the same behavior as a dict object, including raising appropriate exceptions. Your code does not have to be efficient. Any code that uses a Python di...
"""Module to return str repr of floats""" def to_str(n: float) -> str: """Function to get the string representation of floats Args: n (float): [float number] Returns: str: [str repr of n] """ return str(n)
"""Module containing index_range function""" from typing import Tuple def index_range(page: int, page_size: int) -> Tuple[int, int]: """Index range function Args: page (int): [Number of page] page_size (int): [Number of page size] Returns: Tuple[int, int]: [Tuple with two valu...
"""Module to create a measure_time function with integers n and max_delay""" import time import asyncio wait_n = __import__('1-concurrent_coroutines').wait_n def measure_time(n: int, max_delay: int) -> float: """Function o measure time Args: n (int): [number of items] max_delay (int): [max...
"""Module with correct annotation""" from typing import Iterable, Sequence, List, Tuple def element_length(lst: Iterable[Sequence]) -> List[Tuple[Sequence, int]]: """Calculates the length of the tuples inside a list Args: lst (Sequence[Iterable]): [List] Returns: List[Tuple[Sequence, ...
import json from json import JSONDecodeError import random class Learning: def __init__(self): self.previous_state = "0_0_0_0" self.previous_action = 0 self.discount_factor = 0.9 self.learning_rate = 0.8 self.reward = {0: -1, 1: -100} self.epsilon = 0.1 ...
"""A data structure for a simple graph using the model from Martin BroadHurst http://www.martinbroadhurst.com/graph-data-structures.html """ class Node(object): """A Node class for use in a simple graph""" def __init__(self, name, value): """Make a new node object""" self.name = name ...
import time import random def main(): """ A simple number guessing game framework. """ lowerLimit = 1 upperLimit = 20 correctGuess = random.randint(lowerLimit, upperLimit) currentGuess = 'wrong-number' maxTries = 5 currentTry = 0 pauseTime = 1 print('I am thinking of a numb...