text
stringlengths
5
121k
""" Collisions module. Manage objects collisions. """ from typing import Dict, Coroutine, Optional from objects.animations import Fire, SpaceShip from objects.space_garbage import Garbage def _is_point_inside(corner_row: int, corner_column: int, size_rows: int, size_columns: int, ...
"""Normalize the training set data for multiple.""" __author__="Jesse Lord" __date__="January 8, 2015" import numpy as np def featureNormalization(X): X_norm = X shape = X.shape mu = np.empty(shape[1]) sigma = np.empty(shape[1]) for ii in range(shape[1]): mu[ii]=np.mean(X[:,ii]) s...
"""Plots the scatter plot of the logistic regression training set.""" __author__="Jesse Lord" __date__="January 8, 2015" import matplotlib.pyplot as p import numpy as np from polyFeatures import polyFeatures def plotPoints(x,y): p.scatter(x,y,marker='x') p.show() def plotTheta(X,y,theta): p.scatter(X,y,...
"""Computes the gradient descent for linear regression with multiple features.""" __author__="Jesse Lord" __date__="January 8, 2015" import numpy as np from computeCost import computeCost import matplotlib.pyplot as p plotJ = 0 def gradientDescent(X,y,theta,alpha,num_iters): m = len(y) nfeatures = len(thet...
import pandas as pd import numpy as np import matplotlib.pyplot as plt data = pd.read_csv('datasets/customer-churn-model/Customer Churn Model.txt') plt.boxplot(data['Day Calls']) plt.ylabel('Numero de llamadas diarias') plt.title('Boxplot de las llamadas diarias') print(data['Day Calls'].describe()) IQR = data['Day...
import pandas as pd import numpy as np import matplotlib.pyplot as plt x = 1.5 + 2.5 * np.random.randn(100) res = 0 + 0.8 + np.random.randn(100) y_pred = 5 + 1.9*x y_actual = 5 + 1.9*x + res x_list = x.tolist() y_pred_list = y_pred.tolist() y_actual_list = y_actual.tolist() y_mean = [np.mean(y_actual) f...
''' Existen varios tipos de operaciones en Python. El primero, y mas comun es el de la adicion. ''' x, y, z = 3, 9, '4' a = 'String' b = [1, 2, 'lol'] ''' La siguiente linea de codigo imprimira el resultado de sumar x con yield ''' print(x+y) ''' Debemos recordar que es imposible en la gran mayoria de los casos...
from turtle import * from random import * speed(50) penup() bgcolor("#94B3C6") goto(-150,100) for i in range(15): write(i) right(90) forward(10) pendown() forward(10) penup() forward(40) pendown() forward(10) penup() forward(40) pendown() forward(10) penup(...
height = int(input("height : ")) count_star = 0 for i in range(1, height + 1): count_star += i print("*" * i) print("star 개수 : ", count_star)
lst = [ ['B', 'C', 'A', 'A'], ['C', 'C', 'B', 'B'], ['D', 'A', 'A', 'D'] ] data = {0: 'A', 1: 'B', 2: 'C', 3: 'D'} count_lst = [] for _, d in data.items(): count = 0 for row in lst: count += row.count(d) count_lst.append(count) for i, d in data.items(): print(d, "는 ", count_lst[i]...
class Member: def __init__(self): self.name = None self.account = None self.passwd = None self.birthyear = None mem1 = Member() mem2 = Member() mem3 = Member() mem1.name = "피치" mem1.account = 1313 mem1.passwd = "3131" mem1.birthyear = 1990 mem2.name = "릴리" mem2.account = 1414 mem...
import sys def gcd(a, b): if a == 0: return b return gcd(b % a, a) def find_divisors(arr): if len(arr) == 0: return else: gccd = arr[0] for i in range(1, len(arr) - 1): gccd = gcd(gccd, arr[i]) divisors = set() i = 1 while i * i <= ...
from tkinter import * from tkinter.filedialog import * from tkinter.messagebox import * from tkinter.messagebox import * from tkinter.font import Font from tkinter.scrolledtext import * import file_menu import edit_menu ''' import fomrat_menu import help_menu ''' root = Tk() root.title("Text Editor") root.geometr...
""" 通过覆盖类的__new__和__init__方法提供单例支持 """ def singleton(cls): """ 单例模式的装饰器 :param cls: :return: """ _instance = [] _old_new = cls.__new__ _old_init = cls.__init__ def _new_new(cls1, *args, **kwargs): if len(_instance) ...
import fileinput import re for line in fileinput.input(): sum = 0 line = re.sub(r'\s', '', line) for i in range(0, len(line)-1): if (line[i] == line[i+1]): sum += int(line[i]) if line[0] == line[len(line)-1]: sum += int(line[0]) print(sum)
''' author: Kamran Mostafavi given n courses and m directed edges between them representing pre-requisites create a linearly ordered list of courses (topological order) it is given that the graph of the courses is a DAG. input: n m edge 1 . . edge m outp...
import time from datetime import datetime from Utility.MainWinObserver import MainWinObserver from Utility.MainWinMeta import MainWinMeta def elapsed(func): def wrapper(): start = datetime.now() func() end = datetime.now() elapsed = (end - start).total_seconds() * 1000000 p...
"""Cards module defines classes specifically for the card game Blackjack.""" import random suits = ( 'Hearts', 'Diamonds', 'Spades', 'Clubs' ) ranks = ( 'Two','Three','Four','Five','Six','Seven', 'Eight','Nine','Ten','Jack','Queen','King', 'Ace' ) values = { 'Two':2,'Three':3,'Four':4,'F...
a = 3 a *= 2 print(a) a = 7 b = a // 2 print(b) b = a % 2 print(b) a /= 2.3 print(a) print(type(a))
""" Created on Sun Apr 26 22:18:29 2020 @author: lukas """ def fib(num: int): a, b = 0, 1 for i in range(num): a, b = b, a + b return a n = int(input('Który wyraz ciągu Fibonacciego policzyć?' '\nPodaj numer wyrazu: ')) val = fib(n) print('{}. wyraz ciągu wynosi: {}'.format(n,...
a = set([1, 2, 3, 4]) b = set([1, 3, 7, 9]) print(a.intersection(b)) print(a.union(b)) print(a.difference(b)) print(a.symmetric_difference(b))
import matplotlib.pyplot as plt from random import * def score_finder(l_symp): """ this is how i measure the health_index: fever: abs(your fever-37)*100 eg >>> 39.5==250 tiredness: a number between 0 and 10 *10 cough: a number between 0 and 10 *10 difficulty in breathing: a number between 0 and ...
''' ''' class Restaurant(): ''' ''' def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurant(self): print(self.restaurant_name.title()) print(sel...
''' ''' from die import Die my_die = Die(20) [print(f'Roll the die -> {my_die.roll_die()}') for i in range(10)]
''' ''' def sum_with_check(): try: n, m = int(input('Enter first number: ')), int(input('Enter second number: ')) except ValueError: print('Well, you definetly insert not number...') else: print(f'The sum of {n} and {m} is {n + m}.') sum_with_check()
''' ''' class User(): ''' ''' def __init__(self, first_name, last_name, login, password, phone, about): self.first_name = first_name self.last_name = last_name self.login = login self.password = password self.phone = phone self.about = about self.lo...
mytask = "Assign a list to variables temperatures. The list should contain three items, a float, an integer, and a string." print(mytask) temperatures = [7.5, 9, "today"] print(temperatures) mytask1 = "Assign a list to variables rainfall. The list should contain four items, a float, an integer, a string, and ...
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] print(letters[1:4]) letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] print(letters[0:3]) letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] print(letters[4:])
class Animal(object): pass class Dog(Animal): def __init__(self, name): self.name = name class Cat(Animal): def __init__(self, name): self.name = name class Person(object): def __init__(self, name): self.name = name self.pet ...
from sys import argv script, filename = argv txt = open(filename) print(f"Here's your file {filename}:") print(txt.read()) txt.close() file = input("Enter the file name: ") txt1 = open(file) print(txt1.read()) txt1.close()
''' 功能:绘制好多五角星 重点:自定义函数的用法、参数的作用 作者:薛景 最后修改于:2019/05/30 ''' import turtle, math, random t = turtle.Turtle() t.shape("turtle") def drawStar(x, y, r, color, heading): t.up() t.goto(x, y) t.down() t.color(color) t.setheading(heading) edge=r*math.sin(math.radians(36))/math.sin(math.radians(12...
def compress_word(w): """ W is a parameter representing a word that is a string. This function should remove the letters " A, E, I, O, U" from a word. """ newword = " " vowels= ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"] for i in range(len(w)): if w[i] not in vowels : ...
import random def build_random_list(size,max_value): """ Parameters: size : the number of elements in the lsit max_value : the max random value to put in the list """ l = [] i = 0 while i < size: l.append(random.randrange(0,max_value)) i = i ...
def mergesort(arr): start = 0 end = len(arr) - 1 mergesort_inner(arr, start, end) return arr def mergesort_inner(arr, start, end): if (start >= end): return middle = (start + end)//2 mergesort_inner(arr, middle + 1, end) mergesort_inner(arr, start, middle) ...
name = input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) hour = dict() for line in handle: line.rstrip() if not line.startswith('From '): continue words = line.split() hour[words[5]] = hour.get(words[5] , 0 ) + 1 hour2 = dict() for key in hour.keys(): key.spl...
import unittest from user import User class TestUser(unittest.TestCase): """ Test class that defines test cases for the user class behaviours. Args: unittest.TestCase:TestCase that help in creating test cases """ def setUp(self): """ set up method to run before each test...
class Animal(object): """ This is the animal class, an abstract one. """ def __init__(self, name): self.name = name def talk(self): print(self.name) a = Animal('What is sound of Animal?') a.talk() class Cat(Animal): def talk(self): print('I\'m a real one,', self.n...
import pygame """ Variavéis padrões: x x y = Altura x Largura. w x h = Altura x Largura """ class itens: def __init__(self, win, x, y, w, h, img, r): self.x = x self.y = y self.w = w self.h = h self.r = r self.visivel = True self.img = img self.win...
import numpy import numpy numpy.set_printoptions(legacy='1.13') def inputToIntArray(entry): entry = entry.split(" ") return list(map(int, entry)) rayTable = inputToIntArray(input()) finalArray = numpy.zeros(rayTable)...
import numpy as np from numpy.linalg import inv from numpy import dot from numpy import mat X = mat([1, 2, 3]).reshape(3, 1) Y = 2 * X theta = dot(dot(inv(dot(X.T, X)), X.T), Y) theta = 1. alpha = 0.1 for i in range(100): theta = theta + alpha * np.sum((Y - dot(X, theta)) ...
from collections import Counter from random import randint from matplotlib import pyplot as plt from LinearAlgebra.vectors import sum_of_squares, dot from math import sqrt num_friends = [randint(1, 101) for x in range(200)] friend_counts = Counter(num_friends) """ Plot the friend-count vs number of people """ x_axis ...
import torch import torchvision import matplotlib.pyplot as plt import numpy as np import torch.nn as nn x=torch.randn(10,1) y=2*x+3 class Net(nn.Module): def __init__(self): super(Net,self).__init__() self.linear1=nn.Linear(1,3) self.linear2=nn.Linear(3,1) def forward(self,x): ...
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def Treeheight(self, pRoot): if pRoot == None: return 0 if pRoot.left == None and pRoot.right == None: return 1 lh = se...
class Solutions(object): def oddJumpFloor(self, n): if n == 1 or n == 2: return n res = psum = 3 for i in range(n - 2): res = psum + 1 psum += res return res if __name__ == "__main__": print(Solutions().oddJumpFloor(5))
def digit_sum(n, s=0): l = str(n) for x in l: s += int(x) return s
from random import randint num = randint(1, 10) print("Hey i am thinking of a number bet 1 to 10 can you guess :P") print('your are left with three chances !!!!') i=3 while i > 0: i -=1 user_guess1 = int(input('Enter your number Guess1')) if user_guess1== num: print('you guessed it right') ...
def animal_crackers(text): word=text.split( ) print(word) for i in word: if (i[0][0] == i[1][0]): return True else: return False string = 'levalheaded llama' animal_crackers(string)
def longest(s1, s2): s1 += s2 x=set(s1) s1=list(x) s1.sort() return s1 k=longest("aretheyhere", "yestheyarehere") print(k)
import re def jisuan(num): num=chengchu(num) return num def chengchu(num): if re.search('\-?\d+[\.?\d+]?[\*|\/]\d+',num) is None: return num String=re.search('\-?\d+\.?\d+?[\*|\/]\d+',num).group() print(String) if '/' in String: b='%.2f'%(float(re.split('\/',Str...
''' 2分算法思路: 1、func(data,8)调用函数func 传入的实参为data列表,8 2、执行函数体, 此时zhongjian函数的值就等于列表data的长度/2 , 假设为300 3、进行判断此时yuan长度>=1 数据是否还有值...
import time import queue import threading q=queue.Queue() def consumer(n): while True: print("consumer [%s] get task %s"%(n,q.get())) time.sleep(1) q.task_done() def producer(n): count = 1 while True: print("prodcer [%s] produced a new task:%s"%(n,count)) q.put(cou...
n = 4 a = [[0] * n for i in range(n)] for i in range(0, 0): print(i)
from tkinter import * from tkinter import ttk def calculate(*args): try: value = float(fahrenheit.get()) fahren = (value - 32) * 5/9 celsius.set(float('%.3f' % fahren)) except ValueError: pass root = Tk() root.title("fahrenheit to celsius") mainframe = ttk.Frame(root, padding=...
class BlogPost: def __init__(self, user_name, text, number_of_likes): self.user_name = user_name self.text = text self.number_of_likes = number_of_likes post1 = BlogPost(user_name='Oleg', text='Hi', number_of_likes=7) post2 = BlogPost(user_name='Nik', text='Hello', number_of_likes=5) post...
def get_infinite_square_generator(): """ :return: """ i = 1 while True: yield i ** 2 i += 1 infinite_square_generator = get_infinite_square_generator() print(next(infinite_square_generator)) print(next(infinite_square_generator)) print(next(infinite_square_genera...
ex_string = "Just do it!" print (ex_string[10]) print(ex_string[5:7]) print(ex_string[8:11]) print(ex_string[:4]) print("Don't "+ex_string[5:11]) print(type(ex_string)) print ("This is \n next line")
""" Koc University, Turkey KOLT Python Certificate Program Spring 2020 - Assignment 1 Created by @ahmetuysal and @hasancaslan """ import turtle SCREEN_WIDTH = 720 SCREEN_HEIGHT = 720 PEN_SIZE = 5 SQUARE_SIZE = 100 ANIMATION_SPEED = 100 def draw_empty_board(): """ This function should draw the empty tic-t...
def sort_by_strings(s, t): """ sample input: "cats" "atzc" sample output: "catz" assumption(s) => 1. s does not have repeating letters 2. s and t are all lowercased 3. Overall, the goodwill of the person running my code that they will be nice. (have mercy plox) 4. Person running ...
""" A function to find all instances of a substring. This function is not unlike a 'find-all' option that you might see in a text editor. Author: Juliet George Date: 8/5/2020 """ import introcs def findall(text,sub): """ Returns the tuple of all positions of substring sub in text. If sub does not appea...
""" A function to search for the first vowel position Author: Juliet George Date: 7/30/2020 """ import introcs def first_vowel(s): """ Returns the position of the first vowel in s; it returns -1 if there are no vowels. We define the vowels to be the letters 'a','e','i','o', and 'u'. The letter 'y' ...
text1 = str(input("Enter a string: ")) print("The string is:", text1) search = text1.find("a") if(search == -1): print("Character a not present in string") else: text1 = text1.replace("a","$") print(text1) text2 = str(input("Enter a string: ")) print("The string is:", text2) text2 = text2.replace(" ","-...
import tensorflow as tf def relu(x, alpha=0.5, max_value=None): '''ReLU. alpha: slope of negative section. ''' negative_part = tf.nn.relu(-x) x = tf.nn.relu(x) if max_value is not None: x = tf.clip_by_value(x, tf.cast(0., dtype=_FLOATX), tf.ca...
"""@author: Luhow 匿名函数 @time:2018/12/122:57 """ def is_odd(n): return n % 2 == 1 L = list(filter(lambda n : n % 2 == 1, range(1, 20))) print(L)
def reverse_int(n): reverse = [""]*len(n) for i in range(0, len(n)): reverse[-i-1] = n[i] print("".join(reverse)) integer = input("Please enter an integer\n") reverse_int(integer)
import math def merge(B, C, A): i = 0 j = 0 k = 0 while i < len(B) and j < len(C): if B[i] <= C[j]: A[k] = B[i] i += 1 else: A[k] = C[j] j += 1 k += 1 if i == len(B): A[k:] = C[j:] else: A[k:] = B[i:] def merge_sort(A): B = [] C = [] if len(A) > 1: B = A[:math.floor(len(A)/2)] ...
import re N = input() for i in range(int(N)): credit = input().strip() validation = re.search(r'^[456]\d{3}(-?)\d{4}\1\d{4}\1\d{4}$',credit) if validation: flatten = "".join(validation.group(0).split('-')) valid = re.search(r'(\d)\1{3,}',flatten) print('Invalid' if valid el...
from flask import url_for class Pagination(object): """Simple pagination class.""" def __init__(self, per_page, page, count, url_maker, neighbours=5): self.per_page = per_page self.page = page self.count = count self.url_maker = url_maker self.neighbours = 5 def ...
from datetime import datetime import lxml from lxml import html import requests import numpy as np import pandas as pd import bs4 """ To get the name of symbol/ticker of the stocks for which you want information you can look it up on https://finance.yahoo.com/ and from there you can pass the scrip name i...
from cs50 import get_int numbers = [] while True: number = get_int("Number: ") if not number: break if numbeer not in numbers: numbers.append(number) print() for number in numbers: print(number)
def main(): A = [5, 4, 3, 2, 1] print(insertionsort(A)) def insertionsort(A): for j in range(1, len(A)): key = A[j] i = j while i > 0 and A[i - 1] > key: A[i] = A[i - 1] i = i - 1 A[i] = key return A main()
''' Finds the longest common subsequence of two sequences (Given as 2 arrays) ''' from pandas import DataFrame x = [0, 3, 9, 8, 3, 9, 7, 9, 7, 0,] y = [0, 3, 3, 9, 9, 9, 1, 7, 2, 0,6] def main(): longest_subsequence(x, y) def longest_subsequence(a, b): DP = [[0] * (len(a)) for i in range(len(b))] back_t...
''' A simple fibonacci but using memoization and dynamic programing An introduction to the basics of dynamic programming ''' memo = {} def main(): print(fib_naive(5)) print(fib_bottoms_up(4)) def fib_naive(n): ''' We used the recursive method in order to fine every combination from f(n) down the ...
def count_keyboard(): n = int(input()) a = input() count = len(a) if a[0].isupper(): count += 1 for i in range(1, n): if a[i].islower() and a[i - 1].isupper(): count += 1 elif a[i].isupper() and a[i - 1].islower(): count += 1 print(count-1...
from collections import Counter import sys names = ['ZHANG SAN', 'LI SI', 'WANG WU', 'WANG LIU', 'WANG QI', 'ZHANG WU', 'LI WU' ] def get_count(name): first_names = [name.split()[0] for name in names] first_name = name.split()[0] counters = Counter(first_names) return counters.get(first_name) resu...
def SelectSort(arr): n = len(arr) for i in range(0, n-1): min_index = i for j in range(i+1, n): if arr[i]>arr[j]: arr[i],arr[j] = arr[j],arr[i] return arr
x=input(" ") y=input(" ") z=input(" ") if x>y and x>z: print(x) elif y>z: print(y) else: print(z)
s=raw_input() s1=raw_input() l=len(s) l1=len(s1) if(l==l1): for i in range(l): for j in range(i+1,l): if(s[i]==s[j]): if(s1[i]==s1[j]): print("isomarpic") else: print("not a isomorpic") else: print("not a isomorpic")
a1=[1,2,4] a2=[1,2,4,7] c=0 for i in range(len(a2)): if(a1[0]==a2[i]): for j in range(len(a1)): if(a1[j]==a2[i]): i=i+1 c=c+1 if(c==len(a1)): print("subset") else: print("not a subset")
from tree import BinaryTree from random import randint arr = list(set([randint(0, 100) for i in range(20)])) print("array length:", len(arr)) bst = BinaryTree(arr) print("=====") print("is balanced:", bst.is_balanced(bst.root)) print("tree height:", bst.get_height(bst.root)) print("=====") bst.print_tree() print("...
i = int(input()) if i%10 == 1 and i//10!=1: print(i, 'korova') elif i%10<5 and i//10!=1 and i%10!=0: print(i, 'korovy') else: print(i, 'korov')
nums = [1,4,5,-12,576,12,83,-5,3,24,46,100,2,4,1] def Merge_sort(nums): if len(nums)<=1: return nums middle=int(len(nums)//2) left=Merge_sort(nums[:middle]) print(left) right=Merge_sort(nums[middle:]) print(right) return merge(left,right) def merge(left, right): sorted_list...
dna=input(' Enter the nucleotide sequence ') dna=dna.upper(); acount=dna.count('A',0,len(dna)); tcount=dna.count('T',0,len(dna)); gcount=dna.count('G',0,len(dna)); ccount=dna.count('C',0,len(dna)); X=[acount,ccount,gcount,tcount]; print (' '.join(str(x) for x in X))
salario = float(input('Digite o salario atual: ')) aumento = salario + (salario * 0.15) print('O seu novo salario fica \33[4:31m{:.2F}\33[m.'.format(aumento))
class Dog: def __init__(self, name: str, sound="hau"): self.name = name self.sound = sound def make_sound(self) -> str: return f'Dog name is {self.name} sound: {self.sound}'
graph = {'A': ['B', 'C', 'E'], 'B': ['A','D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B','D'], 'F': ['C'], 'G': ['C']} def bfs_shortest_path(graph, start, goal): explored = [] queue = [start] if start == goal: return "...
dicionario = {} stringConhecida = input("").upper() stringCifrada = input("").upper() msgCifrada = input("").upper() msgDecifrada = "" for c in range(len(stringCifrada)): dicionario.update({stringCifrada[c] : stringConhecida[c]}) for c in range(len(msgCifrada)): if(msgCifrada[c] not in dicionario): ...
k=1 num=int(input()) for i in range(1,num+1): k=k*i print(k)
b,d=input().split(' ') b=int(b) d=int(d) for num in range(b+1,d+1): if (num%2!=0): print(num,end=' ')
from util import Queue class Graph: """Represent a graph as a dictionary of vertices mapping labels to edges.""" def __init__(self): self.vertices = {} def add_vertex(self, vertex_id): """ Add a vertex to the graph. """ if vertex_id not in self.vertices: ...
""" NAME this command does things SYNOPSIS command do-things nice DESCRIPTION things are nice when this command does them AUTHOR Mark Shocklee """ import argparse parser = argparse.ArgumentParser( description='Path building utility.', epilog="""Default operation is to read a...
def main(): temp = load_file("data.csv") print(temp) def load_file(filename): dic = {} list1 = [] with open(filename, 'r') as filename: for line in filename: temp1 = line.split(",") dic[temp1[0]] = temp1[1] + temp1[2] ...
def my_gen(): n = 1 print('This is printed first') yield n n += 1 print('This is printed second') yield n n += 1 print('This is printed at last') yield n if __name__ == '__main__': a = my_gen() print(a) print(next(a)) print(next(a)) print(next(a...
mybasket = {'apple':2.99,'orange':1.99,'milk':5.8} print(mybasket['apple']) mynestedbasket = {'apple':2.99,'orange':1.99,'milk':['chocolate','stawbery']} print(mynestedbasket['milk'][1].upper()) mybasket['pizza'] = 4.5 print(mybasket) print(mybasket.keys()) print(mybasket.values()) print(mybasket.it...
''' Created on Nov 18, 2017 @author: ITAUser ''' '''create a function that accepts the filename and character''' def calculate_char(filename, mychar): f = open(filename, 'r') count = 0; isDone = False while not isDone: char=f.read(1) char = char.lower() if char == mychar: ...
import numpy as np import random import matplotlib.pyplot as plt import knapsack random.seed(151) knapsack.N = 10 knapsack.MAX_weight = 10 knapsack.WeightandValue = knapsack.make_randdata(knapsack.N) knapsack.w = [] for i in knapsack.WeightandValue : knapsack.w.append(i[0]) knapsack.MAX_W = sum(knapsack...
import numpy as np import matplotlib.pyplot as plt gaussian_numbers = np.random.randn(1000) plt.hist(gaussian_numbers) plt.title("Gaussian Histogram") plt.xlabel("Value") plt.ylabel("Frequency") plt.show()
from random import randint class HeapArray(): def __init__(self): self.data = [] self.data.append(None) def parent(self, item): if item == (0 or 1): return None return item//2 def leftChild(self, item): if item == 0: return None ...
import pandas as pd from datetime import datetime import matplotlib.pyplot as plt import json """ today=datetime.today().strftime('%Y-%m-%d')#Get today's date location = input("Location: ") # Location to be monitored people_day=1#People you meet in a day """ limit_a = (0.88,15) limit_b = (0.95,20) given_period=1 ...
print("+--------------MENU-----------------+") print("|Chon C de tao hoa don |") print("|Chon R de xem thong tin hoa don |") print("|Chon T de tinh tong doanh thu |") print("|Chon A de tinh tong hang hoa ban ra|") print("|Chon E de thoat |") print("+------------------------------...
class Flight(): def __init__(self,capacity): self.capacity = capacity self.passengers = [] def add_passenger(self,name): if not self.open_seats: return False self.passengers.append(name) return True def open_seats(self): return self.capacity - le...