text
stringlengths
37
1.41M
#!/usr/bin/env python3 """Program that performs the backward algorithm for a hidden markov model""" import numpy as np def backward(Observation, Emission, Transition, Initial): """Function that performs the backward algorithm for a hidden markov model""" if type(Observation) is not np.ndarray or len(Obser...
#!/usr/bin/env python3 """ defines a deep neural network performing binary classification""" import numpy as np class DeepNeuralNetwork(): """ defines a deep neural network performing binary classification using He initialization sqrt(2./layers_dims[l-1]).)""" def __init__(self, nx, layers): """C...
#!/usr/bin/env python3 """Program that calculates the derivative of a polynomial""" def poly_derivative(poly): """Function that calculates the derivative of a polynomial""" if type(poly) is not list or len(poly) == 0: return None elif len(poly) == 1: return [0] else: dvPoly = [...
import random class Deck(object): def __init__(self): self.deck = [] self.createDeck() def createDeck(self): suits = ["Club", "Spade", "Heart", "Diamond"] faceCards = ["Jack", "Queen", "King", "Ace"] for outer_count in range(0, 4): for inner_count in range(1...
students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def printName(a): for x in a: print x['first_name'], x['last_name'] printNa...
class Car(object): def __init__(self, price, speed, fuel, mileage): self.price = price self.speed = speed self.fuel = fuel self.mileage = mileage if self.price < 10000: self.tax = 0.12 else: self.tax = 0.15 def display_all(self): p...
x=10 y=20; larger=x if x>y else y print(f"{larger} is larger") print(f"{x} is greater than {y}" ) if x>y else print(f"{y} is greter than {x}")
from random import randint from typing import Tuple class ListNode: def __init__(self, value: int): self.value = value self.next = None def create_num_list(num) -> ListNode: res = None last_node = None for digit in reversed(str(num)): new_node = ListNode(int(digit)) i...
""" 1.每个词条有一个 id = "bodyContent",包含了正文内容,可以缩小范围。 2.词条页面url很统一: /wiki/Multi-paradigm_programming_language 3.为什么有些p标签的内容无法保存? 4.应该重构一下代码:分为两部分:第一部分专注于获取相关url,第二部分专注于保持内容 """ import urllib.request import urllib.parse from bs4 import BeautifulSoup import re TOPICS = { "python": "https://en.wikipedia.org/wiki/Python_(p...
class Dog: species = "Bulldog" def __init__(self, name, age): self.name = name self.umur = age def toString(self): print(self.name, self.umur) def withParameter(self, parameter): print(self.name, self.umur, parameter) dog = Dog("Doggy", "2") print(dog.species) dog.t...
''' 常用运算 ''' import numpy as np from pandas import Series,DataFrame df1 = DataFrame(np.arange(9).reshape(3,3), columns=list('ABC'), index=list('abc')) print(df1) ''' A B C a 0 1 2 b 3 4 5 c 6 7 8 ''' f = lambda x: x.max() - x.min() c = df1.apply(f) print(c) ''' A 6 B 6 C 6 ''' print(df1.max()...
# -*- coding:utf-8 -*- # Author: 李泽军 # Date: 2020/1/25 6:48 PM # Project: flask-demo import re pattern = re.compile('\w+\d+') s = 'pwdALLLF123' s1 = pattern.search(s) if s1: print(s1) print(s1.group(0)) s2 = '111@#$%' s3 = pattern.search(s2) print(s3.group(0))
def gcd(p,q): while q != 0: p,q = q, p % q return p p = 35 q = 42 result = gcd(p,q) print 'GCD of (%s, %s) is %s: ' % (p, q, result)
''' Author: Manzoor Mohammed URL: https://github.com/manzoormohammed/Python.git Find min operations needed to enter a pattern on dialpad DialPad: 1 2 3 4 5 6 7 8 9 * 0 # Operations: U L S R D ...
# taken from https://wiki.theory.org/Decoding_bencoded_data_with_python # fixed to work with python3 bytearrays # could precompute ords but this is more readable def bdecode(data): # try to be nice and work on strings too # done this way to prevent encoding/decoding issues if type(data) == str: b = bytearray() ...
class Solution: def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ i = 1 while i < len(nums): if nums[i] == nums[i-1]: nums.remove(nums[i]) i = i+1 return nums if __name__ == "__main__": num...
class RLEIterator: def __init__(self, A): """ :type A: List[int] """ # decode, memory error self.ret_list = [] for i in range(0, len(A), 2): self.ret_list.append(A[i]*[A[i+1]]) # trick self.ret_list = sum(self.ret_list, []) print(s...
""" Missing Number Lab written by Kevin Oyowe October 12, 2016 """ def find_missing(firstList, secondList): """ This function compares two lists and returns the extra number in the longer list """ extraList = [] lesserList = [] if len(firstList) > len(secondList): extraList = firstList ...
#!/usr/bin/python def n_gramas(cadena, n): """ Esta función recibe una cadena y un entero. :param cadena: Cadena a procesar. :param n: Número entero que es la ene de los n-gramas. :return: Lista de n-gramas. """ if len(cadena) <= n: return [cadena] else: return [cadena[...
### Coffee Machine Code ### """ ==================== OUTLINE ==================== What I need to happen: Anytime you enter report it will print out a report of the amount of coffee, water , milk, coins in the Machine It processes coins, you put in a number of 50p coins or whatever. Checks it has enou...
import qsimulator as qs import numpy as np import time """ Deutsch's algorithm is a special case of the general Deutsch-Jozsa algorithm. It checks the condition f(0) = f(1). Once all the operations are finished, a measurement is made. If the measured state is |0> the function is constant (f(0) = f(1)). If the measur...
# codes copied from contacts.py from tkinter import * import datetime import sqlite3 from tkinter import messagebox date = datetime.datetime.now().date() date = str(date) conn = sqlite3.connect('database.db') cur = conn.cursor()# we use cursor to run queries class Display(Toplevel): def __init__(self, person_id):...
''' Self Timer Camera By : Ashutosh Maheshwari ''' import pygame.camera import pygame.image import time pygame.camera.init() cam = pygame.camera.Camera(pygame.camera.list_cameras()[0]) print("SELF TIMER\nEnter the time duration in seconds: "); num = int(input()) cam.start() while num > 0: if num <= 3: ...
# _*_ coding: utf8 _*_ import random # Creamos una funcion llamada contenido(nombre) # que recibe el nombre del archivo que vamos a abrir def contenido(nombre): # Abrimos el archivo en modo lectura f = open(nombre, "r") # Leemos el contenido del archivo # y lo guardamos en la variable `texto` text...
import sqlite3 import sys #sqlite3.connect(dbName) will create the db if not exists # http://www.pythondoc.com/flask-sqlalchemy/index.html dbName = "app_service.db" class BaseTable: def __init__(self,table_name): self.table_name = table_name pass def create_table(self,**field_kw): ...
class Car: car="tayota" def __init__(self,made,register,color,module): self.made=made self.register=register self.color=color self.module=module def doings(self): return f"This car is made in {self.made} year of {self.register} is {self.color} have nice {self.module}"
#Shifa Mehreen #121910313005 #Addition of sparse matrix #input def input_matrix(): #size of matrix r= int(input("Enter the number of rows: ")) c = int(input("Enter the number of columns: ")) matrix = [] #taking in elements print("Enter elements: ") for i ...
#uma maheshwar #121910313061 #Binary search with user defined function and dynamic inputs #with recurssion #dynamic inputs def array_input(): n = int(input("Enter no'of elements: ")) print("Enter elements: ") a = [] for i in range(0,n): k = int(input()) a.append(k) return a # recursive func...
#uma maheshwar #121910313061 #Binary search with test cases #function def binarysearch_array(a,x): print("Array is: ",a) a.sort() print("Sorted array is: ",a) #taking ranges f = 0 loc =0 low = 0 high = len(a) - 1 mid = (low+high)//2 #checking with mid valu...
#uma maheshwar #121910313061 #Concatenating arrays def array_input(): #length of array n = int(input("Enter length of an array: ")) a=[] #declaring empty array #taking input from user for elements print("Enter elements: ") for i in range(0,n): k = int(input()) a.append(k) #adding elements return a #a...
#виведіть на екран транспоновану матрицю 3*3 (початкова матриця задана користувачем). import numpy #аналогічно створюємо масив з нулів, типу цілих чисел c=numpy.zeros((3,3),dtype=numpy.int_) for d in range(3): for e in range(3): # міняємо містями e i d , і тоді матриця залишается такою ж, а ітерація йде в...
def maxsubArray(arr,size): max_so_far=0 max_ending_here=0 for i in range(0,size): max_ending_here+=arr[i] if(max_ending_here<0): max_ending_here=0 elif(max_so_far<max_ending_here): max_so_far=max_ending_here return max_so_far arr=[2,3,-1,-9,0] size=len(arr) res=maxsubArray(arr,size) pri...
phone=(input("Enter number: ")) mapping={"1":"one","2":"two","3":"three","4":"four","5":"five","6":"six","7":"seven","8":"eight","9":"nine"} output="" for ch in phone: output+=mapping.get(ch)+" " print(output)
import random guessesTaken=0 print("Hello, What is your name?") name=input() number=random.randint(1,20) print("Well,"+name+",I'm thinking of a number between 1 to 20") while guessesTaken<6: print('Take a guess') guess=input() guess=int(guess) guessesTaken+=1 if(guess<number): print('Number g...
from itertools import permutations def AnagramSearch(a,s,d): e=len(d) for i in range(len(s)): l=[] st=s[i:i+e] c=permutations(st) for j in c: l.append(''.join(j)) print(l) for k in l: if k==d: return "Yes" r...
numbers=[] x=int(input("Enter number of elements in list")) for i in range(x): numbers.append(int(input())) findNum=int(input("The number to be deleted is ")) i=0 for element in numbers: if(element == findNum): numbers.pop(i) x=x-1 i=i-1 i=i+1 print(numbers)
n=int(input()) temp=n t=0 while n>0: c=n%10 # print(c) t=t*10+c print(t) n=n//10 # print(n) if temp==t: print("True") else: print("False")
def uncommon(s1,s2): sr1=s1.split(" ") sr2=s2.split(" ") uncommon="" for i in sr1: if i not in sr2: uncommon=uncommon+" "+i return uncommon s1=input("Enter string1:") s2=input("Enter string2:") result=uncommon(s1,s2) print(result)
def flip_case(str, letter): """given a string and a letter, if the string contains any letter in them, swap the letter case""" result = "" for s in str: if s == letter or s == letter.swapcase(): s = s.swapcase() result += s return result
def multiple_letter_count(str): count = {} for letter in str: count[letter] = count.get(letter, 0) + 1 return count
#! /usr/bin/env python import sys str = "Hello World" print str print str[0] print str[2:7] print str[2:] print sys.argv list = ['first',1,'second',2] tinylist = [3,'ff'] print list+tinylist dict = {} dict['one'] = "this is one" dict[2] = "this is two" tinylist = {'name':'jhon','phone':'15690018743','dept':'3.3'} ...
word = raw_input().split(',') #print " ".join(set(word)) print word l = [] [l.append(i) for i in word if i not in l] print " ".join(l)
#words = raw_input("Enter the words : ").split(',') ''' for i in words: words.sort() print words ''' words = [x for x in raw_input("Enter the words : ").split(',')] words.sort() print words ~
from tkinter import * from PIL import ImageTk, Image from tkinter import messagebox root = Tk() root.title('Message') # showinfo, showwarning, showerror, askquestion, askokcancel, askyesno def popup(): response = messagebox.askyesno("This is my Popup!", "Hello World!") # Label(root, text=response)...
# 共用变量问题————资源竞争 import threading def h1(): global xx for _ in range(0, 1000000): xx += 1 def do1(): li = [] for _ in range(10): t = threading.Thread(target=h1) li.append(t) for x in li: x.start() for x in li: x.join() # 理论值 10,000,000 实际 3,...
# 进程池 import multiprocessing import time def do(x): a=0 for x in range(0,x+1): a+=x print(a) if __name__ == '__main__': pool=multiprocessing.Pool(32) # 异步 good1=time.time() for x in range(1000): pool.apply_async(func=do,args=(x,)) good2=time.time() # 同步 ...
''' 统计一下你写过多少行代码。包括空行和注释,但是要分别列出来 python 代码中的注释块怎么获取没有想到更好的办法,有待优化 ''' import os import re code_lines = 0 empty_lines = 0 notes_lines = 0 file_path = "E:\\file\\workbook\\example.py" is_notes = 0 with open(file_path, encoding='UTF-8') as f: for line in f.readlines(): if not len(line) or re.match(r'\...
import tkinter as tk state = [[0 for i in range(3)] for j in range(3)] window = tk.Tk() canvas = tk.Canvas(window,width = 400,height = 400,bg = "white") canvas.create_line(0,133.33,400,133.33) canvas.create_line(0,266.66,400,266.66) canvas.create_line(133.33,0,133.33,400) canvas.create_line(266.66,0,266.66,400...
''' Created on Nov 2, 2017 Description: Creates a mandlebrot set based on complex numbers @author: Adam Undus ''' from cs5png import PNGImage def update(c,n): """ updates the sum of the complex values c""" z = 0 ct = 0 while ct < n: z = z ** 2 + c ct += 1 return z def inMSet(c,n):...
############################################################################## # # Copyright (c) 1996-2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # TH...
""" flat """ def flat(string): """ flat """ txt = "" for i in string: if i.isnumeric() or i == "-": txt += i else: txt += " " #print(txt) ans = "" num = [] for j in txt: if not j.isspace(): ans += j else: ...
""" shortten """ def shortten(num): """ shortten """ first = num r_first = num count = 0 ans = "" while num != -1: if count == 0: first = num count += 1 elif r_first+1 == num: count += 1 r_first = num elif r_fi...
""" missing card """ def missing_card(): """ missing card """ card = "3S QH 6C JH 2H JD 5D 9D AS 9H 6D 2S 10H JC AH 8S KS 3C\ AD KH AC 9C 7C 5H QS 5C JS 10D 10C 8D 5S QC 3D KC\ 2D QD 10S 3H 7H 4H 8H 7S 7D 4D 6H 9S 8C 6S 4C 4S 2C KD".split() lst = [] for _ in range(51): lst.append...
""" diamond """ def diamond(num): """ diamond """ for i in range(num): if i == 0 or i == num-1: space = " "*((num-1)//2) print(space+"*"+space) elif ((num-1)//2) > i > 0: space = " "*((num-1)//2-i) n_space = " "*(2*i-1) print(...
""" main """ def main(num): """ main """ if num > 1: main(num//2) print(num%2, end="") main(int(input()))
""" multiply """ def multiply_matrix(): """ multiply matrix """ row, col, row2 = int(input()), int(input()), int(input()) lst = [] lst2 = [] last = [[0 for i in range(row2)] for i in range(row)] for _ in range(row): ans = [] for _ in range(col): ans.appe...
""" euclid dis """ def euclid_recur(lst, lst2): """ calculate """ ans = ((lst[0]-lst2[0])**2+(lst[1]-lst2[1])**2)**0.5 return ans def main(): """ main """ plus = 0 num = int(input()) lst = [] for _ in range(num): lst.append([int(i) for i in input().split()]) for i...
""" ink """ def ink(): """ ink """ import math txt = input().split() for _ in range(int(txt[1])): point = input().split() rdis = ((int(point[0])-0)**2+(int(point[1])-0)**2)**(1/2) area = 3.1416*(rdis**2) print(math.ceil(area/int(txt[0]))) ink()
""" kayak """ def kayak(num): """ kayak """ people = input().split(" ") people_n = [] num = 0 for i in people: people_n.append(int(i)) people_n.sort() #print(people_n) while len(people_n) != 2: lst = [] people_n.sort() for i in range(1, len(people_n)): ...
""" gcd N """ def gcdv_1(a_num, b_num): """ gcd """ if b_num == 0: return a_num else: return gcdv_1(b_num, a_num%b_num) def main(): """ main """ reg = int(input()) lst = [int(input()) for i in range(reg)] if len(lst) == 1: print(lst[0]) else: ...
def my_sort(a): for i in range(1, len(a)): while i > 0 and a[i] < a[i - 1]: temp = a[i - 1] a[i - 1] = a[i] a[i] = temp i = i - 1 return a a = [5, 6, 3, 10, 78, 1, 49] # a.sort() print my_sort(a)
def search(arr, n, key): # Travers the given array starting # from leftmost element i = 0 while (i < n): # If key is found at index i if (arr[i] == key): return i # Jump the difference between # current array element and key ...
def subArraySum(arr, n, Sum): d = {} curr_sum = 0 for i in range(0,n): curr_sum = curr_sum + arr[i] if curr_sum == Sum: print("Sum found between indexes 0 to", i) return ...
def strStr(s, x): if not x: return 0 for i in range(len(s) - len(x) + 1): if s[i] == x[0]: j = 1 while j < len(x) and s[i+j] == x[j]: j += 1 if j == len(x): return i ...
var1=int(input("Enter the first vlaue:")) var2=int(input("enter the second value")) var3=int(input("enter the third value")) if var1>var2 and var1>var3 : print("Var1 is greater ") elif var2>var3 : print("var2 is greater") else: print("var3 is greater")
def yazitura(): import random secim=input("Yazı mı 'y', Tura mı 't'?: ") zeka=random.randint(0,1) if zeka==0: print("Yazı...") else: print("Tura...") if secim=="y" and zeka==0: print("Kazandınız...") elif secim=="t" and zeka==1: print("Kazandınız...") else...
def indirimhesap(urun,indirim): ind=indirim/100 hesap=urun*ind sonuc=urun-hesap return sonuc urun=eval(input("Lütfen Ürün Fiyatını Giriniz: ")) indirim=eval(input("Lütfen İndirim Oranını Giriniz: ")) s=indirimhesap(urun,indirim) print("İndirimli Fiyat:",s)
p = 0 def search(lst, n): l = 0 u = len(lst) - 1 while l <= u: mid = (l + u)//2 if lst[mid] == n: globals()['p'] = mid return True else: if lst[mid] < n: l = mid + 1 else: u = mid - 1 return Fals...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @File : replace_words.py @Author : Siwen @Time : 3/5/2020 5:58 PM """ """ 648. Replace Words In English, we have a concept called root, which can be followed by some other words to form another longer word - let's call this word successor. For example, the ro...
# 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 inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ ...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @File : add_and_search_word_data_structure_design.py @Author : Siwen @Time : 3/5/2020 6:32 PM """ """ 211. Add and Search Word - Data structure design Design a data structure that supports the following two operations: void addWord(word) bool search(word) se...
""" <file_name>.py -------------- Graph distance based on <link to paper, or website, or repository>. author: <your name here> email: <name at server dot com> (optional) Submitted as part of the 2019 NetSI Collabathon. """ from .base import BaseDistance class <AlgorithmName>(BaseDistance): def dist(self, G1, ...
def cubeVolume(l): # return sideLength^3 if type(l) is int or type(l) is float: return l * l * l return TypeError def avgList(li): # num of items j = 0 # total of items t = 0 for i in li: if(type(i) is not int): return TypeError j += 1 ...
#!/usr/bin/env python3 # convert-jpg-to-png.py # # Quick and dirty script to convert the book's jpeg scans # into png files, removing the color, and adding transparency. # This way any background color can be used and still look # relatively nice on the illustrations. # # Image Magick Command Example # # magick conver...
# BinaryNode class # Modified code from Listings 5.5, 5.6, 5.7, 5.8 & 5.12 class BinaryNode: # default constructor # makes an empty node def __init__(self): self.key = None self.left = None self.right = None # constructor for nodes # assigns initial value to key def __...
# June 17, 2008, San Diego, CA # This program simulates a factory conveyor system in which all boxes # are the same, but they arrive with random inter-arrival times. We # will investigate the number of boxes N(t) that have arived up to and # including time t. # The simulation input is the ...
from random import * def lol(): loop = 1 cash = 2000 while loop == 1: x = randrange(0,101) y = randrange(0,101) z = randrange(0,101) bets = raw_input("Bet on either x,y or z: ") print "Cash:",cash bet_cash = input("Play your bet: ") cash = cash - bet_...
# This program shows that the return statement can be used to return # multiple number of values not just one, by using a list. from visual import * def compute(x,y): # given two integer values x, y myList = [ ] s=x+y d=x-y p=x*y q=x/y #quotient r=x%y # remainder of division myList = [s]+[d]...
#Shawn Thompson #CSC 360 #ex 1.1 #List of input voltage #Corrosponding output voltage #Vr(t) = Ir2 #Vs(t) = I(r+r2) #Vr(t)/Vs(t)= Ir2/(I(r+r2)) = r2/(r+r2) #Vr(t) becomes equation used in line 12 def inOut_1(r,r2): control = 1 while control == 1: x = input("Please enter the voltage: ") z = ((r2...
# BTTester program from BinaryTree import * # main tester function def main(): # create an empty binary tree btree = BinaryTree() addEmployee(btree) if btree.root: print "Preorder\n" Preorder = btree.root.strPreorder() print "Inorder\n" Inorder = btree.root.strInor...
#defining the function def cnv(n): if n > 1: cnv(n // 2) # floor division: nous permet de prendre juste la resultat sans vergule print(n % 2, end=' ') nbr = int(input("Veuillez entrez un nombre decimal: ")) #calling the function cnv(nbr )
# Conrad Ibanez # Webscraping data from online source import pandas as pd import matplotlib.pyplot as plt from bs4 import BeautifulSoup import requests # this method is from the textbook def decode_content(r, encoding): return (r.content.decode(encoding)) # this method is from the textbook def enc...
# Create a class Time with private attributes hour, minute and second. Overload ‘+’ operator to #find sum of 2 time. class times: def __init__(self,h,m,s): self.h=h self.m=m self.s=s def __add__(self, other): return self.h + other.h, self.m + other.m, self.s + other.s v1 =...
from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import matplotlib.pyplot as plt import matplotlib.tri as tri import numpy as np def tri_plot(x,y,topo): """ This is a super simple function to plot a triangular mesh. It is also an interesting exercize to see how to loop over the mesh ...
N=int(input()) fact=1 if(N==0): print("1") else: for i in range(1,N + 1): fact=fact*i print(fact)
# Q. Take input from the user to get fibonacci series till the number entered # Ex - input:3 # Ouput: 0, 1, 1 nterms = int(input("How many terms do you want? ")) # first two terms n1, n2 = 0, 1 count = 0 # check if the number of terms is valid if nterms <= 0: print("Please enter a positive integer") # if there i...
import ast def tuple_to_string(tupl): separator = "," tuple_list = [] for element in tupl: tuple_list.append(str(element)) string = "(" + separator.join(tuple_list) + ")" return string def string_to_tuple(string): # literal_eval takes a string and duck types it if type(string) ...
def maximum(num1, num2, num3): if (num1 >= num2) and (num1 >= num3): largest = num1 elif (num2 >= num1) and (num2 >= num3): largest = num2 else: largest = num3 return largest num1 = int (input("Enter first number: " )) num2 = int (input("Enter second number: " )) num3 = int (...
# Jonathan Gieg 77804954 and Hieu Dao-Tran 24353293 ICS 31 Lab Assignment 2 print('How many hours?') hours = float(input()) print('This many hours:', hours) print('How many dollars per hour?') rate = float(input()) print('This many dollars per hour: ', rate) print('Weekly salary: ', hours * rate) hours = int(input...
from Tkinter import * import time import random from collections import deque ##################### ##### CLASSES ####### ##################### #square tile #size is the w or h class Tile: def __init__(self, size, centerX, centerY, row, col): self.size = size self.centerX = centerX self.centerY = centerY sel...
with open('pi_digits.txt') as file_object: content = file_object.read() print(content) print() filename = 'pi_digits.txt' with open(filename) as file_object: for line in file_object: print(line.rstrip()) print() with open(filename) as file_object: lines = file_object.readlines() for ...
# В трёх классах проходят занятия в одно и то же время, нужно узнать количество парт для каждого класса. # За каждой партой может сидеть не больше двух учеников. # Известно количество учащихся в каждом из трёх классов. # Сколько всего нужно закупить парт чтобы их хватило на всех учеников? # Программа получает на вход т...
#sequence.py #lists the squares of all integers from some starting number squared down to one # #Colin McCahill #09/10/15 x=eval(input("Give me a number to start with:")) print("Squares from",x**2,"down to 1:") for i in range(x,0,-1): print(i**2,", ",sep='',end='')
#hello.py #classic Hello, World program, but this time we will say hello from multiple #processes # #Colin McCahill #12/2/15 from multiprocessing import * def HelloWorld(name): print("Hello to %s from process %d" %(name,current_process().pid)) def main(): name=input("What is your name? ") n=eval(input("n...
def euclidian(testElement,training): #euclidian distance algorithm import math distances = [] for trainingElement in training: #loops through all the training elements dist = 0 for m in range(1,len(testElement)): #loops through each attribute difference = testElement[m] - traini...
#recstr.py #1.prompt the user for a string s #2.prompt the user for string t, #3.print s backwards #4.print whether or not s is a palindrome, #5.print whether t appears as a (possibly non-consecutive)subsequence of s. def rev(s): if len(s)==0: return s else: return s[-1]+rev(s[0:len(s)-1]) def...
import math # classe usada para armazenar grandezas vetoriais e realizar operacoes envolvendo essas grandezas class Vetor(object): def __init__(self, x, y): self.x = x self.y = y # cria um vetor unitario a partir de um angulo @classmethod def unitario(self, theta): return Vetor...
t=int(input()) for i in range(t): even=0 odd=0 n=int(input()) numbers=list(map(int,input().split())) for i in numbers: if i%2==0: even+=1 else: odd+=1 if even>0 and odd==0: print('Even') elif odd>0 and even==0: print('Odd') else: ...
n=int(input()) matrix=[] l=[] for i in range(n): new=[] for j in range(n): new.append(1) matrix.append(new) if len(matrix)==1: print(1) exit(0) for i in range(n): if i==0: continue for j in range(n): if j==0: continue matrix[i][j]=matrix[i-1][j]+...
def IsPrime(n): prime=[True for i in range(n+1)] prime[0]=False prime[1]=False for i in range(2,n+1): if prime[i]: for j in range(i+i,n+1,i): prime[j]=False return prime l,r=map(int,input().split()) total=0 count=0 p=IsPrime(1000001) for i in range(l,r+1): i...