text
stringlengths
37
1.41M
# 导入类 from collections import OrderedDict # 创建有序空字典 glossary = OrderedDict() # 给有序空字典添加键-值对 glossary['print'] = '打印' glossary['title'] = '首字母大写' glossary['lower'] = '全部小写' glossary['upper'] = '全部大写' glossary['str'] = '字符串' glossary['key'] = '键' glossary['value'] = '值' glossary['items'] = '项目' glossary['sorted'] = '排序...
# 创建类 class User(): """DocString.........""" def __init__(self, first_name, last_name, location, field): """初始化一个用户的属性""" self.first_name = first_name self.last_name = last_name self.location = location self.field = field self.login_attempts = 0 def desc...
# 创建用户名列表 users = ['admin', 'yang yahu', 'gao xiangzhou', 'eric', 'yang yuhang'] # 遍历列表并打印相应的消息 for user in users: if user == 'admin': print("Hello admin, would you like to see a status report?\n") else: print(f"Hello {user}, thank you for logging in again.")
# 创建列表 invited_persons = ['dad','mother','sister','cui ping'] # 打印邀请消息 print(f"Dear {invited_persons[0].title()}, can you have dinner with me?") print(f"\nDear {invited_persons[1].title()}, can you have dinner with me?") print(f"\nDear {invited_persons[2].title()}, can you have dinner with me?") print(f"\nDear {invite...
# 创建列表 favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } # 创建调查人员名单 investigators = ['jen', 'phil', 'gao xiangzhou', 'yang yuhang'] for investigator in investigators: if investigator in favorite_languages.keys(): print(f"{investigato...
# 创建列表 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] # 遍历列表 for number in numbers: if number == 1: print(str(number) + "st") elif number == 2: print(str(number) + "nd") elif number == 3: print(str(number) + "rd") else: print(str(number) + "th")
#! user/bin/env python3 x=100 def sum(x): if x == 1: return 1 else: return x + sum(x-1) total=x+sum(x-1) print(total)
#! usr/bin/env python3 import sys # # Binary Search is an algorithm that splits the information using a mid point # to find the specific data requested. # # This code uses Binary search to find <number> in a list of numbers. # # To run the program # # % python3 binary_search.py <number> # # where <number> can...
class trie: def __init__(self): self.data = None self.wordend = False self.child= [None]*26 def insert(root,word): l = len(word) tmp = root for i in range(l): ind = ord(word[i]) - 97 if(root.child[ind]==None): ptr = trie() ptr.data = word[i] if(i==l-1): ptr.wordend=True root.child...
class Phone(object): def __init__(self, given): self.number = '' for i in given: if i.isnumeric(): self.number += i if len(self.number) == 11 and self.number[0] == '1': self.number = self.number[1:] if len(self.number) != 10: self.n...
class Node(object): def __init__(self, element, previous, next): self.element = element self.previous = previous self.next = next class LinkedList(object): def __init__(self): self.front = None self.back = None self.length = 0 def push(self, element): ...
def detect_anagrams(word, candidates): anagrams = [] for candidate in candidates: letterlist = [] for i in candidate: letterlist += i.lower() for i in word: if i.lower() in letterlist: letterlist.remove(i.lower()) else: ...
def encode(values): encoded = [] for value in values: bits = [] for i in range(7, -1, -1): if value // 128**i > 0 or len(bits) > 0: bits.append(bin(value // 128**i)) if value // 128**i > 0: value -= 128**i * (value // 128**i) ...
def is_isogram(word): for i in range(len(word)): for j in range(len(word)): if word[i].lower() == word[j].lower() and i != j and word[i].isalpha() and word[j].isalpha(): return False return True
def largest_palindrome(max_factor, min_factor=1): largest = 1 factors = [] for i in range(min_factor, max_factor+1): for j in range(i, max_factor+1): if i*j == int(str(i*j)[::-1]): if i*j > largest: largest = i*j factors = [{i, j}] ...
def nth_prime(n): if n < 1: raise ValueError primes = [] num = 2 while len(primes) < n: prime = True for i in primes: if num % i == 0: prime = False if prime: primes.append(num) num += 1 return primes[len(primes)-1]
def transpose(input): rows = input.split("\n") maxlength = 0 for i in rows: if len(i) > maxlength: maxlength = len(i) for i in range(len(rows)): rows[i] = rows[i] + " " * (maxlength - len(rows[i])) newrows = [""] * maxlength for i in rows: for j in range(ma...
#!/usr/bin/env python #-*- coding: utf-8 -*- def sum(arr): if len(arr) == 0: return 0 return arr[0] + sum(arr[1:]) if __name__ == '__main__': arr = [] for n in range(10): arr.append(n) result = sum(arr) print(result)
''' Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre: a. o produto do dobro do primeiro com metade do segundo . b. a soma do triplo do primeiro com o terceiro. c. o terceiro elevado ao cubo. ''' n1 = int(input('Digite um numero inteiro: ')) n2 = int(input('Digit...
''' Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre a temperatura em graus Celsius. calculo: C = 5 * ((F-32) / 9 ''' f = int(input('Digite a temperatura em Fahrenheit: ')) c = 5 * ((f-32)/9) print('A temperatura em Celsius é: {:.0f}º'.format(c))
def ask(_question): _question.ask() input = raw_input().lower() question = _question.answer(input) if not question is None: ask(question) pass class Question: def __init__(self, _prompt, _answers=None, _parse_answer=None): self.prompt = _prompt self.answers = _answers ...
from typing import List Vector = List[float] #%% def add(v: Vector, w: Vector) -> Vector: """Adds corresponding elements""" assert len(v) == len(w), 'vectors must be the same length' return [v_i + w_i for v_i, w_i in zip(v, w)] def subtract(v: Vector, w: Vector) -> Vector: """Subtracts cor...
class Underscore(object): value = [] mapped = [] reduced = [] rejected = [] found = 0 def map(self, arr, function): for i in range(0, len(arr)): ld = function self.mapped.append(ld(arr[i])) return self.mapped def reduce(self, arr): one_digit = 0 for i in range(0, len(arr)): one_digit += arr[i] ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 7 13:29:42 2019 @author: lulumeng """ import pandas as pd from sklearn import preprocessing def data_read(file_path): data_raw = pd.read_csv(file_path,sep=r'\t',header=None, engine='python') x_raw = data_raw.iloc[:,:-1] y = data_raw....
def getNoRectangles(n): from math import sqrt res = 0 for i in range(1, int(sqrt(n))+1): res += int(n/i)-i+1 return res N = int(input()) print (getNoRectangles(N))
#section 1 f = open("data.csv","r") #accessing the file print(f) #display the I/O header stations = f.read() #assign the contents of the file to the variable stations print(stations) #display the contents #section 2 station_list = stations.split('\n') ...
prompt = "If you tell us who you are, we can personalize the messages you see." prompt += "\nWhat is your first name? " name = input(prompt) print("\nHello, " + name + "!") age = input("How old are you: ") age = int(age) if age <= 18: print("You are not eligible to vote") else: print("you are eligible")
for item in range(20): if item == range(20)[-1]: print('*'*item) s = "Sekhar" copy = s s = "Sekhartsr" print("now S: ["+s+"], copy : ["+copy+"]") li = [2, 5, 8, 6] li_copy = li li[0] = 1 print("now li: ["+str(li)+"], li_copy : ["+str(li_copy)+"]")
# m × n = m + (m × (n - 1)). def Multiply(m, n): # generate base case for the recursive algorithm # base case m x 1 = m if n == 1: return m else: return m + Multiply(m, n - 1) def main(): print(Multiply(5, 4)) if __name__ == '__main__': main()
# Practical 1- Nguyen Quoc Minh Quan def main(): # enter your algorithm here # the logic can be included in another method list1 = [] # get number of elements inside a list n = int(input("Input the number of elements inside a list: ")) for i in range(n): elements = int(input(">> ")) ...
""" This model builds an index of web pages. """ import requests import pickle from bs4 import BeautifulSoup from BTrees import BTreeST class IndexWeb(object): """ an index of web pages each web page is stored as a file """ def __init__(self): self.st = BTreeST() def add(self, r): ...
import sqlite3 from tkinter import * from tkinter import messagebox from PIL import Image,ImageTk import os # from tkinter import ttk def insert(): # database con = sqlite3.connect("ContactInfo.db") cur = con.cursor() cur.execute("INSERT INTO addresses VALUES(:First_Name,:Last_Name, :Gender, :Age, :A...
import numpy as np from timeit import repeat from matplotlib import pyplot as plt from tree import make_tree from tree_np import make_tree_np iterations = np.arange(1, 15, 1) length = 1 scale = 0.6 angle = 0.1 def plot_time(iterations): tree_list, = plt.plot(iterations, list(map(time_to...
#################################################################### # Structure: The placement of each element in the binary tree must # satisfy the binary search property: the value of the key of # an element is greater than the value of the key of the any element # element in its lef...
# Using text2 from the nltk book corpa, create your own version of the # MadLib program. # Requirements: # 1) Only use the first 150 tokens # 2) Pick 5 parts of speech to prompt for, including nouns # 3) Replace nouns 15% of the time, everything else 10% # Deliverables: # 1) Print the orginal text (150 tok...
def overLappingArea(R1X1Y1, R1X2Y2, R2X1Y1, R2X2Y2): R1x1 = R1X1Y1.get("x1") R2x1 = R2X1Y1.get("x1") R1x2 = R1X2Y2.get("x2") R2x2 = R2X2Y2.get("x2") R1y1 = R1X1Y1.get("y1") R2y1 = R2X1Y1.get("y1") R1y2 = R1X2Y2.get("y2") R2y2 = R2X2Y2.get("y2") width = min(R1x2, R2x2) - max(R1x1, ...
def findCommon(arr1, arr2): newarr = [] i = 0 j = 0 while i < len(arr1) and j < len(arr2): if arr1[i] == arr2[j]: newarr.append(arr1[i]) i += 1 j += 1 elif(arr1[i] > arr2[j]): j += 1 else: i += 1 return newarr if ...
print("Enter the marks") marks = int(input()) def getPercentage(marks): return (marks/1200)*100 print("Yo got {0}".format(getPercentage(marks)))
#!/usr/bin/env python3.7 string1=input("Enter the String :") print("printing the string :"+string1) print("printing the string :"+string1.upper()) print("printing the string :"+string1.lower()) print("First Character: "+string1[0]) print("Last Character: "+string1[-1]) print("Middle Character: "+string1[int(len(string1...
"""### Problem Statements In an ocean, there are `n` islands some of which are connected via bridges. Travelling over a bridge has some cost attaced with it. Find bridges in such a way that all islands are connected with minimum cost of travelling. You can assume that there is at least one possible way in which all i...
# Python3 implementation to print the path from # root to a given node in a binary tree # Helper Class that allocates a new node # with the given data and None left and # right pointers. class getNode: def __init__(self, data): self.data = data self.left = self.right = None # Returns true if ther...
def subsets(arr, index=0): """ :param: arr - input integer array Return - list of lists (two dimensional array) where each list represents a subset TODO: complete this method to return subsets of an array """ if len(arr) == 0: return [[]] if len(arr[index:]) == 1: return [[a...
class Node: """LinkedListNode class to be used for this problem""" def __init__(self, data): self.data = data self.next = None def swap_nodes(head, left_index, right_index): """ :param: head- head of input linked list :param: left_index - indicates position :param: right_index ...
"""Now that you saw the dynamic programming solution for the knapsack problem, it's time to implement it. Implement the function max_value to return the maximum value given the items (items) and the maximum weight of the knapsack (knapsack_max_weight). The items variable is the type Item, which is a named tuple.""" i...
def binary_search(array, target): # [Mine] '''Write a function that implements the binary search algorithm using iteration args: array: a sorted array of items of the same type target: the element you're searching for returns: int: the index of the target, if found, in the source -...
''' Computes gcd(a, b) ''' def EuclideanAlgorithm(a, b): #continue to divide a by be until remainder is 0 if a == 0: return b else: return EuclideanAlgorithm(b % a, a) def EuclideanIO(): print('\nThis program will calculate the greatest common divisor of 2 numbers.') a = input('Please enter the first value...
import string import sys text = raw_input("What are you trying to decode?") num = int(raw_input("How many characters is it shifting to the right?")) def shift(text, num): alphabet = string.ascii_lowercase shifted_alphabet = alphabet[num:] + alphabet[:num] table = string.maketrans(alphabet, shifted_alphabe...
import pprint partion = 3 def swap (list, i, n, Blist): while i + 1 != n: list[i][0] = list[i + 1][0] list[i][1] = list[i + 1][1] list[i][2] = list[i + 1][2] Blist[i][0] = Blist[i + 1][0] Blist[i][1] = Blist[i + 1][1] Blist[i][2] = Blist[i + 1][2] ...
#Find and replace str = "If monkeys like bananas, then I must be a monkey!" print str print str.find("monkey") print str.replace("monkey", "allegator") # Min. and max x = [2,54,-2,7,12,98] print "max number is:", max(x) print "min number is:", min(x) #first and last x = ["hello",2,54,-2,7,12,98,"world"] print "first ...
import math termX=input("Inserisci il termine in x: ") termN=input("Inserisci il termine noto: ") if termX == 0 and termN ==0: print "L'equazione e' indeterminata. " elif termX == 0: print "L'equazione e' impossibile. " else: ris =float (termN) / float (termX) * (-1.0) print "La soluzione dell'equ...
def ispow2(n): ''' True if n is a power of 2, False otherwise >>> ispow2(5) False >>> ispow2(4) True ''' return (n & (n-1)) == 0 def nextpow2(n): ''' Given n, return the nearest power of two that is >= n >>> nextpow2(1) 1 >>> nextpow2(2) 2 >>> nextpow2(5) ...
import scripts as s def FindPrime(a, b): """Find all primes for all x in a <= x <= b.""" return [x for x in range(a, b + 1) if s.IsPrime(x)] # def IsPrime(x): # """Determine if x is prime.""" # if x < 2: # return False # if x == 2: # return True # for i in range(2, int(sqrt(x))...
from sys import argv script, rezultatai = argv in_rezultatai = open(rezultatai, 'w') in_rezultatai.truncate() print "Hello, I'm %r program." % (script) print "Please type 3 integer numbers. After each, please press ENTER button." first_number = int(raw_input("first number: ")) second_number = int(raw_input("second ...
#lists and strings '''a string is a sequence of characters, and a list is a sequence of values but a list of characters is not the same as a string to convert from a string to a list of characters, you can use LIST''' s = "spam" #naturally creates a string print(type(s)) t = list(s) #leaves the string alone, ...
#build a grade calculator user_input_1 = input("Please enter your class grade in digit form: \n") try: user_input = float(user_input_1) if user_input >= 1.1: print("That's not a valid score, asshole!") elif user_input >= 0.9: print("A") elif user_input >= 0.8: print("B") elif...
#practice parsing strings #you can use the FIND and SLICE methods to take only pieces of strings practice = "From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008" #create practice string found_1 = practice.find("@") #finds position about half way through found_2 = practice.find(" ", found_1) #telling it to ...
#working on list methods #Python provides methods to operate on lists #you do not want to write these as practice = practice.sort(), because most list methods are void #to ADD SOMETHING to a list, you use the APPEND method practice = ["a", "b", "c"] practice.append("d") #adds "d" to end of list print(practice) #to...
#finding largest and smallest values in a set #find the largest value largest = None for i in [3, 41, 12, 9, 74, 15]: if largest is None or i >= largest: #if the largest variable has no value, OR if whatever is in there is greater than or equal to what is encountered in the set... largest = i ...
# by LCCL Coding Academy, www.LccLcoding.com # for Shopee Code League 2020 print() # List of prime numbers def is_prime(n): for i in range(2, n): if n % i == 0: return None return n >= 2 primes = [x for x in range(2, 100) if is_prime(x)] print('Prime numbers between 0 and 100: ') print...
from triangle import Triangle class TriangulatedFigure: # Class Invariant 1: Every triangle in self.triangles has # a unique set of vertices [Note 1 (at end)] # Class Invariant 2: len(self.triangles) < 2 --XOR-- # Every Triangle in self.triangles shares two get_points with another def ...
import sys def read_file(textfile): f=open(textfile,'r') next(f) i=0 j=0 matrix=[[0 for x in range(9)] for y in range(9)] while True: j=0 char=f.readline() for c in char: matrix[i][j]=int(c) j=j+1 if j==9: i=i+1 break if i==9: break return matrix def check_soduku(row,column,number,m...
def count(n): while n > 0: print('befour=%d',n) yield n # 生成值: n n -= 1 print('after=%d',n) c = count(5) c.__next__() c.__next__()
a= input('Please enter a string ') def most_frequent(str): d = dict() for b in str: if b not in d: d[b] = 1 else: d[b] += 1 return d print (most_frequent(a))
#Hangman import sys from sys import argv name, answer = argv words = answer.lower().replace(".", "").replace("'", "").split() print "" # Generates the list of all unique letters list_letters = [] for x in range(0, len(words)): z = 0 word_in_letters = list(words[x]) while z < len(word_in_letters): if word_in_le...
import os.path file_1 = input("Enter 1st FileName:") file_2 = input("Enter 2nd FileName:") if(not os.path.isfile(file_1) and not os.path.isfile(file_2)): print("File1 & File2 Doesn't Exist") exit() if(not os.path.isfile(file_1)): print("File1 Doesn't Exist") exit() if (not os.path.isfile(file_2...
n = int(input("Enter Number:")) i = 1 fact = 1 while (i != n+1): fact = fact * i i = i + 1 print("The factorial of " + str(n) + " is " + str(fact))
def max_toys(prices, k): prices.sort() purchase_count = 0 total_so_far = 0 ​ for toy_price in prices: total_so_far += toy_price if k >= total_so_far: purchase_count += 1 else: return purchase_count ##second solution
#!/usr/bin/env/ python3 #-*- coding: utf-8 -*- class Dict(dict): def __init__(self, **kw):#这一行没什么用 super(Dict, self).__init__(**kw) def __getattr__(self, key): try: return self[key]#self.key调用出来的是self[key]的value, key不是dict的属性 except KeyError as e: raise Attribu...
def backtracking(idx, order, c, arr): # arr 채우기 arr += order[idx] # 다 채웠는지 판단 if len(arr) == c: if arr not in cases[c].keys(): cases[c][arr] = 0 cases[c][arr] += 1 return # 다음 백트래킹 for i in range(idx+1, len(order)): backtracking(i, order, c, arr) d...
from collections import deque def solution(priorities, location): # 인쇄 대기 목록 큐 q = deque() for i in range(len(priorities)): q.append((i, priorities[i])) # 중요도 배열 weights = sorted(priorities, reverse=True) # 프린트 cnt = 0 while q: idx, p = q.popleft() if p == wei...
def find_lowest_cost_node(costs): lowest_cost = float("inf") lowest_cost_node = None for node in costs: cost = costs[node] if cost < lowest_cost and node not in processed: lowest_cost = cost lowest_cost_node = node return lowest_cost_node # 그래프 그리기 graph = {} gr...
str1 = "helloworldsohee" str2 = "hesworldllo" # 격자 만들기 dp = [[-1] * len(str1) for _ in range(len(str2))] for row in range(len(str2)): for column in range(len(str1)): if str1[column] != str2[row]: dp[row][column] = 0 continue else: if 0 <= row-1 < len(str2) and 0...
""" Create a mosaic image from a target image and source images. The sequence is: 1. Load a target image. This is the "big picture" which will be made up of smaller source images. 2. Divide the target image into squares with an edge of n pixels where n is the edge-length of the source images. 3. Iterate over these squa...
import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import sklearn from sklearn import linear_model def prepare_country_stats(oecd_bli, gdp_per_capita): full_country_stats = pd.merge(left=oecd_bli, right=gdp_per_capita, left_index=True, right_index=True) full_country_stats.sort_v...
import unittest #import the unittest module from user import User #import the user class class TestUser(unittest.TestCase): ''' Test class that defines test cases for the user class behaviours. Args: unittest.TestCase: TestCase class that helps in creating test cases. ''' # First test ...
#!/usr/bin/python import time def twiddle_bool(it,a,q): print "child started" while True : print "Itteration %d" % it.value it.value = it.value +1 time.sleep(1) any = False for i in range(len(a)): any = any or a[i] for i in range((len(a)-1), 0, -1): ...
# -*- coding:utf8 -*- # 生成九九乘法表 # 初始化表格为空 table = '' for i in range(1, 10): for j in range(1, 10): if i < j: continue table += '{} * {} = {}\t'.format(j, i, i * j) # 边界情况下换行 if i == j: table += '\n' print(table)
# -*- coding:utf8 -*- # 1. 列出所有人列表,并用3中方式打印信息 yanXiPalace = '延禧宫' yuGarden = '御花园' partyPlace = yanXiPalace invitees = ['太后', '皇后', '纯妃', '小嘉嫔', '舒妃', '皇上'] print('春节将至,请大家过来%s相聚,受邀名单:%s' % (partyPlace, invitees)) print('春节将至,请大家过来{}相聚,受邀名单:{}'.format(partyPlace, invitees)) print(f'春节将至,请大家过来{partyPlace}相聚,受...
class Solution(object): def findCircleNum(self, M): def dfs(M, visited, col): for row in range(len(M)): # if there is a friendship and if friend has not already been added to circle if M[col][row] == 1 and visited[row] == 0: visited[row] = 1 ...
# Count the number of vowels in a String # Bonus - report a sum of each vowel def is_vowel(char): if ((char == 'a') or (char == 'e') or (char == 'i') or (char == 'o') or (char == 'u')): return True else: return False vowelCount = 0 vowels = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0} inp...
from p5 import * x,y = width/2,height/2 import random import math l=[] #radius of the circle radius=350 golden_ratio = 0.61803 n=int(input('enter the no of vertices')) center_x,center_y= width/2+200,height/2+200 angle = 2*math.pi/n #to store the points of the vertices generated for i in range(1,n+1): l.appen...
""" Class controlling car """ import random class Car(): """ Represent a car """ model1 = """ {pos}.-'--`-._ {pos}'-O---O--' """ model2 = r""" {pos} __ {pos} _| =\__ {pos}/o____o_\ """ model3 = r""" {pos} ______ {pos} /|_||_\`.__ {pos}( _ _ _\ {pos}=`-(_)--(_)-' """ model4 = """ {p...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Tests for custom data structures """ # Gör tester # Ta bort första sista och mitt i länkad lista import unittest from unorderedlist import UnorderedList from error import KeyErr, ValErr, ListEmpty class TestLists(unittest.TestCase): """ Test class for lists ""...
# your code goes here f=1 n=int(input()) for i in range(1,n+1): f=f*i print(f)
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) merged_arr = [0] * elements # Your code here new_list = arrA + arrB for i in range(elements): mini = min(new_list) merged_arr[i] = mini new_list.remove...
#code to find the next empty grid def nextCell(grid): for x in range(9): for y in range(9): if grid[x][y] == 0: return x, y return -1, -1 #code to check if row is possible def row_check(grid, row, num): for x in range(9): if grid[row][x] == num: return False return True #code to check if column ...
#This is the 10th program in 99 programs in Python #This is extension of the last program, instead of storing the complete list your store the element and its size #superList2 is the working function def superList2(list): lastEl = None count = 0 finList = [] for i in list: if i == lastEl: ...
#This is the 14th program in 99 programs in Python #This creates a duplicate of each element in the list #working function duplicate_it def duplicate_it(list): finList = [] for i in list: finList.append(i) finList.append(i) return finList #test code, list is hard coded list1 = ...
# https://www.acmicpc.net/problem/7490 import sys import copy def solution(array, n): if len(array) == n: operators_list.append(copy.deepcopy(array)) return array.append(' ') solution(array, n) array.pop() array.append('+') solution(array, n) array.pop() array.append('-...
# https://www.acmicpc.net/problem/11720 def main(): number = int(input()) num_for_cal = input() result = 0 for i in range(number): result += int(num_for_cal[i]) print(result) if __name__ == "__main__": main()
import numpy as np from sklearn.metrics import r2_score def helloworld(): #print("Hello, world!") print("uncomment me") return def simple_linear_regression(x, y): """ Implement simple linear regression below y: list of dependent variables x: list of independent variables return: b1- ...
def add(value1, value2): return value1 + value2 def sub(value1, value2): return value1 - value2 def mul(value1, value2): return value1 * value2 def div(value1, value2): return value1 / value2
try: x1 = float(input()) y1 = float(input()) x2 = float(input()) y2 = float(input()) print("Unsuccessful typification") except ValueError as e: print("Unsuccessful typification: __ ", e) except ZeroDivisionError: print("Trying to devide by zero") except Exception: print("Commo...
import sys from collections import Counter class Task2d: def __init__(self): self.n = 0 self.x = set() self.line = set() def fill_x_list(self): for i in range(self.n-1): self.x.add(str(i+1)) def set_included_values(self): buf1 = set() ...
def union(P,Q) : R = [] for i in range(0,len(P)) : R.insert(i,P[i]) length = len(str(R)) for j in range(0,len(Q)) : if Q[j] not in R : R.insert(length,Q[j]) length = length + 1 return R def difference(P,Q) : #elements of P which are not in Q R = [] #R = P - Q for i in range(0,len(P)) : if P[i...
def add(x,y): a = x + y return a def subtract(x,y): s = x - y return s def multiply(x,y): m = x * y return m def divide(x,y): d = x / y return d x = int(input("Number 1 : ")) y = int(input("Number 2 : ")) print("\nCalculator : ") add = add(x,y) print("\nAddition : "+str(add)) s...
i = 0 x = True trinum = 0 trinumbers = [] #to store which triange number it is while x == True : i = i + 1 trinum = trinum + i trinumbers.append(trinum) checkfac = trinum counter = 1 for y in range(2,checkfac+1) : if checkfac%y == 0 : counter = counter + 1 if counter == 500 : x = False break; ...
numbers = [] for x in range(0,10) : num = int(input("Enter Number "+str(x+1)+" : ")) numbers.append(num) diff = numbers[0] - numbers[1] #finding the pair of numbers with least difference pair1 = 0 pair2 = 0 for y in range(0,9) : if (numbers[y]<numbers[y+1]) < diff : diff = numbers[y] - numbers [y+1] pair1 = nu...
def isPrime(num) : #to check if a number is prime or not if num < 2 : #for negative numbers and 0 and 1 return False else : root = num**0.5 root1 = int(root) prime = True for x in range(2,root1+1) : if(num%x==0) : prime = False if(prime==True) : return True else : return False maximum = ...
array = [] for i in range(0,10) : num = float(input("Enter Number "+str(i+1)+" : ")) array.append(num) sumnum = 0 for i in range(0,10) : sumnum = sumnum + array[i] average = sumnum/10 print("Average of 10 floating point value is : "+str(average))