text
stringlengths
37
1.41M
def readString(a): s = input(a+": ") return s def readDigit(a): s = input(a+": ") try: f = int(s) except ValueError: f = float(s) return f try: country = readString("country") wealth = readDigit("wealth") lifeExp = readDigit("life expectancy") footPr = readDigit(...
import json with open('input.json,'r') as f: inputjson = json.load(f) Remove element from json object Json to python conversion Object -> Dict Array -> List String ->str false ->False null -> None #Remove element crime from state Object for state in inputjson['states']: del state['crime'] #export python dic...
#Currency converter for Euro def desiredDate(dates): #entered value must be a string # Input Rapidapikey provided by the rapidapi webpage RAPIDAPIKEY = 'd88ac81114msh89e702e586cd793p16570djsn90c636b78795' dates = str(dates) # import import http.client import json import pandas as pd ...
# reference: https://github.com/rasbt/deeplearning-models/blob/master/pytorch_ipynb/cnn/cnn-vgg16-celeba.ipynb # dataset preparation process follows the steps used in the reference import pandas as pd import os # file containing the attributes of each image, such as the gender of the person in the image # which will...
# Write regex and scan contract to capture the dates described regex_dates = r"Signed\son\s(\d{2})/(\d{2})/(\d{4})" dates = re.search(regex_dates, contract) # Assign to each key the corresponding match signature = { "day": dates.group(2), "month": dates.group(1), "year": dates.group(3) } # Complete the format ...
# Include both variables and the result of dividing them print(f"{number1} tweets were downloaded in {number2} minutes indicating a speed of {number1/number2:.1f} tweets per min") # Replace the substring http by an empty string print(f"{string1.replace('https', '')}") # Divide the length of list by 120 rounded to tw...
s = input() aa=input() ba=input() if(s>=a): if(s<=ba): print("Yes") elif(s<=aa): if(s>=ba): print("yes") else: print("no")
a = input() if (a % 4) == 0: if (a % 100) == 0: if (a % 400) == 0: print(" leap year") else: print(" not a leap year") else: print(" leap year") else: print(" not a leap year")
x = input("Enter file name: ") y = 0 with open(x, 'r') as f: for c in f: y += 1 print(y)
def reverse(s): str = "" for i in s: str = i + str return str s = input() print (end="") print (s) print (end="") print (reverse(s))
x1,k1=input("Enter string and a char:").split(' ') s=x1.count(k1) print(s)
a=raw_input() b=raw_input() if(len(a)>len(b)): print(a) elif(len(a)==len(b)): print(b) else: print(b)
s =raw_input() rev = ''.join(reversed(s)) if (s == rev): print("palindrome") else: print("not palindrome")
from passwordGenerator import create_password from Database import getData,addData,\ removeService,editService def get(): global key service = input("Enter Service Name: ") if not getData(service): print("Service not found") choice = input("Would you like to enter another Service? (Y/N...
coffees = ["mocha", "cappuccino", "flat white", "latte", "espresso"] # coffee menu price_of_coffees = [1, 1, 2, 1, 2] # prices for coffees price_total = [] # empty list for later chosen_coffees = [] # also list for later trying_for_integer = True # bool starting_code = True # bool print("\u2022please choose one o...
import random student_dict = {'Eric': 80, 'Scott': 75, 'Jessa': 95, 'Mike': 66} print("Dictionary Before Shuffling") print(student_dict) keys = list(student_dict.keys()) random.shuffle(keys) ShuffledStudentDict = dict() for key in keys: ShuffledStudentDict.update({key: student_dict[key]}) print("\nDictionary aft...
class Book: def __init__(self, name,author,tag): self.name = name self.author = author self.tag = tag container = [] container.append(Book('War and Piece', 'Tolstoy', ['love', 'train'])) container.append(Book('Return from the stars', 'Stanislav Lem', ['future'])) def search_by_name(conta...
#Sam Krimmel #1/29/18 #movie.py - asks user for age and prints most scandalous movie they can watch age = int(input('Enter your age: ')) if age > 17: print('You can watch NC-17 movies.') elif age >= 17: print('You can watch R rated movies.') elif age >= 13: print('You can watch PG-13 movies.') elif age >=...
#Sam Krimmel #1/30/18 #compoundDemo.py - how to use and/or num = int(input('Enter a number: ')) if num > 0 and num%7 == 0: print(num, 'is positive and divisible by seven!') elif num > 0: print(num, 'is positive but not divisible by seven. :(') elif num < 0 and num%7 == 0: print(num, 'is negative and divis...
# A Binary Tree Node class Node: # Constructor to create a new node def __init__(self, key): self.key = key self.left = None self.right = None # A utility function to do inorder traversal of BST class BST(object): def __init__(self): self.root = None def inorder(se...
import io import sys import collections # Simulate the redirect stdin. if len(sys.argv) > 1: filename = sys.argv[1] inp = ''.join(open(filename, "r").readlines()) sys.stdin = io.StringIO(inp) def prec(c): if c == '+' or c == '-': return 1 elif c == '*' or c == '/': return 2 el...
import io import sys import collections # Simulate the redirect stdin. if len(sys.argv) > 1: filename = sys.argv[1] inp = ''.join(open(filename, "r").readlines()) sys.stdin = io.StringIO(inp) swap = 0 def merge(A, B): C = [] i = 0 j = 0 while i < len(A) and j < len(B): if A[i] <=...
from abc import ABC, abstractmethod from PadraoVoaveis import PadraoVoaveis from PadraoCorrer import PadraoCorrer class Pato(ABC): @abstractmethod def mostrar(self): pass def nadar(self): return "Pato Nadando." def setComportamento(self, padrao): if not isinstance(padrao...
# KidsCanCode - Intro to Programming # Rock/Paper/Scissors game import random choices = ['r', 'p', 's'] player_wins = ['pr', 'rs', 'sp'] player_score = 0 computer_score = 0 while True: player_move = input("Your move? ") if player_move == 'q': break computer_move = random.choice(choices) pr...
# Multilinear Regression import pandas as pd import numpy as np import matplotlib.pyplot as plt # loading the data Toyotta = pd.read_csv("C:\\Users\\nidhchoudhary\\Desktop\\Assignment\\MULTI_LINEAR_REGRESSION\\ToyotaCorolla.csv",encoding='ANSI') ##Creeating Data Set Toyotta_Cars = Toyotta[["Price","Age_08_04","KM",...
def merge_sort(ls, st, lt): if st < lt: m = int((st + lt) / 2) merge_sort(ls, st, m) merge_sort(ls, m + 1, lt) merge(ls, st, m, lt) def merge(ls, st, m, lt): a = list()
#num = 600851475143 #magnitude = 6.0e11 #so the square root is < 1e6? #1e6 = 1000000 #1e6 ^2 = 1000000 000000 # so we perform a sieve of eratosthenes to find primes up to 1e6, # which is guaranteed to find at least one of each pair of factors. # List of size 1e6 class SieveOfEratosthenes: # Create a sieve of...
"""****************************PASCAL_TRIANGLE V1.1**************************************************""" from __future__ import print_function # for python version below 3.0, this import is necessary to use that end='' in print function. def sol(degree): '''This function will add list of each element into a single lis...
""" Given an array, find out if the array is sorted using recursion. Time complexity: O(n) Space complexity: O(n) """ def is_sorted(lst): if len(lst) <= 1: return True else: if lst[0] < lst[1]: return is_sorted(lst[1:]) else: return False return True asse...
# Animation/Frame generator Library # Part of the Glitch_Heaven Project # Copyright 2015 Penaz <penazarea@altervista.org> import pygame import os class Animation(object): """ This is a simple library that stores frames for a simple animation """ def __init__(self): """ Constructor - No parameters """...
from generator import generate import argparse import random import string def main(): parser = argparse.ArgumentParser() parser.add_argument("--seed",default="random") parser.add_argument("--maxlen",default=50,type=int) parser.add_argument("--numnames",default=1,type=int) args = parser.parse_args() seed = args....
from abc import ABC, abstractmethod from contextlib import closing import sqlite3 import csv import re class Estrategia(ABC): """ Classe Base para as estratégias (algoritmos) """ @abstractmethod def execute(self, dados): """ Método em que o algoritmo é contido. Implementação do al...
import pandas as pd def standardize_all_variables(data, pre_period, post_period): """Standardize all columns of a given time series. Args: data: Pandas DataFrame with one or more columns Returns: dict: data: standardized data UnStandardize: function for undoing the...
import numpy as np def get_downward_diagonal_indices(startRow, startCol, length=3): list_of_indices = [np.zeros(2) for _ in range(length)] for i in range(0, length): list_of_indices[i] = [startRow - 1 - i, startCol + 1 + i] return list_of_indices def get_upward_diagonal_indices(startRow, startCo...
import os with open("input.txt", "r") as f: count = 0 answers = set() for line in f: line = line.strip() if not line: # print(answers, len(answers)) count += len(answers) answers.clear() # print(answers) else: for c in line: if c not in answers: answers.add(c) count += len(answers) ...
import os with open("input.txt", "r") as f: p = 0 count = 0 for line in f: if p >= len(line.strip()): # print(p, len(line)) p -= len(line.strip()) if line[p] == '#': count += 1 p += 3 print(count)
class Pet: def __init__(self, name, type, tricks): self.name = name self.type = type self.tricks = tricks self.health = 90 self.energy = 0 def sleep(self): if self.energy + 25 <= 100: self.energy += 25 else: self.energy = 100 ...
# Imports modules from sys import argv # Unpacks the argv module using two parameters script, filename = argv # specifies a txt file and opens the file specified by the "filename" parameter txt = open(filename) # prints a string along with the name of the file being opened print "Here's your file %r:" % filename # prin...
from datetime import datetime def isPositiveDay(openPrice, closePrice): return openPrice < closePrice def isMarketClosed(): current = datetime.now() # monday is 0 sunday is 6 day = current.weekday() hour = current.hour minute = current.minute if day > 4: # is weekend return True ...
# Email Slicer email = input('Enter your Email ID: ').strip() username = email[ : email.index("@")] domain_name = email[ email.index("@")+1 : email.index('.') ] result = "Your Username is '{}' and your domain name is '{}'". format(username, domain_name) print(result)
a = raw_input('Please input num_1:') a = int(a) b = raw_input('Please input num_2:') b = int(b) c = raw_input('Please input num_3:') c = int(c) def sum3Number(a,b,c): return a+b+c def average3Number(a,b,c): return sum3Number(a,b,c)/3 print('sum3Number=%d'%sum3Number(a,b,c)) print('average3Number=%d'%average3Num...
from math import inf arrays = [[1, 2, 3, 2, 6, 6], [3, 2, 9, 1, 8, 2, 0, 4, 5], [3, 2, 6, 1, 8, 2, 0, 4, 5], [1, 3, 2, 2, 3], [1, 0, 3, 2], [2, 3, 0]] def find_jumps_from(arr, i, jumps): """ finds the minimum number of jumps from i to the end of the array ...
from IPython.display import clear_output class Shopping(): def __init__(self): self.shop_list = [] print("Welcome!") print("You can add, delete, see items in list,") print("or even quit shopping.") print() print("please write add / delete / see / quit ") def ad...
class Rect: def __init__(self, x, y, width, height): self.x = x self.y = y self.width = width self.height = height def __str__(self): return str([self.x, self.y, self.width, self.height]) def as_list(self): return [self.x, self.y, self.width, self.he...
arr = [7,3,2,1,6,4,9,8] # arr = [7,3,2,1,6,4,9,8] c1 = 0 c2 = 0 for i in arr print (arr)
import random import time lst=['rock','paper','scissor'] user_score=0 pc_score=0 for i in range(1,4): print(f"{i} of 3 try") user_choice=input("enter the choice: ") choice=random.choice(lst) print(f"pc choice is {choice}") if user_choice==choice: print('draw') elif user_choice=='rock' an...
import functions import utils if __name__ == '__main__': print("Wprowadź numer macierzy którą chcesz wprowadzić: ") answer = input() if answer == '1': functions.gauss_jordan_solver(utils.parse_matrix("matrices/first_matrix")) elif answer == '2': functions.gauss_jordan_solver(utils.parse...
import math n1 = float(input('Digite um valor: ')) print('O valor a pagar é R${}', math.trunc(n1))
print('\033[32m-=-\033[m' * 20) print('\033[32m***************** Aprovador de Empréstimos *****************\033[m') print('\033[32m-=-\033[m' * 20) vc = float(input('Inisira o valor da casa: R$')) s = float(input('Insira seu salário: R$')) qa = int(input('Insira em quantos anos pretende pagar: ')) vm = vc / (qa * 12) p...
print('\033[33m-=-\033[m' * 20) print('\033[33m************ Sequência de Fibonacci ************\033[m') print('\033[33m-=-\033[m' * 20) i = int(input('Quantos termos para ser mostrados? ')) t1 = 0 t2 = 1 print('{} → {}'.format(t1, t2), end=' ') c = 3 while c <= i: t3 = t1 + t2 print('→ {}'.format(t3), end=' ') ...
print('\033[33m-=-\033[m' * 20) print('\033[33m************* Números pares *************\033[m') print('\033[33m-=-\033[m' * 20) for c in range(1, 51): if c%2 == 0: print(c) print('Apenas esses são pares entre 1 e 50.')
n = float(input('Insira quantos km terá sua viagem: ')) if n <= 200: print('O preço será de: R${:.2f}' .format(n*0.5)) else: print('O preço será de: R${:.2f}' .format(n*0.45))
n = float(input('Digite um valor: ')) print('Você pode comprar UU${}' .format(n/3.27))
v = float(input('Qual a velocidade do carro? ')) if v <= 80: print('Velocidade ok.') else: print('Sua multa será de: R${:.2f}' .format((v-80)*7))
class TreeNode: self.val = None self.right = None self.left = None def __init__(self, val): self.val = val def defectiveNode(TreeNode root): parents = [root] children = [] defective = [] while len(parent)!=None: for parent in parents: if parent.left!=None: ...
#!/usr/bin/env python # check if signs of two integers are opposite def sign_evaluator(a,b): return a ^ b < 0 print sign_evaluator(a=3, b=-3)
inv = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] def display_inventory(): print('Inventory: ') for i in inv: print(inv[i], i) print('Total number of items: ', sum(inv.values())) def add_to_inventory(i...
import functions # or from functions import square # to print all sqaures of 0 to 10 using range and for loop # sqaures function is in functions.py file for i in range(10): print(f"Square of {i} is {functions.square(i)}") # or from functions import square for i in range(10): print(f'square of {i}...
# Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. # Example: # Input: # [ # 1->4->5, # 1->3->4, # 2->6 # ] # Output: 1->1->2->3->4->4->5->6 # Brute force solution: # Traverse over all the linked lists and collect the values in the array # sort and itterate...
# Given a collection of intervals, merge all overlapping intervals. # Example 1: # Input: [[1,3],[2,6],[8,10],[15,18]] # Output: [[1,6],[8,10],[15,18]] # Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. # Example 2: # Input: [[1,4],[4,5]] # Output: [[1,5]] # Explanation: Intervals [1,4] ...
# Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. # Example 1: # Input: # 11110 # 11010 # 11000 # 00000 # Ou...
# Given a positive integer num, write a function which returns True if num is a perfect square else False. # Note: Do not use any built-in library function such as sqrt. # Example 1: # Input: 16 # Output: true # Example 2: # Input: 14 # Output: false def isPerfectSquare(self, num): """ :type num: int :...
# You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. # Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] # Output: true # Example 2: # Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[...
# Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. # Example: # Input: [-2,1,-3,4,-1,2,1,-5,4], # Output: 6 # Explanation: [4,-1,2,1] has the largest sum = 6. # Follow up: # If you have figured out the O(n) solution, try coding a...
# import datetime # c = ord('\n') # today = datetime.datetime.today() # print(f'game {c} {today:%b %d %y}') # val = 4 # can = 'dd' # print(f'i {can} be {val}') # import time # count =3 # for i in reversed(range(count +1)): # if i > 0: # print(i,end=('>>'), flush=True) # time.sleep(1...
from pandas.core.frame import DataFrame import streamlit as st import pandas as pd import numpy as np import matplotlib.pyplot as plt import re import calendar import altair as alt st.title("Maket Segmentation") st.header("Segmentation Analysis on customer data") #reading data dataset_df = pd.read_excel("Dataset.xls"...
#!/usr/bin/env python3 def make_graph(text): graph = {} edges = [] for line in text.split('\n'): val = -1 v0 = v1 = None for i in range(len(line)): char = line[i] if char in ' ->': continue if ord('0') <= ord(char) <= ord('9'): ...
''' 利用selenium模拟登录豆瓣 url = 'https://www.douban.com/ user: 19938467368 passward: Huawei12#$ 如需要输入验证码 分析: 1. 保存页面成快照 2. 等待用户手动输入验证码 3. 继续自动执行提交等动作 ''' from selenium import webdriver url = 'https://accounts.douban.com/' driver = webdriver.Chrome() driver.get(url) # 等待(显性,隐性,强制) driver.implicitly_wait(5) driver.find_eleme...
# -*- coding: utf-8 -*- """ CS 2302 Data Structures Author: John Rodriguez Lab 5 Instructor: Olac Fuentes TA: Anindita Nath Date: 11/4/19 Purpose: Compare the run times between hash tables with one using chaining and the other using linear probing when retrieving word embeddings to compare two given words. The...
# -*- coding: utf-8 -*- """ CS 2302 Data Structures Author: John Rodriguez Lab 2 Instructor: Olac Fuentes TA: Anindita Nath Date: 9/22/19 Purpose: use sorting algorithoms, bubble sort and difftent variations of quick sort to order a list and return index k in that list after it's sorted """ import time # Bu...
""" [basketball.py] Basketball Plugin [Author] Konstantinos Efthymiadis [About] Given the event and year as parameters, the plugin will return the countries that won the medal that year Given the event and country as parameters, the plugin will return the number of medals this country has won [Commands] >>> .basketb...
""" [roman_numeral.py] Roman Numeral Converter Plugin [Author] Nick Wiley [About] Returns the roman numeral equivalent of the number inputted [Commands] >>> .roman <number> returns number represented in roman numerals """ class Plugin: def __init__(self): pass def __convert_roman_numeral(self, num...
""" player class """ # pylint: disable=E1601 import game_init class Player: """player class""" def __init__(self, nr, chips, username): """player initialization""" self.__position_nr = nr self.__general_name = "player" + str(nr) self.__username = username self.__chip...
""" Task 2. Write a program that queries the user for persons’ names and ages and saves them into a dictionary with name as a key and age as a value. When the user enters an empty string as a name, the program outputs the dictionary and terminates. Example run: Enter a name or an empty string to stop: James Enter age: ...
""" Write a procedure remove_duplicates(n), which finds and removes duplicate items from a list given as an argument. Hence, after the procedure is called, only a single instance of each item can be found in a list. lst = [1, 2, 1, 3, 3, 2, -1, 5, 3, 5, -1, 2, 5] remove_duplicates(lst) print (lst) [1, 2, 3, -1, 5] "...
#Question3 def strCase(userStr): upCase =0 lowCase =0 for i in userStr: ascNum = ord(i) #print(ascNum) if((ascNum >= 65 and ascNum <=90)): upCase = upCase + 1 else: lowCase = lowCase + 1 print("Uppercase Letters:",upCase) print("Low...
#Function are defined here #Name function def funcName(firstName,lastName): fName = (firstName +" "+ lastName) return (fName) #Percent function def perMarks(listMark,noSubj): totMark=sum(listMarks) marksPer = totMark/noSubj return marksPer #Marks Fucntion def totMarks(listMark...
#Main Function def main(): #declaring an empty list to add objects of class Course courseList = [] courseListFunc(courseList) #declaring an empty list to add objects of class Student stdList = [] studentList(stdList, courseList) choice = 0 while choice >= 0: ...
for i in range(10): print("begin") print("i is", i) i += 2 print("i is", i) print("end")
# -*- coding: utf-8 -*- from typing import List def binary_search_recursive(arr: List[int], low: int, high: int, x: int) -> int: """ recursive_version 如果x in arr,傳回x的index,否則傳回-1 若x在arr中出現多次時,mid不一定會回傳最先出現的index, 需要再額外的判斷 """ if high >= low: mid = (high + low) // 2 if arr[mid] ...
import numpy as np class Node: def __init__(self, value, previous, next, is_start=False): self.value = value self.previous = previous self.next = next self.is_start = is_start # Linked-in list implementation of Queue class Queue: def __init__(self): self.start_node = ...
import numpy as np import queue import stack class TreeNode: def __init__(self, value, left=None, right=None, is_root=False): self.value = value self._left = left self._right = right self.is_root = is_root self.is_visited = False def find_position_for_element(self, ele...
import math class Solution(object): def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ if n < 0: return False if n == 0: return False elif n == 1: return True n = float(n) while n != 2.0: ...
class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: int """ if not s: return 0 char_count_map = {} for curr_char in s: if curr_char not in char_count_map: char_count_map[curr_char] = 0 ...
import heapq """ # Definition for an Interval. class Interval: def __init__(self, start=None, end=None): self.start = start self.end = end """ class Solution(object): def employeeFreeTime(self, schedule): """ :type schedule: [[Interval]] :rtype: [Interval] """...
class Solution(object): def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ out = [] for x in range(1, n+1): s = '' if (x % 3) == 0: s += 'Fizz' if (x % 5) == 0: s += 'Buzz' if ...
import math class Solution(object): def invalid_sol(self, x): sqrt_val = math.sqrt(x) return int(sqrt_val) def binary_search(self, x): if x <= 1: return x elif 2 <= x <= 3: return 1 elif 4 <= x <= 8: return 2 left_val = 2 ...
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def diameterOfBinaryTree(self, root): if root is None: return 0 _, max_path_len = self._diameterOfBi...
import collections class Solution(object): def order_chars(self, w1, w2): len_w1 = len(w1) len_w2 = len(w2) n = min(len_w1, len_w2) for j in range(n): if w1[j] == w2[j]: continue else: return [w1[j], w2[j]] return None...
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def path_from_leaf_node(self, leaf_node): path = [] curr_node = leaf_node while curr_node is not None: ...
import numpy as np class Pixel: def __init__(self, color, sr, sc): self.color = color self.sr = sr self.sc = sc class Solution(object): def floodFill(self, image, sr, sc, newColor): """ :type image: List[List[int]] :type sr: int :type sc: int :...
class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead. """ num1_right_ptr = m+n-1 nums1_left_p...
import time import queue import threading def cpu_work(i): work_rate = pow(2, 26) print("{} : Work {} rate is {}".format(threading.current_thread(), i, work_rate)) for z in range(work_rate): i += 1 return i def cpu_worker(external_queue): while True: item = external_queue.get() ...
class DegreeDistribution: def __init__(self, network): """ Computes the degree distribution of a network. Make sure that both degree 0 and the maximum degree are included! """ # TODO: initialise a list to store the observations for each degree (including degree 0!) se...
#Write a program that prints the numbers from 1 to 100 #But for multiples of three it will print “Fizz” instead of the number. #For the multiples of five it will print “Buzz” and For multiples #of both three and five it will print “FizzBuzz” . def print_number(n): ''' print 'Fizz'for multiples of three,print'Bu...
from graph.Graph import GraphBase from graph.base import Edge, Node from list.DoubleLinkedList import ListaDoppiamenteCollegata as List class GraphAdjacencyList(GraphBase): """ A graph, implemented as an adjacency list. Each node u has a list containing its adjacent nodes, that is nodes v such that e...
class Node: """ The graph basic element: node. """ def __init__(self, id, value): """ Constructor. :param id: node ID (integer). :param value: node value. """ self.id = id self.value = value def __eq__(self, other): """ Equali...
import numpy as np def h(x, i): return x[i + 1] - x[i] if i + 1 < len(x) else x[i] - x[i - 1] def m(x, i): return h(x, i - 1) / (h(x, i + 1) + h(x, i)) def l(x, i): return h(x, i) / (h(x, i + 1) + h(x, i)) # returns list of answer for matrix def calc_matrix(n, x, y, diff2, a): m_a = np.zeros((n ...
# Реализовать функцию my_func(), которая принимает три позиционных аргумента, # и возвращает сумму наибольших двух аргументов. def my_func(a , b, c): if a <= b or a <= c: return b + c elif b <= a or b <= c: return a + c else: return a + b print(f'Cумма двух наибольших чисел = {my_f...
# Для списка реализовать обмен значений соседних элементов, # т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. # При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо # использовать функцию input(). n = int(input('Введите колличесто элеме...